diff --git a/.babelrc b/.babelrc index c6835a903..eaf32387b 100755 --- a/.babelrc +++ b/.babelrc @@ -1,5 +1,3 @@ { - "presets": [ - "es2015", "stage-0" - ] -} \ No newline at end of file + "presets": ["es2015", "stage-0"] +} diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..31fd7febb --- /dev/null +++ b/.prettierignore @@ -0,0 +1,15 @@ +node_modules/ +conf/config.json +conf/kibana-config.json +conf_copy/ +.idea/** +.vscode/ +*.log +.netbeans.xml +etl-daemon.js +.nyc_output +coverage +conf/config-bk.json +dist +build +.build diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 000000000..1387fd027 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,6 @@ +{ + "trailingComma": "none", + "tabWidth": 2, + "semi": true, + "singleQuote": true +} diff --git a/.travis.yml b/.travis.yml index dd15db648..7d0e381bc 100755 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,8 @@ sudo: required language: node_js node_js: -- '10' -services: + - '10' +services: - docker before_install: - export TZ=Africa/Nairobi @@ -13,16 +13,16 @@ before_install: addons: apt: sources: - - ubuntu-toolchain-r-test + - ubuntu-toolchain-r-test packages: - - g++-5 + - g++-5 script: -- npm test -- npm start + - npm test + - npm start env: - CXX=g++-5 deploy: provider: script script: bash docker/docker_push.sh on: - all_branches: true \ No newline at end of file + all_branches: true diff --git a/README.md b/README.md index 1c116d992..d1e38e2ea 100755 --- a/README.md +++ b/README.md @@ -1,23 +1,22 @@ [![Build Status](https://travis-ci.org/AMPATH/etl-rest-server.svg?branch=master)](https://travis-ci.org/AMPATH/etl-rest-server) -ETL REST Server -=============== +# ETL REST Server This is a node project that uses [hapi](https://github.com/hapijs/hapi) to expose REST endpoints which provide access to data hosted in [ETL](https://en.wikipedia.org/wiki/Extract,_transform,_load) flat tables. These flat tables are flattened derived database tables containing data from OpenMRS. Data generation is done via MySQL stored procedures (found [here](https://github.com/ampath/etl)). This project is currently being battle-tested in production by [AMPATH POC](https://github.com/AMPATH/ng2-amrs). To setup the project, run: -```$ git clone https://github.com/AMPATH/etl-rest-server.git``` +`$ git clone https://github.com/AMPATH/etl-rest-server.git` -```$ cd etl-rest-server ``` +`$ cd etl-rest-server ` -```$ npm install``` +`$ npm install` -```$ mkdir conf && cd conf``` +`$ mkdir conf && cd conf` Create a config.json file -```$ cat config.json``` +`$ cat config.json` With the following content @@ -43,19 +42,18 @@ With the following content "multipleStatements": true } } - ``` -You can set ```tls:false``` if you don't care about https and don't provide the keys but if you set + +You can set `tls:false` if you don't care about https and don't provide the keys but if you set it to true you have to provide the keys. -```npm start``` +`npm start` -Now visit ```https://:``` You should see the welcome message +Now visit `https://:` You should see the welcome message -``` Welcome to ETL reset server for OpenMRS ``` +`Welcome to ETL reset server for OpenMRS` -Using Docker Compose 1.6+ -------------------------- +## Using Docker Compose 1.6+ docker-compose up -d @@ -63,8 +61,7 @@ Confirm by looking for the server at host port 8002 using TLS: curl -k https://docker:8007 -Without Docker Compose ----------------------- +## Without Docker Compose ## Building @@ -78,19 +75,20 @@ Without Docker Compose -e MYSQL_USER=etl_user -e MYSQL_PASSWORD=etl_password mysql #### Running with openmrs instance running at localhost on port 8080 + docker run -d --name etl --link mysql4etl:db -p 8002:8002 etl #### Running with openmrs running at 1.2.3.4 on port 8081 under app name "omrs" docker run -d --name etl --link mysql4etl:db -p 8002:8002 \ - -e OPENMRS_HOST_ADDR=1.2.3.4 -e OPENMRS_NAME=omrs -e OPENMRS_PORT=8081 etl + -e OPENMRS_HOST_ADDR=1.2.3.4 -e OPENMRS_NAME=omrs -e OPENMRS_PORT=8081 etl ### Using your own MySQL server If you have MySQL running at 1.2.3.4 with username "myuser" and password "mypassword": -(This assumes openmrs at localhost port 8080, to use different settings pass - environmental variables as above) - +(This assumes openmrs at localhost port 8080, to use different settings pass +environmental variables as above) + docker run -d --name etl \ -e DB_PORT_3306_TCP_ADDR=1.2.3.4 -e DB_PORT_3306_TCP_PORT=3306 \ -e MYSQL_USER=myuser -e MYSQL_PASSWORD=mypassword \ @@ -100,7 +98,7 @@ If you have MySQL running at 1.2.3.4 with username "myuser" and password "mypass docker run -d -name etl -v /path/to/keys/:/keys -p 8002:8002 etl -The folder /path/to/keys/ should contain SSL certificate and private key in `server.crt` +The folder /path/to/keys/ should contain SSL certificate and private key in `server.crt` and `server.key`. ### Setup CI Integration @@ -111,4 +109,4 @@ and `server.key`. 4. Update your local `etl-rest-server` fork i.e. `git pull upstream master`. The CD setup should be in master. 5. Checkout a branch from master e.g. `git checkout -b test-etl` 6. Push that branch i.e. `git push origin ` -7. Access your test build via the following url: [https://ngx.ampath.or.ke/etl-backend/branchname/etl](https://ngx.ampath.or.ke/etl-backend//etl) where `branchname` is the name of your branch. \ No newline at end of file +7. Access your test build via the following url: [https://ngx.ampath.or.ke/etl-backend/branchname/etl](https://ngx.ampath.or.ke/etl-backend//etl) where `branchname` is the name of your branch. diff --git a/app/case-management/case-management-indicator-service.js b/app/case-management/case-management-indicator-service.js index 005588ea3..aca26611a 100644 --- a/app/case-management/case-management-indicator-service.js +++ b/app/case-management/case-management-indicator-service.js @@ -4,11 +4,10 @@ var defs = { getIndicatorDefinitions: getIndicatorDefinitions }; -function getIndicatorDefinitions(){ - - return new Promise((resolve , reject) => { - resolve (indicatorsDefs) +function getIndicatorDefinitions() { + return new Promise((resolve, reject) => { + resolve(indicatorsDefs); }); } -module.exports = defs; \ No newline at end of file +module.exports = defs; diff --git a/app/case-management/case-management.js b/app/case-management/case-management.js index 0696295db..2e5b86ecc 100644 --- a/app/case-management/case-management.js +++ b/app/case-management/case-management.js @@ -1,265 +1,344 @@ -var db = require("../../etl-db"); +var db = require('../../etl-db'); var moment = require('moment'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); var config = require('../../conf/config'); var rp = require('../../request-config'); const caseDataDao = { + getCaseManagementData: (params, callback) => { + let followupDateRange = []; + let rtcDateRange = []; + let sql = ''; + try { + let queryParts = {}; - getCaseManagementData: (params, callback) => { - let followupDateRange = []; - let rtcDateRange = []; - let sql = '' - try { - let queryParts = {}; + var columns = + "t1.identifiers,CONCAT(COALESCE(DATE_FORMAT(t1.encounter_datetime, '%Y-%m-%d'), ''), ' ', COALESCE(t5.name,'')) AS last_follow_up_date,DATE_FORMAT(t1.rtc_date, '%Y-%m-%d') AS rtc_date,extract(year from (from_days(datediff(now(),t1.birthdate)))) as age, TIMESTAMPDIFF(DAY,DATE(t1.rtc_date),curdate()) AS days_since_missed_appointment, " + + "case_manager_name AS case_manager,t1.person_name AS patient_name,t1.gender,t1.vl_1 AS last_vl, DATE_FORMAT(t1.vl_1_date, '%Y-%m-%d') as last_vl_date, TIMESTAMPDIFF(DAY,DATE(t1.encounter_datetime),curdate()) AS days_since_follow_up, t3.uuid as `attribute_uuid`, DATE_FORMAT(t1.med_pickup_rtc_date, '%Y-%m-%d') AS med_pickup_rtc_date, " + + "DATE_FORMAT(t1.enrollment_date, '%Y-%m-%d') AS enrollment_date, TIMESTAMPDIFF(DAY,DATE(t1.enrollment_date),curdate()) AS days_since_enrollment,t5.name as `encounter_type`,t1.uuid as patient_uuid, DATE_FORMAT(next_phone_appointment, '%Y-%m-%d') AS next_phone_appointment, case_manager_user_id, (CASE WHEN TIMESTAMPDIFF(DAY,DATE(t1.rtc_date),curdate()) > 0 THEN 1 ELSE 0 END) as missed_appointment, " + + getDueForVl() + + 'AS patients_due_for_vl '; - var columns = "t1.identifiers,CONCAT(COALESCE(DATE_FORMAT(t1.encounter_datetime, '%Y-%m-%d'), ''), ' ', COALESCE(t5.name,'')) AS last_follow_up_date,DATE_FORMAT(t1.rtc_date, '%Y-%m-%d') AS rtc_date,extract(year from (from_days(datediff(now(),t1.birthdate)))) as age, TIMESTAMPDIFF(DAY,DATE(t1.rtc_date),curdate()) AS days_since_missed_appointment, " + - "case_manager_name AS case_manager,t1.person_name AS patient_name,t1.gender,t1.vl_1 AS last_vl, DATE_FORMAT(t1.vl_1_date, '%Y-%m-%d') as last_vl_date, TIMESTAMPDIFF(DAY,DATE(t1.encounter_datetime),curdate()) AS days_since_follow_up, t3.uuid as `attribute_uuid`, DATE_FORMAT(t1.med_pickup_rtc_date, '%Y-%m-%d') AS med_pickup_rtc_date, " + - "DATE_FORMAT(t1.enrollment_date, '%Y-%m-%d') AS enrollment_date, TIMESTAMPDIFF(DAY,DATE(t1.enrollment_date),curdate()) AS days_since_enrollment,t5.name as `encounter_type`,t1.uuid as patient_uuid, DATE_FORMAT(next_phone_appointment, '%Y-%m-%d') AS next_phone_appointment, case_manager_user_id, (CASE WHEN TIMESTAMPDIFF(DAY,DATE(t1.rtc_date),curdate()) > 0 THEN 1 ELSE 0 END) as missed_appointment, " + getDueForVl() + "AS patients_due_for_vl "; - - let where = " t1.location_uuid = '" + params.locationUuid + "' "; - if ((params.minDefaultPeriod != null || params.minDefaultPeriod != null)) { - rtcDateRange = convertDaysToDate(params.minDefaultPeriod, params.maxDefaultPeriod); - where = where + " and t1.rtc_date between '" + rtcDateRange[1] + "' and '" + rtcDateRange[0] + "' "; - } - if ((params.minFollowupPeriod != null || params.maxFollowupPeriod != null)) { - followupDateRange = convertDaysToDate(params.minFollowupPeriod, params.maxFollowupPeriod); - where = where + "and t1.encounter_datetime between '" + followupDateRange[1] + "' and '" + followupDateRange[0] + "' "; - } - if ((params.rtcStartDate != null || params.rtcEndDate != null)) { - where = where + "and t1.rtc_date between DATE('" + params.rtcStartDate + "') and DATE('" + params.rtcEndDate + "') "; - } - if (params.phoneFollowUpStartDate != null) { - where = where + "and next_phone_appointment = DATE('" + params.phoneFollowUpStartDate + "') " - } - if (params.hasCaseManager == 1) { - where = where + "and case_manager_user_id is not null " - } else if (params.hasCaseManager == 0) { - where = where + "and case_manager_user_id is null " - } - if (params.elevatedVL == 1) { - where = where + "and t1.vl_1 > 1000 " - } else if (params.elevatedVL == 0) { - where = where + "and t1.vl_1 < 1000 " - } - if (params.hasPhoneRTC == 1) { - where = where + "and next_phone_appointment is not null " - } else if (params.hasPhoneRTC == 0) { - where = where + "and next_phone_appointment is null " - } - if (params.isNewlyEnrolled == 1) { - where = where + "and TIMESTAMPDIFF(DAY,DATE(t1.enrollment_date),curdate()) <= 30 " - } else if (params.isNewlyEnrolled == 0) { - where = where + "and TIMESTAMPDIFF(DAY,DATE(t1.enrollment_date),curdate()) > 30 " - } - if (params.dueForVl == 1) { - where = where + "and " + getDueForVl() + " = 1 " - } else if (params.dueForVl == 0) { - where = where + "and " + getDueForVl() + " = 0 " - } - if (params.caseManagerUserId != null) { - where = where + "and case_manager_user_id in (" + params.caseManagerUserId + ")" - } - sql = "select " + columns + "FROM etl.flat_case_manager `t1` LEFT JOIN amrs.relationship `t2` on (t1.person_id = t2.person_a) " + - "LEFT JOIN amrs.person_attribute `t3` on (t1.person_id = t3.person_id AND t3.person_attribute_type_id = 68 AND t1.case_manager_user_id = t3.value) " + - "LEFT JOIN amrs.encounter_type t5 ON (t1.encounter_type = t5.encounter_type_id) "+ - "INNER JOIN amrs.person t4 ON (t1.person_id = t4.person_id AND dead = 0) "+ - "LEFT JOIN etl.flat_hiv_summary_v15b t6 on (t1.person_id = t6.person_id and t6.is_clinical_encounter = 1 AND t6.next_clinical_datetime_hiv IS NULL and t6.transfer_transfer_out_bncd is not null) "+ - "WHERE ( " + where + " and t1.transfer_out is null and transfer_transfer_out_bncd is null ) group by t1.person_id order by t1.vl_1 desc" - queryParts = { - sql: sql, - startIndex: params.startIndex, - limit: params.limit - }; - db.queryServer(queryParts, function (result) { - result.sql = sql; - callback(result); - }); - } catch (error) { - return error; - } - }, - getCaseManagers: (params) => { - return new Promise((resolve, reject) => { - let queryParts = {}; - let sql = "select CONCAT(COALESCE(t6.given_name, ''), ' ', COALESCE(t6.middle_name,''), ' ', " + - "COALESCE(t6.family_name, '')) as person_name, t2.uuid as `user_uuid`, t5.value_reference as `location_uuid`, " + - "count(DISTINCT t1.person_id) as `number_assigned`,t4.provider_id,t2.user_id FROM amrs.users `t2` " + - "INNER JOIN amrs.person `t3` ON (t3.person_id = t2.person_id) " + - "INNER JOIN amrs.provider `t4` ON (t4.person_id = t3.person_id) " + - "INNER JOIN amrs.provider_attribute `t5` ON (t5.provider_id = t4.provider_id and t5.voided = 0) " + - "INNER JOIN amrs.person_name `t6` ON (t6.person_id = t3.person_id) " + - "LEFT JOIN amrs.person_attribute `t1` ON (t2.user_id = t1.value AND person_attribute_type_id = 68 AND t1.voided = 0 ) " + - "WHERE ( t5.attribute_type_id = 1 AND t5.value_reference = '" + params.locationUuid + "') GROUP by t2.uuid; " + let where = " t1.location_uuid = '" + params.locationUuid + "' "; + if (params.minDefaultPeriod != null || params.minDefaultPeriod != null) { + rtcDateRange = convertDaysToDate( + params.minDefaultPeriod, + params.maxDefaultPeriod + ); + where = + where + + " and t1.rtc_date between '" + + rtcDateRange[1] + + "' and '" + + rtcDateRange[0] + + "' "; + } + if ( + params.minFollowupPeriod != null || + params.maxFollowupPeriod != null + ) { + followupDateRange = convertDaysToDate( + params.minFollowupPeriod, + params.maxFollowupPeriod + ); + where = + where + + "and t1.encounter_datetime between '" + + followupDateRange[1] + + "' and '" + + followupDateRange[0] + + "' "; + } + if (params.rtcStartDate != null || params.rtcEndDate != null) { + where = + where + + "and t1.rtc_date between DATE('" + + params.rtcStartDate + + "') and DATE('" + + params.rtcEndDate + + "') "; + } + if (params.phoneFollowUpStartDate != null) { + where = + where + + "and next_phone_appointment = DATE('" + + params.phoneFollowUpStartDate + + "') "; + } + if (params.hasCaseManager == 1) { + where = where + 'and case_manager_user_id is not null '; + } else if (params.hasCaseManager == 0) { + where = where + 'and case_manager_user_id is null '; + } + if (params.elevatedVL == 1) { + where = where + 'and t1.vl_1 > 1000 '; + } else if (params.elevatedVL == 0) { + where = where + 'and t1.vl_1 < 1000 '; + } + if (params.hasPhoneRTC == 1) { + where = where + 'and next_phone_appointment is not null '; + } else if (params.hasPhoneRTC == 0) { + where = where + 'and next_phone_appointment is null '; + } + if (params.isNewlyEnrolled == 1) { + where = + where + + 'and TIMESTAMPDIFF(DAY,DATE(t1.enrollment_date),curdate()) <= 30 '; + } else if (params.isNewlyEnrolled == 0) { + where = + where + + 'and TIMESTAMPDIFF(DAY,DATE(t1.enrollment_date),curdate()) > 30 '; + } + if (params.dueForVl == 1) { + where = where + 'and ' + getDueForVl() + ' = 1 '; + } else if (params.dueForVl == 0) { + where = where + 'and ' + getDueForVl() + ' = 0 '; + } + if (params.caseManagerUserId != null) { + where = + where + + 'and case_manager_user_id in (' + + params.caseManagerUserId + + ')'; + } + sql = + 'select ' + + columns + + 'FROM etl.flat_case_manager `t1` LEFT JOIN amrs.relationship `t2` on (t1.person_id = t2.person_a) ' + + 'LEFT JOIN amrs.person_attribute `t3` on (t1.person_id = t3.person_id AND t3.person_attribute_type_id = 68 AND t1.case_manager_user_id = t3.value) ' + + 'LEFT JOIN amrs.encounter_type t5 ON (t1.encounter_type = t5.encounter_type_id) ' + + 'INNER JOIN amrs.person t4 ON (t1.person_id = t4.person_id AND dead = 0) ' + + 'LEFT JOIN etl.flat_hiv_summary_v15b t6 on (t1.person_id = t6.person_id and t6.is_clinical_encounter = 1 AND t6.next_clinical_datetime_hiv IS NULL and t6.transfer_transfer_out_bncd is not null) ' + + 'WHERE ( ' + + where + + ' and t1.transfer_out is null and transfer_transfer_out_bncd is null ) group by t1.person_id order by t1.vl_1 desc'; + queryParts = { + sql: sql, + startIndex: params.startIndex, + limit: params.limit + }; + db.queryServer(queryParts, function (result) { + result.sql = sql; + callback(result); + }); + } catch (error) { + return error; + } + }, + getCaseManagers: (params) => { + return new Promise((resolve, reject) => { + let queryParts = {}; + let sql = + "select CONCAT(COALESCE(t6.given_name, ''), ' ', COALESCE(t6.middle_name,''), ' ', " + + "COALESCE(t6.family_name, '')) as person_name, t2.uuid as `user_uuid`, t5.value_reference as `location_uuid`, " + + 'count(DISTINCT t1.person_id) as `number_assigned`,t4.provider_id,t2.user_id FROM amrs.users `t2` ' + + 'INNER JOIN amrs.person `t3` ON (t3.person_id = t2.person_id) ' + + 'INNER JOIN amrs.provider `t4` ON (t4.person_id = t3.person_id) ' + + 'INNER JOIN amrs.provider_attribute `t5` ON (t5.provider_id = t4.provider_id and t5.voided = 0) ' + + 'INNER JOIN amrs.person_name `t6` ON (t6.person_id = t3.person_id) ' + + 'LEFT JOIN amrs.person_attribute `t1` ON (t2.user_id = t1.value AND person_attribute_type_id = 68 AND t1.voided = 0 ) ' + + "WHERE ( t5.attribute_type_id = 1 AND t5.value_reference = '" + + params.locationUuid + + "') GROUP by t2.uuid; "; - queryParts = { - sql: sql - }; - return db.queryServer(queryParts, function (result) { - result.sql = sql; - resolve(result); - }); - }) - }, - assignPatientsToCaseManagers: async (payload) => { - try { - let payloadData = getPayloadData(payload); - let erroredPatients = [] - while (payloadData.length > 0) { - let data = payloadData.splice(0, 10); - let promisesArray = []; + queryParts = { + sql: sql + }; + return db.queryServer(queryParts, function (result) { + result.sql = sql; + resolve(result); + }); + }); + }, + assignPatientsToCaseManagers: async (payload) => { + try { + let payloadData = getPayloadData(payload); + let erroredPatients = []; + while (payloadData.length > 0) { + let data = payloadData.splice(0, 10); + let promisesArray = []; - data.forEach(d => { - const obj = { - user_id: d.user_id, - user_name: d.user_name, - patient_uuid: d.patient_uuid, - user_uuid: d.user_uuid - } - promisesArray.push(postPersonAttributes(obj)) - }) - await Promise.allSettled(promisesArray). - then((results) => results.forEach((result) => { - if (result.isFulfilled()) { - updateCaseManager(result.value(), true); - } else if (result.isRejected()) { - erroredPatients.push(result.reason()); - } - })); + data.forEach((d) => { + const obj = { + user_id: d.user_id, + user_name: d.user_name, + patient_uuid: d.patient_uuid, + user_uuid: d.user_uuid + }; + promisesArray.push(postPersonAttributes(obj)); + }); + await Promise.allSettled(promisesArray).then((results) => + results.forEach((result) => { + if (result.isFulfilled()) { + updateCaseManager(result.value(), true); + } else if (result.isRejected()) { + erroredPatients.push(result.reason()); } - return erroredPatients; - } - catch (error) { - return error; - } - }, - unAssignPatients: async (payloadData) => { - try { - let erroredPatients = [] - while (payloadData.length > 0) { - let data = payloadData.splice(0, 10); - let promisesArray = []; + }) + ); + } + return erroredPatients; + } catch (error) { + return error; + } + }, + unAssignPatients: async (payloadData) => { + try { + let erroredPatients = []; + while (payloadData.length > 0) { + let data = payloadData.splice(0, 10); + let promisesArray = []; - data.forEach(d => { - promisesArray.push(voidPersonAttributes(d)) - }) - await Promise.allSettled(promisesArray). - then((results) => results.forEach((result) => { - if (result.isFulfilled()) { - updateCaseManager(result.value(), false); - } else if (result.isRejected()) { - erroredPatients.push(result.reason()); - } - })); + data.forEach((d) => { + promisesArray.push(voidPersonAttributes(d)); + }); + await Promise.allSettled(promisesArray).then((results) => + results.forEach((result) => { + if (result.isFulfilled()) { + updateCaseManager(result.value(), false); + } else if (result.isRejected()) { + erroredPatients.push(result.reason()); } - return erroredPatients; - } - catch (error) { - return error; - } + }) + ); + } + return erroredPatients; + } catch (error) { + return error; } -} + } +}; function getPayloadData(payload) { - let payloadData = []; - let patients = payload.patients - let managers = payload.caseManagers + let payloadData = []; + let patients = payload.patients; + let managers = payload.caseManagers; - managers.forEach(m => { - const patientsToAssign = patients.splice(0, m.count); - const uuid = m.user_uuid; - const id = m.user_id; - const name = m.user_name; - patientsToAssign.forEach(p => { - const patient = { - user_uuid: uuid, - user_id: id, - user_name: name, - patient_uuid: p.patient_uuid - } - payloadData.push(patient) - }) - }) - return payloadData; + managers.forEach((m) => { + const patientsToAssign = patients.splice(0, m.count); + const uuid = m.user_uuid; + const id = m.user_id; + const name = m.user_name; + patientsToAssign.forEach((p) => { + const patient = { + user_uuid: uuid, + user_id: id, + user_name: name, + patient_uuid: p.patient_uuid + }; + payloadData.push(patient); + }); + }); + return payloadData; } function getRestResource(path) { - var protocol = config.openmrs.https ? 'https' : 'http'; - var link = protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + path; - return link; + var protocol = config.openmrs.https ? 'https' : 'http'; + var link = + protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + path; + return link; } function postPersonAttributes(params) { - var uri = getRestResource('/' + config.openmrs.applicationName + '/ws/rest/v1/person/' + params.patient_uuid); - let payload = { - "attributes": [ - { - "attributeType": "9a6e12b5-98fe-467a-9541-dab11ad87e45", - "value": params.user_uuid - } - ] - } - return new Promise(function (resolve, reject) { - rp.postRequestPromise(payload, uri) - .then(function (r) { - resolve(params); - }) - .catch(function (error) { - const response = { - patieuntUuid: params.patient_uuid - } - reject(response); - }) - }); + var uri = getRestResource( + '/' + + config.openmrs.applicationName + + '/ws/rest/v1/person/' + + params.patient_uuid + ); + let payload = { + attributes: [ + { + attributeType: '9a6e12b5-98fe-467a-9541-dab11ad87e45', + value: params.user_uuid + } + ] + }; + return new Promise(function (resolve, reject) { + rp.postRequestPromise(payload, uri) + .then(function (r) { + resolve(params); + }) + .catch(function (error) { + const response = { + patieuntUuid: params.patient_uuid + }; + reject(response); + }); + }); } function voidPersonAttributes(params) { - var uri = getRestResource('/' + config.openmrs.applicationName + '/ws/rest/v1/person/' + params.patient_uuid + '/attribute/' + params.attribute_uuid); - return new Promise(function (resolve, reject) { - rp.deleteRequestPromise(uri) - .then(function (r) { - resolve(params); - }) - .catch(function (error) { - const response = { - patieuntUuid: params.patient_uuid - } - reject(response); - }) - }); + var uri = getRestResource( + '/' + + config.openmrs.applicationName + + '/ws/rest/v1/person/' + + params.patient_uuid + + '/attribute/' + + params.attribute_uuid + ); + return new Promise(function (resolve, reject) { + rp.deleteRequestPromise(uri) + .then(function (r) { + resolve(params); + }) + .catch(function (error) { + const response = { + patieuntUuid: params.patient_uuid + }; + reject(response); + }); + }); } function updateCaseManager(params, update) { - return new Promise((resolve, reject) => { - let queryParts = {}; - let sql = '' - if (update == true) { - sql = "update etl.flat_case_manager set case_manager_user_id = '" + params.user_id + "', case_manager_user_name='" + params.user_name + "', case_manager_name='" + params.user_name + "' where uuid = '" + params.patient_uuid + "' ;"; - } else { - sql = "update etl.flat_case_manager set case_manager_user_id = NULL, case_manager_user_name = NULL, case_manager_name = NULL where uuid = '" + params.patient_uuid + "' ;" - } - queryParts = { - sql: sql - }; - db.queryServer(queryParts, function (result) { - result.sql = sql; - resolve(result); - }); - }) + return new Promise((resolve, reject) => { + let queryParts = {}; + let sql = ''; + if (update == true) { + sql = + "update etl.flat_case_manager set case_manager_user_id = '" + + params.user_id + + "', case_manager_user_name='" + + params.user_name + + "', case_manager_name='" + + params.user_name + + "' where uuid = '" + + params.patient_uuid + + "' ;"; + } else { + sql = + "update etl.flat_case_manager set case_manager_user_id = NULL, case_manager_user_name = NULL, case_manager_name = NULL where uuid = '" + + params.patient_uuid + + "' ;"; + } + queryParts = { + sql: sql + }; + db.queryServer(queryParts, function (result) { + result.sql = sql; + resolve(result); + }); + }); } function getDueForVl() { - return "(case when (timestampdiff(month,t1.vl_1_date, curdate()) >= 3) and t1.vl_1 > 999 and t1.arv_start_date < t1.vl_1_date then 1 " + - "when (timestampdiff(month,t1.arv_start_date,curdate()) between 6 and 12) and (t1.vl_1_date is null or t1.vl_1_date < t1.arv_start_date ) then 1 " + - "when (timestampdiff(month,t1.arv_start_date,curdate()) > 12) and (t1.vl_1_date is null or timestampdiff(month,t1.vl_1_date,curdate()) > 12) then 1 " + - "WHEN (t1.is_pregnant OR (t2.relationship = 2 AND TIMESTAMPDIFF(MONTH, t2.date_created,curdate()) BETWEEN 0 AND 24 )) AND t1.vl_1 > 400 AND (TIMESTAMPDIFF(MONTH, t1.vl_1_date,curdate()) >= 3) THEN 1 " + - "WHEN (t1.is_pregnant OR (t2.relationship = 2 AND TIMESTAMPDIFF(MONTH, t2.date_created,curdate()) BETWEEN 0 AND 24 )) AND t1.vl_1 <= 400 AND (TIMESTAMPDIFF(MONTH, t1.vl_1_date,curdate()) >= 6) THEN 1 " + - "WHEN t1.arv_first_regimen_start_date is not null and t1.arv_start_date is not null and t1.arv_first_regimen_start_date < t1.arv_start_date AND TIMESTAMPDIFF(MONTH,t1.arv_start_date,curdate()) >= 3 AND t1.vl_1_date is null then 1 " + - "WHEN t1.arv_first_regimen_start_date is not null and t1.arv_start_date is not null and t1.arv_first_regimen_start_date < t1.arv_start_date AND TIMESTAMPDIFF(MONTH,t1.arv_start_date,curdate()) >= 3 AND TIMESTAMPDIFF(MONTH,t1.vl_1_date,t1.arv_start_date)>=1 then 1 else 0 end) " + return ( + '(case when (timestampdiff(month,t1.vl_1_date, curdate()) >= 3) and t1.vl_1 > 999 and t1.arv_start_date < t1.vl_1_date then 1 ' + + 'when (timestampdiff(month,t1.arv_start_date,curdate()) between 6 and 12) and (t1.vl_1_date is null or t1.vl_1_date < t1.arv_start_date ) then 1 ' + + 'when (timestampdiff(month,t1.arv_start_date,curdate()) > 12) and (t1.vl_1_date is null or timestampdiff(month,t1.vl_1_date,curdate()) > 12) then 1 ' + + 'WHEN (t1.is_pregnant OR (t2.relationship = 2 AND TIMESTAMPDIFF(MONTH, t2.date_created,curdate()) BETWEEN 0 AND 24 )) AND t1.vl_1 > 400 AND (TIMESTAMPDIFF(MONTH, t1.vl_1_date,curdate()) >= 3) THEN 1 ' + + 'WHEN (t1.is_pregnant OR (t2.relationship = 2 AND TIMESTAMPDIFF(MONTH, t2.date_created,curdate()) BETWEEN 0 AND 24 )) AND t1.vl_1 <= 400 AND (TIMESTAMPDIFF(MONTH, t1.vl_1_date,curdate()) >= 6) THEN 1 ' + + 'WHEN t1.arv_first_regimen_start_date is not null and t1.arv_start_date is not null and t1.arv_first_regimen_start_date < t1.arv_start_date AND TIMESTAMPDIFF(MONTH,t1.arv_start_date,curdate()) >= 3 AND t1.vl_1_date is null then 1 ' + + 'WHEN t1.arv_first_regimen_start_date is not null and t1.arv_start_date is not null and t1.arv_first_regimen_start_date < t1.arv_start_date AND TIMESTAMPDIFF(MONTH,t1.arv_start_date,curdate()) >= 3 AND TIMESTAMPDIFF(MONTH,t1.vl_1_date,t1.arv_start_date)>=1 then 1 else 0 end) ' + ); } function convertDaysToDate(minDays, maxDays) { - return [moment().subtract(minDays, "days").format("YYYY-MM-DD"), moment().subtract(maxDays, "days").format("YYYY-MM-DD")]; + return [ + moment().subtract(minDays, 'days').format('YYYY-MM-DD'), + moment().subtract(maxDays, 'days').format('YYYY-MM-DD') + ]; } -module.exports = caseDataDao; \ No newline at end of file +module.exports = caseDataDao; diff --git a/app/config/config.service.js b/app/config/config.service.js index fd9e56097..4dd14db36 100755 --- a/app/config/config.service.js +++ b/app/config/config.service.js @@ -1,9 +1,8 @@ const config = require('../../conf/config'); const ConfigService = { - getConfig: () => { - return config; - } -} + getConfig: () => { + return config; + } +}; Object.freeze(ConfigService); export default ConfigService; - \ No newline at end of file diff --git a/app/database-access/mysql-connection.service.js b/app/database-access/mysql-connection.service.js index 4d4735d3d..401b3d777 100755 --- a/app/database-access/mysql-connection.service.js +++ b/app/database-access/mysql-connection.service.js @@ -2,15 +2,15 @@ import ConfigService from '../config/config.service'; const mysql = require('promise-mysql'); let connectionPool = undefined; let MysqlConnectionService = { - getPool: () => { - if(connectionPool !== undefined){ - return connectionPool; - } - console.log('calling connection pool'); - connectionPool = mysql.createPool(ConfigService.getConfig().mysql); - return connectionPool; + getPool: () => { + if (connectionPool !== undefined) { + return connectionPool; } -} + console.log('calling connection pool'); + connectionPool = mysql.createPool(ConfigService.getConfig().mysql); + return connectionPool; + } +}; Object.freeze(MysqlConnectionService); -export default MysqlConnectionService; \ No newline at end of file +export default MysqlConnectionService; diff --git a/app/database-access/query.service.js b/app/database-access/query.service.js index 47fdca32a..048f427c7 100755 --- a/app/database-access/query.service.js +++ b/app/database-access/query.service.js @@ -1,9 +1,7 @@ import MysqlConnectionService from './mysql-connection.service'; export default class QueryService { - constructor() { - - } - executeQuery(sqlString, params) { - return MysqlConnectionService.getPool().query(sqlString, params); - } -} \ No newline at end of file + constructor() {} + executeQuery(sqlString, params) { + return MysqlConnectionService.getPool().query(sqlString, params); + } +} diff --git a/app/lab-integration/adapters/cd4-adapter.js b/app/lab-integration/adapters/cd4-adapter.js index 1fd0454bd..176f2cd15 100644 --- a/app/lab-integration/adapters/cd4-adapter.js +++ b/app/lab-integration/adapters/cd4-adapter.js @@ -1,24 +1,35 @@ import LabAdapter from './lab-adapter'; export class CD4Adapter extends LabAdapter { - constructor(labResults, patientUuid) { super(labResults); this.patientUuid = patientUuid; } getLabResults() { - return Promise.all(this.results.map((result) => this.mapResult(this.transformLabResult(result)))); + return Promise.all( + this.results.map((result) => + this.mapResult(this.transformLabResult(result)) + ) + ); } mapResult(result) { - const cd4PanelHasValidData = this.payloadFormatter.cd4PanelHasValidData(result); + const cd4PanelHasValidData = this.payloadFormatter.cd4PanelHasValidData( + result + ); const cd4PanelHasErrors = this.payloadFormatter.cd4PanelHasErrors(result); if (cd4PanelHasValidData) { - return this.payloadFormatter.convertCD4PayloadTORestConsumableObs(result, this.patientUuid);; + return this.payloadFormatter.convertCD4PayloadTORestConsumableObs( + result, + this.patientUuid + ); } if (cd4PanelHasErrors) { - return this.payloadFormatter.convertCD4ExceptionTORestConsumableObs(result, this.patientUuid); + return this.payloadFormatter.convertCD4ExceptionTORestConsumableObs( + result, + this.patientUuid + ); } } -} \ No newline at end of file +} diff --git a/app/lab-integration/adapters/dnapcr-adpater.js b/app/lab-integration/adapters/dnapcr-adpater.js index d877d2206..a43c3edbb 100644 --- a/app/lab-integration/adapters/dnapcr-adpater.js +++ b/app/lab-integration/adapters/dnapcr-adpater.js @@ -1,17 +1,23 @@ import LabAdapter from './lab-adapter'; export class DNAPCRAdapter extends LabAdapter { - - constructor (labResults, patientUuid) { + constructor(labResults, patientUuid) { super(labResults); this.patientUuid = patientUuid; } - - getLabResults () { - return Promise.all(this.results.map((result) => this.mapResult(this.transformLabResult(result)))); + + getLabResults() { + return Promise.all( + this.results.map((result) => + this.mapResult(this.transformLabResult(result)) + ) + ); } - - mapResult (result) { - return this.payloadFormatter.convertDNAPCRPayloadTORestConsumableObs(result, this.patientUuid); + + mapResult(result) { + return this.payloadFormatter.convertDNAPCRPayloadTORestConsumableObs( + result, + this.patientUuid + ); } -} \ No newline at end of file +} diff --git a/app/lab-integration/adapters/lab-adapter.js b/app/lab-integration/adapters/lab-adapter.js index 39202e9c5..45900bf32 100644 --- a/app/lab-integration/adapters/lab-adapter.js +++ b/app/lab-integration/adapters/lab-adapter.js @@ -4,8 +4,7 @@ import * as _ from 'lodash'; const eidRestFormatter = require('../../../eid-rest-formatter'); export default class LabAdapter { - - constructor (labResults) { + constructor(labResults) { this.payloadFormatter = eidRestFormatter; if (Array.isArray(labResults)) { this.results = labResults || []; @@ -13,18 +12,14 @@ export default class LabAdapter { throw new LabAdapterError('Please provide lab results as an array'); } } - + transformLabResult(result) { return _.mapKeys(result, (v, k) => { - if (k === 'order_number') - k = 'OrderNo'; - if (k === 'AMRs_location') - k = 'AMRSLocation'; - if (k === 'date_collected') - k = 'DateCollected'; - if (k === 'result') - k = 'FinalResult'; + if (k === 'order_number') k = 'OrderNo'; + if (k === 'AMRs_location') k = 'AMRSLocation'; + if (k === 'date_collected') k = 'DateCollected'; + if (k === 'result') k = 'FinalResult'; return k; }); } -} \ No newline at end of file +} diff --git a/app/lab-integration/adapters/lab-result.js b/app/lab-integration/adapters/lab-result.js index 83e536f3c..a00470657 100644 --- a/app/lab-integration/adapters/lab-result.js +++ b/app/lab-integration/adapters/lab-result.js @@ -3,12 +3,12 @@ import * as _ from 'lodash'; var eidRestFormatter = require('../../../eid-rest-formatter'); export default class LabResult { - constructor (data) { - if(!data) { + constructor(data) { + if (!data) { throw new LabResultFormatError('No Lab result data provided'); } - - if(_.isNil(data.conceptUuid) || _.isNil(data.result)) { + + if (_.isNil(data.conceptUuid) || _.isNil(data.result)) { throw new LabResultFormatError('Malformed Result given'); } this.concept = data.conceptUuid; @@ -17,4 +17,4 @@ export default class LabResult { this.comments = data.interpretation; this.rawResult = data; } -} \ No newline at end of file +} diff --git a/app/lab-integration/adapters/vl-adapter.js b/app/lab-integration/adapters/vl-adapter.js index 377179674..f0136e20c 100644 --- a/app/lab-integration/adapters/vl-adapter.js +++ b/app/lab-integration/adapters/vl-adapter.js @@ -1,30 +1,36 @@ import LabAdapter from './lab-adapter'; export class VLAdapter extends LabAdapter { - constructor(labResults, patientUuid) { super(labResults); this.patientUuid = patientUuid; } getLabResults() { - return Promise.all(this.results.map((result) => - this.mapResult(this.transformLabResult(result) - ))); + return Promise.all( + this.results.map((result) => + this.mapResult(this.transformLabResult(result)) + ) + ); } mapResult(result) { const valid = this.payloadFormatter.checkStatusOfViralLoad(result); if (valid === 1) { - return this.payloadFormatter.convertViralLoadPayloadToRestConsumableObs(result, this.patientUuid); - } - else if (valid === 0) { - - return this.payloadFormatter.convertViralLoadWithLessThanToRestConsumableObs(result, this.patientUuid); - - } - else if (valid === 2) { - return this.payloadFormatter.convertViralLoadExceptionToRestConsumableObs(result, this.patientUuid); + return this.payloadFormatter.convertViralLoadPayloadToRestConsumableObs( + result, + this.patientUuid + ); + } else if (valid === 0) { + return this.payloadFormatter.convertViralLoadWithLessThanToRestConsumableObs( + result, + this.patientUuid + ); + } else if (valid === 2) { + return this.payloadFormatter.convertViralLoadExceptionToRestConsumableObs( + result, + this.patientUuid + ); } } -} \ No newline at end of file +} diff --git a/app/lab-integration/eid-rest-formatter.js b/app/lab-integration/eid-rest-formatter.js index 8b6a7e825..7cf62a3ff 100644 --- a/app/lab-integration/eid-rest-formatter.js +++ b/app/lab-integration/eid-rest-formatter.js @@ -4,7 +4,7 @@ var Promise = require('bluebird'); var config = require('./conf/config'); var rp = require('./request-config'); var _ = require('underscore'); -module.exports = function () { +module.exports = (function () { function getRestResource(path) { var link = config.openmrs.host + ':' + config.openmrs.port + path; if (config.openmrs.https === true) { @@ -23,19 +23,19 @@ module.exports = function () { var hasLessThanSymbol = / 0) { _.each(AVGCD3percentLymph, function (groupMember) { body.groupMembers.push(groupMember); }); } - var AVGCD3AbsCnt = cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, "AVGCD3AbsCnt", "a898fcd2-1350-11df-a1f1-0026b9348838", date); + var AVGCD3AbsCnt = cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + 'AVGCD3AbsCnt', + 'a898fcd2-1350-11df-a1f1-0026b9348838', + date + ); if (AVGCD3AbsCnt.length > 0) { _.each(AVGCD3AbsCnt, function (groupMember) { body.groupMembers.push(groupMember); }); } - var AVGCD3CD4percentLymph = cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, "AVGCD3CD4percentLymph", "a8970a26-1350-11df-a1f1-0026b9348838", date); + var AVGCD3CD4percentLymph = cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + 'AVGCD3CD4percentLymph', + 'a8970a26-1350-11df-a1f1-0026b9348838', + date + ); if (AVGCD3CD4percentLymph.length > 0) { _.each(AVGCD3CD4percentLymph, function (groupMember) { body.groupMembers.push(groupMember); }); } - var AVGCD3CD4AbsCnt = cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, "AVGCD3CD4AbsCnt", "a8a8bb18-1350-11df-a1f1-0026b9348838", date); + var AVGCD3CD4AbsCnt = cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + 'AVGCD3CD4AbsCnt', + 'a8a8bb18-1350-11df-a1f1-0026b9348838', + date + ); if (AVGCD3CD4AbsCnt.length > 0) { _.each(AVGCD3CD4AbsCnt, function (groupMember) { body.groupMembers.push(groupMember); }); } - var CD45AbsCnt = cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, "CD45AbsCnt", "a89c4914-1350-11df-a1f1-0026b9348838", date); + var CD45AbsCnt = cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + 'CD45AbsCnt', + 'a89c4914-1350-11df-a1f1-0026b9348838', + date + ); if (CD45AbsCnt.length > 0) { _.each(CD45AbsCnt, function (groupMember) { body.groupMembers.push(groupMember); }); } - + if (CD4payload['OrderNo'] && stringNotEmpty(CD4payload['OrderNo'])) { return attachOrderUuid(body, CD4payload['OrderNo']); } - + return new Promise(function (resolve, reject) { resolve(body); }); - } - - function cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, typeOfTest, labTestConcept, date) { + + function cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + typeOfTest, + labTestConcept, + date + ) { var groupMembers = []; var labExceptions = getLabExceptions(); if (typeOfTest in CD4payload) { if (CD4payload[typeOfTest].toUpperCase() in labExceptions) { - var codedConceptValue = labExceptions[CD4payload[typeOfTest].toUpperCase()]; - var codedPayload = generateCodedPayload(patientUuId, labTestConcept, codedConceptValue, date); + var codedConceptValue = + labExceptions[CD4payload[typeOfTest].toUpperCase()]; + var codedPayload = generateCodedPayload( + patientUuId, + labTestConcept, + codedConceptValue, + date + ); _.each(codedPayload.groupMembers, function (groupMember) { groupMembers.push(groupMember); }); - } - else { + } else { var value = CD4payload[typeOfTest]; - var nonCodedPayload = generateNonCodedPayload(patientUuId, labTestConcept, value, date); + var nonCodedPayload = generateNonCodedPayload( + patientUuId, + labTestConcept, + value, + date + ); _.each(nonCodedPayload.groupMembers, function (groupMember) { groupMembers.push(groupMember); }); @@ -398,34 +483,36 @@ module.exports = function () { } return groupMembers; } - + function convertDNAPCRPayloadTORestConsumableObs(DNAPCRPayload, patientUuId) { var body = { - concept: "a898fe80-1350-11df-a1f1-0026b9348838", + concept: 'a898fe80-1350-11df-a1f1-0026b9348838', person: patientUuId }; var date = moment(DNAPCRPayload.DateCollected).format(); body.obsDatetime = date; console.error('DNA PCR DNAPCRPayload.FinalResult is null'); - if (DNAPCRPayload.FinalResult !== null && - DNAPCRPayload.FinalResult.toUpperCase() == "NEGATIVE") { - body.value = "a896d2cc-1350-11df-a1f1-0026b9348838"; - } - else if (DNAPCRPayload.FinalResult !== null && - DNAPCRPayload.FinalResult.toUpperCase() == "POSITIVE") { - body.value = "a896f3a6-1350-11df-a1f1-0026b9348838"; - } - + if ( + DNAPCRPayload.FinalResult !== null && + DNAPCRPayload.FinalResult.toUpperCase() == 'NEGATIVE' + ) { + body.value = 'a896d2cc-1350-11df-a1f1-0026b9348838'; + } else if ( + DNAPCRPayload.FinalResult !== null && + DNAPCRPayload.FinalResult.toUpperCase() == 'POSITIVE' + ) { + body.value = 'a896f3a6-1350-11df-a1f1-0026b9348838'; + } + if (DNAPCRPayload['OrderNo'] && stringNotEmpty(DNAPCRPayload['OrderNo'])) { return attachOrderUuid(body, DNAPCRPayload['OrderNo']); } - + return new Promise(function (resolve, reject) { resolve(body); }); - } - + function attachOrderUuid(obsPayload, orderNo) { return new Promise(function (resolve, reject) { getOrderByOrderNumber(orderNo) @@ -439,65 +526,69 @@ module.exports = function () { }); }); } - + function stringNotEmpty(val) { if (val && typeof val === 'string' && val.trim() !== '') { return true; } return false; } - + function getLabExceptions() { return { - "POOR SAMPLE QUALITY": "a89c3f1e-1350-11df-a1f1-0026b9348838", - "NOT DONE": "a899ea48-1350-11df-a1f1-0026b9348838", - "INDETERMINATE": "a89a7ae4-1350-11df-a1f1-0026b9348838", - "BELOW DETECTABLE LIMIT": "a89c3f1e-1350-11df-a1f1-0026b9348838", - "UNABLE TO COLLECT SAMPLE": "a8afcec6-1350-11df-a1f1-0026b9348838", - "SPECIMEN NOT RECEIVED": "0271c15e-4f7f-4a18-9b45-2d7e5b6f7057", - "ORDERED FOR WRONG PATIENT": "3366412a-e279-4428-a671-37221804c6e6", - "COLLECT NEW SAMPLE": "a89c3f1e-1350-11df-a1f1-0026b9348838" - } + 'POOR SAMPLE QUALITY': 'a89c3f1e-1350-11df-a1f1-0026b9348838', + 'NOT DONE': 'a899ea48-1350-11df-a1f1-0026b9348838', + INDETERMINATE: 'a89a7ae4-1350-11df-a1f1-0026b9348838', + 'BELOW DETECTABLE LIMIT': 'a89c3f1e-1350-11df-a1f1-0026b9348838', + 'UNABLE TO COLLECT SAMPLE': 'a8afcec6-1350-11df-a1f1-0026b9348838', + 'SPECIMEN NOT RECEIVED': '0271c15e-4f7f-4a18-9b45-2d7e5b6f7057', + 'ORDERED FOR WRONG PATIENT': '3366412a-e279-4428-a671-37221804c6e6', + 'COLLECT NEW SAMPLE': 'a89c3f1e-1350-11df-a1f1-0026b9348838' + }; } - function generateCodedPayload(patientUuId, labTestConcept, codedConceptValue, date) { + function generateCodedPayload( + patientUuId, + labTestConcept, + codedConceptValue, + date + ) { var payload = { - concept: "457c741d-8f71-4829-b59d-594e0a618892", + concept: '457c741d-8f71-4829-b59d-594e0a618892', groupMembers: [ { - concept: "f67ff075-f91e-4b71-897a-9ded87b34984", + concept: 'f67ff075-f91e-4b71-897a-9ded87b34984', person: patientUuId, value: labTestConcept, obsDatetime: date }, { - concept: "5026a3ee-0612-48bf-b9a3-a2944ddc3e04", + concept: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04', person: patientUuId, value: codedConceptValue, obsDatetime: date } ] - } + }; return payload; } function generateNonCodedPayload(patientUuId, labTestConcept, value, date) { var payload = { - concept: "457c741d-8f71-4829-b59d-594e0a618892", + concept: '457c741d-8f71-4829-b59d-594e0a618892', groupMembers: [ { - concept: "f67ff075-f91e-4b71-897a-9ded87b34984", + concept: 'f67ff075-f91e-4b71-897a-9ded87b34984', person: patientUuId, value: labTestConcept, obsDatetime: date }, { - concept: "a8a06fc6-1350-11df-a1f1-0026b9348838", + concept: 'a8a06fc6-1350-11df-a1f1-0026b9348838', person: patientUuId, value: value, obsDatetime: date } - ] - } + }; return payload; } function generateCD4PanelSingleObject(patientUuId, conceptUuId, value, date) { @@ -506,14 +597,16 @@ module.exports = function () { person: patientUuId, value: value, obsDatetime: date - } + }; return payload; } function getOrderByOrderNumber(orderNo) { - var uri = getRestResource('/'+ config.openmrs.applicationName + '/ws/rest/v1/order/' + orderNo); + var uri = getRestResource( + '/' + config.openmrs.applicationName + '/ws/rest/v1/order/' + orderNo + ); var queryString = { v: 'full' - } + }; return new Promise(function (resolve, reject) { rp.getRequestPromise(queryString, uri) .then(function (response) { @@ -521,7 +614,7 @@ module.exports = function () { }) .catch(function (error) { reject(error); - }) + }); }); } return { @@ -544,5 +637,5 @@ module.exports = function () { cd4PanelHasErrors: cd4PanelHasErrors, generateCd4Exceptions: generateCd4Exceptions, generateCd4ValidData: generateCd4ValidData - } -}(); + }; +})(); diff --git a/app/lab-integration/errors/adapter-error.js b/app/lab-integration/errors/adapter-error.js index b4ec85b8e..af113ee6c 100644 --- a/app/lab-integration/errors/adapter-error.js +++ b/app/lab-integration/errors/adapter-error.js @@ -2,6 +2,6 @@ export default class LabAdapterError extends Error { constructor(message) { super(); this.message = message; - this.name = "LabAdapterError"; + this.name = 'LabAdapterError'; } -} \ No newline at end of file +} diff --git a/app/lab-integration/errors/lab-result-error.js b/app/lab-integration/errors/lab-result-error.js index b66f159e2..a8db7da4c 100644 --- a/app/lab-integration/errors/lab-result-error.js +++ b/app/lab-integration/errors/lab-result-error.js @@ -2,6 +2,6 @@ export default class LabResultFormatError extends Error { constructor(message) { super(); this.message = message; - this.name = "LabResultFormatError"; + this.name = 'LabResultFormatError'; } -} \ No newline at end of file +} diff --git a/app/lab-integration/lab-sync-service.js b/app/lab-integration/lab-sync-service.js index 73eeabc60..5c9d844f2 100644 --- a/app/lab-integration/lab-sync-service.js +++ b/app/lab-integration/lab-sync-service.js @@ -1,6 +1,6 @@ const obsService = require('../../service/openmrs-rest/obs.service'); const async = require('async'); -import * as _ from 'lodash'; +import * as _ from 'lodash'; const config = require('../../conf/config'); const moment = require('moment'); const Boom = require('boom'); @@ -19,78 +19,92 @@ export class LabSyncService { Object.keys(config.hivLabSystem).forEach((labLocation) => { tasks.push((cb) => { // delay alupe for a few ms - cb(null, this.syncLabsByPatientUuid(patientUuid, labLocation, labLocation === 'alupe' ? 50 : 0).then((result)=>{ - return result; - })); + cb( + null, + this.syncLabsByPatientUuid( + patientUuid, + labLocation, + labLocation === 'alupe' ? 50 : 0 + ).then((result) => { + return result; + }) + ); }); }); async.parallel(async.reflectAll(tasks), (err, results) => { - // currently we have duplicate data in db. Try to remove here - Promise.all(results.map((result) => result.value)).then((lab_data) => { - const _lab_data = _.map(lab_data, (lab) => { - lab.updatedObs = _.uniqBy(lab.updatedObs, (ob) => { - return ob.concept.uuid + Promise.all(results.map((result) => result.value)) + .then((lab_data) => { + const _lab_data = _.map(lab_data, (lab) => { + lab.updatedObs = _.uniqBy(lab.updatedObs, (ob) => { + return ob.concept.uuid; + }); + return lab; }); - return lab; + reply(_lab_data); + }) + .catch((err) => { + console.log('sync service error', err); + reply(Boom.notFound('Sorry, sync service temporarily unavailable.')); }); - reply(_lab_data); - }).catch((err) => { - console.log('sync service error', err); - reply(Boom.notFound('Sorry, sync service temporarily unavailable.')); - }); - }); } - syncLabsByPatientUuid(patientUuid, labLocation, delay) { //obsService.getPatientIdentifiers(patientUuid); - return this.getLabSyncLog(patientUuid).then((result) => { - var patientHasEverBeenSynced = false; - if (result.result.length > 0) - patientHasEverBeenSynced = true; - if (patientHasEverBeenSynced) { - if (result.result[0]['status'] === 0 && (result.result.length === 1 || result.result[1]['status'] === 0) && - result.result[0]['TIMESTAMPDIFF(HOUR,date_updated,now())'] < 6) { - console.log('Patient synced..'); - return obsService.getPatientTodaysTestObsByPatientUuId(patientUuid) - .then(function (response) { - - return { - updatedObs: response, - lab: labLocation, - last_sync_date: result.result[0]['date_updated'] - } - }).catch((error)=>{ - console.log('ERROR',error); - }); - } - else { - - return this.syncAndGetPatientLabResults(patientUuid, labLocation).then((result) => { - return this.syncLabsByPatientUuid(patientUuid,labLocation); - }).catch((err)=>{ - console.log('ERROR Getting results',err); + return this.getLabSyncLog(patientUuid) + .then((result) => { + var patientHasEverBeenSynced = false; + if (result.result.length > 0) patientHasEverBeenSynced = true; + if (patientHasEverBeenSynced) { + if ( + result.result[0]['status'] === 0 && + (result.result.length === 1 || result.result[1]['status'] === 0) && + result.result[0]['TIMESTAMPDIFF(HOUR,date_updated,now())'] < 6 + ) { + console.log('Patient synced..'); + return obsService + .getPatientTodaysTestObsByPatientUuId(patientUuid) + .then(function (response) { + return { + updatedObs: response, + lab: labLocation, + last_sync_date: result.result[0]['date_updated'] + }; + }) + .catch((error) => { + console.log('ERROR', error); + }); + } else { + return this.syncAndGetPatientLabResults(patientUuid, labLocation) + .then((result) => { + return this.syncLabsByPatientUuid(patientUuid, labLocation); + }) + .catch((err) => { + console.log('ERROR Getting results', err); + }); + } + } else { + return this.syncAndGetPatientLabResults(patientUuid, labLocation) + .then((result) => { + return this.syncLabsByPatientUuid(patientUuid, labLocation); + }) + .catch((error) => { + console.log('ERROR', error); }); } - } - else { - - return this.syncAndGetPatientLabResults(patientUuid, labLocation).then((result) => { - return this.syncLabsByPatientUuid(patientUuid,labLocation); - }).catch((error)=>{ - console.log('ERROR',error); - }); - } - }).catch((error) => { - console.error('getLabSyncLog error', error); - }); + }) + .catch((error) => { + console.error('getLabSyncLog error', error); + }); } syncAndGetPatientLabResults(patientUuid, labLocation) { const that = this; - var table = eidResultsSchema.patientLabResultsSchema.table.schema + '.' + eidResultsSchema.patientLabResultsSchema.table.tableName; + var table = + eidResultsSchema.patientLabResultsSchema.table.schema + + '.' + + eidResultsSchema.patientLabResultsSchema.table.tableName; var fields = [ { person_uuid: patientUuid, @@ -100,111 +114,147 @@ export class LabSyncService { conflicts: null } ]; - return obsService.getPatientIdentifiers(patientUuid).then(function (response) { - if (response.identifiers.length === 0) { - throw new Error('Patient without identifiers!'); - } - let configObj = config.hivLabSystem[labLocation]; - let client = new LabClient(configObj); - return Promise.all([ - client.fetchViralLoad({ patient_id: response.identifiers.join() }), - client.fetchDNAPCR({ patient_id: response.identifiers.join() }), - client.fetchCD4({ patient_id: response.identifiers.join() }) - ]).then((allResults) => { - let viralLoadResults = allResults[0]; - let dnaPCR = allResults[1]; - let cd4Results = allResults[2]; - let labResultsPromises = []; - labResultsPromises.push(that.processViralLoadResults(viralLoadResults.data || [], patientUuid).then((processedObs) => { - const eidCompareOperator = new EidCompareOperator(); - let labVLObs = processedObs[0]; - let amrsObs = []; - if (processedObs[1]) { - amrsObs = processedObs[1].map((obs) => { - return { - person: obs.person.uuid, - obsDatetime: obs.obsDatetime, - concept: obs.concept.uuid, - value: obs.value - } - }); - } - return eidCompareOperator.getAllResults(labVLObs, amrsObs); - }).catch((error) => { - console.error('ERROR : processViralLoadResults', error); - })); + return obsService + .getPatientIdentifiers(patientUuid) + .then(function (response) { + if (response.identifiers.length === 0) { + throw new Error('Patient without identifiers!'); + } + let configObj = config.hivLabSystem[labLocation]; + let client = new LabClient(configObj); + return Promise.all([ + client.fetchViralLoad({ patient_id: response.identifiers.join() }), + client.fetchDNAPCR({ patient_id: response.identifiers.join() }), + client.fetchCD4({ patient_id: response.identifiers.join() }) + ]) + .then((allResults) => { + let viralLoadResults = allResults[0]; + let dnaPCR = allResults[1]; + let cd4Results = allResults[2]; + let labResultsPromises = []; + labResultsPromises.push( + that + .processViralLoadResults( + viralLoadResults.data || [], + patientUuid + ) + .then((processedObs) => { + const eidCompareOperator = new EidCompareOperator(); + let labVLObs = processedObs[0]; + let amrsObs = []; + if (processedObs[1]) { + amrsObs = processedObs[1].map((obs) => { + return { + person: obs.person.uuid, + obsDatetime: obs.obsDatetime, + concept: obs.concept.uuid, + value: obs.value + }; + }); + } + return eidCompareOperator.getAllResults(labVLObs, amrsObs); + }) + .catch((error) => { + console.error('ERROR : processViralLoadResults', error); + }) + ); - labResultsPromises.push(that.processDNAPCRResults(dnaPCR.data || [], patientUuid).then((processedObs) => { - const eidCompareOperator = new EidCompareOperator(); - let labDNAPCRObs = processedObs[0]; - let amrsObs = []; - if (processedObs[1]) { - amrsObs = processedObs[1].map((obs) => { - return { - person: obs.person.uuid, - obsDatetime: obs.obsDatetime, - concept: obs.concept.uuid, - value: obs.value - } - }); - } - return eidCompareOperator.getAllResults(labDNAPCRObs, amrsObs); - }).catch((error) => { - console.error('ERROR : processDNAPCRResults', error); - }) - ); + labResultsPromises.push( + that + .processDNAPCRResults(dnaPCR.data || [], patientUuid) + .then((processedObs) => { + const eidCompareOperator = new EidCompareOperator(); + let labDNAPCRObs = processedObs[0]; + let amrsObs = []; + if (processedObs[1]) { + amrsObs = processedObs[1].map((obs) => { + return { + person: obs.person.uuid, + obsDatetime: obs.obsDatetime, + concept: obs.concept.uuid, + value: obs.value + }; + }); + } + return eidCompareOperator.getAllResults( + labDNAPCRObs, + amrsObs + ); + }) + .catch((error) => { + console.error('ERROR : processDNAPCRResults', error); + }) + ); - labResultsPromises.push(that.processCD4Results(cd4Results.data || [], patientUuid).then((processedObs) => { - const eidCompareOperator = new EidCompareOperator(); - let labCD4Obs = processedObs[0]; - let amrsObs = []; - if (processedObs[1]) { - amrsObs = processedObs[1].map((obs) => { - return { - person: obs.person.uuid, - obsDatetime: obs.obsDatetime, - concept: obs.concept.uuid, - value: obs.value - } - }); - } + labResultsPromises.push( + that + .processCD4Results(cd4Results.data || [], patientUuid) + .then((processedObs) => { + const eidCompareOperator = new EidCompareOperator(); + let labCD4Obs = processedObs[0]; + let amrsObs = []; + if (processedObs[1]) { + amrsObs = processedObs[1].map((obs) => { + return { + person: obs.person.uuid, + obsDatetime: obs.obsDatetime, + concept: obs.concept.uuid, + value: obs.value + }; + }); + } - return eidCompareOperator.getAllResults(labCD4Obs, amrsObs); - }).catch((error) => { - console.error('ERROR: processCD4Results', error); - }) - ); + return eidCompareOperator.getAllResults(labCD4Obs, amrsObs); + }) + .catch((error) => { + console.error('ERROR: processCD4Results', error); + }) + ); - return Promise.all(labResultsPromises).then((obs) => { - const flatten = arr => arr.reduce( - (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [] - ); - //return obsService.postObsToAMRS(obs[0].missingResults[0]); - let flattenResult = flatten(obs); - let combinedMissing = that.combineObs('missingResults', flattenResult); - let combinedconflicting = that.combineObs('conflictingResults', flattenResult); + return Promise.all(labResultsPromises) + .then((obs) => { + const flatten = (arr) => + arr.reduce( + (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), + [] + ); + //return obsService.postObsToAMRS(obs[0].missingResults[0]); + let flattenResult = flatten(obs); + let combinedMissing = that.combineObs( + 'missingResults', + flattenResult + ); + let combinedconflicting = that.combineObs( + 'conflictingResults', + flattenResult + ); - console.log('Conflicting', combinedconflicting); - console.log('Missing', combinedMissing); + console.log('Conflicting', combinedconflicting); + console.log('Missing', combinedMissing); - fields[0].conflicts = JSON.stringify(combinedconflicting); - return Promise.all(that.combineObsPostPromises(combinedMissing)).then((savedObs) => { - fields[0].status = 0; - console.log('Saving EID logs'); - return eidService.saveEidSyncLog(table, fields, savedObs).catch((error)=>{ - console.log('ERROR saving logs',error); - }); - }).catch((error) => { - console.error('ERROR : combineObsPostPromises', error); + fields[0].conflicts = JSON.stringify(combinedconflicting); + return Promise.all(that.combineObsPostPromises(combinedMissing)) + .then((savedObs) => { + fields[0].status = 0; + console.log('Saving EID logs'); + return eidService + .saveEidSyncLog(table, fields, savedObs) + .catch((error) => { + console.log('ERROR saving logs', error); + }); + }) + .catch((error) => { + console.error('ERROR : combineObsPostPromises', error); + }); + }) + .catch((error) => { + console.error('ERROR : labResultsPromises', error); + }); + }) + .catch((error) => { + console.error('ERROR : Fetching results', error); }); - }).catch((error) => { - console.error('ERROR : labResultsPromises', error); - }); - }).catch((error) => { - console.error('ERROR : Fetching results', error); }); - }); - } combineObsPostPromises(payload) { @@ -219,7 +269,7 @@ export class LabSyncService { combineObs(key, obs) { let combined = []; for (let o of obs) { - if(o){ + if (o) { combined = combined.concat(o[key]); } } @@ -228,40 +278,52 @@ export class LabSyncService { getLabExceptions() { return { - "POOR SAMPLE QUALITY": "a89c3f1e-1350-11df-a1f1-0026b9348838", - "NOT DONE": "a899ea48-1350-11df-a1f1-0026b9348838", - "INDETERMINATE": "a89a7ae4-1350-11df-a1f1-0026b9348838", - "BELOW DETECTABLE LIMIT": "a89c3f1e-1350-11df-a1f1-0026b9348838", - "UNABLE TO COLLECT SAMPLE": "a8afcec6-1350-11df-a1f1-0026b9348838", - "SPECIMEN NOT RECEIVED": "0271c15e-4f7f-4a18-9b45-2d7e5b6f7057", - "ORDERED FOR WRONG PATIENT": "3366412a-e279-4428-a671-37221804c6e6", - "COLLECT NEW SAMPLE": "a89c3f1e-1350-11df-a1f1-0026b9348838" - } + 'POOR SAMPLE QUALITY': 'a89c3f1e-1350-11df-a1f1-0026b9348838', + 'NOT DONE': 'a899ea48-1350-11df-a1f1-0026b9348838', + INDETERMINATE: 'a89a7ae4-1350-11df-a1f1-0026b9348838', + 'BELOW DETECTABLE LIMIT': 'a89c3f1e-1350-11df-a1f1-0026b9348838', + 'UNABLE TO COLLECT SAMPLE': 'a8afcec6-1350-11df-a1f1-0026b9348838', + 'SPECIMEN NOT RECEIVED': '0271c15e-4f7f-4a18-9b45-2d7e5b6f7057', + 'ORDERED FOR WRONG PATIENT': '3366412a-e279-4428-a671-37221804c6e6', + 'COLLECT NEW SAMPLE': 'a89c3f1e-1350-11df-a1f1-0026b9348838' + }; } processViralLoadResults(result, patientUuid) { let vlAdapter = new VLAdapter(result, patientUuid); - return Promise.all([vlAdapter.getLabResults(), obsService.getPatientAllTestObsByPatientUuId(patientUuid)]); + return Promise.all([ + vlAdapter.getLabResults(), + obsService.getPatientAllTestObsByPatientUuId(patientUuid) + ]); } processDNAPCRResults(result, patientUuid) { let dnaPCRAdapter = new DNAPCRAdapter(result, patientUuid); - return Promise.all([dnaPCRAdapter.getLabResults(), obsService.getPatientAllTestObsByPatientUuId(patientUuid)]); + return Promise.all([ + dnaPCRAdapter.getLabResults(), + obsService.getPatientAllTestObsByPatientUuId(patientUuid) + ]); } processCD4Results(result, patientUuid) { let cd4Adapter = new CD4Adapter(result, patientUuid); - return Promise.all([cd4Adapter.getLabResults(), obsService.getPatientAllTestObsByPatientUuId(patientUuid)]); + return Promise.all([ + cd4Adapter.getLabResults(), + obsService.getPatientAllTestObsByPatientUuId(patientUuid) + ]); } handleLabRequestError(error) { - throw Error(error.message) + throw Error(error.message); } getLabSyncLog(patientUuid) { var queryParts = { columns: eidResultsSchema.patientLabResultsSchema.columns, - table: eidResultsSchema.patientLabResultsSchema.table.schema + '.' + eidResultsSchema.patientLabResultsSchema.table.tableName, + table: + eidResultsSchema.patientLabResultsSchema.table.schema + + '.' + + eidResultsSchema.patientLabResultsSchema.table.tableName, where: [ eidResultsSchema.patientLabResultsSchema.filters[0].expression, patientUuid @@ -280,4 +342,4 @@ export class LabSyncService { }); }); } -} \ No newline at end of file +} diff --git a/app/lab-integration/utils/eid-compare-operator.js b/app/lab-integration/utils/eid-compare-operator.js index c8e48281b..6be905f7e 100644 --- a/app/lab-integration/utils/eid-compare-operator.js +++ b/app/lab-integration/utils/eid-compare-operator.js @@ -3,83 +3,85 @@ var moment = require('moment'); var _ = require('underscore'); export class EidCompareOperator { - - constructor() { } - getAllResults(eidResults, obsResults) { - return { - missingResults: this.getMissingResults(eidResults, obsResults), - conflictingResults: this.getConflictingResults(eidResults, obsResults) - } + constructor() {} + getAllResults(eidResults, obsResults) { + return { + missingResults: this.getMissingResults(eidResults, obsResults), + conflictingResults: this.getConflictingResults(eidResults, obsResults) + }; + } + getMissingResults(eidResults, obsResults) { + var missingResults = []; + for (var i = 0; i < eidResults.length; i++) { + var found = this.findEquivalentObject(eidResults[i], obsResults); + if (!found) { + missingResults.push(eidResults[i]); + } } - getMissingResults(eidResults, obsResults) { - var missingResults = []; - for (var i = 0; i < eidResults.length; i++) { - var found = this.findEquivalentObject(eidResults[i], obsResults); - if (!found) { - missingResults.push(eidResults[i]); - } - } - return missingResults; - } - - findEquivalentObject(eidObj, obsResults) { - var found = false; - if (eidObj && obsResults) { - for (var i = 0; i < obsResults.length; i++) { - var obsObj = obsResults[i]; - var equalDate = this.areDatesEqual(eidObj.obsDatetime, obsObj.obsDatetime); - var obsValue = ''+obsObj.value; - if (obsValue && obsObj.value !== null) { - if (typeof (obsObj.value) === 'object') { - obsValue = obsObj.value.uuid.toString(); - } else { - obsValue = obsObj.value.toString(); - } - if (obsObj.concept === eidObj.concept && - obsValue.trim() === eidObj.value.toString().trim() && equalDate) { - found = true; - } - } - - if (eidObj.groupMembers) { - //Introduce check for group members - if (obsObj.concept === eidObj.concept && equalDate) { - found = true; - } - } - } - + return missingResults; + } + findEquivalentObject(eidObj, obsResults) { + var found = false; + if (eidObj && obsResults) { + for (var i = 0; i < obsResults.length; i++) { + var obsObj = obsResults[i]; + var equalDate = this.areDatesEqual( + eidObj.obsDatetime, + obsObj.obsDatetime + ); + var obsValue = '' + obsObj.value; + if (obsValue && obsObj.value !== null) { + if (typeof obsObj.value === 'object') { + obsValue = obsObj.value.uuid.toString(); + } else { + obsValue = obsObj.value.toString(); + } + if ( + obsObj.concept === eidObj.concept && + obsValue.trim() === eidObj.value.toString().trim() && + equalDate + ) { + found = true; + } } - return found; + if (eidObj.groupMembers) { + //Introduce check for group members + if (obsObj.concept === eidObj.concept && equalDate) { + found = true; + } + } + } } - getConflictingResults(eidResults, obsResults) { - var conflictingResults = []; + return found; + } - for (var i = 0; i < eidResults.length; i++) { - var found = this.findEquivalentObject(eidResults[i], obsResults); - if (found) { - conflictingResults.push(eidResults[i]); - } - } + getConflictingResults(eidResults, obsResults) { + var conflictingResults = []; - return conflictingResults; + for (var i = 0; i < eidResults.length; i++) { + var found = this.findEquivalentObject(eidResults[i], obsResults); + if (found) { + conflictingResults.push(eidResults[i]); + } } - areDatesEqual(date1, date2) { + return conflictingResults; + } - var d1 = null; - var d2 = null; + areDatesEqual(date1, date2) { + var d1 = null; + var d2 = null; - try { - d1 = new Date(date1); - d2 = new Date(date2); - d1 = new moment(d1); - d2 = new moment(d2); - } catch (e) { } + try { + d1 = new Date(date1); + d2 = new Date(date2); + d1 = new moment(d1); + d2 = new moment(d2); + } catch (e) {} - return d1.isSame(d2, 'day'); - } -} \ No newline at end of file + return d1.isSame(d2, 'day'); + } +} diff --git a/app/lab-integration/utils/lab-client.js b/app/lab-integration/utils/lab-client.js index 41652a97e..b253a8af5 100644 --- a/app/lab-integration/utils/lab-client.js +++ b/app/lab-integration/utils/lab-client.js @@ -3,202 +3,207 @@ const eidFacilityMap = require('../../../service/eid/eid-facility-mappings'); const db = require('../../../etl-db'); // import formurlencoded from 'form-urlencoded'; export class LabClient { - config = null; - constructor(config) { - if (!config.serverUrl && !config.apiKey) { - throw (Error('Please check if the server url and apikey is set')); - } - this.config = config; + config = null; + constructor(config) { + if (!config.serverUrl && !config.apiKey) { + throw Error('Please check if the server url and apikey is set'); } - /* This functions have swallow promise errors because the specific user case where we want all promises resolve when executed with Promise.All + this.config = config; + } + /* This functions have swallow promise errors because the specific user case where we want all promises resolve when executed with Promise.All procced with caution */ - fetchDNAPCR(filterOptions, offset) { - if (!filterOptions) { - throw (Error('Please supply filter options')); - } - filterOptions.test = 1; - filterOptions.dispatched = 1; - return this.getFetchRequest(filterOptions, offset).catch(function (err) { - //return error; - return err; - }); + fetchDNAPCR(filterOptions, offset) { + if (!filterOptions) { + throw Error('Please supply filter options'); } + filterOptions.test = 1; + filterOptions.dispatched = 1; + return this.getFetchRequest(filterOptions, offset).catch(function (err) { + //return error; + return err; + }); + } - fetchViralLoad(filterOptions, offset) { - if (!filterOptions) { - throw (Error('Please supply filter options')); - } - filterOptions.test = 2; - filterOptions.dispatched = 1; - return this.getFetchRequest(filterOptions, offset).catch(function (err) { - //return error; - return err; - }); + fetchViralLoad(filterOptions, offset) { + if (!filterOptions) { + throw Error('Please supply filter options'); } + filterOptions.test = 2; + filterOptions.dispatched = 1; + return this.getFetchRequest(filterOptions, offset).catch(function (err) { + //return error; + return err; + }); + } - fetchPendingViralLoad(filterOptions, offset) { - if (!filterOptions) { - throw (Error('Please supply filter options')); - } - filterOptions.test = 2; - filterOptions.dispatched = 0; - return this.getFetchRequest(filterOptions, offset).catch(function (err) { - //return error; - return err; - }); + fetchPendingViralLoad(filterOptions, offset) { + if (!filterOptions) { + throw Error('Please supply filter options'); } + filterOptions.test = 2; + filterOptions.dispatched = 0; + return this.getFetchRequest(filterOptions, offset).catch(function (err) { + //return error; + return err; + }); + } - - fetchCD4(filterOptions, offset) { - if (!filterOptions) { - throw (Error('Please supply filter options')); - } - filterOptions.test = 3; - filterOptions.dispatched = 1; - return this.getFetchRequest(filterOptions, offset).catch(function (err) { - //return error; - return err; - }); - } - - postLabPayload(payload) { - switch (payload.test) { - case 1: - return this.postDNAPCR(payload); - case 2: - return this.postViralLoad(payload); - case 3: - return this.postCD4(payload); - default: - break; - } - - } - postDNAPCR(payload) { - return this.getPostRequest(payload, `${this.config.serverUrl}/api/eid`,); + fetchCD4(filterOptions, offset) { + if (!filterOptions) { + throw Error('Please supply filter options'); } + filterOptions.test = 3; + filterOptions.dispatched = 1; + return this.getFetchRequest(filterOptions, offset).catch(function (err) { + //return error; + return err; + }); + } - postViralLoad(payload) { - return this.getPostRequest(payload, `${this.config.serverUrl}/api/vl`); + postLabPayload(payload) { + switch (payload.test) { + case 1: + return this.postDNAPCR(payload); + case 2: + return this.postViralLoad(payload); + case 3: + return this.postCD4(payload); + default: + break; } + } + postDNAPCR(payload) { + return this.getPostRequest(payload, `${this.config.serverUrl}/api/eid`); + } - postCD4(payload) { - return this.getPostRequest(payload, `${this.config.serverUrl}/api/cd4`); - } + postViralLoad(payload) { + return this.getPostRequest(payload, `${this.config.serverUrl}/api/vl`); + } - getPostRequest(payload, endpoint) { - const options = { - uri: endpoint, - headers: { - 'apikey': this.config.apiKey, - 'Content-Type': 'application/x-www-form-urlencoded' - }, - method: 'POST', - // json: true, - form: payload, - timeout: 20000 - }; - return rp(options); + postCD4(payload) { + return this.getPostRequest(payload, `${this.config.serverUrl}/api/cd4`); + } - } + getPostRequest(payload, endpoint) { + const options = { + uri: endpoint, + headers: { + apikey: this.config.apiKey, + 'Content-Type': 'application/x-www-form-urlencoded' + }, + method: 'POST', + // json: true, + form: payload, + timeout: 20000 + }; + return rp(options); + } - getFetchRequest(filterOptions, offset) { - // process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0; - let fetchOffset = 1; - // let facilityCodes = this.getFacitityCodes().join(); - // filterOptions.facility_code = facilityCodes; - let facilityCodes = this.getFacitityCodesDictionary(); + getFetchRequest(filterOptions, offset) { + // process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0; + let fetchOffset = 1; + // let facilityCodes = this.getFacitityCodes().join(); + // filterOptions.facility_code = facilityCodes; + let facilityCodes = this.getFacitityCodesDictionary(); - if (offset) { - fetchOffset = offset; - } - // var host = new String(this.config.serverUrl).substr(8); - var options = { - uri: `${this.config.serverUrl}/api/function?page=${fetchOffset}`, - headers: { - 'apikey': this.config.apiKey, - 'Cache-Control': 'no-cache', - 'Connection': 'keep-alive', - 'Content-Type': 'application/x-www-form-urlencoded' - }, - json: true, - insecure: true, - method: 'POST', - timeout: 20000, - form: filterOptions - }; - return new Promise((resolve, reject) => { - rp(options).then((response)=>{ - var unknownMFL = []; - if(Array.isArray(response.data) && response.data.length > 0) { - response.data = response.data.filter((item) => { - if(facilityCodes[item.facility_code]) { - return true; - } else { - unknownMFL.push(item.facility_code); - } - return false; - }); - } - if(unknownMFL.length > 0) { - // post unknown MFL code to slack - console.warn('Unknown MFL codes', unknownMFL); - } - // console.log('RESULTS', response); - resolve(response); - }).catch((err)=>{ - console.error('LAB INTEGRATION ERROR:', err); - this.logRequestError(err,options).then((result) => { - reject(err); - }).catch((error) => { - reject(err); - }); + if (offset) { + fetchOffset = offset; + } + // var host = new String(this.config.serverUrl).substr(8); + var options = { + uri: `${this.config.serverUrl}/api/function?page=${fetchOffset}`, + headers: { + apikey: this.config.apiKey, + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + 'Content-Type': 'application/x-www-form-urlencoded' + }, + json: true, + insecure: true, + method: 'POST', + timeout: 20000, + form: filterOptions + }; + return new Promise((resolve, reject) => { + rp(options) + .then((response) => { + var unknownMFL = []; + if (Array.isArray(response.data) && response.data.length > 0) { + response.data = response.data.filter((item) => { + if (facilityCodes[item.facility_code]) { + return true; + } else { + unknownMFL.push(item.facility_code); + } + return false; + }); + } + if (unknownMFL.length > 0) { + // post unknown MFL code to slack + console.warn('Unknown MFL codes', unknownMFL); + } + // console.log('RESULTS', response); + resolve(response); + }) + .catch((err) => { + console.error('LAB INTEGRATION ERROR:', err); + this.logRequestError(err, options) + .then((result) => { + reject(err); + }) + .catch((error) => { + reject(err); }); }); - } + }); + } - - getFacitityCodes() { - let facilityCodes = []; - for (let key in eidFacilityMap) { - let facility = eidFacilityMap[key]; - if (facility.mflCode && facility.mflCode !== '') { - facilityCodes.push(facility.mflCode); - } - } - return facilityCodes; + getFacitityCodes() { + let facilityCodes = []; + for (let key in eidFacilityMap) { + let facility = eidFacilityMap[key]; + if (facility.mflCode && facility.mflCode !== '') { + facilityCodes.push(facility.mflCode); + } } + return facilityCodes; + } - getFacitityCodesDictionary() { - let facilityCodes = {}; - for (let key in eidFacilityMap) { - let facility = eidFacilityMap[key]; - if (facility.mflCode && facility.mflCode !== '') { - facilityCodes[facility.mflCode] = facility.mflCode; - } - } - return facilityCodes; + getFacitityCodesDictionary() { + let facilityCodes = {}; + for (let key in eidFacilityMap) { + let facility = eidFacilityMap[key]; + if (facility.mflCode && facility.mflCode !== '') { + facilityCodes[facility.mflCode] = facility.mflCode; + } } + return facilityCodes; + } - logRequestError(error,options) { - // console.log('Logging lab request error...', error); - var sql = "INSERT INTO etl.eid_lab_request_errors(error,options)" + - " VALUES('" + error + "','" + JSON.stringify(options) + "');"; - - var queryObject = { - query: sql, - sqlParams: [] - }; - - return new Promise(function (resolve, reject) { - db.queryReportServer(queryObject, function (response) { - if (response.error) { - reject(response); - } else { - resolve(response); - } - }); - }); - } -} \ No newline at end of file + logRequestError(error, options) { + // console.log('Logging lab request error...', error); + var sql = + 'INSERT INTO etl.eid_lab_request_errors(error,options)' + + " VALUES('" + + error + + "','" + + JSON.stringify(options) + + "');"; + + var queryObject = { + query: sql, + sqlParams: [] + }; + + return new Promise(function (resolve, reject) { + db.queryReportServer(queryObject, function (response) { + if (response.error) { + reject(response); + } else { + resolve(response); + } + }); + }); + } +} diff --git a/app/lab-integration/utils/poc-eid-payload-helper.js b/app/lab-integration/utils/poc-eid-payload-helper.js index 3413640a4..66edb5753 100644 --- a/app/lab-integration/utils/poc-eid-payload-helper.js +++ b/app/lab-integration/utils/poc-eid-payload-helper.js @@ -1,219 +1,221 @@ (function () { - 'use strict'; - const _ = require('lodash'); - const eidFacilityMap = require('../../../service/eid/eid-facility-mappings'); - const eidOrderMap = require('./regimen-config-loader'); - const hasEidCode = _.findKey(eidOrderMap.artRegimen, 'eidCode'); - - function generatePocToEidPayLoad(payload) { - console.log('generatePocToEidPayLoad', payload); - return new Promise(function (resolve, reject) { - var eidPayload = { + 'use strict'; + const _ = require('lodash'); + const eidFacilityMap = require('../../../service/eid/eid-facility-mappings'); + const eidOrderMap = require('./regimen-config-loader'); + const hasEidCode = _.findKey(eidOrderMap.artRegimen, 'eidCode'); + + function generatePocToEidPayLoad(payload) { + console.log('generatePocToEidPayLoad', payload); + return new Promise(function (resolve, reject) { + var eidPayload = {}; + + try { + switch (payload.type) { + case 'VL': + eidPayload = { + test: 2, + mflCode: getLocation(payload, 'mflCode'), + patient_identifier: payload.patientIdentifier, + dob: payload.birthDate, + datecollected: payload.dateDrawn, + sex: getGenderCode(payload.sex), + prophylaxis: getArtRegimen(payload) || 16, + regimenline: 1, + order_no: payload.orderNumber, + sampletype: payload.sampleType ? payload.sampleType : 1, + justification: getTestOrderJustification(payload) || 0, + pmtct: + payload.isPregnant === 1 + ? 1 + : payload.breastfeeding === 1 + ? 2 + : 3, + amrs_location: getLocation(payload, 'mrsId') }; - - try { - - switch (payload.type) { - case 'VL': - eidPayload = { - "test": 2, - "mflCode": getLocation(payload, 'mflCode'), - "patient_identifier": payload.patientIdentifier, - "dob": payload.birthDate, - "datecollected": payload.dateDrawn, - "sex": getGenderCode(payload.sex), - "prophylaxis": getArtRegimen(payload) || 16, - "regimenline": 1, - "order_no": payload.orderNumber, - "sampletype": payload.sampleType ? payload.sampleType : 1, - "justification": getTestOrderJustification(payload) || 0, - "pmtct": payload.isPregnant === 1 ? 1 : payload.breastfeeding === 1 ? 2: 3, - "amrs_location": getLocation(payload, 'mrsId') - }; - break; - case 'DNAPCR': - eidPayload = { - "test": 1, - "mflCode": getLocation(payload, 'mflCode'), - "patient_identifier": payload.patientIdentifier, - "dob": payload.birthDate, - "datecollected": payload.dateDrawn, - "sex": getGenderCode(payload.sex), - "feeding": getInfantFeedingPlan(payload) || 0, - "pcrtype": "", - "regimen": getInfantProphylaxis(payload) || 5, - "entry_point": getDnaPcrEntryPoint(payload) || 0, - "mother_prophylaxis": getPmtctIntervention(payload) || 5, - "mother_last_result": "", - "spots": "", - "mother_age": "", - "order_no": payload.orderNumber, - "ccc_no": "", - "lab": "", - "amrs_location": getLocation(payload, 'mrsId') - }; - break; - case 'CD4': - eidPayload = { - "test": 3, - "mflCode": getLocation(payload, 'mflCode'), - "dob": payload.birthDate, - "datecollected": payload.dateDrawn, - "sex": getGenderCode(payload.sex), - "patient_name": payload.patientName, - "medicalrecordno": payload.patientIdentifier, - "order_no": payload.orderNumber, - "amrs_location": getLocation(payload, 'mrsId'), - "provider_identifier": payload.providerIdentifier - }; - break; - default: - - - } - - if (!_.isEmpty(eidPayload)) { - console.log('payload :', eidPayload); - resolve(eidPayload); - } else { - reject('Could not Find payload type'); - } - } catch (e) { - reject(e); - } - - }); - - } - - - //helpers - function getInfantProphylaxis(rawPayload) { - const result = eidOrderMap.infantProphylaxis[rawPayload.infantProphylaxisUuid]; - if (result) return result.eidId; - } - - function getPmtctIntervention(rawPayload) { - var result = eidOrderMap.pmtctIntervention[rawPayload.pmtctInterventionUuid]; - if (result) return result.eidId; - } - - function getInfantFeedingPlan(rawPayload) { - var result = eidOrderMap.infantFeedingPlan[rawPayload.feedingTypeUuid]; - if (result) return result.eidId; - } - - function getDnaPcrEntryPoint(rawPayload) { - var result = eidOrderMap.dnaPcrEntryPoint[rawPayload.entryPointUuid]; - if (result) return result.eidId; - } - - function getHivStatus(rawPayload) { - var result = eidOrderMap.hivStatus[rawPayload.motherHivStatusUuid]; - if (result) return hasEidCode ? result.eidCode : result.eidId; - } - - function getLocation(rawPayload, code) { - var result = eidFacilityMap[rawPayload.locationUuid]; - if (result) return result[code]; - } - - function getTestOrderJustification(rawPayload) { - var result = eidOrderMap.testOrderJustification[rawPayload.vlJustificationUuid]; - if (result) return result.eidId; - } - - function getGenderCode(gender) { - var genderCode; - switch (gender) { - case 'F': - genderCode = 2; - break; - case 'M': - genderCode = 1; - break; - default: - genderCode = 0; + break; + case 'DNAPCR': + eidPayload = { + test: 1, + mflCode: getLocation(payload, 'mflCode'), + patient_identifier: payload.patientIdentifier, + dob: payload.birthDate, + datecollected: payload.dateDrawn, + sex: getGenderCode(payload.sex), + feeding: getInfantFeedingPlan(payload) || 0, + pcrtype: '', + regimen: getInfantProphylaxis(payload) || 5, + entry_point: getDnaPcrEntryPoint(payload) || 0, + mother_prophylaxis: getPmtctIntervention(payload) || 5, + mother_last_result: '', + spots: '', + mother_age: '', + order_no: payload.orderNumber, + ccc_no: '', + lab: '', + amrs_location: getLocation(payload, 'mrsId') + }; + break; + case 'CD4': + eidPayload = { + test: 3, + mflCode: getLocation(payload, 'mflCode'), + dob: payload.birthDate, + datecollected: payload.dateDrawn, + sex: getGenderCode(payload.sex), + patient_name: payload.patientName, + medicalrecordno: payload.patientIdentifier, + order_no: payload.orderNumber, + amrs_location: getLocation(payload, 'mrsId'), + provider_identifier: payload.providerIdentifier + }; + break; + default: } - return genderCode; - - } - function hasCode(list, code) { - let hasCode = false; - try { - _.each(list,(item) => { - if (parseInt(item) === parseInt(code)) { - hasCode = true; - } - }); - } catch (e) {} - return hasCode; + if (!_.isEmpty(eidPayload)) { + console.log('payload :', eidPayload); + resolve(eidPayload); + } else { + reject('Could not Find payload type'); + } + } catch (e) { + reject(e); + } + }); + } + + //helpers + function getInfantProphylaxis(rawPayload) { + const result = + eidOrderMap.infantProphylaxis[rawPayload.infantProphylaxisUuid]; + if (result) return result.eidId; + } + + function getPmtctIntervention(rawPayload) { + var result = + eidOrderMap.pmtctIntervention[rawPayload.pmtctInterventionUuid]; + if (result) return result.eidId; + } + + function getInfantFeedingPlan(rawPayload) { + var result = eidOrderMap.infantFeedingPlan[rawPayload.feedingTypeUuid]; + if (result) return result.eidId; + } + + function getDnaPcrEntryPoint(rawPayload) { + var result = eidOrderMap.dnaPcrEntryPoint[rawPayload.entryPointUuid]; + if (result) return result.eidId; + } + + function getHivStatus(rawPayload) { + var result = eidOrderMap.hivStatus[rawPayload.motherHivStatusUuid]; + if (result) return hasEidCode ? result.eidCode : result.eidId; + } + + function getLocation(rawPayload, code) { + var result = eidFacilityMap[rawPayload.locationUuid]; + if (result) return result[code]; + } + + function getTestOrderJustification(rawPayload) { + var result = + eidOrderMap.testOrderJustification[rawPayload.vlJustificationUuid]; + if (result) return result.eidId; + } + + function getGenderCode(gender) { + var genderCode; + switch (gender) { + case 'F': + genderCode = 2; + break; + case 'M': + genderCode = 1; + break; + default: + genderCode = 0; } - - function getArtRegimenEidCode (rawPayload) { - if (rawPayload.artRegimenUuid === "" || rawPayload.artRegimenUuid === null) return 'AF5X'; // none - const arvconcepts = rawPayload.artRegimenUuid ? rawPayload.artRegimenUuid.split(" ## ") : null; - let resolveId = 'AF5X'; - - if (!(arvconcepts && arvconcepts.length > 0)) return resolvedId; - - _.forEach(eidOrderMap.artRegimen, (artRegimen) => { - - const mrsArvRegimenList = artRegimen.mrsArvRegimen.split(','); - - if (hasCode(mrsArvRegimenList, arvconcepts[0])) { - if (_.isEqual(_.sortBy(mrsArvRegimenList), _.sortBy(arvconcepts))) { - return resolveId = artRegimen.eidCode; - } + return genderCode; + } + + function hasCode(list, code) { + let hasCode = false; + try { + _.each(list, (item) => { + if (parseInt(item) === parseInt(code)) { + hasCode = true; + } + }); + } catch (e) {} + return hasCode; + } + + function getArtRegimenEidCode(rawPayload) { + if (rawPayload.artRegimenUuid === '' || rawPayload.artRegimenUuid === null) + return 'AF5X'; // none + const arvconcepts = rawPayload.artRegimenUuid + ? rawPayload.artRegimenUuid.split(' ## ') + : null; + let resolveId = 'AF5X'; + + if (!(arvconcepts && arvconcepts.length > 0)) return resolvedId; + + _.forEach(eidOrderMap.artRegimen, (artRegimen) => { + const mrsArvRegimenList = artRegimen.mrsArvRegimen.split(','); + + if (hasCode(mrsArvRegimenList, arvconcepts[0])) { + if (_.isEqual(_.sortBy(mrsArvRegimenList), _.sortBy(arvconcepts))) { + return (resolveId = artRegimen.eidCode); + } + } + }); + return resolveId; + } + + const getArtRegimen = (rawPayload) => { + return hasEidCode + ? getArtRegimenEidCode(rawPayload) + : getArtRegimenOld(rawPayload); + }; + + function getArtRegimenOld(rawPayload) { + if (rawPayload.artRegimenUuid === '' || rawPayload.artRegimenUuid === null) + return 15; //15 is none; + + var arvCodes = rawPayload.artRegimenUuid + ? rawPayload.artRegimenUuid.split(' ## ') + : null; + var resolvedId = 16; // 14 is other + + if (!(arvCodes && arvCodes.length > 0)) return resolvedId; + + _.forEach(eidOrderMap.artRegimen, function (artRegimen) { + var mrsArvRegimens = artRegimen.mrsArvRegimen.split(','); + + if (hasCode(mrsArvRegimens, arvCodes[0])) { + var hasCodes = true; + + if (arvCodes.length === 1 && mrsArvRegimens.length != 1) { + hasCodes = false; + } else { + for (var i = 1; i < arvCodes.length; i++) { + var code = arvCodes[i]; + if (!hasCode(mrsArvRegimens, arvCodes[i])) { + hasCodes = false; + break; } - }); - return resolveId; - } - - const getArtRegimen = (rawPayload) => { - return hasEidCode ? getArtRegimenEidCode(rawPayload) : getArtRegimenOld(rawPayload); - } - - function getArtRegimenOld(rawPayload) { - if (rawPayload.artRegimenUuid === "" || rawPayload.artRegimenUuid === null) return 15; //15 is none; - - var arvCodes = rawPayload.artRegimenUuid ? rawPayload.artRegimenUuid.split(" ## ") : null; - var resolvedId = 16; // 14 is other - - if (!(arvCodes && arvCodes.length > 0)) return resolvedId; - - _.forEach(eidOrderMap.artRegimen, function (artRegimen) { - - var mrsArvRegimens = artRegimen.mrsArvRegimen.split(","); - - if (hasCode(mrsArvRegimens, arvCodes[0])) { - - var hasCodes = true; - - if (arvCodes.length === 1 && mrsArvRegimens.length != 1) { - - hasCodes = false; - } else { - - for (var i = 1; i < arvCodes.length; i++) { - - var code = arvCodes[i]; - if (!hasCode(mrsArvRegimens, arvCodes[i])) { - hasCodes = false; - break; - } - } - } + } + } - if (hasCodes) resolvedId = artRegimen.eidId; - } - }); + if (hasCodes) resolvedId = artRegimen.eidId; + } + }); - return resolvedId; - } + return resolvedId; + } - module.exports = { - generatePocToEidPayLoad: generatePocToEidPayLoad - }; + module.exports = { + generatePocToEidPayLoad: generatePocToEidPayLoad + }; })(); diff --git a/app/lab-integration/utils/regimen-config-loader.js b/app/lab-integration/utils/regimen-config-loader.js index f3c9d5888..3cba6065b 100644 --- a/app/lab-integration/utils/regimen-config-loader.js +++ b/app/lab-integration/utils/regimen-config-loader.js @@ -3,9 +3,8 @@ const eidOrderMapV2 = require('../../../service/eid/mappings/eid-order-mappings- const eidOrderMapv1 = require('../../../service/eid/mappings/eid-order-mappings-v1'); const version = require('../../../conf/eid-regimen-config'); - const currentConfig = version.eid_regimen_config[0]; const eidOrderMap = currentConfig.version === 1 ? eidOrderMapv1 : eidOrderMapV2; -module.exports = eidOrderMap; \ No newline at end of file +module.exports = eidOrderMap; diff --git a/app/ovc-report/ovc-indicator-definitions.json b/app/ovc-report/ovc-indicator-definitions.json index 0723707f7..38699c9d7 100644 --- a/app/ovc-report/ovc-indicator-definitions.json +++ b/app/ovc-report/ovc-indicator-definitions.json @@ -1,82 +1,82 @@ [ - { - "sectionTitle": "", - "indicators": [ - { - "label": "Location", - "indicator": "location" - } - ] - }, - { - "sectionTitle": "OVC in Hiv", - "indicators": [ - { - "label": "Active in Care", - "indicator": "active_in_care_this_month" - }, - { - "label": "Active in Care and Eligible for OVC", - "indicator": "active_and_eligible_for_ovc" - }, - { - "label": "Eligible and Enrolled in OVC", - "indicator": "enrolled_in_ovc_this_month" - }, - { - "label": "Eligible for OVC and NOT Enrolled", - "indicator": "ovc_non_enrolment_undocumented" - }, - { - "label": "Declined OVC Enrollment", - "indicator": "ovc_non_enrolment_declined" - }, - { - "label": "Out of OVC Catchment Area", - "indicator": "ovc_non_enrolment_out_of_catchment_area" - }, - { - "label": "Newly Exited this month", - "indicator": "newly_exited_from_ovc_this_month" - }, - { - "label": "Cumulative Exited", - "indicator": "exited_from_ovc_this_month" - } - ] - }, - { - "sectionTitle": "OVC in Hei", - "indicators": [ - { - "label": "Active and Eligible for OVC", - "indicator": "active_and_eligible_for_ovc_hei" - }, + { + "sectionTitle": "", + "indicators": [ + { + "label": "Location", + "indicator": "location" + } + ] + }, + { + "sectionTitle": "OVC in Hiv", + "indicators": [ + { + "label": "Active in Care", + "indicator": "active_in_care_this_month" + }, + { + "label": "Active in Care and Eligible for OVC", + "indicator": "active_and_eligible_for_ovc" + }, + { + "label": "Eligible and Enrolled in OVC", + "indicator": "enrolled_in_ovc_this_month" + }, + { + "label": "Eligible for OVC and NOT Enrolled", + "indicator": "ovc_non_enrolment_undocumented" + }, + { + "label": "Declined OVC Enrollment", + "indicator": "ovc_non_enrolment_declined" + }, + { + "label": "Out of OVC Catchment Area", + "indicator": "ovc_non_enrolment_out_of_catchment_area" + }, + { + "label": "Newly Exited this month", + "indicator": "newly_exited_from_ovc_this_month" + }, + { + "label": "Cumulative Exited", + "indicator": "exited_from_ovc_this_month" + } + ] + }, + { + "sectionTitle": "OVC in Hei", + "indicators": [ + { + "label": "Active and Eligible for OVC", + "indicator": "active_and_eligible_for_ovc_hei" + }, - { - "label": "Enrolled in OVC", - "indicator": "enrolled_in_ovc_this_month_hei" - }, - { - "label": "Eligible for OVC and NOT Enrolled", - "indicator": "ovc_non_enrolment_undocumented_hei" - }, - { - "label": "Declined OVC Enrollment", - "indicator": "ovc_non_enrolment_declined_hei" - }, - { - "label": "Out of Catchment Area", - "indicator": "ovc_non_enrolment_out_of_catchment_area_hei" - }, - { - "label": "Newly Exited this month", - "indicator": "newly_exited_from_ovc_this_month_hei" - }, - { - "label": "Cumulative Exited", - "indicator": "exited_from_ovc_this_month_hei" - } - ] - } -] \ No newline at end of file + { + "label": "Enrolled in OVC", + "indicator": "enrolled_in_ovc_this_month_hei" + }, + { + "label": "Eligible for OVC and NOT Enrolled", + "indicator": "ovc_non_enrolment_undocumented_hei" + }, + { + "label": "Declined OVC Enrollment", + "indicator": "ovc_non_enrolment_declined_hei" + }, + { + "label": "Out of Catchment Area", + "indicator": "ovc_non_enrolment_out_of_catchment_area_hei" + }, + { + "label": "Newly Exited this month", + "indicator": "newly_exited_from_ovc_this_month_hei" + }, + { + "label": "Cumulative Exited", + "indicator": "exited_from_ovc_this_month_hei" + } + ] + } +] diff --git a/app/ovc-report/ovc-monthly-summary.service.js b/app/ovc-report/ovc-monthly-summary.service.js index 94ce9db6f..da915f55b 100644 --- a/app/ovc-report/ovc-monthly-summary.service.js +++ b/app/ovc-report/ovc-monthly-summary.service.js @@ -1,144 +1,165 @@ -import { - MultiDatasetPatientlistReport -} from '../reporting-framework/multi-dataset-patientlist.report'; +import { MultiDatasetPatientlistReport } from '../reporting-framework/multi-dataset-patientlist.report'; import ReportProcessorHelpersService from '../reporting-framework/report-processor-helpers.service'; import { Promise } from 'bluebird'; import indicatorDefinitions from './ovc-indicator-definitions.json'; const Moment = require('moment'); const dao = require('../../etl-dao'); export class OvcMonthlySummary extends MultiDatasetPatientlistReport { - constructor(reportName, params) { - if (params.isAggregated) { - params.joinColumnParam = 'join_location'; - } - params.hivMonthlyDatasetSource = 'etl.hiv_monthly_report_dataset_v1_2'; - super(reportName, params) + constructor(reportName, params) { + if (params.isAggregated) { + params.joinColumnParam = 'join_location'; } + params.hivMonthlyDatasetSource = 'etl.hiv_monthly_report_dataset_v1_2'; + super(reportName, params); + } - generateAggregateReport(additionalParams) { - const that = this; - return new Promise((resolve, reject) => { - that.determineReportSourceTables() - .then((res) => { - super.generateReport(additionalParams) - .then((results) => { - if (additionalParams && additionalParams.type === 'patient-list') { - resolve(results); - } else { + generateAggregateReport(additionalParams) { + const that = this; + return new Promise((resolve, reject) => { + that + .determineReportSourceTables() + .then((res) => { + super + .generateReport(additionalParams) + .then((results) => { + if ( + additionalParams && + additionalParams.type === 'patient-list' + ) { + resolve(results); + } else { + let finalResult = []; + const reportProcessorHelpersService = new ReportProcessorHelpersService(); + for (let result of results) { + if ( + result.report && + result.report.reportSchemas && + result.report.reportSchemas.main && + result.report.reportSchemas.main.transFormDirectives + .joinColumn + ) { + finalResult = reportProcessorHelpersService.joinDataSets( + that.params[ + result.report.reportSchemas.main.transFormDirectives + .joinColumnParam + ] || + result.report.reportSchemas.main.transFormDirectives + .joinColumn, + finalResult, + result.results.results.results + ); + } + } - let finalResult = [] - const reportProcessorHelpersService = new ReportProcessorHelpersService(); - for (let result of results) { - if (result.report && result.report.reportSchemas && result.report.reportSchemas.main && - result.report.reportSchemas.main.transFormDirectives.joinColumn) { - finalResult = reportProcessorHelpersService - .joinDataSets(that.params[result.report.reportSchemas.main.transFormDirectives.joinColumnParam] || - result.report.reportSchemas.main.transFormDirectives.joinColumn, - finalResult, result.results.results.results); - - } - } - - resolve({ - queriesAndSchemas: results, - result: finalResult, - sectionDefinitions: indicatorDefinitions, - indicatorDefinitions: [] - }); - } - }) - .catch((error) => { - console.error('OvcReport generation error: ', error); - reject(error); - }); - }) - .catch((err) => { - console.error('OvcReport generation error: ', err); - reject(error); + resolve({ + queriesAndSchemas: results, + result: finalResult, + sectionDefinitions: indicatorDefinitions, + indicatorDefinitions: [] }); + } + }) + .catch((error) => { + console.error('OvcReport generation error: ', error); + reject(error); + }); + }) + .catch((err) => { + console.error('OvcReport generation error: ', err); + reject(error); }); - } - - generatePatientListReport(indicators) { - let self = this; - if (self.params.locationUuids) { - let locations = self.params.locations ? self.params.locations.split(',') : []; - self.params.locations = locations; - } - return new Promise((resolve, reject) => { - self.determineReportSourceTables() - .then((res) => { - super.generatePatientListReport(indicators) - .then((results) => { - - results.indicators = self.getIndicatorSectionDefinitions(results.indicators, - indicatorDefinitions); - self.resolveLocationUuidsToName(self.params.locationUuids) - .then((locations) => { - results.locations = locations; - delete results['allResults']; - resolve(results); - }) - .catch((err) => { - resolve(results); - }); + }); + } - }) - .catch((err) => { - console.error('Patient list generation error', err); - reject(err); - }); + generatePatientListReport(indicators) { + let self = this; + if (self.params.locationUuids) { + let locations = self.params.locations + ? self.params.locations.split(',') + : []; + self.params.locations = locations; + } + return new Promise((resolve, reject) => { + self + .determineReportSourceTables() + .then((res) => { + super + .generatePatientListReport(indicators) + .then((results) => { + results.indicators = self.getIndicatorSectionDefinitions( + results.indicators, + indicatorDefinitions + ); + self + .resolveLocationUuidsToName(self.params.locationUuids) + .then((locations) => { + results.locations = locations; + delete results['allResults']; + resolve(results); }) .catch((err) => { - console.error('Patient list generation error: ', err); - reject(err); - }); - }); - } - - getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { - let results = []; - _.each(requestIndicators, function (requestIndicator) { - _.each(sectionDefinitions, function (sectionDefinition) { - _.each(sectionDefinition.indicators, function (indicator) { - if (indicator.indicator === requestIndicator) { - results.push(indicator); - } + resolve(results); }); + }) + .catch((err) => { + console.error('Patient list generation error', err); + reject(err); }); + }) + .catch((err) => { + console.error('Patient list generation error: ', err); + reject(err); }); - return results; - } + }); + } - resolveLocationUuidsToName(uuids) { - return new Promise((resolve, reject) => { - dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { - resolve(loc); - }); + getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { + let results = []; + _.each(requestIndicators, function (requestIndicator) { + _.each(sectionDefinitions, function (sectionDefinition) { + _.each(sectionDefinition.indicators, function (indicator) { + if (indicator.indicator === requestIndicator) { + results.push(indicator); + } }); - } + }); + }); + return results; + } - determineReportSourceTables() { - const self = this; - return new Promise((resolve, reject) => { - let query = 'select * from etl.moh_731_last_release_month'; - let runner = self.getSqlRunner(); + resolveLocationUuidsToName(uuids) { + return new Promise((resolve, reject) => { + dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { + resolve(loc); + }); + }); + } - runner.executeQuery(query) - .then( - (results) => { - let lastReleasedMonth = results[0]['last_released_month']; - if (Moment(lastReleasedMonth).isSameOrAfter(Moment(self.params.endDate))) { - self.params.hivMonthlyDatasetSource = 'etl.hiv_monthly_report_dataset_frozen'; - } else { - self.params.hivMonthlyDatasetSource = 'etl.hiv_monthly_report_dataset_v1_2'; - } - resolve(self.params.hivMonthlyDatasetSource); - }) - .catch((error) => { - console.error('Error getting released report month:', error); - reject(error); - }); + determineReportSourceTables() { + const self = this; + return new Promise((resolve, reject) => { + let query = 'select * from etl.moh_731_last_release_month'; + let runner = self.getSqlRunner(); + + runner + .executeQuery(query) + .then((results) => { + let lastReleasedMonth = results[0]['last_released_month']; + if ( + Moment(lastReleasedMonth).isSameOrAfter(Moment(self.params.endDate)) + ) { + self.params.hivMonthlyDatasetSource = + 'etl.hiv_monthly_report_dataset_frozen'; + } else { + self.params.hivMonthlyDatasetSource = + 'etl.hiv_monthly_report_dataset_v1_2'; + } + resolve(self.params.hivMonthlyDatasetSource); + }) + .catch((error) => { + console.error('Error getting released report month:', error); + reject(error); }); - } -} \ No newline at end of file + }); + } +} diff --git a/app/reporting-framework/base-mysql.report.js b/app/reporting-framework/base-mysql.report.js index caba82337..0456ddd2b 100755 --- a/app/reporting-framework/base-mysql.report.js +++ b/app/reporting-framework/base-mysql.report.js @@ -1,9 +1,5 @@ -import { - Json2Sql -} from 'ampath-json2sql'; -import { - Promise -} from 'bluebird'; +import { Json2Sql } from 'ampath-json2sql'; +import { Promise } from 'bluebird'; import QueryService from '../database-access/query.service'; import ReportProcessorHelpersService from './report-processor-helpers.service'; @@ -118,7 +114,7 @@ import * as lung_cancer_patient_list_template from './json-reports/lung-cancer-p import * as differentiated_care_program_aggregate from './json-reports/differentiated-care-program-aggregate.json'; import * as differentiated_care_program_base from './json-reports/differentiated-care-program-base.json'; -import * as differentiated_care_weight_dataset from './json-reports/differentiated-care-weight-dataset.json' +import * as differentiated_care_weight_dataset from './json-reports/differentiated-care-weight-dataset.json'; // appointment adherence import * as appointment_adherence from './json-reports/retention-report/appointment-adherence.json'; @@ -149,13 +145,13 @@ import * as ltfu_surge_baseline_aggregate_report from './json-reports/ltfus-surg import * as prep_report_patient_list_template from './json-reports/prep-report-patient-list-template.json'; import * as hiv_latest_clinical_encounter_date_base from './json-reports/hiv-latest-clinical-encounter-date-base.json'; -import * as prep_monthly_summary from './json-reports/prep-monthly-summary.json' +import * as prep_monthly_summary from './json-reports/prep-monthly-summary.json'; import * as prep_monthly_summary_aggregate_report from './json-reports/prep-monthly-summary-aggregate.json'; import * as prep_monthly_summary_base_report from './json-reports/prep-monthly-summary-base.json'; import * as prep_monthly_populationtype_disaggregation from './json-reports/prep-monthly-population-type-disaggregation.json'; import * as prep_monthly_breastfeeding_disaggregation from './json-reports/prep-monthly-breastfeeding-disaggregation.json'; import * as prep_monthly_pregnancy_disaggregation from './json-reports/prep-monthly-pregnancy-disaggregation.json'; -import * as prep_monthly_newly_enrolled_breastfeeding_disaggregation from './json-reports/prep-monthly-newly-enrolled-breastfeeding-disaggregation.json'; +import * as prep_monthly_newly_enrolled_breastfeeding_disaggregation from './json-reports/prep-monthly-newly-enrolled-breastfeeding-disaggregation.json'; import * as prep_monthly_newly_enrolled_pregnancy_disaggregation from './json-reports/prep-monthly-newly-enrolled-pregnancy-disaggregation.json'; import * as prep_latest_clinical_encounter_date_base from './json-reports/prep_latest_clinical_encounter_date_base.json'; import * as moh_408 from './json-reports/moh-408.json'; @@ -190,698 +186,865 @@ import * as ovc_in_hei_dataset_aggregate from './json-reports/ovc-in-hei-dataset import * as ovc_patient_list_template from './json-reports/ovc-patient-list-template.json'; import * as ovc_in_hei_patient_list_template from './json-reports/ovc-in-hei-patient-list-template.json'; export class BaseMysqlReport { - constructor(reportName, params) { - this.reportName = reportName; - this.params = params; - } + constructor(reportName, params) { + this.reportName = reportName; + this.params = params; + } - generateReport() { - // 1. Fetch report schema - // 2. Generate report sql using json2sql - // 3. Execute sql statement using sql generator - const that = this; - return new Promise((resolve, error) => { - // fetch reports - that.fetchReportSchema(that.reportName) - .then((reportSchemas) => { - that.reportSchemas = reportSchemas; - // generate query - that.generateReportQuery(that.reportSchemas, that.params) - .then((sqlQuery) => { - // allow user to use 'null' as parameter values - sqlQuery = sqlQuery.replace(/\'null\'/g, "null"); + generateReport() { + // 1. Fetch report schema + // 2. Generate report sql using json2sql + // 3. Execute sql statement using sql generator + const that = this; + return new Promise((resolve, error) => { + // fetch reports + that + .fetchReportSchema(that.reportName) + .then((reportSchemas) => { + that.reportSchemas = reportSchemas; + // generate query + that + .generateReportQuery(that.reportSchemas, that.params) + .then((sqlQuery) => { + // allow user to use 'null' as parameter values + sqlQuery = sqlQuery.replace(/\'null\'/g, 'null'); - that.reportQuery = sqlQuery; - // run query - // console.log('Query', sqlQuery); - that.executeReportQuery(that.reportQuery) - .then((result) => { - return that.transFormResults(that.reportSchemas, result); - }) - .then((results) => { - that.queryResults = results; - - resolve({ - schemas: that.reportSchemas, - sqlQuery: that.reportQuery, - results: that.queryResults - }); - }) - .catch((err) => { - error(err); - }); + that.reportQuery = sqlQuery; + // run query + // console.log('Query', sqlQuery); + that + .executeReportQuery(that.reportQuery) + .then((result) => { + return that.transFormResults(that.reportSchemas, result); + }) + .then((results) => { + that.queryResults = results; - }) - .catch((err) => { - error(err); - }); + resolve({ + schemas: that.reportSchemas, + sqlQuery: that.reportQuery, + results: that.queryResults + }); }) .catch((err) => { - error(err); - }) + error(err); + }); + }) + .catch((err) => { + error(err); + }); + }) + .catch((err) => { + error(err); }); - } + }); + } - fetchReportSchema(reportName, version) { - return new Promise((resolve, reject) => { - switch (reportName) { - case 'MOH-731-greencard': - resolve({ - main: this.cloneJsonSchema(moh_731_greencard) - }); - break; - case 'MOH-731-bluecard': - resolve({ - main: this.cloneJsonSchema(moh_731_bluecard) - }); - break; - case 'patient-list-template': - resolve({ - main: this.cloneJsonSchema(patient_list_template) //patient_list_frozen_template - }); - break; - case 'patient-list-frozen-template': - resolve({ - main: this.cloneJsonSchema(patient_list_frozen_template) //patient_list_frozen_template - }); - break; - case 'patient-list-schedules-template': - resolve({ - main: this.cloneJsonSchema(patient_list_schedules_template) - }); - break; - case 'patient-list-with-contacts-template': - resolve({ - main: this.cloneJsonSchema(patient_list_with_contacts_template) - }); - break; - case 'prep-report-patient-list-template': - resolve({ - main: this.cloneJsonSchema(prep_report_patient_list_template) - }); - break; - case 'mainDatasetAggregate': - resolve({ - main: this.cloneJsonSchema(main_dataset_aggregate), - mainDataSetBase: this.cloneJsonSchema(main_dataset_base) - }); - break; - case 'mainDatasetAggregateBlueCard': - resolve({ - main: this.cloneJsonSchema(main_dataset_aggregate_blue_card), - mainDataSetBaseBlueCard: this.cloneJsonSchema(main_dataset_base_blue_card) - }); - break; - case 'regimenDataSetAggregate': - resolve({ - main: this.cloneJsonSchema(regimen_dataset_aggregate), - regimenDataSetbase: this.cloneJsonSchema(regimen_dataset_base) - }); - break; - case 'retentionDataSetAggregate': - resolve({ - main: this.cloneJsonSchema(retention_dataset_aggregate), - retentionDataSetbase: this.cloneJsonSchema(retention_dataset_base) - }); - break; - case 'mainDatasetAggregateAgeDisaggregation': - resolve({ - main: this.cloneJsonSchema(main_dataset_aggregate_age_disaggregation), - mainDataSetBase: this.cloneJsonSchema(main_dataset_base) - }); - break; - case 'mainDatasetAggregateNoDisaggregation': - resolve({ - main: this.cloneJsonSchema(main_dataset_aggregate_no_disaggregation), - mainDataSetBase: this.cloneJsonSchema(main_dataset_base) - }); - break; - case 'mainDatasetAggregateAge15Disaggregation': - resolve({ - main: this.cloneJsonSchema(main_dataset_aggregate_age15_disaggregation), - mainDataSetBaseAge15: this.cloneJsonSchema(main_dataset_base_age15) - }); - break; - case 'mainDatasetAggregateAge18Disaggregation': - resolve({ - main: this.cloneJsonSchema(main_dataset_aggregate_age18_disaggregation), - mainDataSetBaseAge18: this.cloneJsonSchema(main_dataset_base_age18) - }); - break; - case 'pepDatasetAggregate': - resolve({ - main: this.cloneJsonSchema(pep_dataset_aggregate), - pepDataSetbase: this.cloneJsonSchema(pep_dataset_base) - }); - break; - case 'hivMonthlySummaryReportAggregate': - resolve({ - main: this.cloneJsonSchema(hiv_monthly_summary_dataset_aggregation), - hivMonthlySummaryDataSetBase: this.cloneJsonSchema(hiv_monthly_summary_dataset_base) - }); - break; - case 'clinicComparatorAggregate': - resolve({ - main: this.cloneJsonSchema(clinic_comparator_aggregate), - clinicComparatorBase: this.cloneJsonSchema(clinic_comparator_base) - }); - break; - case 'dataEntryStatisticsAggregate': - resolve({ - main: this.cloneJsonSchema(dataentry_statistics_aggregate), - dataEntryStatistics: this.cloneJsonSchema(dataentry_statistics_base) - }); - break; - case 'hivSummaryBaseAggregate': - resolve({ - main: this.cloneJsonSchema(hiv_summary_aggregate), - hivSummaryBase: this.cloneJsonSchema(hiv_summary_base) - }); - break; - case 'patientFlow': - resolve({ - main: this.cloneJsonSchema(patient_flow) - }); - break; - case 'clinicHivComparativeOverviewAggregate': - resolve({ - main: this.cloneJsonSchema(clinical_hiv_comparative_overview_aggregate), - clinicHivComparativeOverviewBase: this.cloneJsonSchema(clinical_hiv_comparative_overview_base) - }); - break; - case 'clinicalArtOverviewAggregeate': - resolve({ - main: this.cloneJsonSchema(clinical_art_overview_aggregate), - clinicalArtOverviewBase: this.cloneJsonSchema(clinical_art_overview_base) - }); - break; - case 'dailyAppointmentsAggregate': - resolve({ - main: this.cloneJsonSchema(daily_appointments_aggregate), - dailyAppointmentsBase: this.cloneJsonSchema(daily_appointments_base), - dailyAppointmentlatestRtcCohortBase: this.cloneJsonSchema(daily_appointment_latest_rtc_cohort_base) - }); - break; - case 'dailyAttendanceAggregate': - resolve({ - main: this.cloneJsonSchema(daily_attendance_aggregate), - dailyAttendanceBase: this.cloneJsonSchema(daily_attendance_base) - }); - break; - case 'dailyHasNotReturnedAggregate': - resolve({ - main: this.cloneJsonSchema(daily_has_not_returned_aggregate), - dailyHasNotReturnedBase: this.cloneJsonSchema(daily_has_not_returned_base), - dailyHasNotReturnedCohort: this.cloneJsonSchema(daily_has_not_returned_cohort), - nextDrugPickupEncounterBase: this.cloneJsonSchema(next_drug_pickup_encounter_base) - }); - break; - case 'dailyHasNotReturnedCohort': - resolve({ - main: this.cloneJsonSchema(daily_has_not_returned_cohort) - }); - break; - case 'patintChangeStatusTrackerAggregate': - resolve({ - main: this.cloneJsonSchema(patint_change_status_tracker_aggregate), - patintChangeStatusTrackerDataSetbase: this.cloneJsonSchema(patint_change_status_tracker_base) - }); - break; - case 'everOnARTAggregate': - resolve({ - main: this.cloneJsonSchema(ever_on_art_aggregate), - everOnARTBase: this.cloneJsonSchema(ever_on_art_base) - }); - break; - case 'everOnARTDisaggregation': - resolve({ - main: this.cloneJsonSchema(ever_on_art_disaggregation), - everOnARTBase: this.cloneJsonSchema(ever_on_art_base) - }) - break; - case 'referral-patient-list-template': - resolve({ - main: this.cloneJsonSchema(referral_patient_list_template) - }); - break; - case 'patients-requiring-viral-load-template': - resolve({ - main: this.cloneJsonSchema(patients_requiring_viral_load_template) - }); - break; - case 'referralAggregate': - resolve({ - main: this.cloneJsonSchema(referral_aggregate), - referralDatasetbase: this.cloneJsonSchema(referral_dataset_base) - }); - break; - case 'referral-patient-peer-navigator-list': - resolve({ - main: this.cloneJsonSchema(referral_peer_aggregate), - referralDatasetbase: this.cloneJsonSchema(referral_patient_list_peer_base) - }); - break; - case 'StartingARTAggregationAge15': - resolve({ - main: this.cloneJsonSchema(starting_art_aggregation_age15), - StartingARTSetBaseAge15: this.cloneJsonSchema(starting_art_base_age15) - }); - break; - case 'StartingARTDisaggregationAge15': - resolve({ - main: this.cloneJsonSchema(starting_art_disaggregation_age15), - StartingARTSetBaseAge15: this.cloneJsonSchema(starting_art_base_age15) - }); - break; - case 'StartingARTAggregationAgeGreen': - resolve({ - main: this.cloneJsonSchema(starting_art_aggregation_age_green), - StartingARTSetBaseAgeGreen: this.cloneJsonSchema(starting_art_base_age_green) - }); - break; - case 'StartingARTDisaggregationAgeGreen': - resolve({ - main: this.cloneJsonSchema(starting_art_disaggregation_age_green), - StartingARTSetBaseAgeGreen: this.cloneJsonSchema(starting_art_base_age_green) - }); - break; - case 'StartingARTDisaggregationAgeOnlyGreen': - resolve({ - main: this.cloneJsonSchema(starting_art_disaggregation_age_only_green), - StartingARTSetBaseAgeGreen: this.cloneJsonSchema(starting_art_base_age_green) - }) - case 'medicalHistoryReport': - resolve({ - main: this.cloneJsonSchema(medical_history_dataset_base) + fetchReportSchema(reportName, version) { + return new Promise((resolve, reject) => { + switch (reportName) { + case 'MOH-731-greencard': + resolve({ + main: this.cloneJsonSchema(moh_731_greencard) + }); + break; + case 'MOH-731-bluecard': + resolve({ + main: this.cloneJsonSchema(moh_731_bluecard) + }); + break; + case 'patient-list-template': + resolve({ + main: this.cloneJsonSchema(patient_list_template) //patient_list_frozen_template + }); + break; + case 'patient-list-frozen-template': + resolve({ + main: this.cloneJsonSchema(patient_list_frozen_template) //patient_list_frozen_template + }); + break; + case 'patient-list-schedules-template': + resolve({ + main: this.cloneJsonSchema(patient_list_schedules_template) + }); + break; + case 'patient-list-with-contacts-template': + resolve({ + main: this.cloneJsonSchema(patient_list_with_contacts_template) + }); + break; + case 'prep-report-patient-list-template': + resolve({ + main: this.cloneJsonSchema(prep_report_patient_list_template) + }); + break; + case 'mainDatasetAggregate': + resolve({ + main: this.cloneJsonSchema(main_dataset_aggregate), + mainDataSetBase: this.cloneJsonSchema(main_dataset_base) + }); + break; + case 'mainDatasetAggregateBlueCard': + resolve({ + main: this.cloneJsonSchema(main_dataset_aggregate_blue_card), + mainDataSetBaseBlueCard: this.cloneJsonSchema( + main_dataset_base_blue_card + ) + }); + break; + case 'regimenDataSetAggregate': + resolve({ + main: this.cloneJsonSchema(regimen_dataset_aggregate), + regimenDataSetbase: this.cloneJsonSchema(regimen_dataset_base) + }); + break; + case 'retentionDataSetAggregate': + resolve({ + main: this.cloneJsonSchema(retention_dataset_aggregate), + retentionDataSetbase: this.cloneJsonSchema(retention_dataset_base) + }); + break; + case 'mainDatasetAggregateAgeDisaggregation': + resolve({ + main: this.cloneJsonSchema( + main_dataset_aggregate_age_disaggregation + ), + mainDataSetBase: this.cloneJsonSchema(main_dataset_base) + }); + break; + case 'mainDatasetAggregateNoDisaggregation': + resolve({ + main: this.cloneJsonSchema( + main_dataset_aggregate_no_disaggregation + ), + mainDataSetBase: this.cloneJsonSchema(main_dataset_base) + }); + break; + case 'mainDatasetAggregateAge15Disaggregation': + resolve({ + main: this.cloneJsonSchema( + main_dataset_aggregate_age15_disaggregation + ), + mainDataSetBaseAge15: this.cloneJsonSchema(main_dataset_base_age15) + }); + break; + case 'mainDatasetAggregateAge18Disaggregation': + resolve({ + main: this.cloneJsonSchema( + main_dataset_aggregate_age18_disaggregation + ), + mainDataSetBaseAge18: this.cloneJsonSchema(main_dataset_base_age18) + }); + break; + case 'pepDatasetAggregate': + resolve({ + main: this.cloneJsonSchema(pep_dataset_aggregate), + pepDataSetbase: this.cloneJsonSchema(pep_dataset_base) + }); + break; + case 'hivMonthlySummaryReportAggregate': + resolve({ + main: this.cloneJsonSchema(hiv_monthly_summary_dataset_aggregation), + hivMonthlySummaryDataSetBase: this.cloneJsonSchema( + hiv_monthly_summary_dataset_base + ) + }); + break; + case 'clinicComparatorAggregate': + resolve({ + main: this.cloneJsonSchema(clinic_comparator_aggregate), + clinicComparatorBase: this.cloneJsonSchema(clinic_comparator_base) + }); + break; + case 'dataEntryStatisticsAggregate': + resolve({ + main: this.cloneJsonSchema(dataentry_statistics_aggregate), + dataEntryStatistics: this.cloneJsonSchema(dataentry_statistics_base) + }); + break; + case 'hivSummaryBaseAggregate': + resolve({ + main: this.cloneJsonSchema(hiv_summary_aggregate), + hivSummaryBase: this.cloneJsonSchema(hiv_summary_base) + }); + break; + case 'patientFlow': + resolve({ + main: this.cloneJsonSchema(patient_flow) + }); + break; + case 'clinicHivComparativeOverviewAggregate': + resolve({ + main: this.cloneJsonSchema( + clinical_hiv_comparative_overview_aggregate + ), + clinicHivComparativeOverviewBase: this.cloneJsonSchema( + clinical_hiv_comparative_overview_base + ) + }); + break; + case 'clinicalArtOverviewAggregeate': + resolve({ + main: this.cloneJsonSchema(clinical_art_overview_aggregate), + clinicalArtOverviewBase: this.cloneJsonSchema( + clinical_art_overview_base + ) + }); + break; + case 'dailyAppointmentsAggregate': + resolve({ + main: this.cloneJsonSchema(daily_appointments_aggregate), + dailyAppointmentsBase: this.cloneJsonSchema( + daily_appointments_base + ), + dailyAppointmentlatestRtcCohortBase: this.cloneJsonSchema( + daily_appointment_latest_rtc_cohort_base + ) + }); + break; + case 'dailyAttendanceAggregate': + resolve({ + main: this.cloneJsonSchema(daily_attendance_aggregate), + dailyAttendanceBase: this.cloneJsonSchema(daily_attendance_base) + }); + break; + case 'dailyHasNotReturnedAggregate': + resolve({ + main: this.cloneJsonSchema(daily_has_not_returned_aggregate), + dailyHasNotReturnedBase: this.cloneJsonSchema( + daily_has_not_returned_base + ), + dailyHasNotReturnedCohort: this.cloneJsonSchema( + daily_has_not_returned_cohort + ), + nextDrugPickupEncounterBase: this.cloneJsonSchema( + next_drug_pickup_encounter_base + ) + }); + break; + case 'dailyHasNotReturnedCohort': + resolve({ + main: this.cloneJsonSchema(daily_has_not_returned_cohort) + }); + break; + case 'patintChangeStatusTrackerAggregate': + resolve({ + main: this.cloneJsonSchema(patint_change_status_tracker_aggregate), + patintChangeStatusTrackerDataSetbase: this.cloneJsonSchema( + patint_change_status_tracker_base + ) + }); + break; + case 'everOnARTAggregate': + resolve({ + main: this.cloneJsonSchema(ever_on_art_aggregate), + everOnARTBase: this.cloneJsonSchema(ever_on_art_base) + }); + break; + case 'everOnARTDisaggregation': + resolve({ + main: this.cloneJsonSchema(ever_on_art_disaggregation), + everOnARTBase: this.cloneJsonSchema(ever_on_art_base) + }); + break; + case 'referral-patient-list-template': + resolve({ + main: this.cloneJsonSchema(referral_patient_list_template) + }); + break; + case 'patients-requiring-viral-load-template': + resolve({ + main: this.cloneJsonSchema(patients_requiring_viral_load_template) + }); + break; + case 'referralAggregate': + resolve({ + main: this.cloneJsonSchema(referral_aggregate), + referralDatasetbase: this.cloneJsonSchema(referral_dataset_base) + }); + break; + case 'referral-patient-peer-navigator-list': + resolve({ + main: this.cloneJsonSchema(referral_peer_aggregate), + referralDatasetbase: this.cloneJsonSchema( + referral_patient_list_peer_base + ) + }); + break; + case 'StartingARTAggregationAge15': + resolve({ + main: this.cloneJsonSchema(starting_art_aggregation_age15), + StartingARTSetBaseAge15: this.cloneJsonSchema( + starting_art_base_age15 + ) + }); + break; + case 'StartingARTDisaggregationAge15': + resolve({ + main: this.cloneJsonSchema(starting_art_disaggregation_age15), + StartingARTSetBaseAge15: this.cloneJsonSchema( + starting_art_base_age15 + ) + }); + break; + case 'StartingARTAggregationAgeGreen': + resolve({ + main: this.cloneJsonSchema(starting_art_aggregation_age_green), + StartingARTSetBaseAgeGreen: this.cloneJsonSchema( + starting_art_base_age_green + ) + }); + break; + case 'StartingARTDisaggregationAgeGreen': + resolve({ + main: this.cloneJsonSchema(starting_art_disaggregation_age_green), + StartingARTSetBaseAgeGreen: this.cloneJsonSchema( + starting_art_base_age_green + ) + }); + break; + case 'StartingARTDisaggregationAgeOnlyGreen': + resolve({ + main: this.cloneJsonSchema( + starting_art_disaggregation_age_only_green + ), + StartingARTSetBaseAgeGreen: this.cloneJsonSchema( + starting_art_base_age_green + ) + }); + case 'medicalHistoryReport': + resolve({ + main: this.cloneJsonSchema(medical_history_dataset_base) + }); + break; + case 'breastCancerDailySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + breast_cancer_daily_screening_summary_aggregate + ), + breastCancerMonthlySummaryBase: this.cloneJsonSchema( + breast_cancer_monthly_screening_summary_base + ) + }); + case 'breastCancerMonthlySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + breast_cancer_monthly_screening_summary_aggregate + ), + breastCancerMonthlySummaryBase: this.cloneJsonSchema( + breast_cancer_monthly_screening_summary_base + ) + }); + break; + case 'lungCancerTreatmentMonthlySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + lung_cancer_treatment_monthly_summary_aggregate + ), + lungCancerTreatmentMonthlySummaryBase: this.cloneJsonSchema( + lung_cancer_treatment_monthly_summary_base + ) + }); + break; + case 'lungCancerTreatmentDailySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + lung_cancer_treatment_daily_summary_aggregate + ), + lungCancerTreatmentSummaryBase: this.cloneJsonSchema( + lung_cancer_treatment_summary_base + ) + }); + break; + case 'lung_cancer_treatment_patient_list_template': + resolve({ + main: this.cloneJsonSchema( + lung_cancer_treatment_patient_list_template + ) + }); + break; + case 'combinedBreastCervicalCancerDailySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + combined_breast_cervical_cancer_daily_screening_summary_aggregate + ), + combinedBreastCervicalCancerDailySummaryBase: this.cloneJsonSchema( + combined_breast_cervical_cancer_daily_screening_summary_base + ) + }); + case 'combinedBreastCervicalCancerMonthlySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + combined_breast_cervical_cancer_monthly_screening_summary_aggregate + ), + combinedBreastCervicalCancerMonthlySummaryBase: this.cloneJsonSchema( + combined_breast_cervical_cancer_monthly_screening_summary_base + ) + }); + break; + case 'breast_cancer_patient_list_template': + resolve({ + main: this.cloneJsonSchema(breast_cancer_patient_list_template) + }); + break; + case 'combined_breast_cervical_cancer_patient_list_template': + resolve({ + main: this.cloneJsonSchema( + combined_breast_cervical_cancer_patient_list_template + ) + }); + break; + case 'cervicalCancerDailySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + cervical_cancer_daily_screening_summary_aggregate + ), + cervicalCancerMonthlyReportBase: this.cloneJsonSchema( + cervical_cancer_monthly_screening_summary_base + ) + }); + case 'cervicalCancerMonthlySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + cervical_cancer_monthly_screening_summary_aggregate + ), + cervicalCancerMonthlyReportBase: this.cloneJsonSchema( + cervical_cancer_monthly_screening_summary_base + ) + }); + break; - }); - break; - case 'breastCancerDailySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(breast_cancer_daily_screening_summary_aggregate), - breastCancerMonthlySummaryBase: this.cloneJsonSchema(breast_cancer_monthly_screening_summary_base) - }); - case 'breastCancerMonthlySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(breast_cancer_monthly_screening_summary_aggregate), - breastCancerMonthlySummaryBase: this.cloneJsonSchema(breast_cancer_monthly_screening_summary_base) - }); - break; - case 'lungCancerTreatmentMonthlySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(lung_cancer_treatment_monthly_summary_aggregate), - lungCancerTreatmentMonthlySummaryBase: this.cloneJsonSchema(lung_cancer_treatment_monthly_summary_base) - }); - break; - case 'lungCancerTreatmentDailySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(lung_cancer_treatment_daily_summary_aggregate), - lungCancerTreatmentSummaryBase: this.cloneJsonSchema(lung_cancer_treatment_summary_base) - }); - break; - case 'lung_cancer_treatment_patient_list_template': - resolve({ - main: this.cloneJsonSchema(lung_cancer_treatment_patient_list_template) - }); - break; - case 'combinedBreastCervicalCancerDailySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(combined_breast_cervical_cancer_daily_screening_summary_aggregate), - combinedBreastCervicalCancerDailySummaryBase: this.cloneJsonSchema(combined_breast_cervical_cancer_daily_screening_summary_base) - }) - case 'combinedBreastCervicalCancerMonthlySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(combined_breast_cervical_cancer_monthly_screening_summary_aggregate), - combinedBreastCervicalCancerMonthlySummaryBase: this.cloneJsonSchema(combined_breast_cervical_cancer_monthly_screening_summary_base) - }); - break; - case 'breast_cancer_patient_list_template': - resolve({ - main: this.cloneJsonSchema(breast_cancer_patient_list_template) - }); - break; - case 'combined_breast_cervical_cancer_patient_list_template': - resolve({ - main: this.cloneJsonSchema(combined_breast_cervical_cancer_patient_list_template) - }); - break; - case 'cervicalCancerDailySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(cervical_cancer_daily_screening_summary_aggregate), - cervicalCancerMonthlyReportBase: this.cloneJsonSchema(cervical_cancer_monthly_screening_summary_base) - }); - case 'cervicalCancerMonthlySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(cervical_cancer_monthly_screening_summary_aggregate), - cervicalCancerMonthlyReportBase: this.cloneJsonSchema(cervical_cancer_monthly_screening_summary_base) - }); - break; + case 'lungCancerDailySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + lung_cancer_daily_screening_summary_aggregate + ), + lungCancerMonthlySummaryBase: this.cloneJsonSchema( + lung_cancer_monthly_screening_summary_base + ) + }); + case 'lungCancerMonthlySummaryAggregate': + resolve({ + main: this.cloneJsonSchema( + lung_cancer_monthly_screening_summary_aggregate + ), + lungCancerMonthlySummaryBase: this.cloneJsonSchema( + lung_cancer_monthly_screening_summary_base + ) + }); + break; + case 'lung_cancer_patient_list_template': + resolve({ + main: this.cloneJsonSchema(lung_cancer_patient_list_template) + }); + break; + case 'labsReportAggregate': + resolve({ + main: this.cloneJsonSchema(labs_report_aggregate), + labsReportBase: this.cloneJsonSchema(labs_report_base) + }); + break; + case 'patients-requiring-viral-load-template': + resolve({ + main: this.cloneJsonSchema(patients_requiring_viral_load_template) + }); + break; + case 'clinicLabOrdersReport': + resolve({ + main: this.cloneJsonSchema(clinic_lab_orders_report) + }); + break; + case 'cdmPatientSummary': + resolve({ + main: this.cloneJsonSchema(cdm_dataset_base) + }); + break; + case 'clinicalReminderReport': + resolve({ + main: this.cloneJsonSchema(clinical_reminders_report), + flatLabsAndImagingDataSetbase: this.cloneJsonSchema( + labs_and_imaging_dataset_base + ) + }); + break; + case 'enhancedAdherenceHIVProgramAggregate': + resolve({ + main: this.cloneJsonSchema( + enhanced_adherence_hiv_program_aggregate + ), + enhancedAdherenceHIVProgramBase: this.cloneJsonSchema( + enhanced_adherence_hiv_program_base + ), + patientProgramCohort: this.cloneJsonSchema(patient_program_cohort), + enhancedAdherenceHIVProgramCohort: this.cloneJsonSchema( + enhanced_adherence_hiv_program_cohort + ), + hivLatestClinicalEncounterDateBase: this.cloneJsonSchema( + hiv_latest_clinical_encounter_date_base + ) + }); + break; + case 'currentlyEnrolledPatientsAggregate': + resolve({ + main: this.cloneJsonSchema(currently_enrolled_patients_aggregate), + currentlyEnrolledPatientsBase: this.cloneJsonSchema( + currently_enrolled_patients_base + ) + }); + break; + case 'differentiatedCareProgramAggregate': + resolve({ + main: this.cloneJsonSchema(differentiated_care_program_aggregate), + differentiatedCareProgramBase: this.cloneJsonSchema( + differentiated_care_program_base + ), + hivLatestClinicalEncounterDateBase: this.cloneJsonSchema( + hiv_latest_clinical_encounter_date_base + ) + }); + break; + case 'surgeReport': + resolve({ + main: this.cloneJsonSchema(surge_report_aggregate), + surgeReport: this.cloneJsonSchema(surge_report_base) + }); + break; + case 'surgeDailyReport': + resolve({ + main: this.cloneJsonSchema(surge_daily_report_aggregate), + surgeDailyReport: this.cloneJsonSchema(surge_daily_report_base) + }); + break; + case 'prepReport': + resolve({ + main: this.cloneJsonSchema(prep_aggregate_report), + prepBaseReport: this.cloneJsonSchema(prep_base_report), + prepDatasetReport: this.cloneJsonSchema(prep_dataset_report) + }); + break; + case 'surgeBaselineReport': + resolve({ + main: this.cloneJsonSchema(ltfu_surge_baseline_aggregate_report), + surgeBaselineReport: this.cloneJsonSchema( + ltfu_surge_baseline_report + ) + }); + break; + case 'surge': + resolve({ + main: this.cloneJsonSchema(surge) + }); + break; + case 'retention-report': + resolve({ + main: this.cloneJsonSchema(appointment_adherence) + }); + break; + case 'retentionAppointmentAdherenceAggregate': + resolve({ + main: this.cloneJsonSchema( + retention_appointment_adherence_aggregate + ), + retentionAppointmentAdherenceBase: this.cloneJsonSchema( + retention_appointment_adherence_base + ) + }); + break; + case 'retentionDefaulterTracingAggregate': + resolve({ + main: this.cloneJsonSchema(retention_defaulter_tracing_aggregate), + retentionDefaulterTracingBase: this.cloneJsonSchema( + retention_defaulter_tracing_base + ) + }); + break; + case 'retentionVisitsAggregate': + resolve({ + main: this.cloneJsonSchema(retention_visits_aggregate), + retentionVisitsBase: this.cloneJsonSchema(retention_visits_base), + retentionInterventionCohort: this.cloneJsonSchema( + retention_intervention_cohort + ) + }); + break; + case 'retentionLtfuAggregate': + resolve({ + main: this.cloneJsonSchema(retention_ltfu_aggregate), + retentionLtfuBase: this.cloneJsonSchema(retention_ltfu_base) + }); + break; + case 'retention-report-patient-list-template': + resolve({ + main: this.cloneJsonSchema(retention_report_patient_list_template) + }); + break; + case 'prepMonthlySummaryReport': + resolve({ + main: this.cloneJsonSchema(prep_monthly_summary), + prepLatestClinicalEncounterDate: this.cloneJsonSchema( + prep_latest_clinical_encounter_date_base + ) + }); + break; + case 'prepMonthlySummaryNoDisaggregation': + resolve({ + main: this.cloneJsonSchema(prep_monthly_summary_aggregate_report), + prepMonthlySummaryBaseReport: this.cloneJsonSchema( + prep_monthly_summary_base_report + ), + prepLatestClinicalEncounterDate: this.cloneJsonSchema( + prep_latest_clinical_encounter_date_base + ) + }); + break; + case 'prepMonthlySummaryPopulationTypeDisaggregation': + resolve({ + main: this.cloneJsonSchema( + prep_monthly_populationtype_disaggregation + ), + prepMonthlySummaryBaseReport: this.cloneJsonSchema( + prep_monthly_summary_base_report + ), + prepLatestClinicalEncounterDate: this.cloneJsonSchema( + prep_latest_clinical_encounter_date_base + ) + }); + break; + case 'prepMonthlySummaryBreastFeedingDisaggregation': + resolve({ + main: this.cloneJsonSchema( + prep_monthly_breastfeeding_disaggregation + ), + prepMonthlySummaryBaseReport: this.cloneJsonSchema( + prep_monthly_summary_base_report + ), + prepLatestClinicalEncounterDate: this.cloneJsonSchema( + prep_latest_clinical_encounter_date_base + ) + }); + break; + case 'prepMonthlyNewlyEnrolledBreastFeedingDisaggregation': + resolve({ + main: this.cloneJsonSchema( + prep_monthly_newly_enrolled_breastfeeding_disaggregation + ), + prepMonthlySummaryBaseReport: this.cloneJsonSchema( + prep_monthly_summary_base_report + ), + prepLatestClinicalEncounterDate: this.cloneJsonSchema( + prep_latest_clinical_encounter_date_base + ) + }); + break; + case 'prepMonthlyNewlyEnrolledPregnancyDisaggregation': + resolve({ + main: this.cloneJsonSchema( + prep_monthly_newly_enrolled_pregnancy_disaggregation + ), + prepMonthlySummaryBaseReport: this.cloneJsonSchema( + prep_monthly_summary_base_report + ), + prepLatestClinicalEncounterDate: this.cloneJsonSchema( + prep_latest_clinical_encounter_date_base + ) + }); + break; + case 'prepMonthlySummaryPregnancyDisaggregation': + resolve({ + main: this.cloneJsonSchema(prep_monthly_pregnancy_disaggregation), + prepMonthlySummaryBaseReport: this.cloneJsonSchema( + prep_monthly_summary_base_report + ), + prepLatestClinicalEncounterDate: this.cloneJsonSchema( + prep_latest_clinical_encounter_date_base + ) + }); + break; + case 'MOH-408': + resolve({ + main: this.cloneJsonSchema(moh_408) + }); + break; + case 'heiInfantFeedingAggregate': + resolve({ + main: this.cloneJsonSchema(hei_infant_feeding_aggregate), + heiInfantFeedingBase: this.cloneJsonSchema(hei_infant_feeding_base) + }); + break; + case 'heiInfantFeedingNoDisaggregationAggregate': + resolve({ + main: this.cloneJsonSchema( + hei_infant_feeding_no_disaggregation_aggregate + ), + heiInfantFeedingNoDisaggregationBase: this.cloneJsonSchema( + hei_infant_feeding_no_disaggregation_base + ) + }); + break; + case 'heiInfantTestingAggregate': + resolve({ + main: this.cloneJsonSchema(hei_infant_testing_aggregate), + heiInfantTestingBase: this.cloneJsonSchema(hei_infant_testing_base) + }); + break; + case 'heiRetentionPairsAggregate': + resolve({ + main: this.cloneJsonSchema(hei_retention_pairs_aggregate), + heiRetentionPairsBase: this.cloneJsonSchema( + hei_retention_pairs_base + ) + }); + break; + case 'heiMotherAggregate': + resolve({ + main: this.cloneJsonSchema(hei_mother_aggregate), + heiMotherBase: this.cloneJsonSchema(hei_mother_base) + }); + break; + case 'heiProgramOutcomeAggregate': + resolve({ + main: this.cloneJsonSchema(hei_program_outcome_aggregate), + heiProgramOutcomeBase: this.cloneJsonSchema( + hei_program_outcome_base + ) + }); + break; + case 'heiUknownProgramOutcomeAggregate': + resolve({ + main: this.cloneJsonSchema(hei_unknown_program_outcome_aggregate), + heiUknownProgramOutcomeBase: this.cloneJsonSchema( + hei_unknown_program_outcome_base + ) + }); + break; + case 'heiOriginalCohortAggregate': + resolve({ + main: this.cloneJsonSchema(hei_original_cohort_aggregate), + heiOriginalCohortBase: this.cloneJsonSchema( + hei_original_cohort_base + ) + }); + break; + case 'hei-report-patient-list-template': + resolve({ + main: this.cloneJsonSchema(hei_report_patient_list_template) + }); + break; + case 'patientGainLoseAggregate': + resolve({ + main: this.cloneJsonSchema(patient_gain_loses_aggregate), + patientGainLosesBaseReport: this.cloneJsonSchema( + patient_gain_loses_base + ), + patientGainLoseDatasetOne: this.cloneJsonSchema( + patient_gain_lose_dataset_1 + ), + patientGainLoseDatasetTwo: this.cloneJsonSchema( + patient_gain_lose_dataset_2 + ) + }); + break; + case 'ovcReport': + resolve({ + main: this.cloneJsonSchema(ovc_report) + }); + case 'ovcInHivDatasetAggregate': + resolve({ + main: this.cloneJsonSchema(ovc_in_hiv_dataset_aggregate), + ovcInHivDatasetBase: this.cloneJsonSchema(ovc_in_hiv_dataset_base) + }); + case 'ovcInHeiDatasetAggregate': + resolve({ + main: this.cloneJsonSchema(ovc_in_hei_dataset_aggregate), + ovcInHeiDatasetBase: this.cloneJsonSchema(ovc_in_hei_dataset_base) + }); + case 'ovc-patient-list-template': + resolve({ + main: this.cloneJsonSchema(ovc_patient_list_template) + }); + break; + case 'ovc-in-hei-patient-list-template': + resolve({ + main: this.cloneJsonSchema(ovc_in_hei_patient_list_template) + }); + break; + default: + reject('Unknown report ', reportName); + break; + } + }); + } - case 'lungCancerDailySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(lung_cancer_daily_screening_summary_aggregate), - lungCancerMonthlySummaryBase: this.cloneJsonSchema(lung_cancer_monthly_screening_summary_base) - }); - case 'lungCancerMonthlySummaryAggregate': - resolve({ - main: this.cloneJsonSchema(lung_cancer_monthly_screening_summary_aggregate), - lungCancerMonthlySummaryBase: this.cloneJsonSchema(lung_cancer_monthly_screening_summary_base) - }); - break; - case 'lung_cancer_patient_list_template': - resolve({ - main: this.cloneJsonSchema(lung_cancer_patient_list_template) - }); - break; + generateReportQuery(reportSchemas, params) { + // console.log('Passed params', params) + // console.log('report schemas', JSON.stringify(reportSchemas, null, 4)); + let jSql = this.getJson2Sql(reportSchemas, params); + return new Promise((resolve, reject) => { + try { + resolve(jSql.generateSQL().toString()); + } catch (error) { + console.error('Error generating report sql statement', error); + reject('Encountered an unexpected error', error); + } + }); + } - case 'labsReportAggregate': - resolve({ - main: this.cloneJsonSchema(labs_report_aggregate), - labsReportBase: this.cloneJsonSchema(labs_report_base), - - }); - break; - case 'patients-requiring-viral-load-template': - resolve({ - main: this.cloneJsonSchema(patients_requiring_viral_load_template) - }); - break; - case 'clinicLabOrdersReport': - resolve({ - main: this.cloneJsonSchema(clinic_lab_orders_report) - }) - break; - case 'cdmPatientSummary': - resolve({ - main: this.cloneJsonSchema(cdm_dataset_base) - }); - break; - case 'clinicalReminderReport': - resolve({ - main: this.cloneJsonSchema(clinical_reminders_report), - flatLabsAndImagingDataSetbase: this.cloneJsonSchema(labs_and_imaging_dataset_base) - }); - break; - case 'enhancedAdherenceHIVProgramAggregate': - resolve({ - main: this.cloneJsonSchema(enhanced_adherence_hiv_program_aggregate), - enhancedAdherenceHIVProgramBase: this.cloneJsonSchema(enhanced_adherence_hiv_program_base), - patientProgramCohort: this.cloneJsonSchema(patient_program_cohort), - enhancedAdherenceHIVProgramCohort: this.cloneJsonSchema(enhanced_adherence_hiv_program_cohort), - hivLatestClinicalEncounterDateBase: this.cloneJsonSchema(hiv_latest_clinical_encounter_date_base) - }); - break; - case 'currentlyEnrolledPatientsAggregate': - resolve({ - main: this.cloneJsonSchema(currently_enrolled_patients_aggregate), - currentlyEnrolledPatientsBase: this.cloneJsonSchema(currently_enrolled_patients_base) - }); - break; - case 'differentiatedCareProgramAggregate': - resolve({ - main: this.cloneJsonSchema(differentiated_care_program_aggregate), - differentiatedCareProgramBase: this.cloneJsonSchema(differentiated_care_program_base), - hivLatestClinicalEncounterDateBase: this.cloneJsonSchema(hiv_latest_clinical_encounter_date_base) - - }); - break; - case 'surgeReport': - resolve({ - main: this.cloneJsonSchema(surge_report_aggregate), - surgeReport: this.cloneJsonSchema(surge_report_base) - }); - break; - case 'surgeDailyReport': - resolve({ - main: this.cloneJsonSchema(surge_daily_report_aggregate), - surgeDailyReport: this.cloneJsonSchema(surge_daily_report_base) - }); - break; - case 'prepReport': - resolve({ - main: this.cloneJsonSchema(prep_aggregate_report), - prepBaseReport: this.cloneJsonSchema(prep_base_report), - prepDatasetReport: this.cloneJsonSchema(prep_dataset_report), - }); - break; - case 'surgeBaselineReport': - resolve({ - main: this.cloneJsonSchema(ltfu_surge_baseline_aggregate_report), - surgeBaselineReport: this.cloneJsonSchema(ltfu_surge_baseline_report) - }); - break; - case 'surge': - resolve({ - main: this.cloneJsonSchema(surge) - }); - break; - case 'retention-report': - resolve({ - main: this.cloneJsonSchema(appointment_adherence) - }); - break; - case 'retentionAppointmentAdherenceAggregate': - resolve({ - main: this.cloneJsonSchema(retention_appointment_adherence_aggregate), - retentionAppointmentAdherenceBase: this.cloneJsonSchema(retention_appointment_adherence_base) - }); - break; - case 'retentionDefaulterTracingAggregate': - resolve({ - main: this.cloneJsonSchema(retention_defaulter_tracing_aggregate), - retentionDefaulterTracingBase: this.cloneJsonSchema(retention_defaulter_tracing_base) - }); - break; - case 'retentionVisitsAggregate': - resolve({ - main: this.cloneJsonSchema(retention_visits_aggregate), - retentionVisitsBase: this.cloneJsonSchema(retention_visits_base), - retentionInterventionCohort: this.cloneJsonSchema(retention_intervention_cohort), - }); - break; - case 'retentionLtfuAggregate': - resolve({ - main: this.cloneJsonSchema(retention_ltfu_aggregate), - retentionLtfuBase: this.cloneJsonSchema(retention_ltfu_base) - }); - break; - case 'retention-report-patient-list-template': - resolve({ - main: this.cloneJsonSchema(retention_report_patient_list_template) - }); - break; - case 'prepMonthlySummaryReport': - resolve({ - main: this.cloneJsonSchema(prep_monthly_summary), - prepLatestClinicalEncounterDate: this.cloneJsonSchema(prep_latest_clinical_encounter_date_base) - }); - break; - case 'prepMonthlySummaryNoDisaggregation': - resolve({ - main: this.cloneJsonSchema(prep_monthly_summary_aggregate_report), - prepMonthlySummaryBaseReport: this.cloneJsonSchema(prep_monthly_summary_base_report), - prepLatestClinicalEncounterDate: this.cloneJsonSchema(prep_latest_clinical_encounter_date_base) - }); - break; - case 'prepMonthlySummaryPopulationTypeDisaggregation': - resolve({ - main: this.cloneJsonSchema(prep_monthly_populationtype_disaggregation), - prepMonthlySummaryBaseReport: this.cloneJsonSchema(prep_monthly_summary_base_report), - prepLatestClinicalEncounterDate: this.cloneJsonSchema(prep_latest_clinical_encounter_date_base) - }); - break; - case 'prepMonthlySummaryBreastFeedingDisaggregation': - resolve({ - main: this.cloneJsonSchema(prep_monthly_breastfeeding_disaggregation), - prepMonthlySummaryBaseReport: this.cloneJsonSchema(prep_monthly_summary_base_report), - prepLatestClinicalEncounterDate: this.cloneJsonSchema(prep_latest_clinical_encounter_date_base) - }); - break; - case 'prepMonthlyNewlyEnrolledBreastFeedingDisaggregation': - resolve({ - main: this.cloneJsonSchema(prep_monthly_newly_enrolled_breastfeeding_disaggregation), - prepMonthlySummaryBaseReport: this.cloneJsonSchema(prep_monthly_summary_base_report), - prepLatestClinicalEncounterDate: this.cloneJsonSchema(prep_latest_clinical_encounter_date_base) - }); - break; - case 'prepMonthlyNewlyEnrolledPregnancyDisaggregation': - resolve({ - main: this.cloneJsonSchema(prep_monthly_newly_enrolled_pregnancy_disaggregation), - prepMonthlySummaryBaseReport: this.cloneJsonSchema(prep_monthly_summary_base_report), - prepLatestClinicalEncounterDate: this.cloneJsonSchema(prep_latest_clinical_encounter_date_base) - }); - break; - case 'prepMonthlySummaryPregnancyDisaggregation': - resolve({ - main: this.cloneJsonSchema(prep_monthly_pregnancy_disaggregation), - prepMonthlySummaryBaseReport: this.cloneJsonSchema(prep_monthly_summary_base_report), - prepLatestClinicalEncounterDate: this.cloneJsonSchema(prep_latest_clinical_encounter_date_base) - }); - break; - case 'MOH-408': - resolve({ - main: this.cloneJsonSchema(moh_408) - }); - break; - case 'heiInfantFeedingAggregate': - resolve({ - main: this.cloneJsonSchema(hei_infant_feeding_aggregate), - heiInfantFeedingBase: this.cloneJsonSchema(hei_infant_feeding_base) - }); - break; - case 'heiInfantFeedingNoDisaggregationAggregate': - resolve({ - main: this.cloneJsonSchema(hei_infant_feeding_no_disaggregation_aggregate), - heiInfantFeedingNoDisaggregationBase: this.cloneJsonSchema(hei_infant_feeding_no_disaggregation_base) - }); - break; - case 'heiInfantTestingAggregate': - resolve({ - main: this.cloneJsonSchema(hei_infant_testing_aggregate), - heiInfantTestingBase: this.cloneJsonSchema(hei_infant_testing_base) - }); - break; - case 'heiRetentionPairsAggregate': - resolve({ - main: this.cloneJsonSchema(hei_retention_pairs_aggregate), - heiRetentionPairsBase: this.cloneJsonSchema(hei_retention_pairs_base) - }); - break; - case 'heiMotherAggregate': - resolve({ - main: this.cloneJsonSchema(hei_mother_aggregate), - heiMotherBase: this.cloneJsonSchema(hei_mother_base) - }); - break; - case 'heiProgramOutcomeAggregate': - resolve({ - main: this.cloneJsonSchema(hei_program_outcome_aggregate), - heiProgramOutcomeBase: this.cloneJsonSchema(hei_program_outcome_base) - }); - break; - case 'heiUknownProgramOutcomeAggregate': - resolve({ - main: this.cloneJsonSchema(hei_unknown_program_outcome_aggregate), - heiUknownProgramOutcomeBase: this.cloneJsonSchema(hei_unknown_program_outcome_base) - }); - break; - case 'heiOriginalCohortAggregate': - resolve({ - main: this.cloneJsonSchema(hei_original_cohort_aggregate), - heiOriginalCohortBase: this.cloneJsonSchema(hei_original_cohort_base) - }); - break; - case 'hei-report-patient-list-template': - resolve({ - main: this.cloneJsonSchema(hei_report_patient_list_template) - }); - break; - case 'patientGainLoseAggregate': - resolve({ - main: this.cloneJsonSchema(patient_gain_loses_aggregate), - patientGainLosesBaseReport: this.cloneJsonSchema(patient_gain_loses_base), - patientGainLoseDatasetOne: this.cloneJsonSchema(patient_gain_lose_dataset_1), - patientGainLoseDatasetTwo: this.cloneJsonSchema(patient_gain_lose_dataset_2) - }); - break; - case 'ovcReport': - resolve({ - main: this.cloneJsonSchema(ovc_report) - }); - case 'ovcInHivDatasetAggregate': - resolve({ - main: this.cloneJsonSchema(ovc_in_hiv_dataset_aggregate), - ovcInHivDatasetBase: this.cloneJsonSchema(ovc_in_hiv_dataset_base) - }) - case 'ovcInHeiDatasetAggregate': - resolve({ - main: this.cloneJsonSchema(ovc_in_hei_dataset_aggregate), - ovcInHeiDatasetBase: this.cloneJsonSchema(ovc_in_hei_dataset_base) - }) - case 'ovc-patient-list-template': - resolve({ - main: this.cloneJsonSchema(ovc_patient_list_template) - }); - break; - case 'ovc-in-hei-patient-list-template': - resolve({ - main: this.cloneJsonSchema(ovc_in_hei_patient_list_template) - }) - break; - default: - reject('Unknown report ', reportName); - break; - } - - }); - } + getJson2Sql(reportSchemas, params) { + return new Json2Sql(reportSchemas.main, reportSchemas, params); + } - generateReportQuery(reportSchemas, params) { - // console.log('Passed params', params) - // console.log('report schemas', JSON.stringify(reportSchemas, null, 4)); - let jSql = this.getJson2Sql(reportSchemas, params); - return new Promise((resolve, reject) => { - try { - resolve(jSql.generateSQL().toString()); - } catch (error) { - console.error('Error generating report sql statement', error); - reject('Encountered an unexpected error', error); - } + executeReportQuery(sqlQuery) { + // console.log('Executing Query', sqlQuery); + let runner = this.getSqlRunner(); + return new Promise((resolve, reject) => { + runner + .executeQuery(sqlQuery) + .then((results) => { + resolve({ + results: results + }); + }) + .catch((error) => { + console.error('Error Executing Mysql Query', error); + reject(error); }); - } + }); + } + transFormResults(reportSchemas, result) { + return new Promise((resolve, reject) => { + try { + if ( + reportSchemas && + reportSchemas.main && + reportSchemas.main.transFormDirectives && + reportSchemas.main.transFormDirectives.disaggregationColumns && + reportSchemas.main.transFormDirectives.joinColumn + ) { + const reportProcessorHelpersService = new ReportProcessorHelpersService(); + let final = reportProcessorHelpersService.tranform(result.results, { + use: reportSchemas.main.transFormDirectives.disaggregationColumns, + skip: reportSchemas.main.transFormDirectives.skipColumns || [], + joinColumn: reportSchemas.main.transFormDirectives.joinColumn + }); + result.results = final; + } + resolve(result); + } catch (error) { + console.error(error); + reject(error); + // expected output: SyntaxError: unterminated string literal + // Note - error messages will vary depending on browser + } + }); + } - getJson2Sql(reportSchemas, params) { - return new Json2Sql(reportSchemas.main, reportSchemas, params); - } - - executeReportQuery(sqlQuery) { - // console.log('Executing Query', sqlQuery); - let runner = this.getSqlRunner(); - return new Promise((resolve, reject) => { - runner.executeQuery(sqlQuery) - .then((results) => { - resolve({ - results: results - }); - }) - .catch((error) => { - console.error('Error Executing Mysql Query', error); - reject(error) - }); - }); - } - - transFormResults(reportSchemas, result) { - return new Promise((resolve, reject) => { - try { - if (reportSchemas && reportSchemas.main && reportSchemas.main.transFormDirectives && - reportSchemas.main.transFormDirectives.disaggregationColumns && - reportSchemas.main.transFormDirectives.joinColumn) { - const reportProcessorHelpersService = new ReportProcessorHelpersService(); - let final = reportProcessorHelpersService.tranform(result.results, { - use: reportSchemas.main.transFormDirectives.disaggregationColumns, - skip: reportSchemas.main.transFormDirectives.skipColumns || [], - joinColumn: reportSchemas.main.transFormDirectives.joinColumn - }); - result.results = final; - } - resolve(result); - } catch (error) { - console.error(error); - reject(error); - // expected output: SyntaxError: unterminated string literal - // Note - error messages will vary depending on browser - } - }); - } - - getSqlRunner() { - return new QueryService(); - } + getSqlRunner() { + return new QueryService(); + } - cloneJsonSchema(schema) { - return JSON.parse(JSON.stringify(schema)); - } -} \ No newline at end of file + cloneJsonSchema(schema) { + return JSON.parse(JSON.stringify(schema)); + } +} diff --git a/app/reporting-framework/clinic-comparator.report.js b/app/reporting-framework/clinic-comparator.report.js index 2d21de45e..bd27c7b16 100644 --- a/app/reporting-framework/clinic-comparator.report.js +++ b/app/reporting-framework/clinic-comparator.report.js @@ -1,27 +1,28 @@ -import { - BaseMysqlReport -} from './base-mysql.report'; -import * as etlProcessors from '../../etl-processors.js' +import { BaseMysqlReport } from './base-mysql.report'; +import * as etlProcessors from '../../etl-processors.js'; export class ClinicComparatorReport extends BaseMysqlReport { - constructor(reportName, params) { - super(reportName, params); - } - generateReport() { - let that = this; - return super.generateReport().then(results=>{ - try { - let finalResult = etlProcessors.processClinicalComparator(that.params.indicators, - results.results.results,that.params.indicators); - let returneResult = {}; - returneResult.schemas = results.schemas; - returneResult.sqlQuery = results.sqlQuery; - returneResult.result = finalResult; - results = returneResult; - } catch (error) { - console.log('Error',error); - return error; - } - return results; - }); - } -} \ No newline at end of file + constructor(reportName, params) { + super(reportName, params); + } + generateReport() { + let that = this; + return super.generateReport().then((results) => { + try { + let finalResult = etlProcessors.processClinicalComparator( + that.params.indicators, + results.results.results, + that.params.indicators + ); + let returneResult = {}; + returneResult.schemas = results.schemas; + returneResult.sqlQuery = results.sqlQuery; + returneResult.result = finalResult; + results = returneResult; + } catch (error) { + console.log('Error', error); + return error; + } + return results; + }); + } +} diff --git a/app/reporting-framework/hei/moh-408.json b/app/reporting-framework/hei/moh-408.json index 22aef516a..94519e946 100644 --- a/app/reporting-framework/hei/moh-408.json +++ b/app/reporting-framework/hei/moh-408.json @@ -1,249 +1,242 @@ [ - { - "sectionTitle": "2.12 Infant Testing", - "indicators": [ - { - "label": "Initial PCR < 8wks", - "ref": "HV02-44", - "indicator": "initial_pcr_less_than_8_wks" - }, - { - "label": "Initial PCR >= 8wks-12mnths", - "ref": "HV02-45", - "indicator": "initial_pcr_8_wks_to_12_months" - }, - { - "label": "Initial PCR < 12 mnths_Total", - "ref": "HV02-46", - "indicator": "initial_pcr_less_than_12_months" - }, - { - "label": "Second PCR at 6 months", - "ref": "", - "indicator": "second_pcr_6_months" - }, - { - "label": "Third PCR at 12 months", - "ref": "", - "indicator": "third_pcr_12_months" - }, - { - "label": "Antibody at 18 months", - "ref": "", - "indicator": "antibody_at_18_months" - }, - { - "label": "Antibody post 18 months", - "ref": "", - "indicator": "antibody_post_18_months" - } - ] - }, - { - "sectionTitle": "2.13 Programme Outcomes", - "indicators": [ - { - "label": "Original Cohort", - "ref": "", - "indicator": "original_cohort" - }, - { - "label": "Transfer In", - "ref": "", - "indicator": "transfer_in" - }, - { - "label": "Transfer Out", - "ref": "", - "indicator": "transfer_out" - }, - { - "label": "Net Cohort HEI at 24 months", - "ref": "", - "indicator": "net_cohort_hei_24_months" - }, - { - "label": "Infected_24months", - "ref": "HV02-47", - "indicator": "infected_24_months" - }, - { - "label": "Uninfected_24months", - "ref": "HV02-48", - "indicator": "uninfected_24_months" - }, - { - "label": "Unknown_Outcome", - "ref": "HV02-49", - "indicator": "unknown_outcome" - } - - ] - }, - { - "sectionTitle": "Uknown Outcomes (Status at 24 months)", - "indicators": [ - { - "label": "LTFU", - "ref": "", - "indicator": "ltfu_uo" - }, - { - "label": "Uninfected Dead", - "ref": "", - "indicator": "uninfected_died_uo" - }, - { - "label": "Infected Dead", - "ref": "", - "indicator": "infected_died_uo" - }, - { - "label": "Still Breastfeeding", - "ref": "", - "indicator": "breastfeeding_uo" - } - ] - }, - { - "sectionTitle": "2.14 Retention of Baby-Mother Pairs at 24 months", - "indicators": [ - { - "label": "Original Baby-Mother pair", - "ref": "", - "indicator": "original_cohort_" - }, - { - "label": "Baby-Mother pair transferred out", - "ref": "", - "indicator": "transfer_out_" - }, - { - "label": "Baby-Mother pair transferred in", - "ref": "", - "indicator": "transfer_in_" - }, - { - "label": "Pair Net cohort", - "ref": "", - "indicator": "pair_net_cohort" - }, - { - "label": "INVALID", - "ref": "", - "indicator": "invalid" - } - - ] - }, - { - "sectionTitle": "Pair-Mother outcomes at 24 months", - "indicators": [ - { - "label": "Active pair", - "ref": "", - "indicator": "mother_baby_pairs_24_months_active" - }, - { - "label": "LTFU", - "ref": "", - "indicator": "ltfu_" - }, - { - "label": "DEAD_B", - "ref": "", - "indicator": "dead_b" - }, - { - "label": "DEAD_M", - "ref": "", - "indicator": "dead_m" - } - - ] - }, - { - "sectionTitle": "2.15 Infant Feeding for HIV+ mothers at 12 months", - "indicators": [ - { - "label": "EBF at 6 months", - "ref": "HV02-53", - "indicator": "EBF_at_6_months" - }, - { - "label": "ERF at 6 months", - "ref": "HV02-54", - "indicator": "ERF_at_6_months" - }, - { - "label": "MF at 6 months", - "ref": "HV02-55", - "indicator": "MF_at_6_months" - }, - { - "label": "BF at 12 months", - "ref": "HV02-56", - "indicator": "BF_at_12_months" - }, - { - "label": "Not BF at 12 months", - "ref": "HV02-57", - "indicator": "Not_BF_at_12_months" - } - - ] - }, - { - "sectionTitle": "2.15 Infant Feeding for HIV+ mothers at 24 months", - "indicators": [ - { - "label": "BF at 18 months", - "ref": "HV02-58", - "indicator": "BF_at_18_months" - }, - { - "label": "Not BF at 18 months", - "ref": "HV02-59", - "indicator": "Not_BF_at_18_months" - } - - ] - }, - { - "sectionTitle": "HIV Status at 24 months", - "indicators": [ - { - "label": "IBF at 24 months", - "ref": "", - "indicator": "dc__status__infected__age_range__24_months__BF" - }, - { - "label": "IBFn at 24 months", - "ref": "", - "indicator": "dc__status__infected__age_range__24_months__Not_BF" - }, - { - "label": "IBFu at 24 months", - "ref": "", - "indicator": "dc__status__infected__age_range__24_months__unknown" - }, - { - "label": "UBF at 24 months", - "ref": "", - "indicator": "dc__status__uninfected__age_range__24_months__BF" - }, - { - "label": "UBFn at 24 months", - "ref": "", - "indicator": "dc__status__uninfected__age_range__24_months__Not_BF" - }, - { - "label": "UBFu at 24 months", - "ref": "", - "indicator": "dc__status__uninfected__age_range__24_months__unknown" - } - - ] - } - + { + "sectionTitle": "2.12 Infant Testing", + "indicators": [ + { + "label": "Initial PCR < 8wks", + "ref": "HV02-44", + "indicator": "initial_pcr_less_than_8_wks" + }, + { + "label": "Initial PCR >= 8wks-12mnths", + "ref": "HV02-45", + "indicator": "initial_pcr_8_wks_to_12_months" + }, + { + "label": "Initial PCR < 12 mnths_Total", + "ref": "HV02-46", + "indicator": "initial_pcr_less_than_12_months" + }, + { + "label": "Second PCR at 6 months", + "ref": "", + "indicator": "second_pcr_6_months" + }, + { + "label": "Third PCR at 12 months", + "ref": "", + "indicator": "third_pcr_12_months" + }, + { + "label": "Antibody at 18 months", + "ref": "", + "indicator": "antibody_at_18_months" + }, + { + "label": "Antibody post 18 months", + "ref": "", + "indicator": "antibody_post_18_months" + } + ] + }, + { + "sectionTitle": "2.13 Programme Outcomes", + "indicators": [ + { + "label": "Original Cohort", + "ref": "", + "indicator": "original_cohort" + }, + { + "label": "Transfer In", + "ref": "", + "indicator": "transfer_in" + }, + { + "label": "Transfer Out", + "ref": "", + "indicator": "transfer_out" + }, + { + "label": "Net Cohort HEI at 24 months", + "ref": "", + "indicator": "net_cohort_hei_24_months" + }, + { + "label": "Infected_24months", + "ref": "HV02-47", + "indicator": "infected_24_months" + }, + { + "label": "Uninfected_24months", + "ref": "HV02-48", + "indicator": "uninfected_24_months" + }, + { + "label": "Unknown_Outcome", + "ref": "HV02-49", + "indicator": "unknown_outcome" + } + ] + }, + { + "sectionTitle": "Uknown Outcomes (Status at 24 months)", + "indicators": [ + { + "label": "LTFU", + "ref": "", + "indicator": "ltfu_uo" + }, + { + "label": "Uninfected Dead", + "ref": "", + "indicator": "uninfected_died_uo" + }, + { + "label": "Infected Dead", + "ref": "", + "indicator": "infected_died_uo" + }, + { + "label": "Still Breastfeeding", + "ref": "", + "indicator": "breastfeeding_uo" + } + ] + }, + { + "sectionTitle": "2.14 Retention of Baby-Mother Pairs at 24 months", + "indicators": [ + { + "label": "Original Baby-Mother pair", + "ref": "", + "indicator": "original_cohort_" + }, + { + "label": "Baby-Mother pair transferred out", + "ref": "", + "indicator": "transfer_out_" + }, + { + "label": "Baby-Mother pair transferred in", + "ref": "", + "indicator": "transfer_in_" + }, + { + "label": "Pair Net cohort", + "ref": "", + "indicator": "pair_net_cohort" + }, + { + "label": "INVALID", + "ref": "", + "indicator": "invalid" + } + ] + }, + { + "sectionTitle": "Pair-Mother outcomes at 24 months", + "indicators": [ + { + "label": "Active pair", + "ref": "", + "indicator": "mother_baby_pairs_24_months_active" + }, + { + "label": "LTFU", + "ref": "", + "indicator": "ltfu_" + }, + { + "label": "DEAD_B", + "ref": "", + "indicator": "dead_b" + }, + { + "label": "DEAD_M", + "ref": "", + "indicator": "dead_m" + } + ] + }, + { + "sectionTitle": "2.15 Infant Feeding for HIV+ mothers at 12 months", + "indicators": [ + { + "label": "EBF at 6 months", + "ref": "HV02-53", + "indicator": "EBF_at_6_months" + }, + { + "label": "ERF at 6 months", + "ref": "HV02-54", + "indicator": "ERF_at_6_months" + }, + { + "label": "MF at 6 months", + "ref": "HV02-55", + "indicator": "MF_at_6_months" + }, + { + "label": "BF at 12 months", + "ref": "HV02-56", + "indicator": "BF_at_12_months" + }, + { + "label": "Not BF at 12 months", + "ref": "HV02-57", + "indicator": "Not_BF_at_12_months" + } + ] + }, + { + "sectionTitle": "2.15 Infant Feeding for HIV+ mothers at 24 months", + "indicators": [ + { + "label": "BF at 18 months", + "ref": "HV02-58", + "indicator": "BF_at_18_months" + }, + { + "label": "Not BF at 18 months", + "ref": "HV02-59", + "indicator": "Not_BF_at_18_months" + } + ] + }, + { + "sectionTitle": "HIV Status at 24 months", + "indicators": [ + { + "label": "IBF at 24 months", + "ref": "", + "indicator": "dc__status__infected__age_range__24_months__BF" + }, + { + "label": "IBFn at 24 months", + "ref": "", + "indicator": "dc__status__infected__age_range__24_months__Not_BF" + }, + { + "label": "IBFu at 24 months", + "ref": "", + "indicator": "dc__status__infected__age_range__24_months__unknown" + }, + { + "label": "UBF at 24 months", + "ref": "", + "indicator": "dc__status__uninfected__age_range__24_months__BF" + }, + { + "label": "UBFn at 24 months", + "ref": "", + "indicator": "dc__status__uninfected__age_range__24_months__Not_BF" + }, + { + "label": "UBFu at 24 months", + "ref": "", + "indicator": "dc__status__uninfected__age_range__24_months__unknown" + } + ] + } ] diff --git a/app/reporting-framework/hiv/case-management-indicators.json b/app/reporting-framework/hiv/case-management-indicators.json index 7010c6bd0..b25b29dea 100644 --- a/app/reporting-framework/hiv/case-management-indicators.json +++ b/app/reporting-framework/hiv/case-management-indicators.json @@ -1,54 +1,54 @@ { "indicators": [ - { - "label": "Due For Viral Load", - "name": "due_for_vl", - "description": "Patients who are due for a Viral Load test." - }, - { - "label": "Elevatated VL", - "name": "elevated_vl", - "description": "Patients with Viral Load greater than 1000." - }, - { - "label": "Case manager", - "name": "case_manager", - "description": "A person who assists in the planning, coordination, monitoring, and evaluation of medical services for a patient with emphasis on quality of care, continuity of services, and cost-effectiveness." - }, - { - "label": "Has case manager", - "name": "has_case_manager", - "description": "Patients who have been assigned a case manager to provide clinical support." - }, - { - "label": "Has Phone RTC", - "name": "has_phone_rtc", - "description": "Patients who have been given a phone follow up date" - }, - { - "label": "RTC Date", - "name": "rtc_date", - "description": "The return to clinic date" - }, - { - "label": "Phone Follow up date", - "name": "phone_follow_up_date", - "description": "The date a patient is scheduled to be followed up via phone" - }, - { - "label": "Days since follow up", - "name": "days_since_follow_up", - "description": "The number of days since the patient's last encounter." - }, - { - "label": "Days since missed appointment", - "name": "days_since_missed_appointment", - "description": "The Number of days a Client has missed coming to Clinic since their last Return to Clinic Date." - }, - { - "label": "Newly Enrolled", - "name": "newly_enrolled", - "description": "Patients who have been enrolled 30 days or less from current date." - } + { + "label": "Due For Viral Load", + "name": "due_for_vl", + "description": "Patients who are due for a Viral Load test." + }, + { + "label": "Elevatated VL", + "name": "elevated_vl", + "description": "Patients with Viral Load greater than 1000." + }, + { + "label": "Case manager", + "name": "case_manager", + "description": "A person who assists in the planning, coordination, monitoring, and evaluation of medical services for a patient with emphasis on quality of care, continuity of services, and cost-effectiveness." + }, + { + "label": "Has case manager", + "name": "has_case_manager", + "description": "Patients who have been assigned a case manager to provide clinical support." + }, + { + "label": "Has Phone RTC", + "name": "has_phone_rtc", + "description": "Patients who have been given a phone follow up date" + }, + { + "label": "RTC Date", + "name": "rtc_date", + "description": "The return to clinic date" + }, + { + "label": "Phone Follow up date", + "name": "phone_follow_up_date", + "description": "The date a patient is scheduled to be followed up via phone" + }, + { + "label": "Days since follow up", + "name": "days_since_follow_up", + "description": "The number of days since the patient's last encounter." + }, + { + "label": "Days since missed appointment", + "name": "days_since_missed_appointment", + "description": "The Number of days a Client has missed coming to Clinic since their last Return to Clinic Date." + }, + { + "label": "Newly Enrolled", + "name": "newly_enrolled", + "description": "Patients who have been enrolled 30 days or less from current date." + } ] -} \ No newline at end of file +} diff --git a/app/reporting-framework/hiv/cbhip-indicator-definitions.json b/app/reporting-framework/hiv/cbhip-indicator-definitions.json index 6284c0600..a64c35e01 100644 --- a/app/reporting-framework/hiv/cbhip-indicator-definitions.json +++ b/app/reporting-framework/hiv/cbhip-indicator-definitions.json @@ -1,123 +1,122 @@ [ - { - "sectionTitle": "Cross Border Patients", - "indicators": [ - { - "label": "Cross Border Patients", - "ref": "HV06-013", - "indicator": "is_cross_border_this_month" - }, - { - "label": "Uganda", - "ref": "HV06-014", - "indicator": "is_cross_border_this_month_uganda" - }, - { - "label": "Kenya", - "ref": "HV06-013", - "indicator": "is_cross_border_this_month_kenya" - }, - { - "label": "Other Countries", - "ref": "HV06-013", - "indicator": "is_cross_border_this_month_other" - } - ] - }, - { - "sectionTitle": "International Travels", - "indicators": [ - { - "label": "Last 3 months", - "ref": "HV06-03", - "indicator": "travelled_outside_last_3_months" - }, - { - "label": "Last 6 months", - "ref": "HV06-04", - "indicator": "travelled_outside_last_6_months" - }, - { - "label": "Last 12 months", - "ref": "HV06-05", - "indicator": "travelled_outside_last_12_months" - } - ] - }, - { - "sectionTitle": "HIV Cascade", - "indicators": [ - { - "label": "Currently on ART", - "ref": "HV06-06", - "indicator": "is_cross_border_on_art_this_month" - }, - { - "label": "On ART at 12 months", - "ref": "HV06-06", - "indicator": "is_cross_border_active_on_art_12_month_cohort_this_month" - }, - { - "label": "Viral load < 1000 at 12 months", - "ref": "HV06-07", - "indicator": "is_cross_border_vl_suppressed_this_month" - } - - ] - }, - { - "sectionTitle": "TB Cascade", - "indicators": [ - { - "label": "On Tb Tx", - "ref": "HV06-11", - "indicator": "is_cross_border_on_tb_tx_this_month" - }, - { - "label": "Presumed TB positive", - "ref": "HV06-09", - "indicator": "is_cross_border_presumed_tb_positive_this_month" - }, - { - "label": "Started Tb Tx this month", - "ref": "HV06-10", - "indicator": "is_cross_border_started_tb_tx_this_month" - }, - { - "label": "Completed Tb Tx", - "ref": "HV06-015", - "indicator": "is_cross_border_completed_tb_tx" - }, - { - "label": "Stopped Tb Tx", - "ref": "HV06-016", - "indicator": "is_cross_border_stopped_tb_tx" - }, - { - "label": "On Tb Tx and Transferred Out", - "ref": "HV06-017", - "indicator": "is_cross_border_on_tb_tx_transferred_out" - }, - { - "label": "On Tb Tx and Turned LTFU", - "ref": "HV06-018", - "indicator": "is_cross_border_on_tb_tx_ltfu" - }, - { - "label": "On Tb Tx and Died", - "ref": "HV06-019", - "indicator": "is_cross_border_on_tb_tx_dead" - } - ] - }, - { - "sectionTitle": "FP/RH and MNCH", - "indicators": [ - { - "label": "On Modern Contraception", - "ref": "HV06-12", - "indicator": "is_cross_border_on_modern_contraception_this_month" - } - ] - } + { + "sectionTitle": "Cross Border Patients", + "indicators": [ + { + "label": "Cross Border Patients", + "ref": "HV06-013", + "indicator": "is_cross_border_this_month" + }, + { + "label": "Uganda", + "ref": "HV06-014", + "indicator": "is_cross_border_this_month_uganda" + }, + { + "label": "Kenya", + "ref": "HV06-013", + "indicator": "is_cross_border_this_month_kenya" + }, + { + "label": "Other Countries", + "ref": "HV06-013", + "indicator": "is_cross_border_this_month_other" + } + ] + }, + { + "sectionTitle": "International Travels", + "indicators": [ + { + "label": "Last 3 months", + "ref": "HV06-03", + "indicator": "travelled_outside_last_3_months" + }, + { + "label": "Last 6 months", + "ref": "HV06-04", + "indicator": "travelled_outside_last_6_months" + }, + { + "label": "Last 12 months", + "ref": "HV06-05", + "indicator": "travelled_outside_last_12_months" + } + ] + }, + { + "sectionTitle": "HIV Cascade", + "indicators": [ + { + "label": "Currently on ART", + "ref": "HV06-06", + "indicator": "is_cross_border_on_art_this_month" + }, + { + "label": "On ART at 12 months", + "ref": "HV06-06", + "indicator": "is_cross_border_active_on_art_12_month_cohort_this_month" + }, + { + "label": "Viral load < 1000 at 12 months", + "ref": "HV06-07", + "indicator": "is_cross_border_vl_suppressed_this_month" + } + ] + }, + { + "sectionTitle": "TB Cascade", + "indicators": [ + { + "label": "On Tb Tx", + "ref": "HV06-11", + "indicator": "is_cross_border_on_tb_tx_this_month" + }, + { + "label": "Presumed TB positive", + "ref": "HV06-09", + "indicator": "is_cross_border_presumed_tb_positive_this_month" + }, + { + "label": "Started Tb Tx this month", + "ref": "HV06-10", + "indicator": "is_cross_border_started_tb_tx_this_month" + }, + { + "label": "Completed Tb Tx", + "ref": "HV06-015", + "indicator": "is_cross_border_completed_tb_tx" + }, + { + "label": "Stopped Tb Tx", + "ref": "HV06-016", + "indicator": "is_cross_border_stopped_tb_tx" + }, + { + "label": "On Tb Tx and Transferred Out", + "ref": "HV06-017", + "indicator": "is_cross_border_on_tb_tx_transferred_out" + }, + { + "label": "On Tb Tx and Turned LTFU", + "ref": "HV06-018", + "indicator": "is_cross_border_on_tb_tx_ltfu" + }, + { + "label": "On Tb Tx and Died", + "ref": "HV06-019", + "indicator": "is_cross_border_on_tb_tx_dead" + } + ] + }, + { + "sectionTitle": "FP/RH and MNCH", + "indicators": [ + { + "label": "On Modern Contraception", + "ref": "HV06-12", + "indicator": "is_cross_border_on_modern_contraception_this_month" + } + ] + } ] diff --git a/app/reporting-framework/hiv/hiv-summary-indicators.service.js b/app/reporting-framework/hiv/hiv-summary-indicators.service.js index e3a90a190..dd47d69da 100755 --- a/app/reporting-framework/hiv/hiv-summary-indicators.service.js +++ b/app/reporting-framework/hiv/hiv-summary-indicators.service.js @@ -1,127 +1,143 @@ -import { - BaseMysqlReport -} from '../base-mysql.report'; -import { - PatientlistMysqlReport -} from '../patientlist-mysql.report'; -import { - IndicatorDefinitionService -} from './indicator-definition.service'; +import { BaseMysqlReport } from '../base-mysql.report'; +import { PatientlistMysqlReport } from '../patientlist-mysql.report'; +import { IndicatorDefinitionService } from './indicator-definition.service'; const dao = require('../../../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); export class HivSummaryIndicatorsService { - - composite_indicators ={ - 'perc_virally_suppressed_in_past_year': { - childIndictors: ['virally_suppressed_in_past_year', 'viral_load_resulted_in_past_year'], - patientlistIndicator: 'virally_suppressed_in_past_year' - }, - 'perc_not_virally_suppressed_in_past_year': { - childIndictors: ['not_virally_suppressed_in_past_year', 'viral_load_resulted_in_past_year'], - patientlistIndicator: 'not_virally_suppressed_in_past_year' - }, - 'perc_on_arvs': { - childIndictors: ['on_arvs'], - patientlistIndicator: 'on_arvs' - }, - 'perc_on_arv_first_line': { - childIndictors: ['on_arvs_first_line', 'on_arvs'], - patientlistIndicator: 'on_arvs_first_line' - }, - 'perc_on_arv_second_line': { - childIndictors: ['on_arvs_second_line', 'on_arvs'], - patientlistIndicator: 'on_arvs_second_line' - }, - 'perc_on_arv_third_line': { - childIndictors: ['on_arvs_third_line', 'on_arvs'], - patientlistIndicator: 'on_arvs_third_line' - }, - 'perc_with_pending_viral_load': { - childIndictors: ['pending_vl_order', 'on_arvs'], - patientlistIndicator: 'pending_vl_order' - }, - 'perc_on_arvs_lte_6_months': { - childIndictors: ['on_arvs_lte_26_weeks', 'on_arvs'], - patientlistIndicator: 'on_arvs_lte_26_weeks' - }, - 'perc_on_arvs_gt_6_months': { - childIndictors: ['on_arvs_gt_26_weeks', 'on_arvs'], - patientlistIndicator: 'on_arvs_gt_26_weeks' - } + composite_indicators = { + perc_virally_suppressed_in_past_year: { + childIndictors: [ + 'virally_suppressed_in_past_year', + 'viral_load_resulted_in_past_year' + ], + patientlistIndicator: 'virally_suppressed_in_past_year' + }, + perc_not_virally_suppressed_in_past_year: { + childIndictors: [ + 'not_virally_suppressed_in_past_year', + 'viral_load_resulted_in_past_year' + ], + patientlistIndicator: 'not_virally_suppressed_in_past_year' + }, + perc_on_arvs: { + childIndictors: ['on_arvs'], + patientlistIndicator: 'on_arvs' + }, + perc_on_arv_first_line: { + childIndictors: ['on_arvs_first_line', 'on_arvs'], + patientlistIndicator: 'on_arvs_first_line' + }, + perc_on_arv_second_line: { + childIndictors: ['on_arvs_second_line', 'on_arvs'], + patientlistIndicator: 'on_arvs_second_line' + }, + perc_on_arv_third_line: { + childIndictors: ['on_arvs_third_line', 'on_arvs'], + patientlistIndicator: 'on_arvs_third_line' + }, + perc_with_pending_viral_load: { + childIndictors: ['pending_vl_order', 'on_arvs'], + patientlistIndicator: 'pending_vl_order' + }, + perc_on_arvs_lte_6_months: { + childIndictors: ['on_arvs_lte_26_weeks', 'on_arvs'], + patientlistIndicator: 'on_arvs_lte_26_weeks' + }, + perc_on_arvs_gt_6_months: { + childIndictors: ['on_arvs_gt_26_weeks', 'on_arvs'], + patientlistIndicator: 'on_arvs_gt_26_weeks' } + }; - getAggregateReport(reportParams) { - let self = this; - reportParams.groupBy = 'groupByLocation'; - reportParams.countBy = 'num_persons'; - let params = reportParams.requestParams; + getAggregateReport(reportParams) { + let self = this; + reportParams.groupBy = 'groupByLocation'; + reportParams.countBy = 'num_persons'; + let params = reportParams.requestParams; - if (params.indicators) { - let indicators = params.indicators.split(','); - let columnWhitelist = indicators.concat(['location_id','location_uuid', 'month', 'location', 'encounter_datetime', 'person_id']); + if (params.indicators) { + let indicators = params.indicators.split(','); + let columnWhitelist = indicators.concat([ + 'location_id', + 'location_uuid', + 'month', + 'location', + 'encounter_datetime', + 'person_id' + ]); - columnWhitelist = this.addDerivateIndicatorsForPercIndicators(columnWhitelist); - params.columnWhitelist = columnWhitelist; + columnWhitelist = this.addDerivateIndicatorsForPercIndicators( + columnWhitelist + ); + params.columnWhitelist = columnWhitelist; + } + let report = new BaseMysqlReport('hivSummaryBaseAggregate', params); + return new Promise(function (resolve, reject) { + Promise.join(report.generateReport(), (result) => { + let indicatorDefinitionService = new IndicatorDefinitionService(); + let returnedResult = {}; + try { + returnedResult.indicatorDefinitions = indicatorDefinitionService.getDefinitions( + params.indicators + ); + } catch (error) { + console.log(error); } - let report = new BaseMysqlReport('hivSummaryBaseAggregate', params) - return new Promise(function (resolve, reject) { - Promise.join(report.generateReport(), - (result) => { - let indicatorDefinitionService = new IndicatorDefinitionService(); - let returnedResult = {}; - try { - returnedResult.indicatorDefinitions = indicatorDefinitionService.getDefinitions(params.indicators) - } catch (error) { - console.log(error); - } - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - //TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - }); - } - getPatientListReport(reportParams) { - console.log('Params',reportParams); - let self = this; - let gender = reportParams.gender.split(','); - let locations = reportParams.locationUuids.split(','); - reportParams.locationUuids = locations; - reportParams.gender = gender; - reportParams.limitParam = reportParams.limit; - reportParams.offSetParam = reportParams.startIndex; - let report = new PatientlistMysqlReport('hivSummaryBaseAggregate', reportParams) - return new Promise(function (resolve, reject) { - //TODO: Do some pre processing - Promise.join(report.generatePatientListReport(reportParams.indicator.split(',')), - (result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - }).catch((errors) => { - reject(errors); - }); - }); - } + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + //TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + }); + } + getPatientListReport(reportParams) { + console.log('Params', reportParams); + let self = this; + let gender = reportParams.gender.split(','); + let locations = reportParams.locationUuids.split(','); + reportParams.locationUuids = locations; + reportParams.gender = gender; + reportParams.limitParam = reportParams.limit; + reportParams.offSetParam = reportParams.startIndex; + let report = new PatientlistMysqlReport( + 'hivSummaryBaseAggregate', + reportParams + ); + return new Promise(function (resolve, reject) { + //TODO: Do some pre processing + Promise.join( + report.generatePatientListReport(reportParams.indicator.split(',')), + (result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + } + ).catch((errors) => { + reject(errors); + }); + }); + } - addDerivateIndicatorsForPercIndicators(indicatorsArray) { - let additionalIndicators = []; - for(var i = 0; i < indicatorsArray.length; i++) { - let indicator = indicatorsArray[i]; + addDerivateIndicatorsForPercIndicators(indicatorsArray) { + let additionalIndicators = []; + for (var i = 0; i < indicatorsArray.length; i++) { + let indicator = indicatorsArray[i]; - if(this.composite_indicators[indicator]) { - additionalIndicators = additionalIndicators.concat(this.composite_indicators[indicator].childIndictors); - } - } - return indicatorsArray.concat(additionalIndicators); + if (this.composite_indicators[indicator]) { + additionalIndicators = additionalIndicators.concat( + this.composite_indicators[indicator].childIndictors + ); + } } -} \ No newline at end of file + return indicatorsArray.concat(additionalIndicators); + } +} diff --git a/app/reporting-framework/hiv/hiv-summary-monthly-indicators.service.js b/app/reporting-framework/hiv/hiv-summary-monthly-indicators.service.js index de3bb9cda..43eccac5e 100755 --- a/app/reporting-framework/hiv/hiv-summary-monthly-indicators.service.js +++ b/app/reporting-framework/hiv/hiv-summary-monthly-indicators.service.js @@ -1,83 +1,91 @@ const dao = require('../../../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../base-mysql.report'; -import { - IndicatorDefinitionService -} from './indicator-definition.service'; -import { - PatientlistMysqlReport -} from '../patientlist-mysql.report'; +import { BaseMysqlReport } from '../base-mysql.report'; +import { IndicatorDefinitionService } from './indicator-definition.service'; +import { PatientlistMysqlReport } from '../patientlist-mysql.report'; export class HivSummaryMonthlyIndicatorsService { + getAggregateReport(reportParams) { + let self = this; + let indicatorDef = new IndicatorDefinitionService(); + return new Promise(function (resolve, reject) { + reportParams.groupBy = 'groupByYear,groupByMonth'; + reportParams.countBy = 'num_persons'; + let indicators; + if (reportParams.requestParams.indicators) { + indicators = reportParams.requestParams.indicators.split(','); + let columnWhitelist = indicators.concat([ + 'location_id', + 'location_uuid', + 'month', + 'reporting_month', + 'location', + 'encounter_datetime', + 'person_id', + 'age_range', + 'gender', + 'encounter_month', + 'encounter_year' + ]); + reportParams.requestParams.columnWhitelist = columnWhitelist; + } - getAggregateReport(reportParams) { - let self = this; - let indicatorDef= new IndicatorDefinitionService(); - return new Promise(function (resolve, reject) { - reportParams.groupBy = 'groupByYear,groupByMonth'; - reportParams.countBy = 'num_persons'; - let indicators; - if (reportParams.requestParams.indicators) { - indicators = reportParams.requestParams.indicators.split(','); - let columnWhitelist = indicators.concat(['location_id','location_uuid', 'month', 'reporting_month', 'location', 'encounter_datetime','person_id', - 'age_range','gender', - 'encounter_month','encounter_year' - ]); - reportParams.requestParams.columnWhitelist = columnWhitelist; - } + let report = new BaseMysqlReport( + 'hivMonthlySummaryReportAggregate', + reportParams.requestParams + ); - let report = new BaseMysqlReport('hivMonthlySummaryReportAggregate',reportParams.requestParams); - - Promise.join(report.generateReport(), - (results) => { - let result =results.results.results; - results.size =result?result.length:0; - results.result=result; - delete results['results']; - results.indicatorDefinitions = indicatorDef.getDefinitions(indicators) - resolve(results); - //TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - }); - } - getPatientListReport(reportParams) { - // let self = this; - // return new Promise(function (resolve, reject) { - // //TODO: Do some pre processing - // Promise.join(dao.getPatientListReport(reportParams), - // (results) => { - // resolve(results); - // }).catch((errors) => { - // reject(errors); - // }); - // }); - console.log('fetching patient list', reportParams); - let self = this; - let gender = reportParams.gender.split(','); - let locations = reportParams.locationUuids.split(','); - reportParams.locationUuids = locations; - reportParams.gender = gender; - reportParams.limitParam = reportParams.limit; - reportParams.offSetParam = reportParams.startIndex; - let report = new PatientlistMysqlReport('hivMonthlySummaryReportAggregate', reportParams) - return new Promise(function (resolve, reject) { - //TODO: Do some pre processing - Promise.join(report.generatePatientListReport(reportParams.indicator.split(',')), - (result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - }).catch((errors) => { - reject(errors); - }); - }); - } - -} \ No newline at end of file + Promise.join(report.generateReport(), (results) => { + let result = results.results.results; + results.size = result ? result.length : 0; + results.result = result; + delete results['results']; + results.indicatorDefinitions = indicatorDef.getDefinitions(indicators); + resolve(results); + //TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + }); + } + getPatientListReport(reportParams) { + // let self = this; + // return new Promise(function (resolve, reject) { + // //TODO: Do some pre processing + // Promise.join(dao.getPatientListReport(reportParams), + // (results) => { + // resolve(results); + // }).catch((errors) => { + // reject(errors); + // }); + // }); + console.log('fetching patient list', reportParams); + let self = this; + let gender = reportParams.gender.split(','); + let locations = reportParams.locationUuids.split(','); + reportParams.locationUuids = locations; + reportParams.gender = gender; + reportParams.limitParam = reportParams.limit; + reportParams.offSetParam = reportParams.startIndex; + let report = new PatientlistMysqlReport( + 'hivMonthlySummaryReportAggregate', + reportParams + ); + return new Promise(function (resolve, reject) { + //TODO: Do some pre processing + Promise.join( + report.generatePatientListReport(reportParams.indicator.split(',')), + (result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + } + ).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/app/reporting-framework/hiv/indicator-definition.service.js b/app/reporting-framework/hiv/indicator-definition.service.js index 95e890b2f..3b519af72 100644 --- a/app/reporting-framework/hiv/indicator-definition.service.js +++ b/app/reporting-framework/hiv/indicator-definition.service.js @@ -1,9 +1,9 @@ import * as hivDefinitions from './indicator-definitions.json'; export class IndicatorDefinitionService { - getDefinitions(indicators){ - console.log('reporting framework', hivDefinitions); - return hivDefinitions.indicatorDefinitions.filter(function (el) { - return indicators.indexOf(el.name) >= 0; - }); - } -} \ No newline at end of file + getDefinitions(indicators) { + console.log('reporting framework', hivDefinitions); + return hivDefinitions.indicatorDefinitions.filter(function (el) { + return indicators.indexOf(el.name) >= 0; + }); + } +} diff --git a/app/reporting-framework/hiv/indicator-definitions.json b/app/reporting-framework/hiv/indicator-definitions.json index 5e75b4de7..af84f2700 100644 --- a/app/reporting-framework/hiv/indicator-definitions.json +++ b/app/reporting-framework/hiv/indicator-definitions.json @@ -1,304 +1,353 @@ { - "indicatorDefinitions": [{ - "name": "patients", - "label": "patients", - "description": "Total number of patients", - "expression": "true" - }, { - "name": "on_arvs", - "label": "on arvs", - "description": "Total # of patients who are on ARVs", - "expression": "cur_arv_line is not null" - }, - { - "name": "on_tdf_3tc_efv_400", - "label": "tdf 3tc efv 400", - "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ 400", - "expression": "" - }, - { - "name": "on_tdf_3tc_efv_600", - "label": "tdf 3tc efv 600", - "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ 600", - "expression": "" - }, - { - "name": "on_tdf_3tc_dtg", - "label": "tdf 3tc dtg", - "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND DOLUTEGRAVIR", - "expression": "" + "indicatorDefinitions": [ + { + "name": "patients", + "label": "patients", + "description": "Total number of patients", + "expression": "true" + }, + { + "name": "on_arvs", + "label": "on arvs", + "description": "Total # of patients who are on ARVs", + "expression": "cur_arv_line is not null" + }, + { + "name": "on_tdf_3tc_efv_400", + "label": "tdf 3tc efv 400", + "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ 400", + "expression": "" + }, + { + "name": "on_tdf_3tc_efv_600", + "label": "tdf 3tc efv 600", + "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ 600", + "expression": "" + }, + { + "name": "on_tdf_3tc_dtg", + "label": "tdf 3tc dtg", + "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND DOLUTEGRAVIR", + "expression": "" + }, + + { + "name": "on_arvs_first_line", + "label": "on arvs first line", + "description": "# of patient on ARVs first line", + "expression": "cur_arv_line=1" + }, + { + "name": "on_arvs_second_line", + "label": "on arvs second line", + "description": "# of patient on ARVs second line", + "expression": "cur_arv_line=2 and coalesce(transfer_out, out_of_care) is null" + }, + { + "name": "newly_on_second_line", + "label": "newly on second line", + "description": "patient newly on second line within a given period", + "expression": "cur_arv_line =2 and (arv_start_date between @startDate and @endDate)" + }, + { + "name": "on_arvs_third_line", + "label": "on arvs third line", + "description": "# of patient on ARVs third line", + "expression": "cur_arv_line>2" + }, + { + "name": "vl_done_past_year", + "label": "vl done past year", + "description": "# of patient(s) whose Viral Load have been taken in the past 1 year", + "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "vl_done_past_year_relative_to_end_date", + "label": "vl done past year relative to end date", + "description": "# of patient(s) whose Viral Load have been taken in the past 1 year", + "expression": "timestampdiff(week,vl_1_date,@endDate) <= 52" + }, + { + "name": "no_vl_done_past_year", + "label": "no vl done past year", + "description": "# of patient(s) whose Viral Load have not been taken in the past 1 year", + "expression": "cur_arv_line is not null and (vl_1_date is null or timestampdiff(week,vl_1_date,encounter_datetime) >= 52)" + }, + { + "name": "vl_done_past_year_lte_1000", + "label": "vl done past year lte 1000", + "description": "# of patient(s) whose Viral Load is Less Than or Equal to 1000", + "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" + }, + { + "name": "on_second_line_not_suppressed", + "label": "on second line not suppressed", + "description": "patient on second line not suppressed", + "expression": "vl_1 > 1000 and cur_arv_line =2" + }, + { + "name": "not_on_arvs_cd4_lte_500", + "label": "not on arvs cd4 lte 500", + "description": "patients who qualify for ART but are not on therapy", + "expression": "arv_start_date is null and cd4_1 < 500" + }, + { + "name": "vl_done_past_year_gt_1000", + "label": "vl done past year gt 1000", + "description": "# of patient(s) whose Viral Load is Greater Than 1000", + "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 > 1000" + }, + { + "name": "vl_done_this_encounter", + "label": "vl done this encounter", + "description": "# of patient(s) whose Viral Load has been taken in this encounter", + "expression": "vl_resulted >= 0 and vl_resulted_date=date(encounter_datetime)" + }, + { + "name": "vl_done_this_encounter_lte_1000", + "label": "vl done this encounter lte 1000", + "description": "# of patient(s) whose Viral Load in this encounter is Less Than 1000", + "expression": "vl_resulted <= 1000 and vl_resulted_date = date(encounter_datetime)" + }, + { + "name": "vl_done_this_encounter_gt_1000", + "label": "vl done this encounter gt 1000", + "description": "# of patient(s) whose Viral Load in this encounter is Greater Than 1000", + "expression": "vl_resulted > 1000 and vl_resulted_date = date(encounter_datetime)" + }, + { + "name": "vl_ordered", + "label": "vl ordered", + "description": "# of patient(s) whose Viral Load has been ordered", + "expression": "date(vl_order_date)=date(encounter_datetime)" + }, + { + "name": "pending_vl_order", + "label": "pending vl order", + "description": "# of patient(s) whose Viral Load has been Ordered but awaiting result", + "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 0 and vl_1_date < vl_order_date" + }, + { + "name": "pending_vl_order_no_result_after_4_weeks", + "label": "pending vl order no result after 4 weeks", + "description": "# of patient(s) whose Pending Viral Load Result is missing even after 4 weeks", + "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 4 and vl_1_date < vl_order_date" + }, + { + "name": "on_arvs_lte_26_weeks", + "label": "on arvs lte 26 weeks", + "description": "# of patient(s) who have been on ARVs for the last 26 weeks or less", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 26" + }, + { + "name": "on_arvs_lte_52_weeks", + "label": "on arvs lte 52 weeks", + "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52" + }, + { + "name": "on_arvs_lte_52_weeks_and_have_vl", + "label": "on arvs lte 52 weeks and have vl", + "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less and have Viral Load", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "label": "on arvs lte 52 weeks and have vl lte 1000", + "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less and their Viral Load is Less Than or Equal to 1000", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" + }, + { + "name": "on_modern_contraception", + "label": "on modern contraception", + "description": "# of patients on modern contraception in a given time period", + "expression": "fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method IN (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817)" + }, + { + "name": "not_on_modern_contraception", + "label": "not on modern contraception", + "description": "# of patients not on modern contraception in a given time period", + "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277))" + }, + { + "name": "on_short_term_modern_contraception", + "label": "On short term modern contraception", + "description": "# of patients on short term modern contraception in a given time period", + "expression": "fhs.contraceptive_method is not null AND fhs.contraceptive_method not in (190, 6717, 6718, 1107, 6700, 9510, 9511, 9734, 9735, 6701) OR (fhs.contraceptive_method = 8300)" + }, + { + "name": "on_long_term_modern_contraception", + "label": "On long term modern contraception", + "description": "# of patients on long term modern contraception in a given time period", + "expression": "fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817)" + }, + { + "name": "on_short_term_modern_contraception_pnc", + "label": "On short term modern contraception pnc", + "description": "# of patients on short term modern contraception in a given time period and in pnc", + "expression": "fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method is not null AND fhs.contraceptive_method in (190,780,907,6218,6217,5841,6717,6718,6725,8134,5274,8300)" + }, + { + "name": "on_long_term_modern_contraception_pnc", + "label": "On long term modern contraception pnc", + "description": "# of patients on long term modern contraception in a given time period and in pnc", + "expression": "fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817)" + }, + { + "name": "on_modern_contraception_pnc", + "label": "on modern contraception pnc", + "description": "# of patients on modern contraception in a given time period", + "expression": "fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method in (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817) AND fhs.visit_type in (68, 55, 52, 18)" + }, + { + "name": "not_on_modern_contraception_pnc", + "label": "not on modern contraception pnc", + "description": "# of patients not on modern contraception in a given time period and they are in PNC", + "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277 )) AND fhs.visit_type in (68, 55, 52, 18)" + }, + { + "name": "in_pnc", + "label": "in pnc", + "description": "# of patients with a pnc visit in a given time period", + "expression": "fhs.visit_type in (68, 55, 52, 18)" + }, + { + "name": "on_art_and_not_on_modern_contraception", + "label": "on art and not on modern contraception", + "description": "# of patients on art and not on modern contraception in a given time period", + "expression": "(fhs.contraceptive_method IS NULL or fhs.contraceptive_method = 1107) and cur_arv_line is not null" + }, + { + "name": "started_modern_contraception", + "label": "started modern contraception", + "description": "# of patients who started modern contraception in a given time period", + "expression": "date(fhs.modern_contraceptive_method_start_date) between @startDate and @endDate" + }, + { + "name": "pregnant", + "label": "pregnant", + "description": "# of pregnant patients in a given time period", + "expression": "count(distinct concat(on_modern_contraception, hsb.person_id))" + }, + { + "name": "pregnant_and_on_arvs", + "label": "pregnant and on arvs", + "description": "# of pregnant patients and are on ARVs in a given time period", + "expression": "edd > encounter_datetime and cur_arv_line is not null" + }, + { + "name": "pregnant_and_started_art", + "label": "pregnant and started art", + "description": "# of pregnant patients and started ART in a given time period", + "expression": "edd > encounter_datetime and date(fhs.arv_first_regimen_start_date) between @startDate and @endDate" + }, + { + "name": "viral_load_resulted_in_past_year", + "label": "viral load resulted in past year", + "description": "patient(s) whose viral load has resulted in the past one year", + "expression": "vl_1 is not null and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "virally_suppressed_in_past_year", + "label": "virally suppressed in past year", + "description": "# of patient(s) who are virally suppressed in the past one year", + "expression": "vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "not_virally_suppressed_in_past_year", + "label": "not virally suppressed in past year", + "description": "# of patient(s) who are not virally suppressed in the past one year", + "expression": "vl_1> 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "perc_virally_suppressed_in_past_year", + "label": "perc virally suppressed in past year", + "description": "% of patient(s) who are virally suppressed in the past one year", + "expression": "" + }, + { + "name": "perc_not_virally_suppressed_in_past_year", + "label": "perc not virally suppressed in past year", + "description": "% of patient(s) who are not virally suppressed in the past one year", + "expression": "" + }, + { + "name": "perc_on_arvs", + "label": "perc on arvs", + "description": "% of patients who are on ARVs", + "expression": "" + }, + { + "name": "perc_on_arv_first_line", + "label": "perc on arv first line", + "description": "% of patients on ARVs first line", + "expression": "" + }, + { + "name": "perc_on_arv_second_line", + "label": "perc on arv second line", + "description": "% of patients on ARVs second line", + "expression": "" + }, + { + "name": "perc_with_pending_viral_load", + "label": "perc with pending viral load", + "description": "% of patients with pending viral load", + "expression": "" + }, + { + "name": "perc_on_arvs_lte_6_months", + "label": "perc on arvs lte 6 months", + "description": "% of patients who have been on ARVs for less than 6 months", + "expression": "" + }, + { + "name": "on_arvs_gt_26_weeks", + "label": "on arvs gt 26 weeks", + "description": "# of patient(s) who have been on ARVs 26 weeks or more", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) > 26" + }, + { + "name": "perc_on_arvs_gt_6_months", + "label": "perc on arvs gt 6 months", + "description": "% of patients who have been on ARVs for more than 6 months", + "expression": "" + }, + { + "name": "transfer_in_patients", + "label": "transfer in patients", + "description": "These are patients who transferred into the selected facility within the reporting period", + "expression": "t1.transfer_in is not null" + }, + { + "name": "patients_with_vl_result", + "label": "patients with vl result", + "description": "# of patients with vl", + "expression": "vl_1_date between @startDate and @endDate" + }, + { + "name": "vl_suppressed_patients", + "label": "vl suppressed patients", + "description": "# of patients with vl < 1000", + "expression": "vl_1_date between @startDate and @endDate and vl_1 < 1000" + }, + { + "name": "vl_unsuppressed_patients", + "label": "vl unsuppressed patients", + "description": "# of patients with vl >= 1000", + "expression": "vl_1_date between @startDate and @endDate and vl_1 >= 1000" + }, + { + "name": "early_scheduled_visits", + "label": "early scheduled visits", + "description": "Early Scheduled visit", + "expression": "(date(encounter_datetime) < date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " + }, + { + "name": "late_scheduled_visits", + "label": " late scheduled visits", + "description": "Late scheduled visit", + "expression": "(date(encounter_datetime) > date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " } - - , { - "name": "on_arvs_first_line", - "label": "on arvs first line", - "description": "# of patient on ARVs first line", - "expression": "cur_arv_line=1" - }, { - "name": "on_arvs_second_line", - "label": "on arvs second line", - "description": "# of patient on ARVs second line", - "expression": "cur_arv_line=2 and coalesce(transfer_out, out_of_care) is null" - }, { - "name": "newly_on_second_line", - "label": "newly on second line", - "description": "patient newly on second line within a given period", - "expression": "cur_arv_line =2 and (arv_start_date between @startDate and @endDate)" - }, { - "name": "on_arvs_third_line", - "label": "on arvs third line", - "description": "# of patient on ARVs third line", - "expression": "cur_arv_line>2" - }, { - "name": "vl_done_past_year", - "label": "vl done past year", - "description": "# of patient(s) whose Viral Load have been taken in the past 1 year", - "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, { - "name": "vl_done_past_year_relative_to_end_date", - "label": "vl done past year relative to end date", - "description": "# of patient(s) whose Viral Load have been taken in the past 1 year", - "expression": "timestampdiff(week,vl_1_date,@endDate) <= 52" - }, { - "name": "no_vl_done_past_year", - "label": "no vl done past year", - "description": "# of patient(s) whose Viral Load have not been taken in the past 1 year", - "expression": "cur_arv_line is not null and (vl_1_date is null or timestampdiff(week,vl_1_date,encounter_datetime) >= 52)" - }, { - "name": "vl_done_past_year_lte_1000", - "label": "vl done past year lte 1000", - "description": "# of patient(s) whose Viral Load is Less Than or Equal to 1000", - "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" - }, { - "name": "on_second_line_not_suppressed", - "label": "on second line not suppressed", - "description": "patient on second line not suppressed", - "expression": "vl_1 > 1000 and cur_arv_line =2" - }, { - "name": "not_on_arvs_cd4_lte_500", - "label": "not on arvs cd4 lte 500", - "description": "patients who qualify for ART but are not on therapy", - "expression": "arv_start_date is null and cd4_1 < 500" - }, { - "name": "vl_done_past_year_gt_1000", - "label": "vl done past year gt 1000", - "description": "# of patient(s) whose Viral Load is Greater Than 1000", - "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 > 1000" - }, { - "name": "vl_done_this_encounter", - "label": "vl done this encounter", - "description": "# of patient(s) whose Viral Load has been taken in this encounter", - "expression": "vl_resulted >= 0 and vl_resulted_date=date(encounter_datetime)" - }, { - "name": "vl_done_this_encounter_lte_1000", - "label": "vl done this encounter lte 1000", - "description": "# of patient(s) whose Viral Load in this encounter is Less Than 1000", - "expression": "vl_resulted <= 1000 and vl_resulted_date = date(encounter_datetime)" - }, { - "name": "vl_done_this_encounter_gt_1000", - "label": "vl done this encounter gt 1000", - "description": "# of patient(s) whose Viral Load in this encounter is Greater Than 1000", - "expression": "vl_resulted > 1000 and vl_resulted_date = date(encounter_datetime)" - }, { - "name": "vl_ordered", - "label": "vl ordered", - "description": "# of patient(s) whose Viral Load has been ordered", - "expression": "date(vl_order_date)=date(encounter_datetime)" - }, { - "name": "pending_vl_order", - "label": "pending vl order", - "description": "# of patient(s) whose Viral Load has been Ordered but awaiting result", - "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 0 and vl_1_date < vl_order_date" - }, { - "name": "pending_vl_order_no_result_after_4_weeks", - "label": "pending vl order no result after 4 weeks", - "description": "# of patient(s) whose Pending Viral Load Result is missing even after 4 weeks", - "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 4 and vl_1_date < vl_order_date" - }, { - "name": "on_arvs_lte_26_weeks", - "label": "on arvs lte 26 weeks", - "description": "# of patient(s) who have been on ARVs for the last 26 weeks or less", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 26" - }, { - "name": "on_arvs_lte_52_weeks", - "label": "on arvs lte 52 weeks", - "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52" - }, { - "name": "on_arvs_lte_52_weeks_and_have_vl", - "label": "on arvs lte 52 weeks and have vl", - "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less and have Viral Load", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, { - "name": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "label": "on arvs lte 52 weeks and have vl lte 1000", - "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less and their Viral Load is Less Than or Equal to 1000", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" - }, { - "name": "on_modern_contraception", - "label": "on modern contraception", - "description": "# of patients on modern contraception in a given time period", - "expression": "fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method IN (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817)" - },{ - "name": "not_on_modern_contraception", - "label": "not on modern contraception", - "description": "# of patients not on modern contraception in a given time period", - "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277))" - },{ - "name": "on_short_term_modern_contraception", - "label": "On short term modern contraception", - "description": "# of patients on short term modern contraception in a given time period", - "expression": "fhs.contraceptive_method is not null AND fhs.contraceptive_method not in (190, 6717, 6718, 1107, 6700, 9510, 9511, 9734, 9735, 6701) OR (fhs.contraceptive_method = 8300)" - },{ - "name": "on_long_term_modern_contraception", - "label": "On long term modern contraception", - "description": "# of patients on long term modern contraception in a given time period", - "expression": "fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817)" - }, - { - "name": "on_short_term_modern_contraception_pnc", - "label": "On short term modern contraception pnc", - "description": "# of patients on short term modern contraception in a given time period and in pnc", - "expression": "fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method is not null AND fhs.contraceptive_method in (190,780,907,6218,6217,5841,6717,6718,6725,8134,5274,8300)" - }, - { - "name": "on_long_term_modern_contraception_pnc", - "label": "On long term modern contraception pnc", - "description": "# of patients on long term modern contraception in a given time period and in pnc", - "expression": "fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817)" - }, - { - "name": "on_modern_contraception_pnc", - "label": "on modern contraception pnc", - "description": "# of patients on modern contraception in a given time period", - "expression": "fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method in (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817) AND fhs.visit_type in (68, 55, 52, 18)" - }, - { - "name": "not_on_modern_contraception_pnc", - "label": "not on modern contraception pnc", - "description": "# of patients not on modern contraception in a given time period and they are in PNC", - "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277 )) AND fhs.visit_type in (68, 55, 52, 18)" - }, - { - "name": "in_pnc", - "label": "in pnc", - "description": "# of patients with a pnc visit in a given time period", - "expression": "fhs.visit_type in (68, 55, 52, 18)" - }, - { - "name": "on_art_and_not_on_modern_contraception", - "label": "on art and not on modern contraception", - "description": "# of patients on art and not on modern contraception in a given time period", - "expression": "(fhs.contraceptive_method IS NULL or fhs.contraceptive_method = 1107) and cur_arv_line is not null" - },{ - "name": "started_modern_contraception", - "label": "started modern contraception", - "description": "# of patients who started modern contraception in a given time period", - "expression": "date(fhs.modern_contraceptive_method_start_date) between @startDate and @endDate" - }, { - "name": "pregnant", - "label": "pregnant", - "description": "# of pregnant patients in a given time period", - "expression": "count(distinct concat(on_modern_contraception, hsb.person_id))" - }, { - "name": "pregnant_and_on_arvs", - "label": "pregnant and on arvs", - "description": "# of pregnant patients and are on ARVs in a given time period", - "expression": "edd > encounter_datetime and cur_arv_line is not null" - },{ - "name": "pregnant_and_started_art", - "label": "pregnant and started art", - "description": "# of pregnant patients and started ART in a given time period", - "expression": "edd > encounter_datetime and date(fhs.arv_first_regimen_start_date) between @startDate and @endDate" - }, { - "name": "viral_load_resulted_in_past_year", - "label": "viral load resulted in past year", - "description": "patient(s) whose viral load has resulted in the past one year", - "expression": "vl_1 is not null and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, { - "name": "virally_suppressed_in_past_year", - "label": "virally suppressed in past year", - "description": "# of patient(s) who are virally suppressed in the past one year", - "expression": "vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, { - "name": "not_virally_suppressed_in_past_year", - "label": "not virally suppressed in past year", - "description": "# of patient(s) who are not virally suppressed in the past one year", - "expression": "vl_1> 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, { - "name": "perc_virally_suppressed_in_past_year", - "label": "perc virally suppressed in past year", - "description": "% of patient(s) who are virally suppressed in the past one year", - "expression": "" - }, { - "name": "perc_not_virally_suppressed_in_past_year", - "label": "perc not virally suppressed in past year", - "description": "% of patient(s) who are not virally suppressed in the past one year", - "expression": "" - }, { - "name": "perc_on_arvs", - "label": "perc on arvs", - "description": "% of patients who are on ARVs", - "expression": "" - }, { - "name": "perc_on_arv_first_line", - "label": "perc on arv first line", - "description": "% of patients on ARVs first line", - "expression": "" - }, { - "name": "perc_on_arv_second_line", - "label": "perc on arv second line", - "description": "% of patients on ARVs second line", - "expression": "" - }, { - "name": "perc_with_pending_viral_load", - "label": "perc with pending viral load", - "description": "% of patients with pending viral load", - "expression": "" - }, { - "name": "perc_on_arvs_lte_6_months", - "label": "perc on arvs lte 6 months", - "description": "% of patients who have been on ARVs for less than 6 months", - "expression": "" - }, { - "name": "on_arvs_gt_26_weeks", - "label": "on arvs gt 26 weeks", - "description": "# of patient(s) who have been on ARVs 26 weeks or more", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) > 26" - }, { - "name": "perc_on_arvs_gt_6_months", - "label": "perc on arvs gt 6 months", - "description": "% of patients who have been on ARVs for more than 6 months", - "expression": "" - }, { - "name": "transfer_in_patients", - "label": "transfer in patients", - "description": "These are patients who transferred into the selected facility within the reporting period", - "expression": "t1.transfer_in is not null" - }, { - "name": "patients_with_vl_result", - "label": "patients with vl result", - "description": "# of patients with vl", - "expression": "vl_1_date between @startDate and @endDate" - }, { - "name": "vl_suppressed_patients", - "label": "vl suppressed patients", - "description": "# of patients with vl < 1000", - "expression": "vl_1_date between @startDate and @endDate and vl_1 < 1000" - }, { - "name": "vl_unsuppressed_patients", - "label": "vl unsuppressed patients", - "description": "# of patients with vl >= 1000", - "expression": "vl_1_date between @startDate and @endDate and vl_1 >= 1000" - }, { - "name": "early_scheduled_visits", - "label": "early scheduled visits", - "description": "Early Scheduled visit", - "expression": "(date(encounter_datetime) < date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " - }, { - "name": "late_scheduled_visits", - "label": " late scheduled visits", - "description": "Late scheduled visit", - "expression": "(date(encounter_datetime) > date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " - }] -} \ No newline at end of file + ] +} diff --git a/app/reporting-framework/hiv/moh-731-2017.json b/app/reporting-framework/hiv/moh-731-2017.json index 4304570b1..42367f56c 100755 --- a/app/reporting-framework/hiv/moh-731-2017.json +++ b/app/reporting-framework/hiv/moh-731-2017.json @@ -1,542 +1,542 @@ [ - { - "sectionTitle": "3.1 Enrolled in Care", - "indicators": [ - { - "label": "Enrolled in care - Below 1yr", - "ref": "HV03-001", - "indicator": "dc__age_range__0_to_1__enrolled_this_month" - }, - { - "label": "Enrolled in care - 1 to 9yrs", - "ref": "HV03-002", - "indicator": "dc__age_range__1_to_9__enrolled_this_month" - }, - { - "label": "Enrolled in care - 10 to 14yrs(M)", - "ref": "HV03-003", - "indicator": "dc__gender__M__age_range__10_to_14__enrolled_this_month" - }, - { - "label": "Enrolled in care - 10 to 14yrs(F)", - "ref": "HV03-004", - "indicator": "dc__gender__F__age_range__10_to_14__enrolled_this_month" - }, - { - "label": "Enrolled in care - 15 to 19yrs(M)", - "ref": "HV03-005", - "indicator": "dc__gender__M__age_range__15_to_19__enrolled_this_month" - }, - { - "label": "Enrolled in care - 15 to 19yrs(F)", - "ref": "HV03-006", - "indicator": "dc__gender__F__age_range__15_to_19__enrolled_this_month" - }, - { - "label": "Enrolled in care - 20 to 24yrs(M)", - "ref": "HV03-007", - "indicator": "dc__gender__M__age_range__20_to_24__enrolled_this_month" - }, - { - "label": "Enrolled in care - 20 to 24yrs(F)", - "ref": "HV03-008", - "indicator": "dc__gender__F__age_range__20_to_24__enrolled_this_month" - }, - { - "label": "Enrolled in care - 25yrs and older(M)", - "ref": "HV03-009", - "indicator": "dc__gender__M__age_range__older_than_24__enrolled_this_month" - }, - { - "label": "Enrolled in care - 25yrs and older(F)", - "ref": "HV03-010", - "indicator": "dc__gender__F__age_range__older_than_24__enrolled_this_month" - }, - { - "label": "Enrolled in care - Total (Sum HV03-001 to HV03-010)", - "ref": "HV03-011", - "indicator": "enrolled_this_month" - }, - { - "label": "Enrolled in care - key population", - "ref": "HV03-012", - "indicator": "" - } - ] - }, - { - "sectionTitle": "3.2 Current On Pre ART", - "indicators": [ - { - "label": "In Pre ART - 0 to 14yrs", - "ref": "HV03-013", - "indicator": "dc__age_range__below_15_years__pre_art" - }, - { - "label": "In Pre ART - 15yrs and older", - "ref": "HV03-014", - "indicator": "dc__age_range__older_than_15__pre_art" - }, - { - "label": "In Pre ART - Total (Sum HV03-013 to HV013-014)", - "ref": "HV03-015", - "indicator": "pre_art" - } - ] - }, - { - "sectionTitle": "3.3 Starting ART", - "indicators": [ - { - "label": "Starting ART - Below 1yr", - "ref": "HV03-016", - "indicator": "dc__age_range__0_to_1__started_art" - }, - { - "label": "Starting ART - 1 to 9yrs", - "ref": "HV03-017", - "indicator": "dc__age_range__1_to_9__started_art" - }, - { - "label": "Starting ART - 10 to 14yrs(M)", - "ref": "HV03-018", - "indicator": "dc__age_range__10_to_14__gender__M__started_art" - }, - { - "label": "Starting ART - 10 to 14yrs(F)", - "ref": "HV03-019", - "indicator": "dc__age_range__10_to_14__gender__F__started_art" - }, - { - "label": "Starting ART - 15 to 19yrs(M)", - "ref": "HV03-020", - "indicator": "dc__age_range__15_to_19__gender__M__started_art" - }, - { - "label": "Starting ART - 15 to 19yrs(F)", - "ref": "HV03-021", - "indicator": "dc__age_range__15_to_19__gender__F__started_art" - }, - { - "label": "Starting ART - 20 to 24yrs(M)", - "ref": "HV03-022", - "indicator": "dc__age_range__20_to_24__gender__M__started_art" - }, - { - "label": "Starting ART - 20 to 24yrs(F)", - "ref": "HV03-023", - "indicator": "dc__age_range__20_to_24__gender__F__started_art" - }, - { - "label": "Starting ART - 25 and older(M)", - "ref": "HV03-024", - "indicator": "dc__age_range__older_than_24__gender__M__started_art" - }, - { - "label": "Starting ART - 25 and older(F)", - "ref": "HV03-025", - "indicator": "dc__age_range__older_than_24__gender__F__started_art" - }, - { - "label": "Starting on ART - Total (Sum HV03-016 to HV03-025)", - "ref": "HV03-026", - "indicator": "started_art" - }, - { - "label": "Starting on ART - key population", - "ref": "HV03-027", - "indicator": "" - } - ] - }, - { - "sectionTitle": "3.4 Currently on ART [ALL] - (Add 3.2 and 3.3 e.g HV03-34=HV03-20+HV03-28)", - "indicators": [ - { - "label": "Currently on ART - Below 1yr", - "ref": "HV03-028", - "indicator": "dc__age_range__0_to_1__current_on_art" - }, - { - "label": "Currently on ART - 1 to 9yrs", - "ref": "HV03-029", - "indicator": "dc__age_range__1_to_9__current_on_art" - }, - { - "label": "Currently on ART - 10 to 14yrs(M)", - "ref": "HV03-030", - "indicator": "dc__gender__M__age_range__10_to_14__current_on_art" - }, - { - "label": "Currently on ART - 10 to 14yrs(F)", - "ref": "HV03-031", - "indicator": "dc__gender__F__age_range__10_to_14__current_on_art" - }, - { - "label": "Currently on ART - 15 to 19yrs(M)", - "ref": "HV03-032", - "indicator": "dc__gender__M__age_range__15_to_19__current_on_art" - }, - { - "label": "Currently on ART - 15 to 19yrs(F)", - "ref": "HV03-033", - "indicator": "dc__gender__F__age_range__15_to_19__current_on_art" - }, - { - "label": "Currently on ART - 20 to 24yrs(M)", - "ref": "HV03-034", - "indicator": "dc__gender__M__age_range__20_to_24__current_on_art" - }, - { - "label": "Currently on ART - 20 to 24yrs(F)", - "ref": "HV03-035", - "indicator": "dc__gender__F__age_range__20_to_24__current_on_art" - }, - { - "label": "Currently on ART - 25yrs and older(M)", - "ref": "HV03-036", - "indicator": "dc__gender__M__age_range__older_than_24__current_on_art" - }, - { - "label": "Currently on ART - 25yrs and older(F)", - "ref": "HV03-037", - "indicator": "dc__gender__F__age_range__older_than_24__current_on_art" - }, - { - "label": "Total currently on ART (Sum HV03-028 to HV03-037)", - "ref": "HV03-038", - "indicator": "current_on_art" - }, - { - "label": "Currently on ART - key population", - "ref": "HV03-039", - "indicator": "" - } - ] - }, - { - "sectionTitle": "3.5 Survival and Retention on ART at 12 months", - "indicators": [ - { - "label": "On ART at 12 months", - "ref": "HV03-040", - "indicator": "active" - }, - { - "label": "ART Net Cohort at 12 months", - "ref": "HV03-041", - "indicator": "net_cohort" - }, - { - "label": "Viral load less than 1000 at 12 months", - "ref": "HV03-042", - "indicator": "suppressed" - }, - { - "label": "Viral load results at 12 months", - "ref": "HV03-043", - "indicator": "total_with_vl" - } - ] - }, - { - "sectionTitle": "3.6 On Cotrimoxazole Prophylaxis (within 2 months)", - "indicators": [ - { - "label": "On CTX - Below 1yr", - "ref": "HV03-044", - "indicator": "dc__age_range__0_to_1__on_ctx_prophylaxis" - }, - { - "label": "On CTX - 1 to 9yrs", - "ref": "HV03-045", - "indicator": "dc__age_range__1_to_9__on_ctx_prophylaxis" - }, - { - "label": "On CTX - 10 to 14yrs", - "ref": "HV03-046", - "indicator": "dc__age_range__10_to_14__on_ctx_prophylaxis" - }, - { - "label": "On CTX - 15 to 19yrs", - "ref": "HV03-047", - "indicator": "dc__age_range__15_to_19__on_ctx_prophylaxis" - }, - { - "label": "On CTX - 20 to 24yrs", - "ref": "HV03-048", - "indicator": "dc__age_range__20_to_24__on_ctx_prophylaxis" - }, - { - "label": "On CTX - 25yrs and older", - "ref": "HV03-049", - "indicator": "dc__age_range__older_than_24__on_ctx_prophylaxis" - }, - { - "label": "Total on CTX (Sum HV03-044 TO HV03-049)", - "ref": "HV03-050", - "indicator": "on_ctx_prophylaxis" - } - ] - }, - { - "sectionTitle": "3.7 Screening", - "indicators": [ - { - "label": "Screened for TB - Below 1yrs(M)", - "ref": "HV03-051", - "indicator": "dc__age_range__0_to_1__screened_for_tb" - }, - { - "label": "Screened for TB - 1 to 9yrs", - "ref": "HV03-052", - "indicator": "dc__age_range__1_to_9__screened_for_tb" - }, - { - "label": "Screened for TB - 10 to 14yrs", - "ref": "HV03-053", - "indicator": "dc__age_range__10_to_14__screened_for_tb" - }, - { - "label": "Screened for TB - 15 to 19yrs", - "ref": "HV03-054", - "indicator": "dc__age_range__15_to_19__screened_for_tb" - }, - { - "label": "Screened for TB - 20 to 24yrs", - "ref": "HV03-055", - "indicator": "dc__age_range__20_to_24__screened_for_tb" - }, - { - "label": "Screened for TB - 25yrs & older", - "ref": "HV03-056", - "indicator": "dc__age_range__older_than_24__screened_for_tb" - }, - { - "label": "Total Screened for TB (Sum HV03-51 to HV03-56)", - "ref": "HV03-057", - "indicator": "screened_for_tb" - }, - { - "label": "Presumed TB Total ", - "ref": "HV03-058", - "indicator": "tb_screened_positive" - } - ] - }, - { - "sectionTitle": "3.8 Starting IPT", - "indicators": [ - { - "label": "Starting IPT - Below 1yrs", - "ref": "HV03-059", - "indicator": "dc__age_range__0_to_1__started_ipt" - }, - { - "label": "Starting IPT - 1 to 9yrs", - "ref": "HV03-060", - "indicator": "dc__age_range__1_to_9__started_ipt" - }, - { - "label": "Starting IPT - 10 to 14yrs", - "ref": "HV03-061", - "indicator": "dc__age_range__10_to_14__started_ipt" - }, - { - "label": "Starting IPT - 15 to 19yrs", - "ref": "HV03-062", - "indicator": "dc__age_range__15_to_19__started_ipt" - }, - { - "label": "Starting IPT - 20 to 24yrs", - "ref": "HV03-063", - "indicator": "dc__age_range__20_to_24__started_ipt" - }, - { - "label": "Starting IPT - 25yrs and older(F)", - "ref": "HV03-064", - "indicator": "dc__age_range__older_than_24__started_ipt" - }, - { - "label": "Total Starting IPT (Sum HV03-059 to HV03-064)", - "ref": "HV03-065", - "indicator": "started_ipt" - }, - { - "label": "Completed IPT 12months ", - "ref": "HV03-066", - "indicator": "completed_ipt_past_12_months" - } - ] - }, - { - "sectionTitle": "3.9 Nutrition and HIV", - "indicators": [ - { - "label": "Nutrition Assess less than 15yrs", - "ref": "HV03-067", - "indicator": "" - }, - { - "label": "Nutrition Assess greater than 15yrs", - "ref": "HV03-068", - "indicator": "" - }, - { - "label": "Nutrition Assess Total (Sum HV03-067 to HV03-068)", - "ref": "HV03-069", - "indicator": "" - }, - { - "label": "Malnourished less than 15", - "ref": "HV03-070", - "indicator": "" - }, - { - "label": "Malnourished greater than 15", - "ref": "HV03-071", - "indicator": "" - }, - { - "label": "Malnourished Total (Sum HV03-070 to HV03-071)", - "ref": "HV03-072", - "indicator": "" - }, - { - "label": "FBP Provided less than 15", - "ref": "HV03-073", - "indicator": "" - }, - { - "label": "FBP Provided greater than 15", - "ref": "HV03-074", - "indicator": "" - }, - { - "label": "FBP Provided (Sum HV03-073 to HV03-074)", - "ref": "HV03-075", - "indicator": "" - } - ] - }, - { - "sectionTitle": "3.10 HIV in TB Clinic", - "indicators": [ - { - "label": "TB cases New", - "ref": "HV03-076", - "indicator": "" - }, - { - "label": "TB cases KP", - "ref": "HV03-077", - "indicator": "HIV_patients_newly_enrolled_into_TB_treatment" - }, - { - "label": "TB Cases Tested HIV", - "ref": "HV03-078", - "indicator": "" - }, - { - "label": "TB Known Status (Sum HV03-077 and HV03-078)", - "ref": "HV03-079", - "indicator": "" - }, - { - "label": "TB New HIV Positive", - "ref": "HV03-080", - "indicator": "TB_patients_newly_enrolled_into_HIV_care" - }, - { - "label": "TB TOTAL HIV Positive (Sum HV03-077 and HV03-080)", - "ref": "HV03-081", - "indicator": "newly_identified_HIV_positive_patient_on_TB_treatment" - }, - { - "label": "TB already on HAART", - "ref": "HV03-082", - "indicator": "patients_on_ARV_starting_TB_treatment" - }, - { - "label": "TB starting HAART", - "ref": "HV03-083", - "indicator": "TB_patients_starting_ARV_medication" - }, - { - "label": "TB Total on HAART (Sum HV03-082 and HV03-083)", - "ref": "HV03-084", - "indicator": "newly_identified_TB_patients_on_ARVs" - } - ] - }, - { - "sectionTitle": "3.11 Community Dispensing of ARVs", - "indicators": [ - { - "label": "Community ART current(M)", - "ref": "HV03-085", - "indicator": "community_ART_dispensing_male" - }, - { - "label": "Community ART current(F)", - "ref": "HV03-086", - "indicator": "community_ART_dispensing_female" - } - ] - }, - { - "sectionTitle": "3.12 Family planning & CaCx screen in HIV CCC", - "indicators": [ - { - "label": "Screen CaCx New F18+", - "ref": "HV03-087", - "indicator": "" - }, - { - "label": "Clinical visits F18+", - "ref": "HV03-089", - "indicator": "f_gte_18_visits" - }, - { - "label": "On modern FP F15+", - "ref": "HV03-090", - "indicator": "dc__age_range__15_and_above__on_modern_contraception" - } - ] - }, - { - "sectionTitle": "5. Post Exposure Prophylaxis", - "indicators": [ - { - "label": "Exposed Occupational", - "ref": "HV05-01", - "indicator": "hiv_exposed_occupational" - }, - { - "label": "Exposed Other", - "ref": "HV05-02", - "indicator": "hiv_exposed_non_occupational" - }, - { - "label": "Exposed Total (Sum HV05-01 and HV05-02)", - "ref": "HV05-03", - "indicator": "total_hiv_exposed" - }, - { - "label": "PEP Occupational", - "ref": "HV05-04", - "indicator": "started_PEP_occupational" - }, - { - "label": "PEP Other", - "ref": "HV05-05", - "indicator": "started_PEP_non_occupational" - }, - { - "label": "PEP Total (Sum HV05-04 and HV05-05)", - "ref": "HV03-06", - "indicator": "total_started_PEP" - } - ] - } + { + "sectionTitle": "3.1 Enrolled in Care", + "indicators": [ + { + "label": "Enrolled in care - Below 1yr", + "ref": "HV03-001", + "indicator": "dc__age_range__0_to_1__enrolled_this_month" + }, + { + "label": "Enrolled in care - 1 to 9yrs", + "ref": "HV03-002", + "indicator": "dc__age_range__1_to_9__enrolled_this_month" + }, + { + "label": "Enrolled in care - 10 to 14yrs(M)", + "ref": "HV03-003", + "indicator": "dc__gender__M__age_range__10_to_14__enrolled_this_month" + }, + { + "label": "Enrolled in care - 10 to 14yrs(F)", + "ref": "HV03-004", + "indicator": "dc__gender__F__age_range__10_to_14__enrolled_this_month" + }, + { + "label": "Enrolled in care - 15 to 19yrs(M)", + "ref": "HV03-005", + "indicator": "dc__gender__M__age_range__15_to_19__enrolled_this_month" + }, + { + "label": "Enrolled in care - 15 to 19yrs(F)", + "ref": "HV03-006", + "indicator": "dc__gender__F__age_range__15_to_19__enrolled_this_month" + }, + { + "label": "Enrolled in care - 20 to 24yrs(M)", + "ref": "HV03-007", + "indicator": "dc__gender__M__age_range__20_to_24__enrolled_this_month" + }, + { + "label": "Enrolled in care - 20 to 24yrs(F)", + "ref": "HV03-008", + "indicator": "dc__gender__F__age_range__20_to_24__enrolled_this_month" + }, + { + "label": "Enrolled in care - 25yrs and older(M)", + "ref": "HV03-009", + "indicator": "dc__gender__M__age_range__older_than_24__enrolled_this_month" + }, + { + "label": "Enrolled in care - 25yrs and older(F)", + "ref": "HV03-010", + "indicator": "dc__gender__F__age_range__older_than_24__enrolled_this_month" + }, + { + "label": "Enrolled in care - Total (Sum HV03-001 to HV03-010)", + "ref": "HV03-011", + "indicator": "enrolled_this_month" + }, + { + "label": "Enrolled in care - key population", + "ref": "HV03-012", + "indicator": "" + } + ] + }, + { + "sectionTitle": "3.2 Current On Pre ART", + "indicators": [ + { + "label": "In Pre ART - 0 to 14yrs", + "ref": "HV03-013", + "indicator": "dc__age_range__below_15_years__pre_art" + }, + { + "label": "In Pre ART - 15yrs and older", + "ref": "HV03-014", + "indicator": "dc__age_range__older_than_15__pre_art" + }, + { + "label": "In Pre ART - Total (Sum HV03-013 to HV013-014)", + "ref": "HV03-015", + "indicator": "pre_art" + } + ] + }, + { + "sectionTitle": "3.3 Starting ART", + "indicators": [ + { + "label": "Starting ART - Below 1yr", + "ref": "HV03-016", + "indicator": "dc__age_range__0_to_1__started_art" + }, + { + "label": "Starting ART - 1 to 9yrs", + "ref": "HV03-017", + "indicator": "dc__age_range__1_to_9__started_art" + }, + { + "label": "Starting ART - 10 to 14yrs(M)", + "ref": "HV03-018", + "indicator": "dc__age_range__10_to_14__gender__M__started_art" + }, + { + "label": "Starting ART - 10 to 14yrs(F)", + "ref": "HV03-019", + "indicator": "dc__age_range__10_to_14__gender__F__started_art" + }, + { + "label": "Starting ART - 15 to 19yrs(M)", + "ref": "HV03-020", + "indicator": "dc__age_range__15_to_19__gender__M__started_art" + }, + { + "label": "Starting ART - 15 to 19yrs(F)", + "ref": "HV03-021", + "indicator": "dc__age_range__15_to_19__gender__F__started_art" + }, + { + "label": "Starting ART - 20 to 24yrs(M)", + "ref": "HV03-022", + "indicator": "dc__age_range__20_to_24__gender__M__started_art" + }, + { + "label": "Starting ART - 20 to 24yrs(F)", + "ref": "HV03-023", + "indicator": "dc__age_range__20_to_24__gender__F__started_art" + }, + { + "label": "Starting ART - 25 and older(M)", + "ref": "HV03-024", + "indicator": "dc__age_range__older_than_24__gender__M__started_art" + }, + { + "label": "Starting ART - 25 and older(F)", + "ref": "HV03-025", + "indicator": "dc__age_range__older_than_24__gender__F__started_art" + }, + { + "label": "Starting on ART - Total (Sum HV03-016 to HV03-025)", + "ref": "HV03-026", + "indicator": "started_art" + }, + { + "label": "Starting on ART - key population", + "ref": "HV03-027", + "indicator": "" + } + ] + }, + { + "sectionTitle": "3.4 Currently on ART [ALL] - (Add 3.2 and 3.3 e.g HV03-34=HV03-20+HV03-28)", + "indicators": [ + { + "label": "Currently on ART - Below 1yr", + "ref": "HV03-028", + "indicator": "dc__age_range__0_to_1__current_on_art" + }, + { + "label": "Currently on ART - 1 to 9yrs", + "ref": "HV03-029", + "indicator": "dc__age_range__1_to_9__current_on_art" + }, + { + "label": "Currently on ART - 10 to 14yrs(M)", + "ref": "HV03-030", + "indicator": "dc__gender__M__age_range__10_to_14__current_on_art" + }, + { + "label": "Currently on ART - 10 to 14yrs(F)", + "ref": "HV03-031", + "indicator": "dc__gender__F__age_range__10_to_14__current_on_art" + }, + { + "label": "Currently on ART - 15 to 19yrs(M)", + "ref": "HV03-032", + "indicator": "dc__gender__M__age_range__15_to_19__current_on_art" + }, + { + "label": "Currently on ART - 15 to 19yrs(F)", + "ref": "HV03-033", + "indicator": "dc__gender__F__age_range__15_to_19__current_on_art" + }, + { + "label": "Currently on ART - 20 to 24yrs(M)", + "ref": "HV03-034", + "indicator": "dc__gender__M__age_range__20_to_24__current_on_art" + }, + { + "label": "Currently on ART - 20 to 24yrs(F)", + "ref": "HV03-035", + "indicator": "dc__gender__F__age_range__20_to_24__current_on_art" + }, + { + "label": "Currently on ART - 25yrs and older(M)", + "ref": "HV03-036", + "indicator": "dc__gender__M__age_range__older_than_24__current_on_art" + }, + { + "label": "Currently on ART - 25yrs and older(F)", + "ref": "HV03-037", + "indicator": "dc__gender__F__age_range__older_than_24__current_on_art" + }, + { + "label": "Total currently on ART (Sum HV03-028 to HV03-037)", + "ref": "HV03-038", + "indicator": "current_on_art" + }, + { + "label": "Currently on ART - key population", + "ref": "HV03-039", + "indicator": "" + } + ] + }, + { + "sectionTitle": "3.5 Survival and Retention on ART at 12 months", + "indicators": [ + { + "label": "On ART at 12 months", + "ref": "HV03-040", + "indicator": "active" + }, + { + "label": "ART Net Cohort at 12 months", + "ref": "HV03-041", + "indicator": "net_cohort" + }, + { + "label": "Viral load less than 1000 at 12 months", + "ref": "HV03-042", + "indicator": "suppressed" + }, + { + "label": "Viral load results at 12 months", + "ref": "HV03-043", + "indicator": "total_with_vl" + } + ] + }, + { + "sectionTitle": "3.6 On Cotrimoxazole Prophylaxis (within 2 months)", + "indicators": [ + { + "label": "On CTX - Below 1yr", + "ref": "HV03-044", + "indicator": "dc__age_range__0_to_1__on_ctx_prophylaxis" + }, + { + "label": "On CTX - 1 to 9yrs", + "ref": "HV03-045", + "indicator": "dc__age_range__1_to_9__on_ctx_prophylaxis" + }, + { + "label": "On CTX - 10 to 14yrs", + "ref": "HV03-046", + "indicator": "dc__age_range__10_to_14__on_ctx_prophylaxis" + }, + { + "label": "On CTX - 15 to 19yrs", + "ref": "HV03-047", + "indicator": "dc__age_range__15_to_19__on_ctx_prophylaxis" + }, + { + "label": "On CTX - 20 to 24yrs", + "ref": "HV03-048", + "indicator": "dc__age_range__20_to_24__on_ctx_prophylaxis" + }, + { + "label": "On CTX - 25yrs and older", + "ref": "HV03-049", + "indicator": "dc__age_range__older_than_24__on_ctx_prophylaxis" + }, + { + "label": "Total on CTX (Sum HV03-044 TO HV03-049)", + "ref": "HV03-050", + "indicator": "on_ctx_prophylaxis" + } + ] + }, + { + "sectionTitle": "3.7 Screening", + "indicators": [ + { + "label": "Screened for TB - Below 1yrs(M)", + "ref": "HV03-051", + "indicator": "dc__age_range__0_to_1__screened_for_tb" + }, + { + "label": "Screened for TB - 1 to 9yrs", + "ref": "HV03-052", + "indicator": "dc__age_range__1_to_9__screened_for_tb" + }, + { + "label": "Screened for TB - 10 to 14yrs", + "ref": "HV03-053", + "indicator": "dc__age_range__10_to_14__screened_for_tb" + }, + { + "label": "Screened for TB - 15 to 19yrs", + "ref": "HV03-054", + "indicator": "dc__age_range__15_to_19__screened_for_tb" + }, + { + "label": "Screened for TB - 20 to 24yrs", + "ref": "HV03-055", + "indicator": "dc__age_range__20_to_24__screened_for_tb" + }, + { + "label": "Screened for TB - 25yrs & older", + "ref": "HV03-056", + "indicator": "dc__age_range__older_than_24__screened_for_tb" + }, + { + "label": "Total Screened for TB (Sum HV03-51 to HV03-56)", + "ref": "HV03-057", + "indicator": "screened_for_tb" + }, + { + "label": "Presumed TB Total ", + "ref": "HV03-058", + "indicator": "tb_screened_positive" + } + ] + }, + { + "sectionTitle": "3.8 Starting IPT", + "indicators": [ + { + "label": "Starting IPT - Below 1yrs", + "ref": "HV03-059", + "indicator": "dc__age_range__0_to_1__started_ipt" + }, + { + "label": "Starting IPT - 1 to 9yrs", + "ref": "HV03-060", + "indicator": "dc__age_range__1_to_9__started_ipt" + }, + { + "label": "Starting IPT - 10 to 14yrs", + "ref": "HV03-061", + "indicator": "dc__age_range__10_to_14__started_ipt" + }, + { + "label": "Starting IPT - 15 to 19yrs", + "ref": "HV03-062", + "indicator": "dc__age_range__15_to_19__started_ipt" + }, + { + "label": "Starting IPT - 20 to 24yrs", + "ref": "HV03-063", + "indicator": "dc__age_range__20_to_24__started_ipt" + }, + { + "label": "Starting IPT - 25yrs and older(F)", + "ref": "HV03-064", + "indicator": "dc__age_range__older_than_24__started_ipt" + }, + { + "label": "Total Starting IPT (Sum HV03-059 to HV03-064)", + "ref": "HV03-065", + "indicator": "started_ipt" + }, + { + "label": "Completed IPT 12months ", + "ref": "HV03-066", + "indicator": "completed_ipt_past_12_months" + } + ] + }, + { + "sectionTitle": "3.9 Nutrition and HIV", + "indicators": [ + { + "label": "Nutrition Assess less than 15yrs", + "ref": "HV03-067", + "indicator": "" + }, + { + "label": "Nutrition Assess greater than 15yrs", + "ref": "HV03-068", + "indicator": "" + }, + { + "label": "Nutrition Assess Total (Sum HV03-067 to HV03-068)", + "ref": "HV03-069", + "indicator": "" + }, + { + "label": "Malnourished less than 15", + "ref": "HV03-070", + "indicator": "" + }, + { + "label": "Malnourished greater than 15", + "ref": "HV03-071", + "indicator": "" + }, + { + "label": "Malnourished Total (Sum HV03-070 to HV03-071)", + "ref": "HV03-072", + "indicator": "" + }, + { + "label": "FBP Provided less than 15", + "ref": "HV03-073", + "indicator": "" + }, + { + "label": "FBP Provided greater than 15", + "ref": "HV03-074", + "indicator": "" + }, + { + "label": "FBP Provided (Sum HV03-073 to HV03-074)", + "ref": "HV03-075", + "indicator": "" + } + ] + }, + { + "sectionTitle": "3.10 HIV in TB Clinic", + "indicators": [ + { + "label": "TB cases New", + "ref": "HV03-076", + "indicator": "" + }, + { + "label": "TB cases KP", + "ref": "HV03-077", + "indicator": "HIV_patients_newly_enrolled_into_TB_treatment" + }, + { + "label": "TB Cases Tested HIV", + "ref": "HV03-078", + "indicator": "" + }, + { + "label": "TB Known Status (Sum HV03-077 and HV03-078)", + "ref": "HV03-079", + "indicator": "" + }, + { + "label": "TB New HIV Positive", + "ref": "HV03-080", + "indicator": "TB_patients_newly_enrolled_into_HIV_care" + }, + { + "label": "TB TOTAL HIV Positive (Sum HV03-077 and HV03-080)", + "ref": "HV03-081", + "indicator": "newly_identified_HIV_positive_patient_on_TB_treatment" + }, + { + "label": "TB already on HAART", + "ref": "HV03-082", + "indicator": "patients_on_ARV_starting_TB_treatment" + }, + { + "label": "TB starting HAART", + "ref": "HV03-083", + "indicator": "TB_patients_starting_ARV_medication" + }, + { + "label": "TB Total on HAART (Sum HV03-082 and HV03-083)", + "ref": "HV03-084", + "indicator": "newly_identified_TB_patients_on_ARVs" + } + ] + }, + { + "sectionTitle": "3.11 Community Dispensing of ARVs", + "indicators": [ + { + "label": "Community ART current(M)", + "ref": "HV03-085", + "indicator": "community_ART_dispensing_male" + }, + { + "label": "Community ART current(F)", + "ref": "HV03-086", + "indicator": "community_ART_dispensing_female" + } + ] + }, + { + "sectionTitle": "3.12 Family planning & CaCx screen in HIV CCC", + "indicators": [ + { + "label": "Screen CaCx New F18+", + "ref": "HV03-087", + "indicator": "" + }, + { + "label": "Clinical visits F18+", + "ref": "HV03-089", + "indicator": "f_gte_18_visits" + }, + { + "label": "On modern FP F15+", + "ref": "HV03-090", + "indicator": "dc__age_range__15_and_above__on_modern_contraception" + } + ] + }, + { + "sectionTitle": "5. Post Exposure Prophylaxis", + "indicators": [ + { + "label": "Exposed Occupational", + "ref": "HV05-01", + "indicator": "hiv_exposed_occupational" + }, + { + "label": "Exposed Other", + "ref": "HV05-02", + "indicator": "hiv_exposed_non_occupational" + }, + { + "label": "Exposed Total (Sum HV05-01 and HV05-02)", + "ref": "HV05-03", + "indicator": "total_hiv_exposed" + }, + { + "label": "PEP Occupational", + "ref": "HV05-04", + "indicator": "started_PEP_occupational" + }, + { + "label": "PEP Other", + "ref": "HV05-05", + "indicator": "started_PEP_non_occupational" + }, + { + "label": "PEP Total (Sum HV05-04 and HV05-05)", + "ref": "HV03-06", + "indicator": "total_started_PEP" + } + ] + } ] diff --git a/app/reporting-framework/hiv/moh-731-legacy.json b/app/reporting-framework/hiv/moh-731-legacy.json index d744fc0e5..f8fe7dbba 100755 --- a/app/reporting-framework/hiv/moh-731-legacy.json +++ b/app/reporting-framework/hiv/moh-731-legacy.json @@ -1,422 +1,422 @@ [ - { - "sectionTitle": "3.1 On Cotrimoxazole Prophylaxis (within 2 months)", - "indicators": [ - { - "label": "HIV Exposed Infants (within 2 months)", - "ref": "HV03-01", - "indicator": "hiv_exposed_infants_below_2_months" - }, - { - "label": "HIV Exposed Infant (Eligible for CTX within 2 months)", - "ref": "HV03-02", - "indicator": "hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below" - }, - { - "label": "On CTX Below 15 yrs(M)", - "ref": "HV03-03", - "indicator": "dc__gender__M__age_range__below_15_years__on_ctx_prophylaxis" - }, - { - "label": "On CTX Below 15 yrs(F)", - "ref": "HV03-04", - "indicator": "dc__gender__F__age_range__below_15_years__on_ctx_prophylaxis" - }, - { - "label": "On CTX 15 yrs and Older(M)", - "ref": "HV03-05", - "indicator": "dc__gender__M__age_range__older_than_15__on_ctx_prophylaxis" - }, - { - "label": "On CTX 15 yrs and Older(F)", - "ref": "HV03-06", - "indicator": "dc__gender__F__age_range__older_than_15__on_ctx_prophylaxis" - }, - { - "label": "Total on CTX (Sum HV03-03 TO HV03-06)", - "ref": "HV03-07", - "indicator": "on_ctx_prophylaxis" - } - ] - }, - { - "sectionTitle": "3.2 Enrolled in Care", - "indicators": [ - { - "label": "Enrolled in care Below 1yr(M)", - "ref": "HV03-08", - "indicator": "dc__gender__M__age_range__0_to_1__enrolled_this_month" - }, - { - "label": "Enrolled in care Below 1yr(F)", - "ref": "HV03-08", - "indicator": "dc__gender__F__age_range__0_to_1__enrolled_this_month" - }, - { - "label": "Enrolled in care Below 15yrs(M)", - "ref": "HV03-09", - "indicator": "dc__gender__M__age_range__below_15_years__enrolled_this_month" - }, - { - "label": "Enrolled in care Below 15yrs(F)", - "ref": "HV03-10", - "indicator": "dc__gender__F__age_range__below_15_years__enrolled_this_month" - }, - { - "label": "Enrolled in care 15yrs & Older(M)", - "ref": "HV03-11", - "indicator": "dc__gender__M__age_range__older_than_15__enrolled_this_month" - }, - { - "label": "Enrolled in care 15yrs & Older(F)", - "ref": "HV03-12", - "indicator": "dc__gender__F__age_range__older_than_15__enrolled_this_month" - }, - { - "label": "Enrolled in care - Total (Sum HV03-09 to HV03-12)", - "ref": "HV03-13", - "indicator": "enrolled_this_month" - } - ] - }, - { - "sectionTitle": "3.3 Currently in Care -(from the total sheet-this month only and from last 2 months)", - "indicators": [ - { - "label": "Currently in care Below 1yr(M)", - "ref": "HV03-14", - "indicator": "dc__gender__M__age_range__0_to_1__current_in_care" - }, - { - "label": "Currently in care Below 1yr(F)", - "ref": "HV03-14", - "indicator": "dc__gender__F__age_range__0_to_1__current_in_care" - }, - { - "label": "Currently in care Below 15yrs(M)", - "ref": "HV03-15", - "indicator": "dc__gender__M__age_range__below_15_years__current_in_care" - }, - { - "label": "Currently in care Below 15yrs(F)", - "ref": "HV03-16", - "indicator": "dc__gender__F__age_range__below_15_years__current_in_care" - }, - { - "label": "Currently in care 15yrs and older(M)", - "ref": "HV03-17", - "indicator": "dc__gender__M__age_range__older_than_15__current_in_care" - }, - { - "label": "Currently in care 15yrs and older(F)", - "ref": "HV03-18", - "indicator": "dc__gender__F__age_range__older_than_15__current_in_care" - }, - { - "label": "Currently in Care-Total (Sum HV03-15 to HV03-18)", - "ref": "HV03-19", - "indicator": "current_in_care" - } - ] - }, - { - "sectionTitle": "3.4 Starting ART", - "indicators": [ - { - "label": "Starting ART -Below 1yr(M)", - "ref": "HV03-20", - "indicator": "dc__age_range__0_to_1__gender__M__started_art" - }, - { - "label": "Starting ART -Below 1yr(F)", - "ref": "HV03-20", - "indicator": "dc__age_range__0_to_1__gender__F__started_art" - }, - { - "label": "Starting ART -Below 15yrs(M)", - "ref": "HV03-21", - "indicator": "dc__age_range__below_15_years__gender__M__started_art" - }, - { - "label": "Starting ART -Below 15yrs(F)", - "ref": "HV03-22", - "indicator": "dc__age_range__below_15_years__gender__F__started_art" - }, - { - "label": "Starting ART -15yr and Older(M)", - "ref": "HV03-23", - "indicator": "dc__age_range__older_than_15__gender__M__started_art" - }, - { - "label": "Starting ART -15yr and Older(F)", - "ref": "HV03-24", - "indicator": "dc__age_range__older_than_15__gender__F__started_art" - }, - { - "label": "Starting on ART -Total (Sum HV03-21 to HV03-24)", - "ref": "HV03-25", - "indicator": "started_art" - }, - { - "label": "Starting -Pregnant", - "ref": "HV03-26", - "indicator": "started_art_pregnant" - }, - { - "label": "Starting -TB Patient", - "ref": "HV03-27", - "indicator": "started_art_and_has_tb" - } - ] - }, - { - "sectionTitle": "3.5 Revisits on ART (from the tally sheet -this month only and from last 2 months)", - "indicators": [ - { - "label": "Revisit on ART -Below 1yr(M)", - "ref": "HV03-28", - "indicator": "dc__gender__M__age_range__0_to_1__art_revisit_this_month" - }, - { - "label": "Revisit on ART -Below 1yr(F)", - "ref": "HV03-28", - "indicator": "dc__gender__F__age_range__0_to_1__art_revisit_this_month" - }, - { - "label": "Revisit on ART -Below 15yrs(M)", - "ref": "HV03-29", - "indicator": "dc__gender__M__age_range__below_15_years__art_revisit_this_month" - }, - { - "label": "Revisit on ART -Below 15yrs(F)", - "ref": "HV03-30", - "indicator": "dc__gender__F__age_range__below_15_years__art_revisit_this_month" - }, - { - "label": "Revisit on ART -15yrs and older(M)", - "ref": "HV03-31", - "indicator": "dc__gender__M__age_range__older_than_15__art_revisit_this_month" - }, - { - "label": "Revisit on ART -15yrs and older(F)", - "ref": "HV03-32", - "indicator": "dc__gender__F__age_range__older_than_15__art_revisit_this_month" - }, - { - "label": "Total Revisit on ART (Sum HV03-29 to HV03-32)", - "ref": "HV03-33", - "indicator": "art_revisit_this_month" - } - ] - }, - { - "sectionTitle": "3.6 Currently on ART [ALL] - (Add 3.4 and 3.5 e.g HV03-34=HV03-20+HV03-28)", - "indicators": [ - { - "label": "Currently on ART - Below 1yr(M)", - "ref": "HV03-34", - "indicator": "dc__gender__M__age_range__0_to_1__current_on_art" - }, - { - "label": "Currently on ART - Below 1yr(F)", - "ref": "HV03-34", - "indicator": "dc__gender__F__age_range__0_to_1__current_on_art" - }, - { - "label": "Currently on ART - Below 15 yrs(M)", - "ref": "HV03-35", - "indicator": "dc__gender__M__age_range__below_15_years__current_on_art" - }, - { - "label": "Currently on ART - Below 15 yrs(F)", - "ref": "HV03-36", - "indicator": "dc__gender__F__age_range__below_15_years__current_on_art" - }, - { - "label": "Currently on ART -15yr and older(M)", - "ref": "HV03-37", - "indicator": "dc__gender__M__age_range__older_than_15__current_on_art" - }, - { - "label": "Currently on ART -15yr and older(F)", - "ref": "HV03-38", - "indicator": "dc__gender__F__age_range__older_than_15__current_on_art" - }, - { - "label": "Total currently on ART (Sum HV03-35 to HV03-38)", - "ref": "HV03-39", - "indicator": "current_on_art" - } - ] - }, - { - "sectionTitle": "3.7 Cumulative Ever on ART", - "indicators": [ - { - "label": "Ever on ART - Below 15yrs(M)", - "ref": "HV03-40", - "indicator": "dc__gender__M__age_range__below_15__ever_on_art" - }, - { - "label": "Ever on ART - Below 15yrs(F)", - "ref": "HV03-41", - "indicator": "dc__gender__F__age_range__below_15__ever_on_art" - }, - { - "label": "Ever on ART - 15yrs & older(M)", - "ref": "HV03-42", - "indicator": "dc__gender__M__age_range__15_and_above__ever_on_art" - }, - { - "label": "Ever on ART - 15yrs & older(F)", - "ref": "HV03-43", - "indicator": "dc__gender__F__age_range__15_and_above__ever_on_art" - }, - { - "label": "Total Ever on ART (Sum HV03-40 to HV03-43)", - "ref": "HV03-44", - "indicator": "ever_on_art" - } - ] - }, - { - "sectionTitle": "3.8 Survival and Retention on ART at 12 months", - "indicators": [ - { - "label": "ART Net Cohort at 12 months", - "ref": "HV03-45", - "indicator": "net_cohort" - }, - { - "label": "On Original 1st Line at 12 months", - "ref": "HV03-46", - "indicator": "on_original_first_line" - }, - { - "label": "On alternative 1st Line at 12 months", - "ref": "HV03-47", - "indicator": "on_alternative_first_line" - }, - { - "label": "On 2nd Line (or higher) at 12 months", - "ref": "HV03-48", - "indicator": "on_second_line" - }, - { - "label": "Total on therapy at 12 months (Sum HV03-46 to HV03-48)", - "ref": "HV03-49", - "indicator": "on_tx" - } - ] - }, - { - "sectionTitle": "3.9 Screening", - "indicators": [ - { - "label": "Screened for TB -Below 15yrs(M)", - "ref": "HV03-50", - "indicator": "dc__gender__M__age_range__below_15_years__tb_screened_this_visit_this_month" - }, - { - "label": "Screened for TB -Below 15yrs(F)", - "ref": "HV03-51", - "indicator": "dc__gender__F__age_range__below_15_years__tb_screened_this_visit_this_month" - }, - { - "label": "Screened for TB -15yrs & older(M)", - "ref": "HV03-52", - "indicator": "dc__gender__M__age_range__older_than_15__tb_screened_this_visit_this_month" - }, - { - "label": "Screened for TB -15yrs & older(F)", - "ref": "HV03-53", - "indicator": "dc__gender__F__age_range__older_than_15__tb_screened_this_visit_this_month" - }, - { - "label": "Total Screened for TB (Sum HV03-50 to HV03-53)", - "ref": "HV03-54", - "indicator": "tb_screened_this_visit_this_month" - }, - { - "label": "Screened for cervical cancer (F 18 years and older)", - "ref": "HV03-55", - "indicator": "Screened_for_cervical_cancer" - } - ] - }, - { - "sectionTitle": "3.10 Prevention with Positives", - "indicators": [ - { - "label": "Modern contraceptive methods", - "ref": "HV09-04", - "indicator": "on_modern_contraception" - }, - { - "label": "Provided with condoms", - "ref": "HV09-05", - "indicator": "condoms_provided" - } - ] - }, - { - "sectionTitle": "3.11 HIV Care Visits", - "indicators": [ - { - "label": "Females (18 years and older)", - "ref": "HV03-70", - "indicator": "f_gte_18_visits" - }, - { - "label": "Scheduled", - "ref": "HV03-71", - "indicator": "scheduled_visits" - }, - { - "label": "Unscheduled", - "ref": "HV03-72", - "indicator": "unscheduled_visits" - }, - { - "label": "Total HIV Care visit", - "ref": "HV03-73", - "indicator": "total_visits" - } - ] - }, - { - "sectionTitle": "5. Post Exposure Prophylaxis", - "indicators": [ - { - "label": "Exposed Occupational", - "ref": "HV05-01", - "indicator": "hiv_exposed_occupational" - }, - { - "label": "Exposed Other", - "ref": "HV05-02", - "indicator": "hiv_exposed_non_occupational" - }, - { - "label": "Exposed Total (Sum HV05-01 and HV05-02)", - "ref": "HV05-03", - "indicator": "total_hiv_exposed" - }, - { - "label": "PEP Occupational", - "ref": "HV05-04", - "indicator": "started_PEP_occupational" - }, - { - "label": "PEP Other", - "ref": "HV05-05", - "indicator": "started_PEP_non_occupational" - }, - { - "label": "PEP Total (Sum HV05-04 and HV05-05)", - "ref": "HV03-06", - "indicator": "total_started_PEP" - } - ] - } + { + "sectionTitle": "3.1 On Cotrimoxazole Prophylaxis (within 2 months)", + "indicators": [ + { + "label": "HIV Exposed Infants (within 2 months)", + "ref": "HV03-01", + "indicator": "hiv_exposed_infants_below_2_months" + }, + { + "label": "HIV Exposed Infant (Eligible for CTX within 2 months)", + "ref": "HV03-02", + "indicator": "hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below" + }, + { + "label": "On CTX Below 15 yrs(M)", + "ref": "HV03-03", + "indicator": "dc__gender__M__age_range__below_15_years__on_ctx_prophylaxis" + }, + { + "label": "On CTX Below 15 yrs(F)", + "ref": "HV03-04", + "indicator": "dc__gender__F__age_range__below_15_years__on_ctx_prophylaxis" + }, + { + "label": "On CTX 15 yrs and Older(M)", + "ref": "HV03-05", + "indicator": "dc__gender__M__age_range__older_than_15__on_ctx_prophylaxis" + }, + { + "label": "On CTX 15 yrs and Older(F)", + "ref": "HV03-06", + "indicator": "dc__gender__F__age_range__older_than_15__on_ctx_prophylaxis" + }, + { + "label": "Total on CTX (Sum HV03-03 TO HV03-06)", + "ref": "HV03-07", + "indicator": "on_ctx_prophylaxis" + } + ] + }, + { + "sectionTitle": "3.2 Enrolled in Care", + "indicators": [ + { + "label": "Enrolled in care Below 1yr(M)", + "ref": "HV03-08", + "indicator": "dc__gender__M__age_range__0_to_1__enrolled_this_month" + }, + { + "label": "Enrolled in care Below 1yr(F)", + "ref": "HV03-08", + "indicator": "dc__gender__F__age_range__0_to_1__enrolled_this_month" + }, + { + "label": "Enrolled in care Below 15yrs(M)", + "ref": "HV03-09", + "indicator": "dc__gender__M__age_range__below_15_years__enrolled_this_month" + }, + { + "label": "Enrolled in care Below 15yrs(F)", + "ref": "HV03-10", + "indicator": "dc__gender__F__age_range__below_15_years__enrolled_this_month" + }, + { + "label": "Enrolled in care 15yrs & Older(M)", + "ref": "HV03-11", + "indicator": "dc__gender__M__age_range__older_than_15__enrolled_this_month" + }, + { + "label": "Enrolled in care 15yrs & Older(F)", + "ref": "HV03-12", + "indicator": "dc__gender__F__age_range__older_than_15__enrolled_this_month" + }, + { + "label": "Enrolled in care - Total (Sum HV03-09 to HV03-12)", + "ref": "HV03-13", + "indicator": "enrolled_this_month" + } + ] + }, + { + "sectionTitle": "3.3 Currently in Care -(from the total sheet-this month only and from last 2 months)", + "indicators": [ + { + "label": "Currently in care Below 1yr(M)", + "ref": "HV03-14", + "indicator": "dc__gender__M__age_range__0_to_1__current_in_care" + }, + { + "label": "Currently in care Below 1yr(F)", + "ref": "HV03-14", + "indicator": "dc__gender__F__age_range__0_to_1__current_in_care" + }, + { + "label": "Currently in care Below 15yrs(M)", + "ref": "HV03-15", + "indicator": "dc__gender__M__age_range__below_15_years__current_in_care" + }, + { + "label": "Currently in care Below 15yrs(F)", + "ref": "HV03-16", + "indicator": "dc__gender__F__age_range__below_15_years__current_in_care" + }, + { + "label": "Currently in care 15yrs and older(M)", + "ref": "HV03-17", + "indicator": "dc__gender__M__age_range__older_than_15__current_in_care" + }, + { + "label": "Currently in care 15yrs and older(F)", + "ref": "HV03-18", + "indicator": "dc__gender__F__age_range__older_than_15__current_in_care" + }, + { + "label": "Currently in Care-Total (Sum HV03-15 to HV03-18)", + "ref": "HV03-19", + "indicator": "current_in_care" + } + ] + }, + { + "sectionTitle": "3.4 Starting ART", + "indicators": [ + { + "label": "Starting ART -Below 1yr(M)", + "ref": "HV03-20", + "indicator": "dc__age_range__0_to_1__gender__M__started_art" + }, + { + "label": "Starting ART -Below 1yr(F)", + "ref": "HV03-20", + "indicator": "dc__age_range__0_to_1__gender__F__started_art" + }, + { + "label": "Starting ART -Below 15yrs(M)", + "ref": "HV03-21", + "indicator": "dc__age_range__below_15_years__gender__M__started_art" + }, + { + "label": "Starting ART -Below 15yrs(F)", + "ref": "HV03-22", + "indicator": "dc__age_range__below_15_years__gender__F__started_art" + }, + { + "label": "Starting ART -15yr and Older(M)", + "ref": "HV03-23", + "indicator": "dc__age_range__older_than_15__gender__M__started_art" + }, + { + "label": "Starting ART -15yr and Older(F)", + "ref": "HV03-24", + "indicator": "dc__age_range__older_than_15__gender__F__started_art" + }, + { + "label": "Starting on ART -Total (Sum HV03-21 to HV03-24)", + "ref": "HV03-25", + "indicator": "started_art" + }, + { + "label": "Starting -Pregnant", + "ref": "HV03-26", + "indicator": "started_art_pregnant" + }, + { + "label": "Starting -TB Patient", + "ref": "HV03-27", + "indicator": "started_art_and_has_tb" + } + ] + }, + { + "sectionTitle": "3.5 Revisits on ART (from the tally sheet -this month only and from last 2 months)", + "indicators": [ + { + "label": "Revisit on ART -Below 1yr(M)", + "ref": "HV03-28", + "indicator": "dc__gender__M__age_range__0_to_1__art_revisit_this_month" + }, + { + "label": "Revisit on ART -Below 1yr(F)", + "ref": "HV03-28", + "indicator": "dc__gender__F__age_range__0_to_1__art_revisit_this_month" + }, + { + "label": "Revisit on ART -Below 15yrs(M)", + "ref": "HV03-29", + "indicator": "dc__gender__M__age_range__below_15_years__art_revisit_this_month" + }, + { + "label": "Revisit on ART -Below 15yrs(F)", + "ref": "HV03-30", + "indicator": "dc__gender__F__age_range__below_15_years__art_revisit_this_month" + }, + { + "label": "Revisit on ART -15yrs and older(M)", + "ref": "HV03-31", + "indicator": "dc__gender__M__age_range__older_than_15__art_revisit_this_month" + }, + { + "label": "Revisit on ART -15yrs and older(F)", + "ref": "HV03-32", + "indicator": "dc__gender__F__age_range__older_than_15__art_revisit_this_month" + }, + { + "label": "Total Revisit on ART (Sum HV03-29 to HV03-32)", + "ref": "HV03-33", + "indicator": "art_revisit_this_month" + } + ] + }, + { + "sectionTitle": "3.6 Currently on ART [ALL] - (Add 3.4 and 3.5 e.g HV03-34=HV03-20+HV03-28)", + "indicators": [ + { + "label": "Currently on ART - Below 1yr(M)", + "ref": "HV03-34", + "indicator": "dc__gender__M__age_range__0_to_1__current_on_art" + }, + { + "label": "Currently on ART - Below 1yr(F)", + "ref": "HV03-34", + "indicator": "dc__gender__F__age_range__0_to_1__current_on_art" + }, + { + "label": "Currently on ART - Below 15 yrs(M)", + "ref": "HV03-35", + "indicator": "dc__gender__M__age_range__below_15_years__current_on_art" + }, + { + "label": "Currently on ART - Below 15 yrs(F)", + "ref": "HV03-36", + "indicator": "dc__gender__F__age_range__below_15_years__current_on_art" + }, + { + "label": "Currently on ART -15yr and older(M)", + "ref": "HV03-37", + "indicator": "dc__gender__M__age_range__older_than_15__current_on_art" + }, + { + "label": "Currently on ART -15yr and older(F)", + "ref": "HV03-38", + "indicator": "dc__gender__F__age_range__older_than_15__current_on_art" + }, + { + "label": "Total currently on ART (Sum HV03-35 to HV03-38)", + "ref": "HV03-39", + "indicator": "current_on_art" + } + ] + }, + { + "sectionTitle": "3.7 Cumulative Ever on ART", + "indicators": [ + { + "label": "Ever on ART - Below 15yrs(M)", + "ref": "HV03-40", + "indicator": "dc__gender__M__age_range__below_15__ever_on_art" + }, + { + "label": "Ever on ART - Below 15yrs(F)", + "ref": "HV03-41", + "indicator": "dc__gender__F__age_range__below_15__ever_on_art" + }, + { + "label": "Ever on ART - 15yrs & older(M)", + "ref": "HV03-42", + "indicator": "dc__gender__M__age_range__15_and_above__ever_on_art" + }, + { + "label": "Ever on ART - 15yrs & older(F)", + "ref": "HV03-43", + "indicator": "dc__gender__F__age_range__15_and_above__ever_on_art" + }, + { + "label": "Total Ever on ART (Sum HV03-40 to HV03-43)", + "ref": "HV03-44", + "indicator": "ever_on_art" + } + ] + }, + { + "sectionTitle": "3.8 Survival and Retention on ART at 12 months", + "indicators": [ + { + "label": "ART Net Cohort at 12 months", + "ref": "HV03-45", + "indicator": "net_cohort" + }, + { + "label": "On Original 1st Line at 12 months", + "ref": "HV03-46", + "indicator": "on_original_first_line" + }, + { + "label": "On alternative 1st Line at 12 months", + "ref": "HV03-47", + "indicator": "on_alternative_first_line" + }, + { + "label": "On 2nd Line (or higher) at 12 months", + "ref": "HV03-48", + "indicator": "on_second_line" + }, + { + "label": "Total on therapy at 12 months (Sum HV03-46 to HV03-48)", + "ref": "HV03-49", + "indicator": "on_tx" + } + ] + }, + { + "sectionTitle": "3.9 Screening", + "indicators": [ + { + "label": "Screened for TB -Below 15yrs(M)", + "ref": "HV03-50", + "indicator": "dc__gender__M__age_range__below_15_years__tb_screened_this_visit_this_month" + }, + { + "label": "Screened for TB -Below 15yrs(F)", + "ref": "HV03-51", + "indicator": "dc__gender__F__age_range__below_15_years__tb_screened_this_visit_this_month" + }, + { + "label": "Screened for TB -15yrs & older(M)", + "ref": "HV03-52", + "indicator": "dc__gender__M__age_range__older_than_15__tb_screened_this_visit_this_month" + }, + { + "label": "Screened for TB -15yrs & older(F)", + "ref": "HV03-53", + "indicator": "dc__gender__F__age_range__older_than_15__tb_screened_this_visit_this_month" + }, + { + "label": "Total Screened for TB (Sum HV03-50 to HV03-53)", + "ref": "HV03-54", + "indicator": "tb_screened_this_visit_this_month" + }, + { + "label": "Screened for cervical cancer (F 18 years and older)", + "ref": "HV03-55", + "indicator": "Screened_for_cervical_cancer" + } + ] + }, + { + "sectionTitle": "3.10 Prevention with Positives", + "indicators": [ + { + "label": "Modern contraceptive methods", + "ref": "HV09-04", + "indicator": "on_modern_contraception" + }, + { + "label": "Provided with condoms", + "ref": "HV09-05", + "indicator": "condoms_provided" + } + ] + }, + { + "sectionTitle": "3.11 HIV Care Visits", + "indicators": [ + { + "label": "Females (18 years and older)", + "ref": "HV03-70", + "indicator": "f_gte_18_visits" + }, + { + "label": "Scheduled", + "ref": "HV03-71", + "indicator": "scheduled_visits" + }, + { + "label": "Unscheduled", + "ref": "HV03-72", + "indicator": "unscheduled_visits" + }, + { + "label": "Total HIV Care visit", + "ref": "HV03-73", + "indicator": "total_visits" + } + ] + }, + { + "sectionTitle": "5. Post Exposure Prophylaxis", + "indicators": [ + { + "label": "Exposed Occupational", + "ref": "HV05-01", + "indicator": "hiv_exposed_occupational" + }, + { + "label": "Exposed Other", + "ref": "HV05-02", + "indicator": "hiv_exposed_non_occupational" + }, + { + "label": "Exposed Total (Sum HV05-01 and HV05-02)", + "ref": "HV05-03", + "indicator": "total_hiv_exposed" + }, + { + "label": "PEP Occupational", + "ref": "HV05-04", + "indicator": "started_PEP_occupational" + }, + { + "label": "PEP Other", + "ref": "HV05-05", + "indicator": "started_PEP_non_occupational" + }, + { + "label": "PEP Total (Sum HV05-04 and HV05-05)", + "ref": "HV03-06", + "indicator": "total_started_PEP" + } + ] + } ] diff --git a/app/reporting-framework/hiv/moh-731.report.js b/app/reporting-framework/hiv/moh-731.report.js index 5bfc6c880..1be930744 100755 --- a/app/reporting-framework/hiv/moh-731.report.js +++ b/app/reporting-framework/hiv/moh-731.report.js @@ -1,10 +1,6 @@ -import { - MultiDatasetPatientlistReport -} from '..//multi-dataset-patientlist.report'; +import { MultiDatasetPatientlistReport } from '..//multi-dataset-patientlist.report'; import ReportProcessorHelpersService from '../report-processor-helpers.service'; -import { - Promise -} from 'bluebird'; +import { Promise } from 'bluebird'; const Moment = require('moment'); const moh731GreenCarddefs = require('./moh-731-2017'); const moh731BlueCarddefs = require('./moh-731-legacy'); @@ -12,161 +8,201 @@ const cbhipIndicatorDefs = require('./cbhip-indicator-definitions.json'); const dao = require('../../../etl-dao'); export class Moh731Report extends MultiDatasetPatientlistReport { - constructor(reportName, params) { - if (params.isAggregated) { - params.excludeParam = ['location_id', 'arv_first_regimen_location_id']; - params.joinColumnParam = 'join_location'; - } - params.hivMonthlyDatasetSource = 'etl.hiv_monthly_report_dataset_frozen'; // defaults to frozen - - console.log('creating new moh 731 report service') - super(reportName, params) + constructor(reportName, params) { + if (params.isAggregated) { + params.excludeParam = ['location_id', 'arv_first_regimen_location_id']; + params.joinColumnParam = 'join_location'; } - - generateReport(additionalParams) { - const that = this; - return new Promise((resolve, reject) => { - that.determineMohReportSourceTables() - .then((res)=> { - console.log('Params:::', that.params); - super.generateReport(additionalParams) - .then((results) => { - if (additionalParams && additionalParams.type === 'patient-list') { - resolve(results); - } else { - - let finalResult = [] - const reportProcessorHelpersService = new ReportProcessorHelpersService(); - for (let result of results) { - if (result.report && result.report.reportSchemas && result.report.reportSchemas.main && - result.report.reportSchemas.main.transFormDirectives.joinColumn) { - finalResult = reportProcessorHelpersService - .joinDataSets(that.params[result.report.reportSchemas.main.transFormDirectives.joinColumnParam] || - result.report.reportSchemas.main.transFormDirectives.joinColumn, - finalResult, result.results.results.results); - - } - } - - if(this.params && this.params.isAggregated === true) { - finalResult[0].location = 'Multiple Locations...'; - } - - let sectionDefs = null; - - if(that.params.exclude == 'moh731') { - sectionDefs = cbhipIndicatorDefs; - }else { - sectionDefs = that.reportName === 'MOH-731-greencard' ? moh731GreenCarddefs : moh731BlueCarddefs; - } - - resolve({ - queriesAndSchemas: results, - result: finalResult, - sectionDefinitions: sectionDefs, - indicatorDefinitions: [], - isReleased: that.params.hivMonthlyDatasetSource === 'etl.hiv_monthly_report_dataset_frozen' - }); - } - }) - .catch((error) => { - console.error('MOH 731 generation error: ', error); - reject(error); + params.hivMonthlyDatasetSource = 'etl.hiv_monthly_report_dataset_frozen'; // defaults to frozen + + console.log('creating new moh 731 report service'); + super(reportName, params); + } + + generateReport(additionalParams) { + const that = this; + return new Promise((resolve, reject) => { + that + .determineMohReportSourceTables() + .then((res) => { + console.log('Params:::', that.params); + super + .generateReport(additionalParams) + .then((results) => { + if ( + additionalParams && + additionalParams.type === 'patient-list' + ) { + resolve(results); + } else { + let finalResult = []; + const reportProcessorHelpersService = new ReportProcessorHelpersService(); + for (let result of results) { + if ( + result.report && + result.report.reportSchemas && + result.report.reportSchemas.main && + result.report.reportSchemas.main.transFormDirectives + .joinColumn + ) { + finalResult = reportProcessorHelpersService.joinDataSets( + that.params[ + result.report.reportSchemas.main.transFormDirectives + .joinColumnParam + ] || + result.report.reportSchemas.main.transFormDirectives + .joinColumn, + finalResult, + result.results.results.results + ); + } + } + + if (this.params && this.params.isAggregated === true) { + finalResult[0].location = 'Multiple Locations...'; + } + + let sectionDefs = null; + + if (that.params.exclude == 'moh731') { + sectionDefs = cbhipIndicatorDefs; + } else { + sectionDefs = + that.reportName === 'MOH-731-greencard' + ? moh731GreenCarddefs + : moh731BlueCarddefs; + } + + resolve({ + queriesAndSchemas: results, + result: finalResult, + sectionDefinitions: sectionDefs, + indicatorDefinitions: [], + isReleased: + that.params.hivMonthlyDatasetSource === + 'etl.hiv_monthly_report_dataset_frozen' }); + } }) - .catch((err)=>{ - console.error('MOH 731 generation error: ', err); - reject(error); + .catch((error) => { + console.error('MOH 731 generation error: ', error); + reject(error); }); + }) + .catch((err) => { + console.error('MOH 731 generation error: ', err); + reject(error); }); - } - - generatePatientListReport(indicators) { - let self = this; - let moh731defs = this.reportName === 'MOH-731-greencard' ? moh731GreenCarddefs : moh731BlueCarddefs; - return new Promise((resolve, reject) => { - self.determineMohReportSourceTables() - .then((res) => { - super.generatePatientListReport(indicators) - .then((results) => { - let indicatorLabels = self.getIndicatorSectionDefinitions(results.indicators, - moh731defs); - - results.indicators = indicatorLabels; - - results.isReleased = self.params.hivMonthlyDatasetSource === 'etl.hiv_monthly_report_dataset_frozen'; - - self.resolveLocationUuidsToName(self.params.locationUuids) - .then((locations) => { - results.locations = locations; - resolve(results); - }) - .catch((err) => { - resolve(results); - }); - - }) - .catch((err) => { - console.error('MOH patient list generation error', err); - reject(err); - }); + }); + } + + generatePatientListReport(indicators) { + let self = this; + let moh731defs = + this.reportName === 'MOH-731-greencard' + ? moh731GreenCarddefs + : moh731BlueCarddefs; + return new Promise((resolve, reject) => { + self + .determineMohReportSourceTables() + .then((res) => { + super + .generatePatientListReport(indicators) + .then((results) => { + let indicatorLabels = self.getIndicatorSectionDefinitions( + results.indicators, + moh731defs + ); + + results.indicators = indicatorLabels; + + results.isReleased = + self.params.hivMonthlyDatasetSource === + 'etl.hiv_monthly_report_dataset_frozen'; + + self + .resolveLocationUuidsToName(self.params.locationUuids) + .then((locations) => { + results.locations = locations; + resolve(results); }) .catch((err) => { - console.error('MOH 731 generation error: ', err); - reject(error); - }); - }); - } - - getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { - let results = []; - _.each(requestIndicators, function (requestIndicator) { - _.each(sectionDefinitions, function (sectionDefinition) { - _.each(sectionDefinition.indicators, function (indicator) { - if (indicator.indicator === requestIndicator) { - // console.log('Found indicator', requestIndicator); - results.push(indicator); - } + resolve(results); }); + }) + .catch((err) => { + console.error('MOH patient list generation error', err); + reject(err); }); + }) + .catch((err) => { + console.error('MOH 731 generation error: ', err); + reject(error); }); - return results; - } - - resolveLocationUuidsToName(uuids) { - return new Promise((resolve, reject) => { - // resolve location name - dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { - resolve(loc); - }); + }); + } + + getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { + let results = []; + _.each(requestIndicators, function (requestIndicator) { + _.each(sectionDefinitions, function (sectionDefinition) { + _.each(sectionDefinition.indicators, function (indicator) { + if (indicator.indicator === requestIndicator) { + // console.log('Found indicator', requestIndicator); + results.push(indicator); + } }); - } - - determineMohReportSourceTables() { - const self = this; - return new Promise((resolve, reject) => { - let query = 'select * from etl.moh_731_last_release_month'; - let runner = self.getSqlRunner(); - - runner.executeQuery(query) - .then( - (results) => { - let lastReleasedMonth = results[0]['last_released_month']; - console.log('Last released MOH 731 month: ' + Moment(lastReleasedMonth).toLocaleString()); - console.log('MOH 731 Request Month: ' + Moment(self.params.endDate).toLocaleString()); - if (Moment(lastReleasedMonth).isSameOrAfter(Moment(self.params.endDate))) { - self.params.hivMonthlyDatasetSource = 'etl.hiv_monthly_report_dataset_frozen'; - } else { - self.params.hivMonthlyDatasetSource = 'etl.hiv_monthly_report_dataset_v1_2'; - } - console.log('Using Datasource::: ', self.params.hivMonthlyDatasetSource) - resolve(self.params.hivMonthlyDatasetSource); - }) - .catch((error) => { - console.error('Error getting moh 731 released report month:', error); - reject(error); - }); - + }); + }); + return results; + } + + resolveLocationUuidsToName(uuids) { + return new Promise((resolve, reject) => { + // resolve location name + dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { + resolve(loc); + }); + }); + } + + determineMohReportSourceTables() { + const self = this; + return new Promise((resolve, reject) => { + let query = 'select * from etl.moh_731_last_release_month'; + let runner = self.getSqlRunner(); + + runner + .executeQuery(query) + .then((results) => { + let lastReleasedMonth = results[0]['last_released_month']; + console.log( + 'Last released MOH 731 month: ' + + Moment(lastReleasedMonth).toLocaleString() + ); + console.log( + 'MOH 731 Request Month: ' + + Moment(self.params.endDate).toLocaleString() + ); + if ( + Moment(lastReleasedMonth).isSameOrAfter(Moment(self.params.endDate)) + ) { + self.params.hivMonthlyDatasetSource = + 'etl.hiv_monthly_report_dataset_frozen'; + } else { + self.params.hivMonthlyDatasetSource = + 'etl.hiv_monthly_report_dataset_v1_2'; + } + console.log( + 'Using Datasource::: ', + self.params.hivMonthlyDatasetSource + ); + resolve(self.params.hivMonthlyDatasetSource); + }) + .catch((error) => { + console.error('Error getting moh 731 released report month:', error); + reject(error); }); - } -} \ No newline at end of file + }); + } +} diff --git a/app/reporting-framework/hiv/retention-adherence-indicators.json b/app/reporting-framework/hiv/retention-adherence-indicators.json index d9f0401df..067c5fdbb 100644 --- a/app/reporting-framework/hiv/retention-adherence-indicators.json +++ b/app/reporting-framework/hiv/retention-adherence-indicators.json @@ -1,94 +1,94 @@ +{ + "indicators": [ { - "indicators": [ - { - "label": "Patients Scheduled", - "name": "patients_scheduled", - "description": "Clients booked for that day" - }, - { - "label": "Attended clinic on the date scheduled", - "name": "attended_clinic_on_date_scheduled", - "description": "Clients attended on the booked day" - }, - { - "label": "Number of unscheduled Early visits", - "name": "unscheduled_early_visits", - "description": "Clients who come before their scheduled appointment day" - }, - { - "label": "Number of unscheduled Late visits", - "name": "unscheduled_late_visits", - "description": "Clients who come after their scheduled appointment day" - }, - { - "label": "Number of defaulters during the day", - "name": "defaulted", - "description": "Clients who did not attend clinic on the appointment date" - }, - { - "label": "Number Newly enrolled", - "name": "newly_enrolled", - "description": "Clients new on ART" - }, - { - "label": "Number of transfer Ins", - "name": "transfer_in", - "description": "Clients coming from another ampath or Non-ampath facility" - }, - { - "label": "Number reached by Phone", - "name": "reached_by_phone", - "description": "Defaulted clients whom a phone attempt was done and were reached" - }, - { - "label": "Number Not reached by Phone", - "name": "not_reached_by_phone", - "description": "Defaulted clients whom a phone attempt was done but was not reached.(due to phone inactive,phone not answered,wrong phone number)" - }, - { - "label": "Number traced physically/visited and found", - "name": "home_visit_found", - "description": "Defaulted clients whom a home visit was done and they were found" - }, - { - "label": "Number traced physically/visited and not found", - "name": "home_visit_not_found", - "description": "Defaulted clients whom a home visit was done and they were not found" - }, - { - "label": "Number with No attempt to locate(28 days after RTC date)", - "name": "no_attempt_to_contact_28_days_after_rtc", - "description": "Defaulted clients whom a home visit/Phone call attempt was not done (28 days after RTC date)- i.e they don't have a defaulter tracing form" - }, - { - "label": "Number returned back to care after an intervention", - "name": "returned_back_after_intervention", - "description": "Defaulters returned to care after a phone or home visit" - }, - { - "label": "Number returned back to care without any intervention", - "name": "returned_back_without_intervention", - "description": "Defaulters returned to care without a phone or home visit" - }, - { - "label": "Number self-transferred out", - "name": "self_transferred_out", - "description": "Defaulters silently transferred (No documented transfer form filled)" - }, - { - "label": "Number deceased", - "name": "deceased", - "description": "Defaulters with a deceased outcome" - }, - { - "label": "Number self-disengaged from care", - "name": "self_disengaged", - "description": "Defaulters who have refused to continue with care and have self-disengaged outcome" - }, - { - "label": "Number Newly LTFU", - "name": "newly_ltfu", - "description": "Defaulters who have missed care 90+ days" - } - ] - } \ No newline at end of file + "label": "Patients Scheduled", + "name": "patients_scheduled", + "description": "Clients booked for that day" + }, + { + "label": "Attended clinic on the date scheduled", + "name": "attended_clinic_on_date_scheduled", + "description": "Clients attended on the booked day" + }, + { + "label": "Number of unscheduled Early visits", + "name": "unscheduled_early_visits", + "description": "Clients who come before their scheduled appointment day" + }, + { + "label": "Number of unscheduled Late visits", + "name": "unscheduled_late_visits", + "description": "Clients who come after their scheduled appointment day" + }, + { + "label": "Number of defaulters during the day", + "name": "defaulted", + "description": "Clients who did not attend clinic on the appointment date" + }, + { + "label": "Number Newly enrolled", + "name": "newly_enrolled", + "description": "Clients new on ART" + }, + { + "label": "Number of transfer Ins", + "name": "transfer_in", + "description": "Clients coming from another ampath or Non-ampath facility" + }, + { + "label": "Number reached by Phone", + "name": "reached_by_phone", + "description": "Defaulted clients whom a phone attempt was done and were reached" + }, + { + "label": "Number Not reached by Phone", + "name": "not_reached_by_phone", + "description": "Defaulted clients whom a phone attempt was done but was not reached.(due to phone inactive,phone not answered,wrong phone number)" + }, + { + "label": "Number traced physically/visited and found", + "name": "home_visit_found", + "description": "Defaulted clients whom a home visit was done and they were found" + }, + { + "label": "Number traced physically/visited and not found", + "name": "home_visit_not_found", + "description": "Defaulted clients whom a home visit was done and they were not found" + }, + { + "label": "Number with No attempt to locate(28 days after RTC date)", + "name": "no_attempt_to_contact_28_days_after_rtc", + "description": "Defaulted clients whom a home visit/Phone call attempt was not done (28 days after RTC date)- i.e they don't have a defaulter tracing form" + }, + { + "label": "Number returned back to care after an intervention", + "name": "returned_back_after_intervention", + "description": "Defaulters returned to care after a phone or home visit" + }, + { + "label": "Number returned back to care without any intervention", + "name": "returned_back_without_intervention", + "description": "Defaulters returned to care without a phone or home visit" + }, + { + "label": "Number self-transferred out", + "name": "self_transferred_out", + "description": "Defaulters silently transferred (No documented transfer form filled)" + }, + { + "label": "Number deceased", + "name": "deceased", + "description": "Defaulters with a deceased outcome" + }, + { + "label": "Number self-disengaged from care", + "name": "self_disengaged", + "description": "Defaulters who have refused to continue with care and have self-disengaged outcome" + }, + { + "label": "Number Newly LTFU", + "name": "newly_ltfu", + "description": "Defaulters who have missed care 90+ days" + } + ] +} diff --git a/app/reporting-framework/hiv/retention-report.json b/app/reporting-framework/hiv/retention-report.json index 8a0bf20ee..17d97262a 100644 --- a/app/reporting-framework/hiv/retention-report.json +++ b/app/reporting-framework/hiv/retention-report.json @@ -1,102 +1,102 @@ [ - { - "sectionTitle": "Appointment Adherence", - "indicators": [ - { - "label": "Patients Scheduled", - "ref": "", - "indicator": "patients_scheduled" - }, - { - "label": "Attended clinic on the date scheduled", - "ref": "", - "indicator": "attended_clinic_on_date_scheduled" - }, - { - "label": "Number of unscheduled Early visits", - "ref": "", - "indicator": "unscheduled_early_visits" - }, - { - "label": "Number of unscheduled Late visits", - "ref": "", - "indicator": "unscheduled_late_visits" - }, - { - "label": "Number of defaulters during the day", - "ref": "", - "indicator": "defaulted" - }, - { - "label": "Number Newly enrolled", - "ref": "", - "indicator": "newly_enrolled" - }, - { - "label": "Number of transfer Ins", - "ref": "", - "indicator": "transfer_in" - } - ] - }, - { - "sectionTitle": "Defaulter Tracing", - "indicators": [ - { - "label": "Number reached by Phone", - "ref": "", - "indicator": "reached_by_phone" - }, - { - "label": "Number Not reached by Phone", - "ref": "", - "indicator": "not_reached_by_phone" - }, - { - "label": "Number traced physically/visited and found", - "ref": "", - "indicator": "home_visit_found" - }, - { - "label": "Number traced physically/visited and not found", - "ref": "", - "indicator": "home_visit_not_found" - }, - { - "label": "Number with No attempt to locate(28 days after RTC date)", - "ref": "", - "indicator": "no_attempt_to_contact_28_days_after_rtc" - }, - { - "label": "Number returned back to care after an intervention", - "ref": "", - "indicator": "returned_after_intervention" - }, - { - "label": "Number returned back to care without any intervention", - "ref": "", - "indicator": "returned_without_intervention" - }, - { - "label": "Number self-transferred out", - "ref": "", - "indicator": "self_transferred_out" - }, - { - "label": "Number deceased", - "ref": "", - "indicator": "deceased" - }, - { - "label": "Number self-disengaged from care", - "ref": "", - "indicator": "self_disengaged" - }, - { - "label": "Number Newly LTFU", - "ref": "", - "indicator": "newly_ltfu" - } - ] - } -] \ No newline at end of file + { + "sectionTitle": "Appointment Adherence", + "indicators": [ + { + "label": "Patients Scheduled", + "ref": "", + "indicator": "patients_scheduled" + }, + { + "label": "Attended clinic on the date scheduled", + "ref": "", + "indicator": "attended_clinic_on_date_scheduled" + }, + { + "label": "Number of unscheduled Early visits", + "ref": "", + "indicator": "unscheduled_early_visits" + }, + { + "label": "Number of unscheduled Late visits", + "ref": "", + "indicator": "unscheduled_late_visits" + }, + { + "label": "Number of defaulters during the day", + "ref": "", + "indicator": "defaulted" + }, + { + "label": "Number Newly enrolled", + "ref": "", + "indicator": "newly_enrolled" + }, + { + "label": "Number of transfer Ins", + "ref": "", + "indicator": "transfer_in" + } + ] + }, + { + "sectionTitle": "Defaulter Tracing", + "indicators": [ + { + "label": "Number reached by Phone", + "ref": "", + "indicator": "reached_by_phone" + }, + { + "label": "Number Not reached by Phone", + "ref": "", + "indicator": "not_reached_by_phone" + }, + { + "label": "Number traced physically/visited and found", + "ref": "", + "indicator": "home_visit_found" + }, + { + "label": "Number traced physically/visited and not found", + "ref": "", + "indicator": "home_visit_not_found" + }, + { + "label": "Number with No attempt to locate(28 days after RTC date)", + "ref": "", + "indicator": "no_attempt_to_contact_28_days_after_rtc" + }, + { + "label": "Number returned back to care after an intervention", + "ref": "", + "indicator": "returned_after_intervention" + }, + { + "label": "Number returned back to care without any intervention", + "ref": "", + "indicator": "returned_without_intervention" + }, + { + "label": "Number self-transferred out", + "ref": "", + "indicator": "self_transferred_out" + }, + { + "label": "Number deceased", + "ref": "", + "indicator": "deceased" + }, + { + "label": "Number self-disengaged from care", + "ref": "", + "indicator": "self_disengaged" + }, + { + "label": "Number Newly LTFU", + "ref": "", + "indicator": "newly_ltfu" + } + ] + } +] diff --git a/app/reporting-framework/json-reports/breast-cancer-daily-screening-summary-aggregate.json b/app/reporting-framework/json-reports/breast-cancer-daily-screening-summary-aggregate.json index 278c79f6b..8a56fd6bb 100644 --- a/app/reporting-framework/json-reports/breast-cancer-daily-screening-summary-aggregate.json +++ b/app/reporting-framework/json-reports/breast-cancer-daily-screening-summary-aggregate.json @@ -285,10 +285,7 @@ ], "groupBy": { "groupParam": "groupByParam", - "columns": [ - "location_id", - "DATE(bcsd.encounter_datetime)" - ], + "columns": ["location_id", "DATE(bcsd.encounter_datetime)"], "excludeParam": "excludeParam" }, "dynamicJsonQueryGenerationDirectives": { @@ -305,4 +302,4 @@ } } } -} \ No newline at end of file +} diff --git a/app/reporting-framework/json-reports/breast-cancer-monthly-screening-summary-aggregate.json b/app/reporting-framework/json-reports/breast-cancer-monthly-screening-summary-aggregate.json index f0d1eeab2..9ff47e0fa 100644 --- a/app/reporting-framework/json-reports/breast-cancer-monthly-screening-summary-aggregate.json +++ b/app/reporting-framework/json-reports/breast-cancer-monthly-screening-summary-aggregate.json @@ -306,4 +306,4 @@ } } } -} \ No newline at end of file +} diff --git a/app/reporting-framework/json-reports/breast-cancer-monthly-screening-summary-base.json b/app/reporting-framework/json-reports/breast-cancer-monthly-screening-summary-base.json index dc9dc19ec..81830d996 100644 --- a/app/reporting-framework/json-reports/breast-cancer-monthly-screening-summary-base.json +++ b/app/reporting-framework/json-reports/breast-cancer-monthly-screening-summary-base.json @@ -1009,8 +1009,6 @@ }, "groupBy": { "groupParam": "groupByParam", - "columns": [ - "encounter_id" - ] + "columns": ["encounter_id"] } -} \ No newline at end of file +} diff --git a/app/reporting-framework/json-reports/breast-cancer-patient-list-template.json b/app/reporting-framework/json-reports/breast-cancer-patient-list-template.json index fa48fd3c9..a81b28c3b 100644 --- a/app/reporting-framework/json-reports/breast-cancer-patient-list-template.json +++ b/app/reporting-framework/json-reports/breast-cancer-patient-list-template.json @@ -186,8 +186,6 @@ } ], "groupBy": { - "columns": [ - "t1.person_id" - ] + "columns": ["t1.person_id"] } -} \ No newline at end of file +} diff --git a/app/reporting-framework/json-reports/cdm/cdm-dataset-base.json b/app/reporting-framework/json-reports/cdm/cdm-dataset-base.json index 4e266c398..8fa9aab7d 100644 --- a/app/reporting-framework/json-reports/cdm/cdm-dataset-base.json +++ b/app/reporting-framework/json-reports/cdm/cdm-dataset-base.json @@ -1,221 +1,218 @@ { - "name": "cdmDataSetbase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - - { - "table": "etl.flat_cdm", - "alias": "t1" - }, - { - "table": "amrs.person", - "alias": "t2", - "join": { - "type": "INNER", - "joinCondition": "t2.person_id = t1.person_id" - } - }, - { - "table": "amrs.person_name", - "alias": "t3", - "join": { - "type": "INNER", - "joinCondition": "t3.person_id = t2.person_id" - } - }, - { - "table": "amrs.encounter_type", - "alias": "t4", - "join": { - "type": "INNER", - "joinCondition": "t4.encounter_type_id = t1.encounter_type" - } - } - ], - "columns": [ - - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "encounter_id", - "column": "t1.encounter_id" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "t4.name" - }, - { - "type": "simple_column", - "alias": "encounter_type_description", - "column": "t4.description" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "t1.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "is_clinical_encounter", - "column": "t1.is_clinical_encounter" - }, - { - "type": "simple_column", - "alias": "rtc_date", - "column": "t1.rtc_date" - }, - { - "type": "simple_column", - "alias": "prev_encounter_datetime_cdm", - "column": "t1.prev_encounter_datetime_cdm" - }, - { - "type": "simple_column", - "alias": "prev_clinical_datetime_cdm", - "column": "t1.prev_clinical_datetime_cdm" - }, - { - "type": "simple_column", - "alias": "prev_encounter_type_cdm", - "column": "t1.prev_encounter_type_cdm" - }, - { - "type": "simple_column", - "alias": "next_encounter_datetime_cdm", - "column": "t1.next_encounter_datetime_cdm" - }, - { - "type": "simple_column", - "alias": "death_date", - "column": "t1.death_date" - }, - { - "type": "simple_column", - "alias": "sbp", - "column": "t1.sbp" - }, - { - "type": "simple_column", - "alias": "dbp", - "column": "t1.dbp" - }, - { - "type": "simple_column", - "alias": "rbs", - "column": "t1.rbs" - }, - { - "type": "simple_column", - "alias": "fbs", - "column": "t1.fbs" - }, - { - "type": "simple_column", - "alias": "hb_a1c", - "column": "t1.hb_a1c" - }, - { - "type": "simple_column", - "alias": "hb_a1c_date", - "column": "t1.hb_a1c_date" - }, - { - "type": "simple_column", - "alias": "dm_status", - "column": "t1.dm_status" - }, - { - "type": "simple_column", - "alias": "htn_status", - "column": "t1.htn_status" - }, - { - "type": "simple_column", - "alias": "dm_meds", - "column": "t1.dm_meds" - }, - { - "type": "simple_column", - "alias": "htn_meds", - "column": "t1.htn_meds" - }, - { - "type": "simple_column", - "alias": "lmp", - "column": "t1.lmp" - }, - { - "type": "simple_column", - "alias": "pulse", - "column": "t1.pulse" - }, - { - "type": "simple_column", - "alias": "creatinine", - "column": "t1.creatinine" - }, - { - "type": "simple_column", - "alias": "creatinine_date", - "column": "t1.creatinine_date" - }, - { - "type": "simple_column", - "alias": "total_cholesterol", - "column": "t1.total_cholesterol" - }, - { - "type": "simple_column", - "alias": "ldl", - "column": "t1.ldl" - }, - { - "type": "simple_column", - "alias": "triglycerides", - "column": "t1.triglycerides" - }, - { - "type": "simple_column", - "alias": "lipid_panel_date", - "column": "t1.lipid_panel_date" - }, - { - "type": "simple_column", - "alias": "problems", - "column": "t1.problems" - }, - { - "type": "simple_column", - "alias": "prescriptions", - "column": "t1.prescriptions" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.uuid in (?)", - "parameterName": "patientUuids" - } - ] - }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [{ - "column": "encounter_datetime", - "order": "desc" - } - - ] - + "name": "cdmDataSetbase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_cdm", + "alias": "t1" + }, + { + "table": "amrs.person", + "alias": "t2", + "join": { + "type": "INNER", + "joinCondition": "t2.person_id = t1.person_id" + } + }, + { + "table": "amrs.person_name", + "alias": "t3", + "join": { + "type": "INNER", + "joinCondition": "t3.person_id = t2.person_id" + } + }, + { + "table": "amrs.encounter_type", + "alias": "t4", + "join": { + "type": "INNER", + "joinCondition": "t4.encounter_type_id = t1.encounter_type" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "encounter_id", + "column": "t1.encounter_id" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "t4.name" + }, + { + "type": "simple_column", + "alias": "encounter_type_description", + "column": "t4.description" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "t1.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "is_clinical_encounter", + "column": "t1.is_clinical_encounter" + }, + { + "type": "simple_column", + "alias": "rtc_date", + "column": "t1.rtc_date" + }, + { + "type": "simple_column", + "alias": "prev_encounter_datetime_cdm", + "column": "t1.prev_encounter_datetime_cdm" + }, + { + "type": "simple_column", + "alias": "prev_clinical_datetime_cdm", + "column": "t1.prev_clinical_datetime_cdm" + }, + { + "type": "simple_column", + "alias": "prev_encounter_type_cdm", + "column": "t1.prev_encounter_type_cdm" + }, + { + "type": "simple_column", + "alias": "next_encounter_datetime_cdm", + "column": "t1.next_encounter_datetime_cdm" + }, + { + "type": "simple_column", + "alias": "death_date", + "column": "t1.death_date" + }, + { + "type": "simple_column", + "alias": "sbp", + "column": "t1.sbp" + }, + { + "type": "simple_column", + "alias": "dbp", + "column": "t1.dbp" + }, + { + "type": "simple_column", + "alias": "rbs", + "column": "t1.rbs" + }, + { + "type": "simple_column", + "alias": "fbs", + "column": "t1.fbs" + }, + { + "type": "simple_column", + "alias": "hb_a1c", + "column": "t1.hb_a1c" + }, + { + "type": "simple_column", + "alias": "hb_a1c_date", + "column": "t1.hb_a1c_date" + }, + { + "type": "simple_column", + "alias": "dm_status", + "column": "t1.dm_status" + }, + { + "type": "simple_column", + "alias": "htn_status", + "column": "t1.htn_status" + }, + { + "type": "simple_column", + "alias": "dm_meds", + "column": "t1.dm_meds" + }, + { + "type": "simple_column", + "alias": "htn_meds", + "column": "t1.htn_meds" + }, + { + "type": "simple_column", + "alias": "lmp", + "column": "t1.lmp" + }, + { + "type": "simple_column", + "alias": "pulse", + "column": "t1.pulse" + }, + { + "type": "simple_column", + "alias": "creatinine", + "column": "t1.creatinine" + }, + { + "type": "simple_column", + "alias": "creatinine_date", + "column": "t1.creatinine_date" + }, + { + "type": "simple_column", + "alias": "total_cholesterol", + "column": "t1.total_cholesterol" + }, + { + "type": "simple_column", + "alias": "ldl", + "column": "t1.ldl" + }, + { + "type": "simple_column", + "alias": "triglycerides", + "column": "t1.triglycerides" + }, + { + "type": "simple_column", + "alias": "lipid_panel_date", + "column": "t1.lipid_panel_date" + }, + { + "type": "simple_column", + "alias": "problems", + "column": "t1.problems" + }, + { + "type": "simple_column", + "alias": "prescriptions", + "column": "t1.prescriptions" } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.uuid in (?)", + "parameterName": "patientUuids" + } + ] + }, + "orderBy": { + "orderByParam": "orderByParam", + "columns": [ + { + "column": "encounter_datetime", + "order": "desc" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/cervical-cancer-daily-screening-summary-aggregate.json b/app/reporting-framework/json-reports/cervical-cancer-daily-screening-summary-aggregate.json index 5c1d57e06..3c012ef56 100644 --- a/app/reporting-framework/json-reports/cervical-cancer-daily-screening-summary-aggregate.json +++ b/app/reporting-framework/json-reports/cervical-cancer-daily-screening-summary-aggregate.json @@ -270,7 +270,7 @@ "expressionType": "simple_expression", "expressionOptions": { "expression": "count(procedures_done)" - } + } }, { "type": "derived_column", @@ -323,10 +323,7 @@ ], "groupBy": { "groupParam": "groupByParam", - "columns": [ - "location_id", - "DATE(t1.encounter_datetime)" - ], + "columns": ["location_id", "DATE(t1.encounter_datetime)"], "excludeParam": "excludeParam" }, "dynamicJsonQueryGenerationDirectives": { @@ -343,4 +340,4 @@ } } } -} \ No newline at end of file +} diff --git a/app/reporting-framework/json-reports/cervical-cancer-monthly-screening-summary-aggregate.json b/app/reporting-framework/json-reports/cervical-cancer-monthly-screening-summary-aggregate.json index a1f64e83e..54d4bf4a7 100644 --- a/app/reporting-framework/json-reports/cervical-cancer-monthly-screening-summary-aggregate.json +++ b/app/reporting-framework/json-reports/cervical-cancer-monthly-screening-summary-aggregate.json @@ -270,7 +270,7 @@ "expressionType": "simple_expression", "expressionOptions": { "expression": "count(procedures_done)" - } + } }, { "type": "derived_column", @@ -344,4 +344,4 @@ } } } -} \ No newline at end of file +} diff --git a/app/reporting-framework/json-reports/cervical-cancer-monthly-screening-summary-base.json b/app/reporting-framework/json-reports/cervical-cancer-monthly-screening-summary-base.json index 9ec91ff9e..391f473ee 100644 --- a/app/reporting-framework/json-reports/cervical-cancer-monthly-screening-summary-base.json +++ b/app/reporting-framework/json-reports/cervical-cancer-monthly-screening-summary-base.json @@ -832,8 +832,6 @@ }, "groupBy": { "groupParam": "groupByParam", - "columns": [ - "fccs.encounter_id" - ] + "columns": ["fccs.encounter_id"] } -} \ No newline at end of file +} diff --git a/app/reporting-framework/json-reports/clinic-comparator-aggregate.json b/app/reporting-framework/json-reports/clinic-comparator-aggregate.json index e57e6a11a..8f483cb99 100644 --- a/app/reporting-framework/json-reports/clinic-comparator-aggregate.json +++ b/app/reporting-framework/json-reports/clinic-comparator-aggregate.json @@ -1,376 +1,378 @@ { - "name": "clinicComparatorBaseAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "clinicComparatorBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "clinicComparatorBase", - "alias": "hmsd" - } - ], + "name": "clinicComparatorBaseAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "clinicComparatorBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "clinicComparatorBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_first_line)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_second_line)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_third_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_third_line)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct vl_done_past_year)" + } + }, + { + "type": "derived_column", + "alias": "no_vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct no_vl_done_past_year)" + } + }, + { + "type": "derived_column", + "alias": "on_second_line_not_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_second_line_not_suppressed)" + } + }, + { + "type": "derived_column", + "alias": "not_on_arvs_cd4_lte_500", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct not_on_arvs_cd4_lte_500)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct vl_done_past_year_lte_1000)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct vl_done_past_year_gt_1000)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct vl_done_this_encounter)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct vl_done_this_encounter_lte_1000)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct vl_done_this_encounter_gt_1000)" + } + }, + { + "type": "derived_column", + "alias": "vl_ordered", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct vl_ordered)" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct pending_vl_order)" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order_no_result_after_4_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct pending_vl_order_no_result_after_4_weeks)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_lte_26_weeks)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_lte_52_weeks)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_lte_52_weeks_and_have_vl)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_lte_52_weeks_and_have_vl_lte_1000)" + } + }, + { + "type": "derived_column", + "alias": "pregnant", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct pregnant)" + } + }, + { + "type": "derived_column", + "alias": "pregnant_and_on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct pregnant_and_on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct newly_enrolled)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_care_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct enrolled_in_care_total)" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct virally_suppressed)" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct virally_suppressed_in_past_year)" + } + }, + { + "type": "derived_column", + "alias": "viral_load_resulted_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct viral_load_resulted_in_past_year)" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct not_virally_suppressed_in_past_year)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_gt_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_gt_26_weeks)" + } + }, + { + "type": "derived_column", + "alias": "perc_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct virally_suppressed_in_past_year)/count(distinct viral_load_resulted_in_past_year)" + } + }, + { + "type": "derived_column", + "alias": "perc_not_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct not_virally_suppressed_in_past_year) / count(distinct viral_load_resulted_in_past_year)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs) / count(distinct person_id)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arv_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_first_line) / count(distinct on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arv_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_second_line) / count(distinct on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arv_third_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_third_line) / count(distinct on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "perc_with_pending_viral_load", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct pending_vl_order) / count(distinct on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arvs_lte_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_lte_26_weeks) / count(distinct on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arvs_gt_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_arvs_gt_26_weeks) / count(distinct person_id)" + } + }, + { + "type": "simple_column", + "alias": "location", + "column": "location" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "hmsd.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "hmsd.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "date_format(encounter_datetime, '%m/%Y')" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "reporting_month" + } + ], + "groupBy": { + "groupParam": "groupByParam", "columns": [ - { - "type": "derived_column", - "alias": "on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_first_line)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_second_line)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_third_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_third_line)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct vl_done_past_year)" - } - }, - { - "type": "derived_column", - "alias": "no_vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct no_vl_done_past_year)" - } - }, - { - "type": "derived_column", - "alias": "on_second_line_not_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_second_line_not_suppressed)" - } - }, - { - "type": "derived_column", - "alias": "not_on_arvs_cd4_lte_500", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct not_on_arvs_cd4_lte_500)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct vl_done_past_year_lte_1000)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct vl_done_past_year_gt_1000)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct vl_done_this_encounter)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct vl_done_this_encounter_lte_1000)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct vl_done_this_encounter_gt_1000)" - } - }, - { - "type": "derived_column", - "alias": "vl_ordered", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct vl_ordered)" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct pending_vl_order)" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_order_no_result_after_4_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct pending_vl_order_no_result_after_4_weeks)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_lte_26_weeks)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_lte_52_weeks)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks_and_have_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_lte_52_weeks_and_have_vl)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_lte_52_weeks_and_have_vl_lte_1000)" - } - }, - { - "type": "derived_column", - "alias": "pregnant", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct pregnant)" - } - }, - { - "type": "derived_column", - "alias": "pregnant_and_on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct pregnant_and_on_arvs)" - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct newly_enrolled)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_care_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct enrolled_in_care_total)" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct virally_suppressed)" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct virally_suppressed_in_past_year)" - } - }, - { - "type": "derived_column", - "alias": "viral_load_resulted_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct viral_load_resulted_in_past_year)" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct not_virally_suppressed_in_past_year)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_gt_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_gt_26_weeks)" - } - }, - { - "type": "derived_column", - "alias": "perc_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct virally_suppressed_in_past_year)/count(distinct viral_load_resulted_in_past_year)" - } - }, - { - "type": "derived_column", - "alias": "perc_not_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct not_virally_suppressed_in_past_year) / count(distinct viral_load_resulted_in_past_year)" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs) / count(distinct person_id)" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arv_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_first_line) / count(distinct on_arvs)" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arv_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_second_line) / count(distinct on_arvs)" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arv_third_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_third_line) / count(distinct on_arvs)" - } - }, - { - "type": "derived_column", - "alias": "perc_with_pending_viral_load", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct pending_vl_order) / count(distinct on_arvs)" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arvs_lte_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_lte_26_weeks) / count(distinct on_arvs)" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arvs_gt_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_arvs_gt_26_weeks) / count(distinct person_id)" - } - }, - { - "type": "simple_column", - "alias": "location", - "column": "location" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "hmsd.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "month", - "column": "hmsd.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "month", - "column": "date_format(encounter_datetime, '%m/%Y')" - }, - { - "type": "simple_column", - "alias": "reporting_month", - "column": "reporting_month" - } + "location_id", + "month(encounter_datetime)", + "YEAR(encounter_datetime)" ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id","month(encounter_datetime)","YEAR(encounter_datetime)" - ], - "excludeParam": "excludeParam" - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/clinic-comparator-base.json b/app/reporting-framework/json-reports/clinic-comparator-base.json index 508773549..012ebde67 100644 --- a/app/reporting-framework/json-reports/clinic-comparator-base.json +++ b/app/reporting-framework/json-reports/clinic-comparator-base.json @@ -1,356 +1,356 @@ { - "name": "clinicComparatorBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - }, - { - "table": "amrs.person", - "alias": "p", - "join": { - "type": "INNER", - "joinCondition": "p.person_id = hmsd.person_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "derived_column", - "alias": "on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_line is not null,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_line=1,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_line=2,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_third_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_line>2,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "no_vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_line is not null and (vl_1_date is null or timestampdiff(week,vl_1_date,encounter_datetime) >= 52),hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_second_line_not_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(vl_1 > 1000 and cur_arv_line =2,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "not_on_arvs_cd4_lte_500", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(arv_start_date is null and cd4_1 < 500,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 > 1000,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(vl_resulted >= 0 and vl_resulted_date=date(encounter_datetime),hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(vl_resulted <= 1000 and vl_resulted_date = date(encounter_datetime),hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(vl_resulted > 1000 and vl_resulted_date = date(encounter_datetime),hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_ordered", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(date(vl_order_date)=date(encounter_datetime),hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,vl_order_date,encounter_datetime) >= 0 and vl_1_date < vl_order_date,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_order_no_result_after_4_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,vl_order_date,encounter_datetime) >= 4 and vl_1_date < vl_order_date,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) <= 26,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) <= 52,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks_and_have_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "pregnant", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(edd > encounter_datetime,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "pregnant_and_on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(is_pregnant is not null and cur_arv_line is not null,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(is_clinical_encounter=1 and prev_clinical_datetime_hiv is null,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_care_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((date(prev_clinical_datetime_hiv) between '{startDate}' and '{endDate}' or prev_clinical_datetime_hiv is null) and date(enrollment_date) between '{startDate}' and '{endDate}',hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "viral_load_resulted_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(vl_1 is not null and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(vl_1> 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_gt_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) > 26,hmsd.person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_gt_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) > 26,hmsd.person_id,null)" - } - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "hmsd.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "month", - "column": "hmsd.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "reporting_month", - "column": "date_format(hmsd.encounter_datetime, '%m/%Y')" - }, - { - "type": "simple_column", - "alias": "year", - "column": "YEAR(encounter_datetime)" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "encounter_datetime >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "encounter_datetime <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "location_uuid in ?", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "round(datediff(hmsd.encounter_datetime,p.birthdate)/365) >= ?", - "parameterName": "startAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "round(datediff(hmsd.encounter_datetime,p.birthdate)/365) <= ?", - "parameterName": "endAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "p.gender in ?", - "parameterName": "gender" - }, - { - "filterType": "tableColumns", - "conditionExpression": "is_clinical_encounter = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "coalesce(hmsd.death_date, out_of_care) is null", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(hmsd.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= ?)", - "parameterName": "startDate" - } - ] + "name": "clinicComparatorBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } + }, + { + "table": "amrs.person", + "alias": "p", + "join": { + "type": "INNER", + "joinCondition": "p.person_id = hmsd.person_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "derived_column", + "alias": "on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_line is not null,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_line=1,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_line=2,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_third_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_line>2,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "no_vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_line is not null and (vl_1_date is null or timestampdiff(week,vl_1_date,encounter_datetime) >= 52),hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_second_line_not_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(vl_1 > 1000 and cur_arv_line =2,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "not_on_arvs_cd4_lte_500", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(arv_start_date is null and cd4_1 < 500,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 > 1000,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(vl_resulted >= 0 and vl_resulted_date=date(encounter_datetime),hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(vl_resulted <= 1000 and vl_resulted_date = date(encounter_datetime),hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(vl_resulted > 1000 and vl_resulted_date = date(encounter_datetime),hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_ordered", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(date(vl_order_date)=date(encounter_datetime),hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,vl_order_date,encounter_datetime) >= 0 and vl_1_date < vl_order_date,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order_no_result_after_4_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,vl_order_date,encounter_datetime) >= 4 and vl_1_date < vl_order_date,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) <= 26,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) <= 52,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "pregnant", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(edd > encounter_datetime,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "pregnant_and_on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(is_pregnant is not null and cur_arv_line is not null,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(is_clinical_encounter=1 and prev_clinical_datetime_hiv is null,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_care_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((date(prev_clinical_datetime_hiv) between '{startDate}' and '{endDate}' or prev_clinical_datetime_hiv is null) and date(enrollment_date) between '{startDate}' and '{endDate}',hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "viral_load_resulted_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(vl_1 is not null and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(vl_1> 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_gt_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) > 26,hmsd.person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_gt_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,arv_start_date,encounter_datetime) > 26,hmsd.person_id,null)" + } + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "hmsd.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "hmsd.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "date_format(hmsd.encounter_datetime, '%m/%Y')" + }, + { + "type": "simple_column", + "alias": "year", + "column": "YEAR(encounter_datetime)" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "encounter_datetime >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "encounter_datetime <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "location_uuid in ?", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "round(datediff(hmsd.encounter_datetime,p.birthdate)/365) >= ?", + "parameterName": "startAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "round(datediff(hmsd.encounter_datetime,p.birthdate)/365) <= ?", + "parameterName": "endAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "p.gender in ?", + "parameterName": "gender" + }, + { + "filterType": "tableColumns", + "conditionExpression": "is_clinical_encounter = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "coalesce(hmsd.death_date, out_of_care) is null", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(hmsd.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= ?)", + "parameterName": "startDate" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/clinic-lab-orders-report-base.json b/app/reporting-framework/json-reports/clinic-lab-orders-report-base.json index 5499a0558..b94404965 100644 --- a/app/reporting-framework/json-reports/clinic-lab-orders-report-base.json +++ b/app/reporting-framework/json-reports/clinic-lab-orders-report-base.json @@ -1,148 +1,144 @@ { - "name": "clinic_lab_orders_report", - "version": "1.0", - "tag": "clinic_lab_orders_report", - "description": "Clinic Lab Orders Report", - "sources": [ - { - "table": "amrs.orders", - "alias": "t1" - }, - { - "table": "amrs.encounter", - "alias": "t2", - "join": { - "type": "LEFT OUTER", - "joinCondition": "t1.encounter_id=t2.encounter_id" - } - }, - { - "table": "amrs.person_name", - "alias": "t3", - "join": { - "type": "LEFT OUTER", - "joinCondition": "t1.patient_id = t3.person_id and (t3.voided is null || t3.voided = 0)" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "t4", - "join": { - "type": "LEFT OUTER", - "joinCondition": "t1.patient_id = t4.patient_id" - } - }, - { - "table": "amrs.location", - "alias": "t5", - "join": { - "type": "LEFT OUTER", - "joinCondition": "t2.location_id = t5.location_id" - } - }, - { - "table": "amrs.person", - "alias": "t6", - "join": { - "type": "LEFT OUTER", - "joinCondition": "t1.patient_id = t6.person_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "order_no", - "column": "t1.order_number" - }, - { - "type": "simple_column", - "alias": "order_type", - "column": "t1.concept_id" - }, - { - "type": "simple_column", - "alias": "date_activated", - "column": "t1.date_activated" - }, - { - "type": "simple_column", - "alias": "patient_id", - "column": "t1.patient_id" - }, - { - "type": "simple_column", - "alias": "given_name", - "column": "t3.given_name" - }, - { - "type": "simple_column", - "alias": "middle_name", - "column": "t3.middle_name" - }, - { - "type": "simple_column", - "alias": "family_name", - "column": "t3.family_name" - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "group_concat(distinct t4.identifier)" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(t3.given_name, ''), ' ', COALESCE(t3.middle_name, ''), ' ', COALESCE(t3.family_name, ''))" - } - }, - { - "type": "simple_column", - "alias":"location", - "column":"t5.name" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"t5.location_id" - }, - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t6.uuid" - } - - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "t3.person_id" - ], - "excludeParam": "excludeParam" - }, - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "date(t1.date_activated) = ?", - "parameterName": "dateActivated" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.location_id in ?", - "parameterName": "locations" - } - ] - }, - "paging": { - "offSetParam":"offSetParam", - "limitParam": "limitParam" + "name": "clinic_lab_orders_report", + "version": "1.0", + "tag": "clinic_lab_orders_report", + "description": "Clinic Lab Orders Report", + "sources": [ + { + "table": "amrs.orders", + "alias": "t1" + }, + { + "table": "amrs.encounter", + "alias": "t2", + "join": { + "type": "LEFT OUTER", + "joinCondition": "t1.encounter_id=t2.encounter_id" + } + }, + { + "table": "amrs.person_name", + "alias": "t3", + "join": { + "type": "LEFT OUTER", + "joinCondition": "t1.patient_id = t3.person_id and (t3.voided is null || t3.voided = 0)" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "t4", + "join": { + "type": "LEFT OUTER", + "joinCondition": "t1.patient_id = t4.patient_id" + } + }, + { + "table": "amrs.location", + "alias": "t5", + "join": { + "type": "LEFT OUTER", + "joinCondition": "t2.location_id = t5.location_id" + } + }, + { + "table": "amrs.person", + "alias": "t6", + "join": { + "type": "LEFT OUTER", + "joinCondition": "t1.patient_id = t6.person_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "order_no", + "column": "t1.order_number" + }, + { + "type": "simple_column", + "alias": "order_type", + "column": "t1.concept_id" + }, + { + "type": "simple_column", + "alias": "date_activated", + "column": "t1.date_activated" + }, + { + "type": "simple_column", + "alias": "patient_id", + "column": "t1.patient_id" + }, + { + "type": "simple_column", + "alias": "given_name", + "column": "t3.given_name" + }, + { + "type": "simple_column", + "alias": "middle_name", + "column": "t3.middle_name" + }, + { + "type": "simple_column", + "alias": "family_name", + "column": "t3.family_name" + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "group_concat(distinct t4.identifier)" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(t3.given_name, ''), ' ', COALESCE(t3.middle_name, ''), ' ', COALESCE(t3.family_name, ''))" + } + }, + { + "type": "simple_column", + "alias": "location", + "column": "t5.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "t5.location_id" + }, + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t6.uuid" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["t3.person_id"], + "excludeParam": "excludeParam" + }, + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "date(t1.date_activated) = ?", + "parameterName": "dateActivated" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.location_id in ?", + "parameterName": "locations" } - -} \ No newline at end of file + ] + }, + "paging": { + "offSetParam": "offSetParam", + "limitParam": "limitParam" + } +} diff --git a/app/reporting-framework/json-reports/clinical-art-overview-aggregate.json b/app/reporting-framework/json-reports/clinical-art-overview-aggregate.json index 1295152ff..2940161cf 100644 --- a/app/reporting-framework/json-reports/clinical-art-overview-aggregate.json +++ b/app/reporting-framework/json-reports/clinical-art-overview-aggregate.json @@ -1,108 +1,106 @@ { - "name": "clinicalArtOverviewAggregeate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "clinicalArtOverviewBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "clinicalArtOverviewBase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t1.location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t1.location_id" - }, - { - "type": "derived_column", - "alias": "on_nevirapine", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_nevirapine)" - } - }, - { - "type": "derived_column", - "alias": "on_lopinavir", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_lopinavir)" - } - }, - { - "type": "derived_column", - "alias": "on_efavirenz", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_efavirenz)" - } - }, - { - "type": "derived_column", - "alias": "on_atazanavir", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_atazanavir)" - } - }, - { - "type": "derived_column", - "alias": "on_raltegravir", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_raltegravir)" - } - }, - { - "type": "derived_column", - "alias": "on_other_arv_drugs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct on_other_arv_drugs)" - } - }, - { - "type": "derived_column", - "alias": "not_on_arv", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct not_on_arv)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" + "name": "clinicalArtOverviewAggregeate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "clinicalArtOverviewBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "clinicalArtOverviewBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t1.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "t1.location_id" + }, + { + "type": "derived_column", + "alias": "on_nevirapine", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_nevirapine)" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "on_lopinavir", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_lopinavir)" + } + }, + { + "type": "derived_column", + "alias": "on_efavirenz", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_efavirenz)" + } + }, + { + "type": "derived_column", + "alias": "on_atazanavir", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_atazanavir)" + } + }, + { + "type": "derived_column", + "alias": "on_raltegravir", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_raltegravir)" + } + }, + { + "type": "derived_column", + "alias": "on_other_arv_drugs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct on_other_arv_drugs)" + } + }, + { + "type": "derived_column", + "alias": "not_on_arv", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct not_on_arv)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/clinical-art-overview-base.json b/app/reporting-framework/json-reports/clinical-art-overview-base.json index b28b3c90a..a5e7b186c 100644 --- a/app/reporting-framework/json-reports/clinical-art-overview-base.json +++ b/app/reporting-framework/json-reports/clinical-art-overview-base.json @@ -1,116 +1,116 @@ { - "name": "clinicalArtOverviewBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "t1" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t1.location_uuid" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t1.location_id" - }, - { - "type": "derived_column", - "alias": "on_nevirapine", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(631|6467|792)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_lopinavir", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(9026|794)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_efavirenz", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(633|6964)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_atazanavir", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(6159|6160)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_raltegravir", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(6156)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_other_arv_drugs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(not (cur_arv_meds regexp '(6156|6159|6160|633|6964|9026|794|631|6467|792)'), person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "not_on_arv", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds is null,person_id,null)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.encounter_datetime >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t1.encounter_datetime <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t1.location_uuid in (?)", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t1.is_clinical_encounter = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(t1.next_encounter_datetime_hiv is null or t1.next_encounter_datetime_hiv > ?)", - "parameterName": "endDate" - } - ] + "name": "clinicalArtOverviewBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "t1" } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t1.location_uuid" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "t1.location_id" + }, + { + "type": "derived_column", + "alias": "on_nevirapine", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(631|6467|792)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_lopinavir", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(9026|794)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_efavirenz", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(633|6964)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_atazanavir", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(6159|6160)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_raltegravir", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(6156)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_other_arv_drugs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(not (cur_arv_meds regexp '(6156|6159|6160|633|6964|9026|794|631|6467|792)'), person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "not_on_arv", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds is null,person_id,null)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.encounter_datetime >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t1.encounter_datetime <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t1.location_uuid in (?)", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t1.is_clinical_encounter = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(t1.next_encounter_datetime_hiv is null or t1.next_encounter_datetime_hiv > ?)", + "parameterName": "endDate" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/clinical-hiv-comparative-overview-aggregate.json b/app/reporting-framework/json-reports/clinical-hiv-comparative-overview-aggregate.json index 21031d88c..905b9def2 100644 --- a/app/reporting-framework/json-reports/clinical-hiv-comparative-overview-aggregate.json +++ b/app/reporting-framework/json-reports/clinical-hiv-comparative-overview-aggregate.json @@ -1,181 +1,179 @@ { - "name": "clinicHivComparativeOverviewAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "clinicHivComparativeOverviewBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "clinicHivComparativeOverviewBase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_id", - "column": "location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "location_uuid" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "person_id" - }, - { - "type": "derived_column", - "alias": "currently_in_care_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(currently_in_care_total, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_art_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_art_total, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_on_art_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(not_on_art_total, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "patients_requiring_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(patients_requiring_vl, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "tested_appropriately", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(tested_appropriately, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_tested_appropriately", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(not_tested_appropriately, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "due_for_annual_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(due_for_annual_vl, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_orders", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(pending_vl_orders, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "missing_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(missing_vl_order, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(virally_suppressed, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(not_virally_suppressed, hmsd.person_id))" - } - }, - { - "type": "derived_column", - "alias": "perc_tested_appropriately", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(count(distinct concat(tested_appropriately, hmsd.person_id))=0, 0,(count(distinct concat(tested_appropriately, hmsd.person_id))/count(distinct concat(patients_requiring_vl, hmsd.person_id))*100))" - } - }, - { - "type": "derived_column", - "alias": "perc_virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(count(distinct concat(virally_suppressed, hmsd.person_id))=0, 0,(count(distinct concat(virally_suppressed, hmsd.person_id))/count(distinct concat(tested_appropriately, hmsd.person_id))*100))" - } - }, - { - "type": "simple_column", - "alias": "reporting_date", - "column": "reporting_date" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "location_id" - }, - { - "type": "simple_column", - "alias": "reporting_month", - "column": "reporting_month" - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "endDate" - ], - "excludeParam": "excludeParam" - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "name": "clinicHivComparativeOverviewAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "clinicHivComparativeOverviewBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "clinicHivComparativeOverviewBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_id", + "column": "location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "location_uuid" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "person_id" + }, + { + "type": "derived_column", + "alias": "currently_in_care_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(currently_in_care_total, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_art_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_art_total, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "not_on_art_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(not_on_art_total, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "patients_requiring_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(patients_requiring_vl, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "tested_appropriately", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(tested_appropriately, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "not_tested_appropriately", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(not_tested_appropriately, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "due_for_annual_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(due_for_annual_vl, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_orders", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(pending_vl_orders, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "missing_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(missing_vl_order, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(virally_suppressed, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(not_virally_suppressed, hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "perc_tested_appropriately", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(count(distinct concat(tested_appropriately, hmsd.person_id))=0, 0,(count(distinct concat(tested_appropriately, hmsd.person_id))/count(distinct concat(patients_requiring_vl, hmsd.person_id))*100))" + } + }, + { + "type": "derived_column", + "alias": "perc_virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(count(distinct concat(virally_suppressed, hmsd.person_id))=0, 0,(count(distinct concat(virally_suppressed, hmsd.person_id))/count(distinct concat(tested_appropriately, hmsd.person_id))*100))" + } + }, + { + "type": "simple_column", + "alias": "reporting_date", + "column": "reporting_date" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "reporting_month" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["endDate"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/clinical-hiv-comparative-overview-base.json b/app/reporting-framework/json-reports/clinical-hiv-comparative-overview-base.json index 6dfda1483..e5d890485 100644 --- a/app/reporting-framework/json-reports/clinical-hiv-comparative-overview-base.json +++ b/app/reporting-framework/json-reports/clinical-hiv-comparative-overview-base.json @@ -1,201 +1,202 @@ { - "name": "clinicHivComparativeOverviewBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hiv_monthly_report_dataset_frozen", - "alias": "fhs" - }, - { - "table": "amrs.orders", - "alias": "orders", - "join": { - "type": "LEFT", - "joinCondition": "orders.voided=0 and fhs.encounter_id=orders.encounter_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_id", - "column": "fhs.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "fhs.location_uuid" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "fhs.person_id" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "fhs.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "fhs.age" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "fhs.gender" - }, - { - "type": "derived_column", - "alias": "currently_in_care_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when status='active' then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "on_art_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when on_art_this_month=1 then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "not_on_art_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when on_art_this_month=0 then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "patients_requiring_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when eligible_for_vl=1 AND status = 'active' then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "tested_appropriately", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(month, fhs.arv_start_date, fhs.encounter_date) >= 6 and timestampdiff(day, date(fhs.vl_1_date), date(fhs.endDate)) <= 365,1,null)" - } - }, - { - "type": "derived_column", - "alias": "not_tested_appropriately", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(month, fhs.arv_start_date, fhs.encounter_date) >= 6 and (timestampdiff(day,fhs.vl_1_date, date(fhs.endDate)) > 365 or fhs.vl_1_date is null),1,null)" - } - }, - { - "type": "derived_column", - "alias": "due_for_annual_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when vl_in_past_year=0 AND status = 'active' then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_orders", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(orders.concept_id=856 and (date(orders.date_created) between DATE_FORMAT(fhs.endDate,'%Y-%m-01') and fhs.endDate) and date(fhs.vl_1_date) != date(orders.date_created) and date(fhs.vl_1_date) < DATE_FORMAT(fhs.endDate,'%Y-%m-01'),1,null)" - } - }, - { - "type": "derived_column", - "alias": "missing_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(month, fhs.arv_start_date, fhs.encounter_date) >= 6 and (timestampdiff(day,fhs.vl_1_date, date(fhs.endDate)) > 365 or fhs.vl_1_date is null) and (orders.date_created is null or orders.concept_id!=856),1,null)" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(month,fhs.arv_start_date,fhs.encounter_date) >= 6 and timestampdiff(day, date(fhs.vl_1_date), date(fhs.endDate)) <= 365 and fhs.vl_1 < 1000,1,null)" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(month,fhs.arv_start_date,fhs.encounter_date) >= 6 and timestampdiff(day, date(fhs.vl_1_date), date(fhs.endDate)) <= 365 and fhs.vl_1 >= 1000,1,null)" - } - }, - { - "type": "simple_column", - "alias": "reporting_date", - "column": "fhs.endDate" - }, - { - "type": "simple_column", - "alias": "endDate", - "column": "fhs.endDate" - }, - { - "type": "simple_column", - "alias": "end_date", - "column": "date(fhs.endDate)" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "fhs.location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "fhs.location_id" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "fhs.person_id" - }, - { - "type": "simple_column", - "alias": "reporting_month", - "column": "date_format(fhs.endDate, '%Y/%m')" - } - ], - "indexDirectives": [ - { - "type": "force", - "indexList": ["endDate_location_id"] - }], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "fhs.endDate > date(?)", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.endDate <= date(?)", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.location_id in ?", - "parameterName": "locations" - } - ] + "name": "clinicHivComparativeOverviewBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hiv_monthly_report_dataset_frozen", + "alias": "fhs" + }, + { + "table": "amrs.orders", + "alias": "orders", + "join": { + "type": "LEFT", + "joinCondition": "orders.voided=0 and fhs.encounter_id=orders.encounter_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_id", + "column": "fhs.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "fhs.location_uuid" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "fhs.person_id" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "fhs.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "fhs.age" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "fhs.gender" + }, + { + "type": "derived_column", + "alias": "currently_in_care_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when status='active' then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "on_art_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when on_art_this_month=1 then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "not_on_art_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when on_art_this_month=0 then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "patients_requiring_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when eligible_for_vl=1 AND status = 'active' then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "tested_appropriately", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(month, fhs.arv_start_date, fhs.encounter_date) >= 6 and timestampdiff(day, date(fhs.vl_1_date), date(fhs.endDate)) <= 365,1,null)" + } + }, + { + "type": "derived_column", + "alias": "not_tested_appropriately", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(month, fhs.arv_start_date, fhs.encounter_date) >= 6 and (timestampdiff(day,fhs.vl_1_date, date(fhs.endDate)) > 365 or fhs.vl_1_date is null),1,null)" + } + }, + { + "type": "derived_column", + "alias": "due_for_annual_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when vl_in_past_year=0 AND status = 'active' then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_orders", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(orders.concept_id=856 and (date(orders.date_created) between DATE_FORMAT(fhs.endDate,'%Y-%m-01') and fhs.endDate) and date(fhs.vl_1_date) != date(orders.date_created) and date(fhs.vl_1_date) < DATE_FORMAT(fhs.endDate,'%Y-%m-01'),1,null)" + } + }, + { + "type": "derived_column", + "alias": "missing_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(month, fhs.arv_start_date, fhs.encounter_date) >= 6 and (timestampdiff(day,fhs.vl_1_date, date(fhs.endDate)) > 365 or fhs.vl_1_date is null) and (orders.date_created is null or orders.concept_id!=856),1,null)" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(month,fhs.arv_start_date,fhs.encounter_date) >= 6 and timestampdiff(day, date(fhs.vl_1_date), date(fhs.endDate)) <= 365 and fhs.vl_1 < 1000,1,null)" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(month,fhs.arv_start_date,fhs.encounter_date) >= 6 and timestampdiff(day, date(fhs.vl_1_date), date(fhs.endDate)) <= 365 and fhs.vl_1 >= 1000,1,null)" + } + }, + { + "type": "simple_column", + "alias": "reporting_date", + "column": "fhs.endDate" + }, + { + "type": "simple_column", + "alias": "endDate", + "column": "fhs.endDate" + }, + { + "type": "simple_column", + "alias": "end_date", + "column": "date(fhs.endDate)" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "fhs.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "fhs.location_id" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "fhs.person_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "date_format(fhs.endDate, '%Y/%m')" + } + ], + "indexDirectives": [ + { + "type": "force", + "indexList": ["endDate_location_id"] + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "fhs.endDate > date(?)", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.endDate <= date(?)", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/clinical-patient-care-status-overview-base.json b/app/reporting-framework/json-reports/clinical-patient-care-status-overview-base.json index f76c8cae5..07acdcbc5 100644 --- a/app/reporting-framework/json-reports/clinical-patient-care-status-overview-base.json +++ b/app/reporting-framework/json-reports/clinical-patient-care-status-overview-base.json @@ -1,111 +1,111 @@ { - "name": "clinicalArtOverviewBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "t1" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t1.location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t1.location_id" - }, - { - "type": "derived_column", - "alias": "on_nevirapine", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(631|6467|792)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_lopinavir", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(9026|794)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_efavirenz", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(633|6964)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_atazanavir", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(6159|6160)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_raltegravir", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds regexp '(6156)', person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "on_other_arv_drugs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(not (cur_arv_meds regexp '(6156|6159|6160|633|6964|9026|794|631|6467|792)'), person_id,null)" - } - }, - { - "type": "derived_column", - "alias": "not_on_arv", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(cur_arv_meds is null,person_id,null)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.encounter_datetime >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t1.encounter_datetime <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t1.location_uuid in (?)", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t1.is_clinical_encounter = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(t1.next_encounter_datetime_hiv is null or t1.next_encounter_datetime_hiv > ?)", - "parameterName": "endDate" - } - ] + "name": "clinicalArtOverviewBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "t1" } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t1.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "t1.location_id" + }, + { + "type": "derived_column", + "alias": "on_nevirapine", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(631|6467|792)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_lopinavir", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(9026|794)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_efavirenz", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(633|6964)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_atazanavir", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(6159|6160)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_raltegravir", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds regexp '(6156)', person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "on_other_arv_drugs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(not (cur_arv_meds regexp '(6156|6159|6160|633|6964|9026|794|631|6467|792)'), person_id,null)" + } + }, + { + "type": "derived_column", + "alias": "not_on_arv", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(cur_arv_meds is null,person_id,null)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.encounter_datetime >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t1.encounter_datetime <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t1.location_uuid in (?)", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t1.is_clinical_encounter = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(t1.next_encounter_datetime_hiv is null or t1.next_encounter_datetime_hiv > ?)", + "parameterName": "endDate" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/clinical-reminder-report.json b/app/reporting-framework/json-reports/clinical-reminder-report.json index 98fe99a15..00c308623 100644 --- a/app/reporting-framework/json-reports/clinical-reminder-report.json +++ b/app/reporting-framework/json-reports/clinical-reminder-report.json @@ -1,338 +1,338 @@ -{ - "name": "clinical_reminder_report", - "version": "1.0", - "tag": "clinical_reminder_report", - "description": "Clinical Reminder Report", - "uses":[ - { - "name":"flatLabsAndImagingDataSetbase", - "version":"1.0", - "type":"dataset_def" - } - ], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "t1" - }, - { - "table": "etl.flat_labs_and_imaging", - "alias": "t2", - "join": { - "type": "left", - "joinCondition": "date(t1.encounter_datetime) = date(t2.test_datetime)" - } - }, - { - "table": "amrs.person", - "alias": "t5", - "join": { - "type": "left", - "joinCondition": "t5.person_id = t1.person_id" - } - }, - { - "table": "amrs.patient_program", - "alias": "p", - "join": { - "type": "left", - "joinCondition": "t1.person_id = p.patient_id AND p.program_id = 9 AND date_completed IS NULL" - } - }, - { - "dataSet": "flatLabsAndImagingDataSetbase", - "alias": "t3", - "join": { - "type": "left", - "joinCondition": "t3.person_uuid = t1.uuid" - } - }, - { - "table": "amrs.relationship", - "alias": "t6", - "join": { - "type": "left", - "joinCondition": "t6.person_a = t1.person_id" - } - }, - { - "table": "amrs.patient_program", - "alias": "t9", - "join": { - "type": "left", - "joinCondition": "t1.person_id = t9.patient_id AND t9.program_id = 29 AND t9.date_completed IS NULL" - } - }, - { - "table": "amrs.patient_program", - "alias": "t10", - "join": { - "type": "left", - "joinCondition": "t1.person_id = t10.patient_id AND t10.program_id = 4 AND t10.date_completed IS NULL" - } - }, - { - "table": "amrs.patient_program", - "alias": "t7", - "join": { - "type": "left", - "joinCondition": "t1.person_id = t7.patient_id AND t7.program_id = 27 AND t7.date_completed IS NULL" - } - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "needs_vl_coded", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when (cur_arv_meds is null) then 0 when (timestampdiff(month,vl_1_date, date('{referenceDate}')) > 3) and vl_1 > 1000 and arv_start_date < vl_1_date then 1 when (timestampdiff(month,arv_start_date,date('{referenceDate}')) between 6 and 12) and (vl_1_date is null or vl_1_date < arv_start_date ) then 2 when (timestampdiff(month,arv_start_date,'{referenceDate}') > 12) and (vl_1_date is null or timestampdiff(month,vl_1_date,'{referenceDate}') > 12) then 3 WHEN (t1.is_pregnant OR (t6.relationship = 2 AND TIMESTAMPDIFF(MONTH, t6.date_created,'{referenceDate}') BETWEEN 0 AND 24 )) AND vl_1 > 400 AND (TIMESTAMPDIFF(MONTH, vl_1_date,'{referenceDate}') >= 3) THEN 4 WHEN (t1.is_pregnant OR (t6.relationship = 2 AND TIMESTAMPDIFF(MONTH, t6.date_created,'{referenceDate}') BETWEEN 0 AND 24 )) AND vl_1 <= 400 AND (TIMESTAMPDIFF(MONTH, vl_1_date,'{referenceDate}') >= 6) THEN 5 else 0 end" - } - }, - { - "type": "derived_column", - "alias": "overdue_vl_lab_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when (timestampdiff(day,vl_order_date, '{referenceDate}') >= 14) and (vl_1_date is null or vl_order_date > vl_1_date) and vl_error <> 1 then timestampdiff(day,vl_order_date, '{referenceDate}') else 0 end" - } - }, - { - "type": "derived_column", - "alias": "new_viral_load_present", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"DATE_ADD(vl_1_date, INTERVAL 90 DAY) > NOW()" - } - }, - { - "type": "derived_column", - "alias": "needs_cd4_count_coded", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when cur_arv_meds is not null and vl_1 > 1000 and timestampdiff(day,cd4_1_date, '{referenceDate}') >= 90 then 1 when timestampdiff(month,arv_start_date, '{referenceDate}') <= 12 and (cd4_1_date is null or timestampdiff(month,cd4_1_date, '{referenceDate}') > 6) then 2 when timestampdiff(month,arv_start_date, '{referenceDate}') > 12 and (cd4_1_date is null or timestampdiff(month,cd4_1_date, '{referenceDate}') > 12) then 3 else 0 end" - } - }, - { - "type": "derived_column", - "alias": "months_since_last_vl_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"timestampdiff(month,vl_1_date, '{referenceDate}')" - } - }, - { - "type": "derived_column", - "alias": "overdue_cd4_count_lab_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when timestampdiff(day,cd4_order_date, '{referenceDate}') > 30 and cd4_1_date is null or cd4_order_date > cd4_1_date then timestampdiff(day,cd4_order_date, '{referenceDate}') else 0 end " - } - }, - { - "type": "derived_column", - "alias": "is_on_inh_treatment", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"ipt_start_date is not null " - } - }, - { - "type": "derived_column", - "alias": "qualifies_differenciated_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when vl_1 < 401 and (timestampdiff(year,birthdate, date('{referenceDate}')) >= 20) and (timestampdiff(month,ipt_start_date,if(ipt_completion_date,ipt_completion_date,'{referenceDate}')) >= 6 ) and (timestampdiff(month,vl_1_date,now()) <= 11 ) and (timestampdiff(month,arv_start_date, '{referenceDate}') >= 12) AND p.program_id IS NULL and t10.program_id is null and DATE(t1.prev_rtc_date) = DATE(t1.encounter_datetime) then 1 else 0 end" - } - }, - { - "type": "simple_column", - "alias":"last_encounter_date", - "column":"t1.encounter_datetime" - }, - { - "type": "simple_column", - "alias":"birth_date", - "column":"t5.birthdate" - }, - { - "type": "simple_column", - "alias":"person_id", - "column":"t1.person_id" - }, - { - "type": "simple_column", - "alias":"person_uuid", - "column":"t1.uuid" - }, - { - "type": "simple_column", - "alias":"arv_start_date", - "column":"t1.arv_start_date" - }, - { - "type": "simple_column", - "alias":"cur_arv_meds", - "column":"t1.cur_arv_meds" - }, - { - "type": "simple_column", - "alias":"viral_load", - "column":"t1.vl_1" - }, - { - "type": "simple_column", - "alias":"vl_order_date", - "column":"t1.vl_order_date" - }, - { - "type": "simple_column", - "alias":"last_vl_date", - "column":"t1.vl_1_date" - }, - { - "type": "simple_column", - "alias":"vl_error", - "column":"t2.vl_error" - }, - { - "type": "simple_column", - "alias":"vl_error_date", - "column":"t2.test_datetime" - }, - { - "type": "simple_column", - "alias":"test_date", - "column":"DATE_FORMAT(t2.test_datetime,'%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias":"ordered_vl_has_error", - "column":"t3.ordered_vl_has_error" - }, - { - "type": "simple_column", - "alias":"vl_error_order_date", - "column":"t3.vl_error_order_date" - }, - { - "type": "derived_column", - "alias": "ipt_completion_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_ADD(t1.ipt_start_date, INTERVAL 180 DAY)" - } - }, - { - "type": "simple_column", - "alias":"ipt_start_date", - "column":"t1.ipt_start_date" - }, - { - "type": "derived_column", - "alias": "inh_treatment_days_remaining", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATEDIFF(DATE_ADD(t1.ipt_start_date, INTERVAL 180 DAY), now())" - } - }, - { - "type": "derived_column", - "alias": "is_pregnant", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when t1.is_pregnant = 1 then 1 else 0 end" - } - }, - { - "type": "derived_column", - "alias": "is_postnatal", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when t6.relationship = 2 and timestampdiff(month,t6.date_created, '{referenceDate}') between 0 and 24 then 1 else 0 end" - } - }, - { - "type": "derived_column", - "alias": "is_infant", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when timestampdiff(month,t5.birthdate, '{referenceDate}') between 0 and 24 then 1 else 0 end" - } - }, - { - "type": "derived_column", - "alias": "dna_pcr_reminder", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when t9.program_id is not null and timestampdiff(month,t5.birthdate, '{referenceDate}') between 0 and 2 then 1 when t9.program_id is not null and timestampdiff(month,t5.birthdate, '{referenceDate}') = 6 then 2 when t9.program_id is not null and timestampdiff(month,t5.birthdate, '{referenceDate}') = 12 then 3 when t9.program_id is not null and timestampdiff(month,t5.birthdate, '{referenceDate}') between 18 and 24 then 4 else 0 end" - } - }, - { - "type": "derived_column", - "alias": "qualifies_enhanced", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when vl_1 >= 401 and (t7.program_id is null) then 1 when (vl_1 < 401) and (t7.program_id is not null) then 2 when (t7.program_id is not null and t7.date_completed is null) and timestampdiff(month,vl_1_date, '{referenceDate}') >= 3 then 3 else 0 end" - } - }, - { - "type": "derived_column", - "alias": "has_gene_xpert_result", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when t3.gene_expert_image is not null then 1 else 0 end" - } - }, - { - "type": "derived_column", - "alias": "has_dst_result", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when t3.dst_image is not null then 1 else 0 end" - } - }, - { - "type": "derived_column", - "alias": "not_completed_ipt", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when (timestampdiff(day,t1.ipt_start_date,curdate()) > 180) and t1.ipt_completion_date is null and t1.ipt_stop_date is null then 1 else 0 end" - } - } - - ], - "indexDirectives": [ - { - "type": "force", - "indexList": ["person_uuid"] - }], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.uuid = ?", - "parameterName": "patientUuid" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t1.encounter_datetime < ?", - "parameterName": "referenceDate" - } - ] - }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [ - { - "column": "t1.encounter_datetime", - "order": "desc" - } - ] - }, - "paging": { - "offSetParam":"offSetParam", - "limitParam": "limitParam" - } +{ + "name": "clinical_reminder_report", + "version": "1.0", + "tag": "clinical_reminder_report", + "description": "Clinical Reminder Report", + "uses": [ + { + "name": "flatLabsAndImagingDataSetbase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "t1" + }, + { + "table": "etl.flat_labs_and_imaging", + "alias": "t2", + "join": { + "type": "left", + "joinCondition": "date(t1.encounter_datetime) = date(t2.test_datetime)" + } + }, + { + "table": "amrs.person", + "alias": "t5", + "join": { + "type": "left", + "joinCondition": "t5.person_id = t1.person_id" + } + }, + { + "table": "amrs.patient_program", + "alias": "p", + "join": { + "type": "left", + "joinCondition": "t1.person_id = p.patient_id AND p.program_id = 9 AND date_completed IS NULL" + } + }, + { + "dataSet": "flatLabsAndImagingDataSetbase", + "alias": "t3", + "join": { + "type": "left", + "joinCondition": "t3.person_uuid = t1.uuid" + } + }, + { + "table": "amrs.relationship", + "alias": "t6", + "join": { + "type": "left", + "joinCondition": "t6.person_a = t1.person_id" + } + }, + { + "table": "amrs.patient_program", + "alias": "t9", + "join": { + "type": "left", + "joinCondition": "t1.person_id = t9.patient_id AND t9.program_id = 29 AND t9.date_completed IS NULL" + } + }, + { + "table": "amrs.patient_program", + "alias": "t10", + "join": { + "type": "left", + "joinCondition": "t1.person_id = t10.patient_id AND t10.program_id = 4 AND t10.date_completed IS NULL" + } + }, + { + "table": "amrs.patient_program", + "alias": "t7", + "join": { + "type": "left", + "joinCondition": "t1.person_id = t7.patient_id AND t7.program_id = 27 AND t7.date_completed IS NULL" + } + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "needs_vl_coded", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when (cur_arv_meds is null) then 0 when (timestampdiff(month,vl_1_date, date('{referenceDate}')) > 3) and vl_1 > 1000 and arv_start_date < vl_1_date then 1 when (timestampdiff(month,arv_start_date,date('{referenceDate}')) between 6 and 12) and (vl_1_date is null or vl_1_date < arv_start_date ) then 2 when (timestampdiff(month,arv_start_date,'{referenceDate}') > 12) and (vl_1_date is null or timestampdiff(month,vl_1_date,'{referenceDate}') > 12) then 3 WHEN (t1.is_pregnant OR (t6.relationship = 2 AND TIMESTAMPDIFF(MONTH, t6.date_created,'{referenceDate}') BETWEEN 0 AND 24 )) AND vl_1 > 400 AND (TIMESTAMPDIFF(MONTH, vl_1_date,'{referenceDate}') >= 3) THEN 4 WHEN (t1.is_pregnant OR (t6.relationship = 2 AND TIMESTAMPDIFF(MONTH, t6.date_created,'{referenceDate}') BETWEEN 0 AND 24 )) AND vl_1 <= 400 AND (TIMESTAMPDIFF(MONTH, vl_1_date,'{referenceDate}') >= 6) THEN 5 else 0 end" + } + }, + { + "type": "derived_column", + "alias": "overdue_vl_lab_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when (timestampdiff(day,vl_order_date, '{referenceDate}') >= 14) and (vl_1_date is null or vl_order_date > vl_1_date) and vl_error <> 1 then timestampdiff(day,vl_order_date, '{referenceDate}') else 0 end" + } + }, + { + "type": "derived_column", + "alias": "new_viral_load_present", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_ADD(vl_1_date, INTERVAL 90 DAY) > NOW()" + } + }, + { + "type": "derived_column", + "alias": "needs_cd4_count_coded", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when cur_arv_meds is not null and vl_1 > 1000 and timestampdiff(day,cd4_1_date, '{referenceDate}') >= 90 then 1 when timestampdiff(month,arv_start_date, '{referenceDate}') <= 12 and (cd4_1_date is null or timestampdiff(month,cd4_1_date, '{referenceDate}') > 6) then 2 when timestampdiff(month,arv_start_date, '{referenceDate}') > 12 and (cd4_1_date is null or timestampdiff(month,cd4_1_date, '{referenceDate}') > 12) then 3 else 0 end" + } + }, + { + "type": "derived_column", + "alias": "months_since_last_vl_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(month,vl_1_date, '{referenceDate}')" + } + }, + { + "type": "derived_column", + "alias": "overdue_cd4_count_lab_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when timestampdiff(day,cd4_order_date, '{referenceDate}') > 30 and cd4_1_date is null or cd4_order_date > cd4_1_date then timestampdiff(day,cd4_order_date, '{referenceDate}') else 0 end " + } + }, + { + "type": "derived_column", + "alias": "is_on_inh_treatment", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "ipt_start_date is not null " + } + }, + { + "type": "derived_column", + "alias": "qualifies_differenciated_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when vl_1 < 401 and (timestampdiff(year,birthdate, date('{referenceDate}')) >= 20) and (timestampdiff(month,ipt_start_date,if(ipt_completion_date,ipt_completion_date,'{referenceDate}')) >= 6 ) and (timestampdiff(month,vl_1_date,now()) <= 11 ) and (timestampdiff(month,arv_start_date, '{referenceDate}') >= 12) AND p.program_id IS NULL and t10.program_id is null and DATE(t1.prev_rtc_date) = DATE(t1.encounter_datetime) then 1 else 0 end" + } + }, + { + "type": "simple_column", + "alias": "last_encounter_date", + "column": "t1.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "birth_date", + "column": "t5.birthdate" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "person_uuid", + "column": "t1.uuid" + }, + { + "type": "simple_column", + "alias": "arv_start_date", + "column": "t1.arv_start_date" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "t1.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "viral_load", + "column": "t1.vl_1" + }, + { + "type": "simple_column", + "alias": "vl_order_date", + "column": "t1.vl_order_date" + }, + { + "type": "simple_column", + "alias": "last_vl_date", + "column": "t1.vl_1_date" + }, + { + "type": "simple_column", + "alias": "vl_error", + "column": "t2.vl_error" + }, + { + "type": "simple_column", + "alias": "vl_error_date", + "column": "t2.test_datetime" + }, + { + "type": "simple_column", + "alias": "test_date", + "column": "DATE_FORMAT(t2.test_datetime,'%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "ordered_vl_has_error", + "column": "t3.ordered_vl_has_error" + }, + { + "type": "simple_column", + "alias": "vl_error_order_date", + "column": "t3.vl_error_order_date" + }, + { + "type": "derived_column", + "alias": "ipt_completion_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_ADD(t1.ipt_start_date, INTERVAL 180 DAY)" + } + }, + { + "type": "simple_column", + "alias": "ipt_start_date", + "column": "t1.ipt_start_date" + }, + { + "type": "derived_column", + "alias": "inh_treatment_days_remaining", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATEDIFF(DATE_ADD(t1.ipt_start_date, INTERVAL 180 DAY), now())" + } + }, + { + "type": "derived_column", + "alias": "is_pregnant", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t1.is_pregnant = 1 then 1 else 0 end" + } + }, + { + "type": "derived_column", + "alias": "is_postnatal", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t6.relationship = 2 and timestampdiff(month,t6.date_created, '{referenceDate}') between 0 and 24 then 1 else 0 end" + } + }, + { + "type": "derived_column", + "alias": "is_infant", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when timestampdiff(month,t5.birthdate, '{referenceDate}') between 0 and 24 then 1 else 0 end" + } + }, + { + "type": "derived_column", + "alias": "dna_pcr_reminder", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t9.program_id is not null and timestampdiff(month,t5.birthdate, '{referenceDate}') between 0 and 2 then 1 when t9.program_id is not null and timestampdiff(month,t5.birthdate, '{referenceDate}') = 6 then 2 when t9.program_id is not null and timestampdiff(month,t5.birthdate, '{referenceDate}') = 12 then 3 when t9.program_id is not null and timestampdiff(month,t5.birthdate, '{referenceDate}') between 18 and 24 then 4 else 0 end" + } + }, + { + "type": "derived_column", + "alias": "qualifies_enhanced", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when vl_1 >= 401 and (t7.program_id is null) then 1 when (vl_1 < 401) and (t7.program_id is not null) then 2 when (t7.program_id is not null and t7.date_completed is null) and timestampdiff(month,vl_1_date, '{referenceDate}') >= 3 then 3 else 0 end" + } + }, + { + "type": "derived_column", + "alias": "has_gene_xpert_result", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t3.gene_expert_image is not null then 1 else 0 end" + } + }, + { + "type": "derived_column", + "alias": "has_dst_result", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t3.dst_image is not null then 1 else 0 end" + } + }, + { + "type": "derived_column", + "alias": "not_completed_ipt", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when (timestampdiff(day,t1.ipt_start_date,curdate()) > 180) and t1.ipt_completion_date is null and t1.ipt_stop_date is null then 1 else 0 end" + } + } + ], + "indexDirectives": [ + { + "type": "force", + "indexList": ["person_uuid"] + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.uuid = ?", + "parameterName": "patientUuid" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t1.encounter_datetime < ?", + "parameterName": "referenceDate" + } + ] + }, + "orderBy": { + "orderByParam": "orderByParam", + "columns": [ + { + "column": "t1.encounter_datetime", + "order": "desc" + } + ] + }, + "paging": { + "offSetParam": "offSetParam", + "limitParam": "limitParam" + } } diff --git a/app/reporting-framework/json-reports/cohort-report-base.json b/app/reporting-framework/json-reports/cohort-report-base.json index 2fe18cb74..296177659 100644 --- a/app/reporting-framework/json-reports/cohort-report-base.json +++ b/app/reporting-framework/json-reports/cohort-report-base.json @@ -1,89 +1,90 @@ { - "name": "cohort_report", - "version": "1.0", - "tag": "cohort_report", - "description": "Cohort Report", - "sources": [ - { - "table": "amrs.cohort", - "alias": "t1" - }, - { - "table": "etl.cohort_user", - "alias": "t2", - "join": { - "type": "LEFT OUTER", - "joinCondition": "t1.cohort_id = t2.cohort_id and t2.voided=0" - } - }, - { - "table": "amrs.users", - "alias": "t3", - "join": { - "type": "INNER", - "joinCondition": "t1.creator = t3.user_id or t2.user_id = t3.user_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "name", - "column": "distinct t1.name" - }, - { - "type": "simple_column", - "alias": "description", - "column": "t1.description" - }, - { - "type": "simple_column", - "alias": "date_created", - "column": "t1.date_created" - }, - { - "type": "simple_column", - "alias": "cohort_id", - "column": "t1.cohort_id" - }, - { - "type": "simple_column", - "alias": "uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "role", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when t2.role is null or t2.user_id != t3.user_id then'admin' else t2.role end" - } - }, - { - "type": "derived_column", - "alias": "access", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"case when t2.role is null then 'private' else 'shared' end" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.voided=0 and t3.uuid = ?", - "parameterName": "userUuid" - } - ] + "name": "cohort_report", + "version": "1.0", + "tag": "cohort_report", + "description": "Cohort Report", + "sources": [ + { + "table": "amrs.cohort", + "alias": "t1" + }, + { + "table": "etl.cohort_user", + "alias": "t2", + "join": { + "type": "LEFT OUTER", + "joinCondition": "t1.cohort_id = t2.cohort_id and t2.voided=0" + } + }, + { + "table": "amrs.users", + "alias": "t3", + "join": { + "type": "INNER", + "joinCondition": "t1.creator = t3.user_id or t2.user_id = t3.user_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "name", + "column": "distinct t1.name" + }, + { + "type": "simple_column", + "alias": "description", + "column": "t1.description" + }, + { + "type": "simple_column", + "alias": "date_created", + "column": "t1.date_created" }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [{ - "column": "t1.name", - "order": "asc" - }] - } - -} \ No newline at end of file + { + "type": "simple_column", + "alias": "cohort_id", + "column": "t1.cohort_id" + }, + { + "type": "simple_column", + "alias": "uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "role", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t2.role is null or t2.user_id != t3.user_id then'admin' else t2.role end" + } + }, + { + "type": "derived_column", + "alias": "access", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t2.role is null then 'private' else 'shared' end" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.voided=0 and t3.uuid = ?", + "parameterName": "userUuid" + } + ] + }, + "orderBy": { + "orderByParam": "orderByParam", + "columns": [ + { + "column": "t1.name", + "order": "asc" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-daily-screening-summary-aggregate.json b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-daily-screening-summary-aggregate.json index 7dd8cafc8..206424b7f 100644 --- a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-daily-screening-summary-aggregate.json +++ b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-daily-screening-summary-aggregate.json @@ -1,92 +1,89 @@ { - "name": "combinedBreastCervicalCancerDailySummaryAggregate", - "version": "1.0", - "tag": "combined_breast_cervical_cancer_summary_aggregate", - "uses": [ - { - "name": "combinedBreastCervicalCancerDailySummaryBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "combinedBreastCervicalCancerDailySummaryBase", - "alias": "bcsd" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_name", - "column": "location_name" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "location_uuid" - }, - { - "type": "derived_column", - "alias": "encounter_datetime", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(bcsd.encounter_datetime, '%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "total_breast_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(bcsd.total_breast_screened)" - } - }, - { - "type": "derived_column", - "alias": "total_cervical_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(bcsd.total_cervical_screened)" - } - }, - { - "type": "derived_column", - "alias": "total_breast_and_cervical_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(bcsd.both_cervical_and_breast)" - } - }, - { - "type": "derived_column", - "alias": "total_screens", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "(sum(bcsd.both_cervical_and_breast) * 2) + sum(bcsd.total_cervical_screened) + sum(bcsd.total_breast_screened)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id", - "DATE(bcsd.encounter_datetime)" - ], - "excludeParam": "excludeParam" + "name": "combinedBreastCervicalCancerDailySummaryAggregate", + "version": "1.0", + "tag": "combined_breast_cervical_cancer_summary_aggregate", + "uses": [ + { + "name": "combinedBreastCervicalCancerDailySummaryBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "combinedBreastCervicalCancerDailySummaryBase", + "alias": "bcsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_name", + "column": "location_name" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "location_uuid" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "combined_breast_cervical_cancer_patient_list_template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "patient_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "encounter_datetime", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(bcsd.encounter_datetime, '%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "total_breast_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(bcsd.total_breast_screened)" + } + }, + { + "type": "derived_column", + "alias": "total_cervical_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(bcsd.total_cervical_screened)" + } + }, + { + "type": "derived_column", + "alias": "total_breast_and_cervical_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(bcsd.both_cervical_and_breast)" + } + }, + { + "type": "derived_column", + "alias": "total_screens", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "(sum(bcsd.both_cervical_and_breast) * 2) + sum(bcsd.total_cervical_screened) + sum(bcsd.total_breast_screened)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id", "DATE(bcsd.encounter_datetime)"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "combined_breast_cervical_cancer_patient_list_template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "patient_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-daily-screening-summary-base.json b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-daily-screening-summary-base.json index 0ecfe984c..39c3dfb27 100644 --- a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-daily-screening-summary-base.json +++ b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-daily-screening-summary-base.json @@ -1,209 +1,201 @@ { - "name": "combinedBreastCervicalCancerDailySummaryBase", - "version": "1.0", - "tag": "combined_breast_cervical_cancer_daily_summary_base", - "uses": [], - "sources": [ - { - "table": "amrs.encounter", - "alias": "e" - }, - { - "table": "etl.flat_breast_cancer_screening", - "alias": "fbcs", - "join":{ - "type":"left", - "joinCondition": "e.patient_id = fbcs.person_id " - } - }, - { - "table": "etl.flat_cervical_cancer_screening", - "alias": "fccs", - "join":{ - "type":"left", - "joinCondition": "e.patient_id = fccs.person_id " - } - }, - { - "table": "amrs.person_name", - "alias": "patient_name", - "join": { - "type": "inner", - "joinCondition": "e.patient_id = patient_name.person_id and (patient_name.voided is null || patient_name.voided = 0)" - - } - }, - { - "table": "amrs.patient_identifier", - "alias": "patient_id", - "join": { - "type": "inner", - "joinCondition": "e.patient_id = patient_id.patient_id and (patient_id.voided is null || patient_id.voided = 0)" - - } - - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "e.location_id = l.location_id" - - } - }, - { - "table": "amrs.person_attribute", - "alias": "p", - "join": { - "type": "left", - "joinCondition": "e.patient_id = p.person_id and (p.voided is null || p.voided = 0 and (p.person_attribute_type_id = 10))" - - } - }, - { - "table": "amrs.person", - "alias": "person", - "join": { - "type": "left", - "joinCondition": "e.patient_id = person.person_id and (person.voided is null || person.voided = 0 )" - - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "fbcs_person_id", - "column": "fbcs.person_id" - }, - { - "type": "simple_column", - "alias": "fccs_person_id", - "column": "fccs.person_id" - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "concat(coalesce(patient_name.given_name, ''), ' ', coalesce(patient_name.middle_name, ''), ' ', coalesce(patient_name.family_name, ''))" - } - }, - { - "type": "simple_column", - "alias": "phone_number", - "column": "p.value" - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "group_concat(distinct patient_id.identifier separator ', ')" - } - }, - { - "type": "simple_column", - "alias": "gender", - "column": "person.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "l.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_name", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "e.encounter_datetime" - }, - { - "type": "derived_column", - "alias": "total_breast_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF((fbcs.person_id IS NOT NULL) AND (fccs.person_id IS NULL), 1, 0)" - } - }, - { - "type": "derived_column", - "alias": "total_cervical_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF((fccs.person_id IS NOT NULL) AND (fbcs.person_id IS NULL), 1, 0)" - } - }, - { - "type": "derived_column", - "alias": "both_cervical_and_breast", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF (fccs.person_id = fbcs.person_id,1,0)" - } - } - - - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,person.birthdate,NOW()) >= ?", - "parameterName": "startAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,person.birthdate,NOW()) <= ?", - "parameterName": "endAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(e.encounter_datetime) >= ? ", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(e.encounter_datetime) <= ? ", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "e.encounter_type in (86,69)" - }, - { - "filterType": "tableColumns", - "conditionExpression": "l.uuid in ?", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "person.gender in ?", - "parameterName": "genders" - }, - { - "filterType": "tableColumns", - "conditionExpression": "l.location_id not in (195)" - } - ] - }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "person.person_id", - "l.location_id", - "DATE_FORMAT(e.encounter_datetime, '%D-%M-%Y')" - ] + "name": "combinedBreastCervicalCancerDailySummaryBase", + "version": "1.0", + "tag": "combined_breast_cervical_cancer_daily_summary_base", + "uses": [], + "sources": [ + { + "table": "amrs.encounter", + "alias": "e" + }, + { + "table": "etl.flat_breast_cancer_screening", + "alias": "fbcs", + "join": { + "type": "left", + "joinCondition": "e.patient_id = fbcs.person_id " + } + }, + { + "table": "etl.flat_cervical_cancer_screening", + "alias": "fccs", + "join": { + "type": "left", + "joinCondition": "e.patient_id = fccs.person_id " + } + }, + { + "table": "amrs.person_name", + "alias": "patient_name", + "join": { + "type": "inner", + "joinCondition": "e.patient_id = patient_name.person_id and (patient_name.voided is null || patient_name.voided = 0)" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "patient_id", + "join": { + "type": "inner", + "joinCondition": "e.patient_id = patient_id.patient_id and (patient_id.voided is null || patient_id.voided = 0)" + } + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "e.location_id = l.location_id" + } + }, + { + "table": "amrs.person_attribute", + "alias": "p", + "join": { + "type": "left", + "joinCondition": "e.patient_id = p.person_id and (p.voided is null || p.voided = 0 and (p.person_attribute_type_id = 10))" + } + }, + { + "table": "amrs.person", + "alias": "person", + "join": { + "type": "left", + "joinCondition": "e.patient_id = person.person_id and (person.voided is null || person.voided = 0 )" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "fbcs_person_id", + "column": "fbcs.person_id" + }, + { + "type": "simple_column", + "alias": "fccs_person_id", + "column": "fccs.person_id" + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "concat(coalesce(patient_name.given_name, ''), ' ', coalesce(patient_name.middle_name, ''), ' ', coalesce(patient_name.family_name, ''))" + } + }, + { + "type": "simple_column", + "alias": "phone_number", + "column": "p.value" + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "group_concat(distinct patient_id.identifier separator ', ')" + } + }, + { + "type": "simple_column", + "alias": "gender", + "column": "person.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "l.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_name", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "e.encounter_datetime" + }, + { + "type": "derived_column", + "alias": "total_breast_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF((fbcs.person_id IS NOT NULL) AND (fccs.person_id IS NULL), 1, 0)" + } + }, + { + "type": "derived_column", + "alias": "total_cervical_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF((fccs.person_id IS NOT NULL) AND (fbcs.person_id IS NULL), 1, 0)" + } + }, + { + "type": "derived_column", + "alias": "both_cervical_and_breast", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF (fccs.person_id = fbcs.person_id,1,0)" + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,person.birthdate,NOW()) >= ?", + "parameterName": "startAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,person.birthdate,NOW()) <= ?", + "parameterName": "endAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(e.encounter_datetime) >= ? ", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(e.encounter_datetime) <= ? ", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "e.encounter_type in (86,69)" + }, + { + "filterType": "tableColumns", + "conditionExpression": "l.uuid in ?", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "person.gender in ?", + "parameterName": "genders" + }, + { + "filterType": "tableColumns", + "conditionExpression": "l.location_id not in (195)" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": [ + "person.person_id", + "l.location_id", + "DATE_FORMAT(e.encounter_datetime, '%D-%M-%Y')" + ] + } +} diff --git a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-monthly-screening-summary-aggregate.json b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-monthly-screening-summary-aggregate.json index b26179b7b..3964c3101 100644 --- a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-monthly-screening-summary-aggregate.json +++ b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-monthly-screening-summary-aggregate.json @@ -1,93 +1,93 @@ { - "name": "combinedBreastCervicalCancerMonthlySummaryAggregate", - "version": "1.0", - "tag": "combined_breast_cervical_cancer_summary_aggregate", - "uses": [ - { - "name": "combinedBreastCervicalCancerMonthlySummaryBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "combinedBreastCervicalCancerMonthlySummaryBase", - "alias": "bcsd" - } - ], + "name": "combinedBreastCervicalCancerMonthlySummaryAggregate", + "version": "1.0", + "tag": "combined_breast_cervical_cancer_summary_aggregate", + "uses": [ + { + "name": "combinedBreastCervicalCancerMonthlySummaryBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "combinedBreastCervicalCancerMonthlySummaryBase", + "alias": "bcsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_name", + "column": "location_name" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "location_uuid" + }, + { + "type": "derived_column", + "alias": "encounter_datetime", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(bcsd.encounter_datetime, '%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "total_breast_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(bcsd.total_breast_screened)" + } + }, + { + "type": "derived_column", + "alias": "total_cervical_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(bcsd.total_cervical_screened)" + } + }, + { + "type": "derived_column", + "alias": "total_breast_and_cervical_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(bcsd.both_cervical_and_breast)" + } + }, + { + "type": "derived_column", + "alias": "total_screens", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "(sum(bcsd.both_cervical_and_breast) * 2) + sum(bcsd.total_cervical_screened) + sum(bcsd.total_breast_screened)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", "columns": [ - { - "type": "simple_column", - "alias": "location_name", - "column": "location_name" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "location_uuid" - }, - { - "type": "derived_column", - "alias": "encounter_datetime", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(bcsd.encounter_datetime, '%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "total_breast_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(bcsd.total_breast_screened)" - } - }, - { - "type": "derived_column", - "alias": "total_cervical_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(bcsd.total_cervical_screened)" - } - }, - { - "type": "derived_column", - "alias": "total_breast_and_cervical_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(bcsd.both_cervical_and_breast)" - } - }, - { - "type": "derived_column", - "alias": "total_screens", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "(sum(bcsd.both_cervical_and_breast) * 2) + sum(bcsd.total_cervical_screened) + sum(bcsd.total_breast_screened)" - } - } + "bcsd.location_id", + "year(bcsd.encounter_datetime)", + "month(bcsd.encounter_datetime)" ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "bcsd.location_id", - "year(bcsd.encounter_datetime)", - "month(bcsd.encounter_datetime)" - ], - "excludeParam": "excludeParam" - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "combined_breast_cervical_cancer_patient_list_template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "patient_id", - "templateColumn": "person_id" - } - } + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "combined_breast_cervical_cancer_patient_list_template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "patient_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-monthly-screening-summary-base.json b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-monthly-screening-summary-base.json index 7c5166738..ecc648e3d 100644 --- a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-monthly-screening-summary-base.json +++ b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-monthly-screening-summary-base.json @@ -1,209 +1,201 @@ { - "name": "combinedBreastCervicalCancerMonthlySummaryBase", - "version": "1.0", - "tag": "combined_breast_cervical_cancer_monthly_summary_base", - "uses": [], - "sources": [ - { - "table": "amrs.encounter", - "alias": "e" - }, - { - "table": "etl.flat_breast_cancer_screening", - "alias": "fbcs", - "join":{ - "type":"left", - "joinCondition": "e.encounter_id = fbcs.encounter_id" - } - }, - { - "table": "etl.flat_cervical_cancer_screening", - "alias": "fccs", - "join":{ - "type":"left", - "joinCondition": "e.encounter_id = fccs.encounter_id" - } - }, - { - "table": "amrs.person_name", - "alias": "patient_name", - "join": { - "type": "inner", - "joinCondition": "e.patient_id = patient_name.person_id and (patient_name.voided is null || patient_name.voided = 0)" - - } - }, - { - "table": "amrs.patient_identifier", - "alias": "patient_id", - "join": { - "type": "inner", - "joinCondition": "e.patient_id = patient_id.patient_id and (patient_id.voided is null || patient_id.voided = 0)" - - } - - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "e.location_id = l.location_id" - - } - }, - { - "table": "amrs.person_attribute", - "alias": "p", - "join": { - "type": "left", - "joinCondition": "e.patient_id = p.person_id and (p.voided is null || p.voided = 0 and (p.person_attribute_type_id = 10))" - - } - }, - { - "table": "amrs.person", - "alias": "person", - "join": { - "type": "left", - "joinCondition": "e.patient_id = person.person_id and (person.voided is null || person.voided = 0 )" - - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "fbcs_person_id", - "column": "fbcs.person_id" - }, - { - "type": "simple_column", - "alias": "fccs_person_id", - "column": "fccs.person_id" - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "concat(coalesce(patient_name.given_name, ''), ' ', coalesce(patient_name.middle_name, ''), ' ', coalesce(patient_name.family_name, ''))" - } - }, - { - "type": "simple_column", - "alias": "phone_number", - "column": "p.value" - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "group_concat(distinct patient_id.identifier separator ', ')" - } - }, - { - "type": "simple_column", - "alias": "gender", - "column": "person.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "l.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_name", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "DATE_FORMAT(e.encounter_datetime, '%Y-%m-%d')" - }, - { - "type": "derived_column", - "alias": "total_breast_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF((fbcs.person_id IS NOT NULL) AND (fccs.person_id IS NULL), 1, 0)" - } - }, - { - "type": "derived_column", - "alias": "total_cervical_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF((fccs.person_id IS NOT NULL) AND (fbcs.person_id IS NULL), 1, 0)" - } - }, - { - "type": "derived_column", - "alias": "both_cervical_and_breast", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF (fccs.person_id = fbcs.person_id,1,0)" - } - } - - - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "(fbcs.age OR fccs.age >= ?)", - "parameterName": "startAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(fbcs.age OR fccs.age <= ?)", - "parameterName": "endAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(e.encounter_datetime) >= ? ", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(e.encounter_datetime) <= ? ", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "e.encounter_type in (86,69)" - }, - { - "filterType": "tableColumns", - "conditionExpression": "l.uuid in ?", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "person.gender in ?", - "parameterName": "genders" - }, - { - "filterType": "tableColumns", - "conditionExpression": "l.location_id not in (195)" - } - ] - }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "e.encounter_id", - "l.location_id", - "DATE_FORMAT(e.encounter_datetime, '%M-%Y')" - ] + "name": "combinedBreastCervicalCancerMonthlySummaryBase", + "version": "1.0", + "tag": "combined_breast_cervical_cancer_monthly_summary_base", + "uses": [], + "sources": [ + { + "table": "amrs.encounter", + "alias": "e" + }, + { + "table": "etl.flat_breast_cancer_screening", + "alias": "fbcs", + "join": { + "type": "left", + "joinCondition": "e.encounter_id = fbcs.encounter_id" + } + }, + { + "table": "etl.flat_cervical_cancer_screening", + "alias": "fccs", + "join": { + "type": "left", + "joinCondition": "e.encounter_id = fccs.encounter_id" + } + }, + { + "table": "amrs.person_name", + "alias": "patient_name", + "join": { + "type": "inner", + "joinCondition": "e.patient_id = patient_name.person_id and (patient_name.voided is null || patient_name.voided = 0)" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "patient_id", + "join": { + "type": "inner", + "joinCondition": "e.patient_id = patient_id.patient_id and (patient_id.voided is null || patient_id.voided = 0)" + } + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "e.location_id = l.location_id" + } + }, + { + "table": "amrs.person_attribute", + "alias": "p", + "join": { + "type": "left", + "joinCondition": "e.patient_id = p.person_id and (p.voided is null || p.voided = 0 and (p.person_attribute_type_id = 10))" + } + }, + { + "table": "amrs.person", + "alias": "person", + "join": { + "type": "left", + "joinCondition": "e.patient_id = person.person_id and (person.voided is null || person.voided = 0 )" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "fbcs_person_id", + "column": "fbcs.person_id" + }, + { + "type": "simple_column", + "alias": "fccs_person_id", + "column": "fccs.person_id" + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "concat(coalesce(patient_name.given_name, ''), ' ', coalesce(patient_name.middle_name, ''), ' ', coalesce(patient_name.family_name, ''))" + } + }, + { + "type": "simple_column", + "alias": "phone_number", + "column": "p.value" + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "group_concat(distinct patient_id.identifier separator ', ')" + } + }, + { + "type": "simple_column", + "alias": "gender", + "column": "person.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "l.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_name", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "DATE_FORMAT(e.encounter_datetime, '%Y-%m-%d')" + }, + { + "type": "derived_column", + "alias": "total_breast_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF((fbcs.person_id IS NOT NULL) AND (fccs.person_id IS NULL), 1, 0)" + } + }, + { + "type": "derived_column", + "alias": "total_cervical_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF((fccs.person_id IS NOT NULL) AND (fbcs.person_id IS NULL), 1, 0)" + } + }, + { + "type": "derived_column", + "alias": "both_cervical_and_breast", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF (fccs.person_id = fbcs.person_id,1,0)" + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "(fbcs.age OR fccs.age >= ?)", + "parameterName": "startAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(fbcs.age OR fccs.age <= ?)", + "parameterName": "endAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(e.encounter_datetime) >= ? ", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(e.encounter_datetime) <= ? ", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "e.encounter_type in (86,69)" + }, + { + "filterType": "tableColumns", + "conditionExpression": "l.uuid in ?", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "person.gender in ?", + "parameterName": "genders" + }, + { + "filterType": "tableColumns", + "conditionExpression": "l.location_id not in (195)" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": [ + "e.encounter_id", + "l.location_id", + "DATE_FORMAT(e.encounter_datetime, '%M-%Y')" + ] + } +} diff --git a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-patient-list-template.json b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-patient-list-template.json index 8861387dc..1fa7f31df 100644 --- a/app/reporting-framework/json-reports/combined-breast-cervical-cancer-patient-list-template.json +++ b/app/reporting-framework/json-reports/combined-breast-cervical-cancer-patient-list-template.json @@ -1,92 +1,92 @@ { - "name": "combined_breast_cervical_cancer_patient_list_template", - "version": "1.0", - "tag": "combined_breast_cervical_cancer_patient_list_template", - "description": "Combined Breast and Cervical Cancer patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "INNER", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0)" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "t1.birthdate" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "simple_column", - "alias": "given_name", - "column": "person_name.given_name" - }, - { - "type": "simple_column", - "alias": "family_name", - "column": "person_name.family_name" - }, - { - "type": "simple_column", - "alias": "middle_name", - "column": "person_name.middle_name" - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "combined_breast_cervical_cancer_patient_list_template", + "version": "1.0", + "tag": "combined_breast_cervical_cancer_patient_list_template", + "description": "Combined Breast and Cervical Cancer patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "INNER", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0)" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "t1.birthdate" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "simple_column", + "alias": "given_name", + "column": "person_name.given_name" + }, + { + "type": "simple_column", + "alias": "family_name", + "column": "person_name.family_name" + }, + { + "type": "simple_column", + "alias": "middle_name", + "column": "person_name.middle_name" + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/currently-enrolled-patients-aggregate.json b/app/reporting-framework/json-reports/currently-enrolled-patients-aggregate.json index 6c8bba293..ca09c4d12 100644 --- a/app/reporting-framework/json-reports/currently-enrolled-patients-aggregate.json +++ b/app/reporting-framework/json-reports/currently-enrolled-patients-aggregate.json @@ -1,57 +1,55 @@ { - "name": "currentlyEnrolledPtaientsAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "currentlyEnrolledPatientsBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "currentlyEnrolledPatientsBase", - "alias": "pl" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "enrollment_count", - "column": "count(distinct pl.patient_id,pl.program_id)" - }, - { - "type": "simple_column", - "alias": "program_name", - "column": "pl.program_name" - }, - { - "type": "simple_column", - "alias": "program_uuid", - "column": "pl.program_uuid" - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "pl.program_id" - ], - "excludeParam": "excludeParam" + "name": "currentlyEnrolledPtaientsAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "currentlyEnrolledPatientsBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "currentlyEnrolledPatientsBase", + "alias": "pl" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "enrollment_count", + "column": "count(distinct pl.patient_id,pl.program_id)" + }, + { + "type": "simple_column", + "alias": "program_name", + "column": "pl.program_name" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "patient_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "program_uuid", + "column": "pl.program_uuid" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["pl.program_id"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "patient_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/currently-enrolled-patients.base.json b/app/reporting-framework/json-reports/currently-enrolled-patients.base.json index 915748692..8b33ffec4 100644 --- a/app/reporting-framework/json-reports/currently-enrolled-patients.base.json +++ b/app/reporting-framework/json-reports/currently-enrolled-patients.base.json @@ -1,104 +1,101 @@ { - "name": "currentlyEnrolledPatientsBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "amrs.patient_program", - "alias": "pp" - }, - { - "table": "amrs.program", - "alias": "pr", - "join": { - "type": "INNER", - "joinCondition": "pr.program_id = pp.program_id" - } - }, - { - "table": "amrs.person", - "alias": "p1", - "join": { - "type": "INNER", - "joinCondition": "p1.person_id = pp.patient_id" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "i", - "join": { - "type": "INNER", - "joinCondition": "i.patient_id = pp.patient_id" - } - }, - { - "table": "amrs.person_attribute", - "alias": "t5", - "join": { - "type": "LEFT", - "joinCondition": "p1.person_id = t5.person_id AND t5.person_attribute_type_id = 28 AND t5.voided = 0" - } - } - ], - "columns": [ - - { - "type": "simple_column", - "alias": "", - "column": "distinct pp.patient_id,pp.program_id" - }, - { - "type": "simple_column", - "alias": "program_name", - "column": "pr.name" - }, - { - "type": "simple_column", - "alias": "program_uuid", - "column": "pr.uuid" - }, - { - "type": "simple_column", - "alias": "date_completed", - "column": "pp.date_completed" - }, - { - "type": "simple_column", - "alias": "date_enrolled", - "column": "pp.date_enrolled" - } - - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "pp.program_id IN ?", - "parameterName": "programTypeIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "pp.location_id IN ?", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(pp.date_enrolled IS NULL || pp.date_enrolled <= ?)", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(pp.date_completed IS NULL || pp.date_completed >= ?)", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "pp.voided IS NULL or pp.voided = 0 " - } - - ] + "name": "currentlyEnrolledPatientsBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "amrs.patient_program", + "alias": "pp" + }, + { + "table": "amrs.program", + "alias": "pr", + "join": { + "type": "INNER", + "joinCondition": "pr.program_id = pp.program_id" + } + }, + { + "table": "amrs.person", + "alias": "p1", + "join": { + "type": "INNER", + "joinCondition": "p1.person_id = pp.patient_id" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "i", + "join": { + "type": "INNER", + "joinCondition": "i.patient_id = pp.patient_id" + } + }, + { + "table": "amrs.person_attribute", + "alias": "t5", + "join": { + "type": "LEFT", + "joinCondition": "p1.person_id = t5.person_id AND t5.person_attribute_type_id = 28 AND t5.voided = 0" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "", + "column": "distinct pp.patient_id,pp.program_id" + }, + { + "type": "simple_column", + "alias": "program_name", + "column": "pr.name" + }, + { + "type": "simple_column", + "alias": "program_uuid", + "column": "pr.uuid" + }, + { + "type": "simple_column", + "alias": "date_completed", + "column": "pp.date_completed" + }, + { + "type": "simple_column", + "alias": "date_enrolled", + "column": "pp.date_enrolled" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "pp.program_id IN ?", + "parameterName": "programTypeIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "pp.location_id IN ?", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(pp.date_enrolled IS NULL || pp.date_enrolled <= ?)", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(pp.date_completed IS NULL || pp.date_completed >= ?)", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "pp.voided IS NULL or pp.voided = 0 " + } + ] + } +} diff --git a/app/reporting-framework/json-reports/daily-appointment-latest-rtc-cohort-base.json b/app/reporting-framework/json-reports/daily-appointment-latest-rtc-cohort-base.json index 7ae53a925..ee55bbfe3 100644 --- a/app/reporting-framework/json-reports/daily-appointment-latest-rtc-cohort-base.json +++ b/app/reporting-framework/json-reports/daily-appointment-latest-rtc-cohort-base.json @@ -1,72 +1,71 @@ { - "name": "dailyAppointmentlatestRtcCohortBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_appointment", - "alias": "fa" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "encounter_id", - "column": "fa.encounter_id" - }, - { - "type": "simple_column", - "alias": "max_encounter_id", - "column": "MAX(fa.encounter_id)" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "person_id" - } - ], - "indexDirectives": [ - { - "type": "force", - "indexList": ["location_med_pickup_rtc_date"] - }], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "date(fa.scheduled_date) >= '{startDate}'", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "date(fa.scheduled_date) <= '{startDate}'", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.is_clinical = 1 OR fa.encounter_type = 186", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.encounter_type NOT IN (21 , 99999)", - "parameterName": "" - } - ] + "name": "dailyAppointmentlatestRtcCohortBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_appointment", + "alias": "fa" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "encounter_id", + "column": "fa.encounter_id" + }, + { + "type": "simple_column", + "alias": "max_encounter_id", + "column": "MAX(fa.encounter_id)" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "person_id" - ], - "excludeParam": "excludeParam" + { + "type": "simple_column", + "alias": "person_id", + "column": "person_id" + } + ], + "indexDirectives": [ + { + "type": "force", + "indexList": ["location_med_pickup_rtc_date"] } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "date(fa.scheduled_date) >= '{startDate}'", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "date(fa.scheduled_date) <= '{startDate}'", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.is_clinical = 1 OR fa.encounter_type = 186", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.encounter_type NOT IN (21 , 99999)", + "parameterName": "" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["person_id"], + "excludeParam": "excludeParam" + } } diff --git a/app/reporting-framework/json-reports/daily-appointments-aggregate.json b/app/reporting-framework/json-reports/daily-appointments-aggregate.json index 68376fe18..6a2e7150e 100644 --- a/app/reporting-framework/json-reports/daily-appointments-aggregate.json +++ b/app/reporting-framework/json-reports/daily-appointments-aggregate.json @@ -1,67 +1,65 @@ { - "name": "dailyAppointmentsAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "dailyAppointmentsBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "dailyAppointmentsBase", - "alias": "t2" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t2.person_id" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "t2.encounter_type" - }, - { - "type": "simple_column", - "alias": "scheduled", - "column": "count(distinct t2.person_id)" - }, - { - "type": "simple_column", - "alias": "scheduled_date", - "column": "scheduled_date" - }, - { - "type": "simple_column", - "alias": "patients", - "column": "patients" - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "scheduled_date" - ], - "excludeParam": "excludeParam" + "name": "dailyAppointmentsAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "dailyAppointmentsBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "dailyAppointmentsBase", + "alias": "t2" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t2.person_id" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-schedules-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "encounter_type", + "column": "t2.encounter_type" + }, + { + "type": "simple_column", + "alias": "scheduled", + "column": "count(distinct t2.person_id)" + }, + { + "type": "simple_column", + "alias": "scheduled_date", + "column": "scheduled_date" + }, + { + "type": "simple_column", + "alias": "patients", + "column": "patients" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["scheduled_date"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-schedules-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/daily-appointments-base.json b/app/reporting-framework/json-reports/daily-appointments-base.json index c4cf8dc57..f0b77f899 100644 --- a/app/reporting-framework/json-reports/daily-appointments-base.json +++ b/app/reporting-framework/json-reports/daily-appointments-base.json @@ -1,172 +1,173 @@ { - "name": "dailyAppointmentsBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_appointment", - "alias": "t2" - }, - { - "dataSet": "dailyAppointmentlatestRtcCohortBase", - "alias": "latest_encounter", - "join": { - "type": "LEFT", - "joinCondition": "latest_encounter.person_id = t2.person_id" - } - }, - { - "table": "etl.flat_appointment", - "alias": "t3", - "join": { - "type": "LEFT", - "joinCondition": "t3.person_id = t2.person_id AND t3.encounter_id = latest_encounter.max_encounter_id" - } - }, - { - "table": "etl.flat_appointment", - "alias": "death_reporting", - "join": { - "type": "LEFT", - "joinCondition": "death_reporting.person_id = t2.person_id AND death_reporting.encounter_type in (31) AND death_reporting.encounter_datetime >= t2.encounter_datetime" - } - }, - { - "table": "amrs.program", - "alias": "pr", - "join": { - "type": "LEFT", - "joinCondition": "pr.program_id = t3.program_id" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs", - "join": { - "type": "LEFT", - "joinCondition": "t2.encounter_id = fhs.encounter_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t2.person_id" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "t2.encounter_type" - }, - { - "type": "simple_column", - "alias": "program", - "column": "pr.name" - }, - { - "type": "simple_column", - "alias": "rtc_date", - "column": "t2.rtc_date" - }, - { - "type": "simple_column", - "alias": "med_pick_up_date", - "column": "date_format(t2.med_pickup_rtc_date,'%Y-%m-%d')" - }, - { - "alias": "prev_clinical_encounter_datetime", - "column": "t2.prev_clinical_encounter_datetime" - }, - { - "type": "simple_column", - "alias": "next_clinical_encounter_datetime", - "column": "t2.next_clinical_encounter_datetime" - }, - { - "type": "simple_column", - "alias": "scheduled_date", - "column": "date_format(t2.scheduled_date,'%Y-%m-%d')" - }, - { - "type": "derived_column", - "alias": "patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(DATE_FORMAT(t2.scheduled_date, '%Y-%m-%d') = '{startDate}',1,null)" - } - } - ], - "indexDirectives": [ - { - "type": "force", - "indexList": ["location_med_pickup_rtc_date"] - }], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "date(t2.scheduled_date) >= '{startDate}'", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "date(t2.scheduled_date) <= '{endDate}'", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.encounter_type in ?", - "parameterName": "encounterIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.visit_type_id in ?", - "parameterName": "visitTypeIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t3.program_id in ? OR t3.program_id IS NULL", - "parameterName": "programTypeIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.encounter_type not in (21,99999)", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "((t2.next_encounter_type<>116 OR t2.next_encounter_type is null ) OR t2.scheduled_date >= t2.next_encounter_datetime)", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.is_clinical = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.is_clinical = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.transfer_out_location_id IS NULL or fhs.transfer_out_location_id <> 9999", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(death_reporting.encounter_datetime IS NULL) OR (DATE(t2.scheduled_date) < DATE(death_reporting.encounter_datetime))", - "parameterName": "" - } - ] + "name": "dailyAppointmentsBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_appointment", + "alias": "t2" + }, + { + "dataSet": "dailyAppointmentlatestRtcCohortBase", + "alias": "latest_encounter", + "join": { + "type": "LEFT", + "joinCondition": "latest_encounter.person_id = t2.person_id" + } + }, + { + "table": "etl.flat_appointment", + "alias": "t3", + "join": { + "type": "LEFT", + "joinCondition": "t3.person_id = t2.person_id AND t3.encounter_id = latest_encounter.max_encounter_id" + } + }, + { + "table": "etl.flat_appointment", + "alias": "death_reporting", + "join": { + "type": "LEFT", + "joinCondition": "death_reporting.person_id = t2.person_id AND death_reporting.encounter_type in (31) AND death_reporting.encounter_datetime >= t2.encounter_datetime" + } + }, + { + "table": "amrs.program", + "alias": "pr", + "join": { + "type": "LEFT", + "joinCondition": "pr.program_id = t3.program_id" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs", + "join": { + "type": "LEFT", + "joinCondition": "t2.encounter_id = fhs.encounter_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t2.person_id" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "t2.encounter_type" + }, + { + "type": "simple_column", + "alias": "program", + "column": "pr.name" + }, + { + "type": "simple_column", + "alias": "rtc_date", + "column": "t2.rtc_date" + }, + { + "type": "simple_column", + "alias": "med_pick_up_date", + "column": "date_format(t2.med_pickup_rtc_date,'%Y-%m-%d')" + }, + { + "alias": "prev_clinical_encounter_datetime", + "column": "t2.prev_clinical_encounter_datetime" + }, + { + "type": "simple_column", + "alias": "next_clinical_encounter_datetime", + "column": "t2.next_clinical_encounter_datetime" + }, + { + "type": "simple_column", + "alias": "scheduled_date", + "column": "date_format(t2.scheduled_date,'%Y-%m-%d')" + }, + { + "type": "derived_column", + "alias": "patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(DATE_FORMAT(t2.scheduled_date, '%Y-%m-%d') = '{startDate}',1,null)" + } + } + ], + "indexDirectives": [ + { + "type": "force", + "indexList": ["location_med_pickup_rtc_date"] + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "date(t2.scheduled_date) >= '{startDate}'", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "date(t2.scheduled_date) <= '{endDate}'", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.encounter_type in ?", + "parameterName": "encounterIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.visit_type_id in ?", + "parameterName": "visitTypeIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t3.program_id in ? OR t3.program_id IS NULL", + "parameterName": "programTypeIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.encounter_type not in (21,99999)", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "((t2.next_encounter_type<>116 OR t2.next_encounter_type is null ) OR t2.scheduled_date >= t2.next_encounter_datetime)", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.is_clinical = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.is_clinical = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.transfer_out_location_id IS NULL or fhs.transfer_out_location_id <> 9999", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(death_reporting.encounter_datetime IS NULL) OR (DATE(t2.scheduled_date) < DATE(death_reporting.encounter_datetime))", + "parameterName": "" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/daily-attendance-aggregate.json b/app/reporting-framework/json-reports/daily-attendance-aggregate.json index d5cfe61e5..a43a15cd3 100644 --- a/app/reporting-framework/json-reports/daily-attendance-aggregate.json +++ b/app/reporting-framework/json-reports/daily-attendance-aggregate.json @@ -1,59 +1,55 @@ { - "name": "dailyAttendanceAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "dailyAttendanceBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "dailyAttendanceBase", - "alias": "t2" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "attended_date", - "column": "attended_date" - }, - { - "type": "simple_column", - "alias": "attended", - "column": "count(distinct person_id)" - }, - { - "type": "simple_column", - "alias": "patients", - "column": "patients" - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "attended_date" - ], - "excludeParam": "excludeParam" + "name": "dailyAttendanceAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "dailyAttendanceBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "dailyAttendanceBase", + "alias": "t2" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "attended_date", + "column": "attended_date" + }, + { + "type": "simple_column", + "alias": "attended", + "column": "count(distinct person_id)" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-schedules-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "patients", + "column": "patients" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["attended_date"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-schedules-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } - - -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/daily-attendance-base.json b/app/reporting-framework/json-reports/daily-attendance-base.json index 895846330..db88dfa85 100644 --- a/app/reporting-framework/json-reports/daily-attendance-base.json +++ b/app/reporting-framework/json-reports/daily-attendance-base.json @@ -1,101 +1,101 @@ { - "name": "dailyAttendanceBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_appointment", - "alias": "t2" - }, - { - "table": "amrs.program", - "alias": "pr", - "join": { - "type": "LEFT", - "joinCondition": "pr.program_id = t2.program_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t2.person_id" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "t2.encounter_type" - }, - { - "type": "simple_column", - "alias": "program", - "column": "pr.name" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "t2.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "attended_date", - "column": "date(t2.encounter_datetime)" - }, - { - "type": "derived_column", - "alias": "patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(DATE_FORMAT(t2.encounter_datetime, '%Y-%m-%d') = '{startDate}',1,null)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "date(t2.encounter_datetime) >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "date(t2.encounter_datetime) <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "encounter_type in ?", - "parameterName": "encounterIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.visit_type_id in ?", - "parameterName": "visitTypeIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.program_id in ? OR t2.program_id IS NULL", - "parameterName": "programTypeIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.encounter_type not in (21,99999)", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.is_clinical = 1", - "parameterName": "" - } - ] + "name": "dailyAttendanceBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_appointment", + "alias": "t2" + }, + { + "table": "amrs.program", + "alias": "pr", + "join": { + "type": "LEFT", + "joinCondition": "pr.program_id = t2.program_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t2.person_id" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "t2.encounter_type" + }, + { + "type": "simple_column", + "alias": "program", + "column": "pr.name" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "t2.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "attended_date", + "column": "date(t2.encounter_datetime)" + }, + { + "type": "derived_column", + "alias": "patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(DATE_FORMAT(t2.encounter_datetime, '%Y-%m-%d') = '{startDate}',1,null)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "date(t2.encounter_datetime) >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "date(t2.encounter_datetime) <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "encounter_type in ?", + "parameterName": "encounterIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.visit_type_id in ?", + "parameterName": "visitTypeIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.program_id in ? OR t2.program_id IS NULL", + "parameterName": "programTypeIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.encounter_type not in (21,99999)", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.is_clinical = 1", + "parameterName": "" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/daily-has-not-returned-aggregate.json b/app/reporting-framework/json-reports/daily-has-not-returned-aggregate.json index 465d3394d..d5aa59072 100644 --- a/app/reporting-framework/json-reports/daily-has-not-returned-aggregate.json +++ b/app/reporting-framework/json-reports/daily-has-not-returned-aggregate.json @@ -1,67 +1,65 @@ { - "name": "dailyHasNotReturnedAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "dailyHasNotReturnedBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "dailyHasNotReturnedBase", - "alias": "t2" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t2.person_id" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "t2.encounter_type" - }, - { - "type": "simple_column", - "alias": "has_not_returned", - "column": "count(distinct if(has_not_returned, t2.person_id, null))" - }, - { - "type": "simple_column", - "alias": "patients", - "column": "patients" - }, - { - "type": "simple_column", - "alias": "d", - "column": "t2.d" - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "d" - ], - "excludeParam": "excludeParam" + "name": "dailyHasNotReturnedAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "dailyHasNotReturnedBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "dailyHasNotReturnedBase", + "alias": "t2" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t2.person_id" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-with-contacts-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "encounter_type", + "column": "t2.encounter_type" + }, + { + "type": "simple_column", + "alias": "has_not_returned", + "column": "count(distinct if(has_not_returned, t2.person_id, null))" + }, + { + "type": "simple_column", + "alias": "patients", + "column": "patients" + }, + { + "type": "simple_column", + "alias": "d", + "column": "t2.d" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["d"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-with-contacts-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } + } } diff --git a/app/reporting-framework/json-reports/daily-has-not-returned-base.json b/app/reporting-framework/json-reports/daily-has-not-returned-base.json index 3edfb24c1..7300dfdb9 100644 --- a/app/reporting-framework/json-reports/daily-has-not-returned-base.json +++ b/app/reporting-framework/json-reports/daily-has-not-returned-base.json @@ -1,213 +1,213 @@ { - "name": "dailyHasNotReturnedBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "dailyHasNotReturnedCohort", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "table": "etl.flat_appointment", - "alias": "t2" - }, - { - "table": "etl.flat_appointment", - "alias": "t8", - "join": { - "type": "LEFT", - "joinCondition": "t2.person_id = t8.person_id and t8.encounter_type=116 and t2.encounter_datetime < t8.encounter_datetime" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "t9", - "join": { - "type": "LEFT", - "joinCondition": "t9.encounter_id = t2.encounter_id" - } - }, - { - "table": "amrs.person", - "alias": "t10", - "join": { - "type": "INNER", - "joinCondition": "t2.person_id = t10.person_id" - } - }, - { - "table": "amrs.visit", - "alias": "t20", - "join": { - "type": "INNER", - "joinCondition": "t2.visit_id = t20.visit_id" - } - }, - { - "table": "etl.program_visit_map", - "alias": "t21", - "join": { - "type": "INNER", - "joinCondition": "t21.visit_type_id = t20.visit_type_id" - } - }, - { - "dataSet": "dailyHasNotReturnedCohort", - "alias": "t7", - "join": { - "type": "LEFT", - "joinCondition": "t2.person_id = t7.person_id" - } - }, - { - "table": "amrs.program", - "alias": "pr", - "join": { - "type": "LEFT", - "joinCondition": "pr.program_id = t2.program_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t2.person_id" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "t2.encounter_type" - }, - { - "type": "simple_column", - "alias": "program", - "column": "pr.name" - }, - { - "type": "simple_column", - "alias": "d", - "column": "date_format(t2.scheduled_date,'%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "med_pick_up_date", - "column": "date_format(t2.med_pickup_rtc_date,'%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "transfer_out", - "column": "t9.transfer_out" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t2.location_id" - }, - { - "type": "simple_column", - "alias": "prev_location_id", - "column": "t9.prev_clinical_location_id" - }, - { - "type": "derived_column", - "alias": "has_not_returned", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((date(t2.scheduled_date) < DATE(NOW())) AND ((t2.department_id = t7.department_id) OR (t2.department_id is NULL AND t7.department_id is NULL)), 1 , NULL)" - } - }, - { - "type": "derived_column", - "alias": "patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((date(t2.scheduled_date) = DATE('{startDate}')) and (t2.scheduled_date = t7.latest_rtc_date)AND t2.next_program_clinical_datetime IS NULL, 1, null)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "date(t2.scheduled_date) >= '{startDate}'", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "date(t2.scheduled_date) <= '{endDate}'", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.encounter_type in ?", - "parameterName": "encounterIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t21.visit_type_id in ?", - "parameterName": "visitTypeIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t21.program_type_id in ? OR t7.program_id IS NULL", - "parameterName": "programTypeIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.next_program_clinical_datetime IS NULL", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.encounter_type != 110", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.next_clinical_encounter_datetime IS NULL", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t7.is_clinical = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(t2.scheduled_date) < DATE(NOW())", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(t2.scheduled_date) = DATE(t7.latest_rtc_date)", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t10.dead = 0", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t9.transfer_out_location_id is NULL || t9.transfer_out_location_id <> 9999", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t9.out_of_care is NULL", - "parameterName": "" - } - ] + "name": "dailyHasNotReturnedBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "dailyHasNotReturnedCohort", + "version": "1.0", + "type": "dataset_def" } + ], + "sources": [ + { + "table": "etl.flat_appointment", + "alias": "t2" + }, + { + "table": "etl.flat_appointment", + "alias": "t8", + "join": { + "type": "LEFT", + "joinCondition": "t2.person_id = t8.person_id and t8.encounter_type=116 and t2.encounter_datetime < t8.encounter_datetime" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "t9", + "join": { + "type": "LEFT", + "joinCondition": "t9.encounter_id = t2.encounter_id" + } + }, + { + "table": "amrs.person", + "alias": "t10", + "join": { + "type": "INNER", + "joinCondition": "t2.person_id = t10.person_id" + } + }, + { + "table": "amrs.visit", + "alias": "t20", + "join": { + "type": "INNER", + "joinCondition": "t2.visit_id = t20.visit_id" + } + }, + { + "table": "etl.program_visit_map", + "alias": "t21", + "join": { + "type": "INNER", + "joinCondition": "t21.visit_type_id = t20.visit_type_id" + } + }, + { + "dataSet": "dailyHasNotReturnedCohort", + "alias": "t7", + "join": { + "type": "LEFT", + "joinCondition": "t2.person_id = t7.person_id" + } + }, + { + "table": "amrs.program", + "alias": "pr", + "join": { + "type": "LEFT", + "joinCondition": "pr.program_id = t2.program_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t2.person_id" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "t2.encounter_type" + }, + { + "type": "simple_column", + "alias": "program", + "column": "pr.name" + }, + { + "type": "simple_column", + "alias": "d", + "column": "date_format(t2.scheduled_date,'%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "med_pick_up_date", + "column": "date_format(t2.med_pickup_rtc_date,'%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "transfer_out", + "column": "t9.transfer_out" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "t2.location_id" + }, + { + "type": "simple_column", + "alias": "prev_location_id", + "column": "t9.prev_clinical_location_id" + }, + { + "type": "derived_column", + "alias": "has_not_returned", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((date(t2.scheduled_date) < DATE(NOW())) AND ((t2.department_id = t7.department_id) OR (t2.department_id is NULL AND t7.department_id is NULL)), 1 , NULL)" + } + }, + { + "type": "derived_column", + "alias": "patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((date(t2.scheduled_date) = DATE('{startDate}')) and (t2.scheduled_date = t7.latest_rtc_date)AND t2.next_program_clinical_datetime IS NULL, 1, null)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "date(t2.scheduled_date) >= '{startDate}'", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "date(t2.scheduled_date) <= '{endDate}'", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.encounter_type in ?", + "parameterName": "encounterIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t21.visit_type_id in ?", + "parameterName": "visitTypeIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t21.program_type_id in ? OR t7.program_id IS NULL", + "parameterName": "programTypeIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.next_program_clinical_datetime IS NULL", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.encounter_type != 110", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.next_clinical_encounter_datetime IS NULL", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t7.is_clinical = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(t2.scheduled_date) < DATE(NOW())", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(t2.scheduled_date) = DATE(t7.latest_rtc_date)", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t10.dead = 0", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t9.transfer_out_location_id is NULL || t9.transfer_out_location_id <> 9999", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t9.out_of_care is NULL", + "parameterName": "" + } + ] + } } diff --git a/app/reporting-framework/json-reports/daily-has-not-returned-cohort.json b/app/reporting-framework/json-reports/daily-has-not-returned-cohort.json index 155d052f0..6b2facae9 100644 --- a/app/reporting-framework/json-reports/daily-has-not-returned-cohort.json +++ b/app/reporting-framework/json-reports/daily-has-not-returned-cohort.json @@ -1,71 +1,69 @@ { - "name": "dailyHasNotReturnedCohort", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_appointment", - "alias": "t2" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t2.person_id" - }, - { - "type": "simple_column", - "alias": "is_clinical", - "column": "t2.is_clinical" - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "scheduled_date" - }, - { - "type": "simple_column", - "alias": "department_id", - "column": "department_id" - }, - { - "type": "simple_column", - "alias": "next_clinical_encounter_datetime", - "column": "next_clinical_encounter_datetime" - }, - { - "type": "simple_column", - "alias": "program_id", - "column": "program_id" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t2.location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.is_clinical = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.next_clinical_encounter_datetime IS NULL" - } - ] + "name": "dailyHasNotReturnedCohort", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_appointment", + "alias": "t2" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t2.person_id" + }, + { + "type": "simple_column", + "alias": "is_clinical", + "column": "t2.is_clinical" + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "scheduled_date" + }, + { + "type": "simple_column", + "alias": "department_id", + "column": "department_id" + }, + { + "type": "simple_column", + "alias": "next_clinical_encounter_datetime", + "column": "next_clinical_encounter_datetime" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "person_id" - ], - "excludeParam": "excludeParam" + { + "type": "simple_column", + "alias": "program_id", + "column": "program_id" } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t2.location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.is_clinical = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.next_clinical_encounter_datetime IS NULL" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["person_id"], + "excludeParam": "excludeParam" + } } diff --git a/app/reporting-framework/json-reports/dataentry-statistics-aggregate.json b/app/reporting-framework/json-reports/dataentry-statistics-aggregate.json index 9239bd419..c137cbb6d 100644 --- a/app/reporting-framework/json-reports/dataentry-statistics-aggregate.json +++ b/app/reporting-framework/json-reports/dataentry-statistics-aggregate.json @@ -1,70 +1,68 @@ { - "name": "dataEntryStatisticsAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "dataEntryStatistics", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "dataEntryStatistics", - "alias": "des" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "date", - "column": "date" - }, - { - "type": "simple_column", - "alias": "encounter_type_id", - "column": "encounter_type_id" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "encounter_type" - }, - { - "type": "simple_column", - "alias": "encounter_type_uuid", - "column": "encounter_type_uuid" - }, - { - "type": "derived_column", - "alias": "encounters_count", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(*)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "encounter_type_id" - ], - "excludeParam": "excludeParam" + "name": "dataEntryStatisticsAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "dataEntryStatistics", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "dataEntryStatistics", + "alias": "des" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "date", + "column": "date" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "encounter_type_id", + "column": "encounter_type_id" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "encounter_type" + }, + { + "type": "simple_column", + "alias": "encounter_type_uuid", + "column": "encounter_type_uuid" + }, + { + "type": "derived_column", + "alias": "encounters_count", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(*)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["encounter_type_id"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/dataentry-statistics-base.json b/app/reporting-framework/json-reports/dataentry-statistics-base.json index e6932b8bd..5b1481710 100644 --- a/app/reporting-framework/json-reports/dataentry-statistics-base.json +++ b/app/reporting-framework/json-reports/dataentry-statistics-base.json @@ -1,109 +1,109 @@ { - "name": "dataEntryStatistics", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "amrs.encounter_provider", - "alias": "ep" - }, - { - "table": "amrs.encounter", - "alias": "e", - "join": { - "type": "INNER", - "joinCondition": "ep.encounter_id = e.encounter_id" - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "INNER", - "joinCondition": "et.encounter_type_id = e.encounter_type" - } - }, - { - "table": "amrs.provider", - "alias": "p", - "join": { - "type": "INNER", - "joinCondition": "p.provider_id = ep.provider_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "date", - "column": "date(e.encounter_datetime)" - }, - { - "type": "simple_column", - "alias": "month", - "column": "DATE_FORMAT(e.encounter_datetime, '%M, %Y')" - }, - { - "type": "simple_column", - "alias": "creator_id", - "column": "e.creator" - }, - { - "type": "simple_column", - "alias": "provider_id", - "column": "p.provider_id" - }, - { - "type": "simple_column", - "alias": "encounter_type_id", - "column": "e.encounter_type" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "et.name" - }, - { - "type": "simple_column", - "alias": "encounter_type_uuid", - "column": "et.uuid" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "date(e.encounter_datetime) <= date(?)", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "date(e.encounter_datetime) >= date(?)", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "e.location_id in ?", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "p.uuid = ?", - "parameterName": "providerUuid" - }, - { - "filterType": "tableColumns", - "conditionExpression": "e.form_id in ?", - "parameterName": "encounterTypeIds" - }, - { - "filterType": "tableColumns", - "conditionExpression": "e.encounter_type in ?", - "parameterName": "encounterTypeIds" - } - ] + "name": "dataEntryStatistics", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "amrs.encounter_provider", + "alias": "ep" + }, + { + "table": "amrs.encounter", + "alias": "e", + "join": { + "type": "INNER", + "joinCondition": "ep.encounter_id = e.encounter_id" + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "INNER", + "joinCondition": "et.encounter_type_id = e.encounter_type" + } + }, + { + "table": "amrs.provider", + "alias": "p", + "join": { + "type": "INNER", + "joinCondition": "p.provider_id = ep.provider_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "date", + "column": "date(e.encounter_datetime)" + }, + { + "type": "simple_column", + "alias": "month", + "column": "DATE_FORMAT(e.encounter_datetime, '%M, %Y')" + }, + { + "type": "simple_column", + "alias": "creator_id", + "column": "e.creator" + }, + { + "type": "simple_column", + "alias": "provider_id", + "column": "p.provider_id" + }, + { + "type": "simple_column", + "alias": "encounter_type_id", + "column": "e.encounter_type" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "et.name" + }, + { + "type": "simple_column", + "alias": "encounter_type_uuid", + "column": "et.uuid" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "date(e.encounter_datetime) <= date(?)", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "date(e.encounter_datetime) >= date(?)", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "e.location_id in ?", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "p.uuid = ?", + "parameterName": "providerUuid" + }, + { + "filterType": "tableColumns", + "conditionExpression": "e.form_id in ?", + "parameterName": "encounterTypeIds" + }, + { + "filterType": "tableColumns", + "conditionExpression": "e.encounter_type in ?", + "parameterName": "encounterTypeIds" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/differentiated-care-height-dataset.json b/app/reporting-framework/json-reports/differentiated-care-height-dataset.json index e2241cd09..e4f19ae18 100644 --- a/app/reporting-framework/json-reports/differentiated-care-height-dataset.json +++ b/app/reporting-framework/json-reports/differentiated-care-height-dataset.json @@ -1,47 +1,45 @@ { - "name": "differentiatedCareHeightDataset", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_vitals", - "alias": "t1" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "latest_encounter_date", - "column": "MAX(t1.encounter_datetime )" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t1.location_id" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.height IS NOT NULL AND DATE(encounter_datetime) <= '{endDate}'", - "parameterName": "" - } - ] + "name": "differentiatedCareHeightDataset", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_vitals", + "alias": "t1" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "latest_encounter_date", + "column": "MAX(t1.encounter_datetime )" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "t1.person_id" - ], - "excludeParam": "excludeParam" + { + "type": "simple_column", + "alias": "location_id", + "column": "t1.location_id" } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.height IS NOT NULL AND DATE(encounter_datetime) <= '{endDate}'", + "parameterName": "" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["t1.person_id"], + "excludeParam": "excludeParam" + } } diff --git a/app/reporting-framework/json-reports/differentiated-care-program-aggregate.json b/app/reporting-framework/json-reports/differentiated-care-program-aggregate.json index f69079fbf..2dd3f4744 100644 --- a/app/reporting-framework/json-reports/differentiated-care-program-aggregate.json +++ b/app/reporting-framework/json-reports/differentiated-care-program-aggregate.json @@ -1,121 +1,119 @@ { - "name": "differentiatedCareProgramAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "differentiatedCareProgramBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "differentiatedCareProgramBase", - "alias": "dcp" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "dcp.person_id" - }, - { - "type": "derived_column", - "alias": "total_eligible_for_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(dcp.total_eligible_for_dc, dcp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "eligible_not_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(dcp.eligible_not_on_dc, dcp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "eligible_and_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(dcp.eligible_and_on_dc, dcp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "enrolled_not_elligible", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(dcp.enrolled_not_elligible, dcp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(dcp.enrolled_in_dc, dcp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_dc_community", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(dcp.enrolled_in_dc_community, dcp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_dc_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(dcp.enrolled_in_dc_active, dcp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "enrolled_and_vl_due", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(dcp.enrolled_and_vl_due, dcp.person_id))" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - ] + "name": "differentiatedCareProgramAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "differentiatedCareProgramBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "differentiatedCareProgramBase", + "alias": "dcp" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "dcp.person_id" + }, + { + "type": "derived_column", + "alias": "total_eligible_for_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(dcp.total_eligible_for_dc, dcp.person_id))" + } }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - ], - "excludeParam": "excludeParam" + { + "type": "derived_column", + "alias": "eligible_not_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(dcp.eligible_not_on_dc, dcp.person_id))" + } }, - "transFormDirectives": { - "joinColumn": "", - "joinColumnParam": "", - "skipColumns": [""], - "disaggregationColumns": [] + { + "type": "derived_column", + "alias": "eligible_and_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(dcp.eligible_and_on_dc, dcp.person_id))" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-with-contacts-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "enrolled_not_elligible", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(dcp.enrolled_not_elligible, dcp.person_id))" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(dcp.enrolled_in_dc, dcp.person_id))" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_dc_community", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(dcp.enrolled_in_dc_community, dcp.person_id))" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_dc_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(dcp.enrolled_in_dc_active, dcp.person_id))" + } + }, + { + "type": "derived_column", + "alias": "enrolled_and_vl_due", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(dcp.enrolled_and_vl_due, dcp.person_id))" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": [], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "", + "joinColumnParam": "", + "skipColumns": [""], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-with-contacts-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/differentiated-care-program-base.json b/app/reporting-framework/json-reports/differentiated-care-program-base.json index 36ae06deb..cc7b87580 100644 --- a/app/reporting-framework/json-reports/differentiated-care-program-base.json +++ b/app/reporting-framework/json-reports/differentiated-care-program-base.json @@ -1,160 +1,160 @@ { - "name": "differentiatedCareProgramBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.dc_monthly_report_dataset", - "alias": "dcr" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "persons_id", - "column": "dcr.person_id" - }, - { - "type": "derived_column", - "alias": "total_eligible_for_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "dcr.total_eligible_for_dc" - } - }, - { - "type": "derived_column", - "alias": "eligible_not_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "dcr.eligible_not_on_dc" - } - }, - { - "type": "derived_column", - "alias": "eligible_and_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "eligible_and_on_dc" - } - }, - { - "type": "derived_column", - "alias": "enrolled_not_elligible", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "enrolled_not_eligible" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "dcr.enrolled_in_dc" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_dc_community", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "dcr.enrolled_in_dc_community" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_dc_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "dcr.enrolled_in_dc" - } - }, - { - "type": "derived_column", - "alias": "enrolled_and_vl_due", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(dcr.enrolled_in_dc = 1 and dcr.patients_due_for_vl = 1, 1, 0)" - } - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "dcr.vl_1" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "dcr.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "vl_1_date", - "column": "dcr.vl_1_date" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "dcr.cur_arv_meds_names" - }, - { - "type": "simple_column", - "alias": "height", - "column": "dcr.height" - }, - { - "type": "simple_column", - "alias": "weight", - "column": "dcr.weight" - }, - { - "type": "simple_column", - "alias": "dc_group", - "column": "dcr.cohort_name" - }, - { - "type": "simple_column", - "alias": "status", - "column": "dcr.cur_status" - }, - { - "type": "simple_column", - "alias": "ipt_start_date", - "column": "date_format(dcr.ipt_start_date,'%Y-%m-%d')" - }, - { - "type": "derived_column", - "alias": "completed_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(dcr.ipt_completion_date is not null, 1, 0)" - } - }, - { - "type": "derived_column", - "alias": "days_since_rtc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "TIMESTAMPDIFF(DAY,DATE(dcr.rtc_date),curdate())" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "dcr.end_date = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "dcr.location_uuid in (?)", - "parameterName": "locationUuids" - } - ] + "name": "differentiatedCareProgramBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.dc_monthly_report_dataset", + "alias": "dcr" } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "persons_id", + "column": "dcr.person_id" + }, + { + "type": "derived_column", + "alias": "total_eligible_for_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "dcr.total_eligible_for_dc" + } + }, + { + "type": "derived_column", + "alias": "eligible_not_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "dcr.eligible_not_on_dc" + } + }, + { + "type": "derived_column", + "alias": "eligible_and_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "eligible_and_on_dc" + } + }, + { + "type": "derived_column", + "alias": "enrolled_not_elligible", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "enrolled_not_eligible" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "dcr.enrolled_in_dc" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_dc_community", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "dcr.enrolled_in_dc_community" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_dc_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "dcr.enrolled_in_dc" + } + }, + { + "type": "derived_column", + "alias": "enrolled_and_vl_due", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(dcr.enrolled_in_dc = 1 and dcr.patients_due_for_vl = 1, 1, 0)" + } + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "dcr.vl_1" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "dcr.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "vl_1_date", + "column": "dcr.vl_1_date" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "dcr.cur_arv_meds_names" + }, + { + "type": "simple_column", + "alias": "height", + "column": "dcr.height" + }, + { + "type": "simple_column", + "alias": "weight", + "column": "dcr.weight" + }, + { + "type": "simple_column", + "alias": "dc_group", + "column": "dcr.cohort_name" + }, + { + "type": "simple_column", + "alias": "status", + "column": "dcr.cur_status" + }, + { + "type": "simple_column", + "alias": "ipt_start_date", + "column": "date_format(dcr.ipt_start_date,'%Y-%m-%d')" + }, + { + "type": "derived_column", + "alias": "completed_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(dcr.ipt_completion_date is not null, 1, 0)" + } + }, + { + "type": "derived_column", + "alias": "days_since_rtc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "TIMESTAMPDIFF(DAY,DATE(dcr.rtc_date),curdate())" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "dcr.end_date = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "dcr.location_uuid in (?)", + "parameterName": "locationUuids" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/differentiated-care-weight-dataset.json b/app/reporting-framework/json-reports/differentiated-care-weight-dataset.json index 803eaed8d..e866418dc 100644 --- a/app/reporting-framework/json-reports/differentiated-care-weight-dataset.json +++ b/app/reporting-framework/json-reports/differentiated-care-weight-dataset.json @@ -1,47 +1,45 @@ { - "name": "differentiatedCareWeightDataset", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_vitals", - "alias": "t1" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "latest_encounter_date", - "column": "MAX(t1.encounter_datetime )" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t1.location_id" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.weight IS NOT NULL AND t1.height IS NOT NULL AND DATE(encounter_datetime) <= '{endDate}'", - "parameterName": "" - } - ] + "name": "differentiatedCareWeightDataset", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_vitals", + "alias": "t1" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "latest_encounter_date", + "column": "MAX(t1.encounter_datetime )" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "t1.person_id" - ], - "excludeParam": "excludeParam" + { + "type": "simple_column", + "alias": "location_id", + "column": "t1.location_id" } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.weight IS NOT NULL AND t1.height IS NOT NULL AND DATE(encounter_datetime) <= '{endDate}'", + "parameterName": "" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["t1.person_id"], + "excludeParam": "excludeParam" + } } diff --git a/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-aggregate.json b/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-aggregate.json index 6a6560e34..61017f71e 100644 --- a/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-aggregate.json +++ b/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-aggregate.json @@ -1,105 +1,103 @@ { - "name": "enhancedAdherenceHIVProgramAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "enhancedAdherenceHIVProgramBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "enhancedAdherenceHIVProgramBase", - "alias": "ehp" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "ehp.person_id" - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(ehp.not_virally_suppressed_total, ehp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_enhanced_care_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(ehp.not_virally_suppressed_in_enhanced_care_active, ehp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_not_in_enhanced_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(ehp.not_virally_suppressed_not_in_enhanced_care, ehp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_enhanced_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(ehp.not_virally_suppressed_in_enhanced_care, ehp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_enhanced_care_vl_due", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(ehp.not_virally_suppressed_in_enhanced_care_vl_due, ehp.person_id))" - } - }, - { - "type": "derived_column", - "alias": "mdt_form_completed", - "expressionType": "derived_column", - "expressionOptions": { - "expression": "count(distinct concat(ehp.mdt_form_completed, ehp.person_id))" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - ] + "name": "enhancedAdherenceHIVProgramAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "enhancedAdherenceHIVProgramBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "enhancedAdherenceHIVProgramBase", + "alias": "ehp" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "ehp.person_id" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - ], - "excludeParam": "excludeParam" + { + "type": "derived_column", + "alias": "not_virally_suppressed_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(ehp.not_virally_suppressed_total, ehp.person_id))" + } }, - "transFormDirectives": { - "joinColumn": "", - "joinColumnParam": "", - "skipColumns": [""], - "disaggregationColumns": [] + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_enhanced_care_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(ehp.not_virally_suppressed_in_enhanced_care_active, ehp.person_id))" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-with-contacts-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "not_virally_suppressed_not_in_enhanced_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(ehp.not_virally_suppressed_not_in_enhanced_care, ehp.person_id))" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_enhanced_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(ehp.not_virally_suppressed_in_enhanced_care, ehp.person_id))" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_enhanced_care_vl_due", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(ehp.not_virally_suppressed_in_enhanced_care_vl_due, ehp.person_id))" + } + }, + { + "type": "derived_column", + "alias": "mdt_form_completed", + "expressionType": "derived_column", + "expressionOptions": { + "expression": "count(distinct concat(ehp.mdt_form_completed, ehp.person_id))" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": [], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "", + "joinColumnParam": "", + "skipColumns": [""], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-with-contacts-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-base.json b/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-base.json index 84613f822..2fa890dd9 100644 --- a/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-base.json +++ b/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-base.json @@ -1,224 +1,224 @@ { - "name": "enhancedAdherenceHIVProgramBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "enhancedAdherenceHIVProgramCohort", - "version": "1.0", - "type": "dataset_def" - }, - { - "name": "hivLatestClinicalEncounterDateBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs" - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs2", - "join": { - "type": "LEFT", - "joinCondition": "fhs2.person_id = fhs.person_id AND fhs2.encounter_type = 129" - } - }, - { - "dataSet": "enhancedAdherenceHIVProgramCohort", - "alias": "max_record", - "join": { - "type": "INNER", - "joinCondition": "max_record.person_id = fhs.person_id and max_record.maxdate = fhs.vl_1_date" - } - }, - { - "dataSet": "hivLatestClinicalEncounterDateBase", - "alias": "latest_clinical_encounter_date", - "join": { - "type": "LEFT", - "joinCondition": "latest_clinical_encounter_date.person_id = fhs.person_id" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "latest_clinical_encounter", - "join": { - "type": "LEFT", - "joinCondition": "latest_clinical_encounter.person_id = latest_clinical_encounter_date.person_id AND latest_clinical_encounter.encounter_datetime = latest_clinical_encounter_date.latest_encounter_date" - } - }, - { - "table": "amrs.patient_program", - "alias": "pp", - "join": { - "type": "LEFT", - "joinCondition": "pp.patient_id = fhs.person_id AND pp.program_id = 27 and (pp.date_completed is null || date(pp.date_completed) <= date('{startDate}'))" - } - }, - { - "table": "amrs.encounter_type", - "alias": "aet", - "join": { - "type": "LEFT", - "joinCondition": "latest_clinical_encounter.encounter_type = aet.encounter_type_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "fhs.person_id" - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " IF(program_id IS NULL or pp.program_id = 27, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_enhanced_care_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(pp.program_id = 27 AND TIMESTAMPDIFF(DAY, latest_clinical_encounter.rtc_date,'{endDate}') <= 28, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_not_in_enhanced_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " IF(program_id IS NULL, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_enhanced_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(pp.program_id = 27, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_enhanced_care_vl_due", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(program_id = 27 AND TIMESTAMPDIFF(DAY, latest_clinical_encounter.vl_1_date,'{endDate}') > 90, 1 ,NULL)" - } - }, - { - "type": "derived_column", - "alias": "mdt_form_completed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(pp.program_id = 27 AND fhs2.encounter_type IS NULL, 1,NULL)" - } - }, - { - "type": "simple_column", - "alias": "vl_1_max", - "column": "latest_clinical_encounter.vl_1" - }, - { - "type": "simple_column", - "alias": "vl_1_date_max", - "column": "date_format(latest_clinical_encounter.vl_1_date, '%d-%m-%Y')" - }, - { - "type": "simple_column", - "alias": "vl_2_max", - "column": "latest_clinical_encounter.vl_2" - }, - { - "type": "simple_column", - "alias": "vl_2_date_max", - "column": "date_format(latest_clinical_encounter.vl_2_date, '%d-%m-%Y')" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds_max", - "column": "latest_clinical_encounter.cur_arv_meds" - }, - { - "type": "derived_column", - "alias": "days_since_rtc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "TIMESTAMPDIFF(DAY, latest_clinical_encounter.rtc_date,'{endDate}')" - } - }, - { - "type": "simple_column", - "alias": "last_appointment_max", - "column": "CONCAT(COALESCE(DATE_FORMAT(latest_clinical_encounter.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(aet.name, ''))" - }, - { - "type": "simple_column", - "alias": "latest_rtc_date_max", - "column": "date_format(latest_clinical_encounter.rtc_date, '%d-%m-%Y')" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fhs.encounter_datetime) >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fhs.encounter_datetime) <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(DATE(fhs.next_clinical_datetime_hiv) IS NULL OR DATE(fhs.next_clinical_datetime_hiv) > ? )", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.is_clinical_encounter = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.location_uuid in (?)", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.vl_1 >= ?", - "parameterName": "lower_vl" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.vl_1 <= ?", - "parameterName": "upper_vl" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.death_date <= ? || fhs.death_date IS NULL", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.transfer_out_location_id IS NULL" - }, - { - "filterType": "tableColumns", - "conditionExpression": "TIMESTAMPDIFF(DAY,fhs.rtc_date,'{endDate}') < 90", - "parameterName": "endDate" - } - ] + "name": "enhancedAdherenceHIVProgramBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "enhancedAdherenceHIVProgramCohort", + "version": "1.0", + "type": "dataset_def" + }, + { + "name": "hivLatestClinicalEncounterDateBase", + "version": "1.0", + "type": "dataset_def" } + ], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs" + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs2", + "join": { + "type": "LEFT", + "joinCondition": "fhs2.person_id = fhs.person_id AND fhs2.encounter_type = 129" + } + }, + { + "dataSet": "enhancedAdherenceHIVProgramCohort", + "alias": "max_record", + "join": { + "type": "INNER", + "joinCondition": "max_record.person_id = fhs.person_id and max_record.maxdate = fhs.vl_1_date" + } + }, + { + "dataSet": "hivLatestClinicalEncounterDateBase", + "alias": "latest_clinical_encounter_date", + "join": { + "type": "LEFT", + "joinCondition": "latest_clinical_encounter_date.person_id = fhs.person_id" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "latest_clinical_encounter", + "join": { + "type": "LEFT", + "joinCondition": "latest_clinical_encounter.person_id = latest_clinical_encounter_date.person_id AND latest_clinical_encounter.encounter_datetime = latest_clinical_encounter_date.latest_encounter_date" + } + }, + { + "table": "amrs.patient_program", + "alias": "pp", + "join": { + "type": "LEFT", + "joinCondition": "pp.patient_id = fhs.person_id AND pp.program_id = 27 and (pp.date_completed is null || date(pp.date_completed) <= date('{startDate}'))" + } + }, + { + "table": "amrs.encounter_type", + "alias": "aet", + "join": { + "type": "LEFT", + "joinCondition": "latest_clinical_encounter.encounter_type = aet.encounter_type_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "fhs.person_id" + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " IF(program_id IS NULL or pp.program_id = 27, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_enhanced_care_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(pp.program_id = 27 AND TIMESTAMPDIFF(DAY, latest_clinical_encounter.rtc_date,'{endDate}') <= 28, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_not_in_enhanced_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " IF(program_id IS NULL, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_enhanced_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(pp.program_id = 27, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_enhanced_care_vl_due", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(program_id = 27 AND TIMESTAMPDIFF(DAY, latest_clinical_encounter.vl_1_date,'{endDate}') > 90, 1 ,NULL)" + } + }, + { + "type": "derived_column", + "alias": "mdt_form_completed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(pp.program_id = 27 AND fhs2.encounter_type IS NULL, 1,NULL)" + } + }, + { + "type": "simple_column", + "alias": "vl_1_max", + "column": "latest_clinical_encounter.vl_1" + }, + { + "type": "simple_column", + "alias": "vl_1_date_max", + "column": "date_format(latest_clinical_encounter.vl_1_date, '%d-%m-%Y')" + }, + { + "type": "simple_column", + "alias": "vl_2_max", + "column": "latest_clinical_encounter.vl_2" + }, + { + "type": "simple_column", + "alias": "vl_2_date_max", + "column": "date_format(latest_clinical_encounter.vl_2_date, '%d-%m-%Y')" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds_max", + "column": "latest_clinical_encounter.cur_arv_meds" + }, + { + "type": "derived_column", + "alias": "days_since_rtc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "TIMESTAMPDIFF(DAY, latest_clinical_encounter.rtc_date,'{endDate}')" + } + }, + { + "type": "simple_column", + "alias": "last_appointment_max", + "column": "CONCAT(COALESCE(DATE_FORMAT(latest_clinical_encounter.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(aet.name, ''))" + }, + { + "type": "simple_column", + "alias": "latest_rtc_date_max", + "column": "date_format(latest_clinical_encounter.rtc_date, '%d-%m-%Y')" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fhs.encounter_datetime) >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fhs.encounter_datetime) <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(DATE(fhs.next_clinical_datetime_hiv) IS NULL OR DATE(fhs.next_clinical_datetime_hiv) > ? )", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.is_clinical_encounter = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.location_uuid in (?)", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.vl_1 >= ?", + "parameterName": "lower_vl" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.vl_1 <= ?", + "parameterName": "upper_vl" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.death_date <= ? || fhs.death_date IS NULL", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.transfer_out_location_id IS NULL" + }, + { + "filterType": "tableColumns", + "conditionExpression": "TIMESTAMPDIFF(DAY,fhs.rtc_date,'{endDate}') < 90", + "parameterName": "endDate" + } + ] + } } diff --git a/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-cohort.json b/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-cohort.json index e57ffb010..1230da9e6 100644 --- a/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-cohort.json +++ b/app/reporting-framework/json-reports/enhanced-adherence-hiv-program-cohort.json @@ -1,73 +1,71 @@ { - "name": "enhancedAdherenceHIVProgramCohort", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "fhs.person_id" - }, - { - "type": "derived_column", - "alias": "maxdate", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " MAX(vl_1_date)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "date(fhs.encounter_datetime) >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "date(fhs.encounter_datetime) <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.location_uuid in (?)", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fhs.rtc_date) <= DATE_ADD(?, INTERVAL -4 DAY)", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.death_date IS NULL", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.transfer_out IS NULL", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "TIMESTAMPDIFF(DAY, IF(fhs.rtc_date, fhs.rtc_date, DATE_ADD(fhs.encounter_datetime, INTERVAL 30 DAY)), ?) < 90", - "parameterName": "endDate" - } - ] + "name": "enhancedAdherenceHIVProgramCohort", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "fhs.person_id" }, - "groupBy": { - "columns": [ - "fhs.person_id" - ] + { + "type": "derived_column", + "alias": "maxdate", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " MAX(vl_1_date)" + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "date(fhs.encounter_datetime) >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "date(fhs.encounter_datetime) <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.location_uuid in (?)", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fhs.rtc_date) <= DATE_ADD(?, INTERVAL -4 DAY)", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.death_date IS NULL", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.transfer_out IS NULL", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "TIMESTAMPDIFF(DAY, IF(fhs.rtc_date, fhs.rtc_date, DATE_ADD(fhs.encounter_datetime, INTERVAL 30 DAY)), ?) < 90", + "parameterName": "endDate" + } + ] + }, + "groupBy": { + "columns": ["fhs.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/ever-on-art-aggregate.json b/app/reporting-framework/json-reports/ever-on-art-aggregate.json index abcd2a3e1..849da511a 100755 --- a/app/reporting-framework/json-reports/ever-on-art-aggregate.json +++ b/app/reporting-framework/json-reports/ever-on-art-aggregate.json @@ -1,66 +1,64 @@ { - "name": "everOnARTAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "everOnARTBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "everOnARTBase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "derived_column", - "alias": "ever_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(hmsd.ever_on_art, hmsd.person_id))" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" + "name": "everOnARTAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "everOnARTBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "everOnARTBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" }, - "transFormDirectives": { - "joinColumn": "location_id", - "joinColumnParam": "joinColumnParam", - "skipColumns": ["join_location"], - "disaggregationColumns": [] + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "ever_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(hmsd.ever_on_art, hmsd.person_id))" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "joinColumnParam": "joinColumnParam", + "skipColumns": ["join_location"], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/ever-on-art-base.json b/app/reporting-framework/json-reports/ever-on-art-base.json index 45e2b84a5..451238719 100755 --- a/app/reporting-framework/json-reports/ever-on-art-base.json +++ b/app/reporting-framework/json-reports/ever-on-art-base.json @@ -1,78 +1,78 @@ { - "name": "everOnARTBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "hmsd" - }, - { - "table": "amrs.person", - "alias": "ps", - "join": { - "type": "INNER", - "joinCondition": "ps.person_id = hmsd.person_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "ps.gender" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "extract(year from (from_days(datediff(now(),ps.birthdate)))) >= 15", - "value": "15_and_above" - }, - { - "condition": "else", - "value": "below_15" - } - ] - } - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "derived_column", - "alias": "ever_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when hmsd.arv_first_regimen_start_date IS NOT NULL AND hmsd.location_id = hmsd.arv_first_regimen_location_id then 1 else null end" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.location_id in ?", - "parameterName": "locations" - } + "name": "everOnARTBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "hmsd" + }, + { + "table": "amrs.person", + "alias": "ps", + "join": { + "type": "INNER", + "joinCondition": "ps.person_id = hmsd.person_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "ps.gender" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "extract(year from (from_days(datediff(now(),ps.birthdate)))) >= 15", + "value": "15_and_above" + }, + { + "condition": "else", + "value": "below_15" + } ] + } + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "derived_column", + "alias": "ever_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when hmsd.arv_first_regimen_start_date IS NOT NULL AND hmsd.location_id = hmsd.arv_first_regimen_location_id then 1 else null end" + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/ever-on-art-disaggregation.json b/app/reporting-framework/json-reports/ever-on-art-disaggregation.json index a0d04391b..811bebfd9 100755 --- a/app/reporting-framework/json-reports/ever-on-art-disaggregation.json +++ b/app/reporting-framework/json-reports/ever-on-art-disaggregation.json @@ -1,92 +1,88 @@ { - "name": "everOnARTDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "everOnARTBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "everOnARTBase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "ever_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(hmsd.ever_on_art, hmsd.person_id))" - } - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "gender", - "age_range", - "location_id" - ], - "excludeParam": "excludeParam" + "name": "everOnARTDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "everOnARTBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "everOnARTBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": ["location_uuid","join_location","person_id"], - "disaggregationColumns": ["gender", "age_range"] + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "ever_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(hmsd.ever_on_art, hmsd.person_id))" + } + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["gender", "age_range", "location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "join_location", "person_id"], + "disaggregationColumns": ["gender", "age_range"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/hei-infant-feeding-aggregate.json b/app/reporting-framework/json-reports/hei-infant-feeding-aggregate.json index fcb9123e7..b5696a169 100644 --- a/app/reporting-framework/json-reports/hei-infant-feeding-aggregate.json +++ b/app/reporting-framework/json-reports/hei-infant-feeding-aggregate.json @@ -1,119 +1,113 @@ { - "name": "heiInfantFeedingAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "heiInfantFeedingBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "heiInfantFeedingBase", - "alias": "hmds" - } - ], - "columns": [ - - { - "type": "simple_column", - "alias":"reporting_month", - "column":"hmds.reporting_month" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmds.location" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"hmds.location_uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmds.location_id" - }, - { - "type": "simple_column", - "alias":"age_range", - "column":"hmds.age_range" - }, - { - "type": "derived_column", - "alias":"Not_BF", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.Not_BF)" - } - }, - { - "type": "derived_column", - "alias":"MF", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.MF)" - } - }, - { - "type": "derived_column", - "alias":"ERF", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.ERF)" - } - }, - { - "type": "derived_column", - "alias":"BF", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.BF)" - } - }, - { - "type": "simple_column", - "alias":"status", - "column":"hmds.status" - } - - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "hmds.reporting_month", - "hmds.location", - "hmds.status", - "hmds.age_range" - ], - "excludeParam": "excludeParam" + "name": "heiInfantFeedingAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "heiInfantFeedingBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "heiInfantFeedingBase", + "alias": "hmds" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmds.reporting_month" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmds.location" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - ], - "disaggregationColumns": [ - "status", - "age_range" - ] + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmds.location_uuid" }, - "dynamicJsonQueryGenerationDirectives": { + { + "type": "simple_column", + "alias": "location_id", + "column": "hmds.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmds.age_range" + }, + { + "type": "derived_column", + "alias": "Not_BF", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.Not_BF)" + } + }, + { + "type": "derived_column", + "alias": "MF", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.MF)" + } + }, + { + "type": "derived_column", + "alias": "ERF", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.ERF)" + } + }, + { + "type": "derived_column", + "alias": "BF", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.BF)" + } + }, + { + "type": "simple_column", + "alias": "status", + "column": "hmds.status" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": [ + "hmds.reporting_month", + "hmds.location", + "hmds.status", + "hmds.age_range" + ], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": [], + "disaggregationColumns": ["status", "age_range"] + }, + "dynamicJsonQueryGenerationDirectives": { "patientListGenerator": { - "useTemplate": "hei-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + "useTemplate": "hei-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" + } + }, + "skipParams": [] } + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hei-infant-feeding-base.json b/app/reporting-framework/json-reports/hei-infant-feeding-base.json index 676b3651f..6e82973ff 100644 --- a/app/reporting-framework/json-reports/hei-infant-feeding-base.json +++ b/app/reporting-framework/json-reports/hei-infant-feeding-base.json @@ -1,156 +1,147 @@ { - "name": "heiInfantFeedingBase", - "version": "1.0", - "tag": "hei_monthly_summary_base", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hei_monthly_report_dataset", - "alias": "hmd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "hmd.location_id = l.location_id" - - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias":"person_id", - "column":"hmd.person_id" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmd.clinic" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"l.uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmd.location_id" - }, - { - "type": "simple_column", - "alias":"reporting_month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "simple_column", - "alias":"month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "derived_column", - "alias": "Not_BF", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 17,1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "MF", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 5,1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "ERF", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 18,1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "BF", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month in(4,6),1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmd.age_in_months between 0 and 6", - "value": "6_months" - }, - { - "condition": "hmd.age_in_months between 7 and 18", - "value": "7_to_18_months" - }, - { - "condition": "hmd.age_in_months = 24", - "value": "24_months" - } - ] - } - }, - { - "type": "derived_column", - "alias": "status", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmd.infection_status_this_month = 1", - "value": "uninfected" - }, - { - "condition": "hmd.infection_status_this_month = 2", - "value": "infected" - }, - { - "condition": "hmd.infection_status_this_month NOT IN (1,2)", - "value": "unknown" - } - ] - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.location_id in (?)", - "parameterName": "locations" - } + "name": "heiInfantFeedingBase", + "version": "1.0", + "tag": "hei_monthly_summary_base", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hei_monthly_report_dataset", + "alias": "hmd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "hmd.location_id = l.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmd.person_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmd.clinic" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmd.location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "simple_column", + "alias": "month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "derived_column", + "alias": "Not_BF", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 17,1,null)" + } + }, + { + "type": "derived_column", + "alias": "MF", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 5,1,null)" + } + }, + { + "type": "derived_column", + "alias": "ERF", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 18,1,null)" + } + }, + { + "type": "derived_column", + "alias": "BF", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month in(4,6),1,null)" + } + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmd.age_in_months between 0 and 6", + "value": "6_months" + }, + { + "condition": "hmd.age_in_months between 7 and 18", + "value": "7_to_18_months" + }, + { + "condition": "hmd.age_in_months = 24", + "value": "24_months" + } + ] + } + }, + { + "type": "derived_column", + "alias": "status", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmd.infection_status_this_month = 1", + "value": "uninfected" + }, + { + "condition": "hmd.infection_status_this_month = 2", + "value": "infected" + }, + { + "condition": "hmd.infection_status_this_month NOT IN (1,2)", + "value": "unknown" + } ] + } } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.location_id in (?)", + "parameterName": "locations" + } + ] + } } diff --git a/app/reporting-framework/json-reports/hei-infant-feeding-no-disaggregation-aggregate.json b/app/reporting-framework/json-reports/hei-infant-feeding-no-disaggregation-aggregate.json index 46e61cb26..43400e4de 100644 --- a/app/reporting-framework/json-reports/hei-infant-feeding-no-disaggregation-aggregate.json +++ b/app/reporting-framework/json-reports/hei-infant-feeding-no-disaggregation-aggregate.json @@ -1,129 +1,122 @@ { - "name": "heiInfantFeedingNoDisaggregationAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "heiInfantFeedingNoDisaggregationBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "heiInfantFeedingNoDisaggregationBase", - "alias": "hmds" - } - ], - "columns": [ - - { - "type": "simple_column", - "alias":"reporting_month", - "column":"hmds.reporting_month" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmds.location" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"hmds.location_uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmds.location_id" - }, - { - "type": "derived_column", - "alias":"EBF_at_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.EBF_at_6_months)" - } - }, - { - "type": "derived_column", - "alias":"ERF_at_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.ERF_at_6_months)" - } - }, - { - "type": "derived_column", - "alias":"MF_at_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.MF_at_6_months)" - } - }, - { - "type": "derived_column", - "alias":"BF_at_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.BF_at_12_months)" - } - }, - { - "type": "derived_column", - "alias":"Not_BF_at_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.Not_BF_at_12_months)" - } - }, - { - "type": "derived_column", - "alias":"BF_at_18_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.BF_at_18_months)" - } - }, - { - "type": "derived_column", - "alias":"Not_BF_at_18_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"sum(hmds.Not_BF_at_18_months)" - } - } - - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "hmds.reporting_month", - "hmds.location_id" - ], - "excludeParam": "excludeParam" + "name": "heiInfantFeedingNoDisaggregationAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "heiInfantFeedingNoDisaggregationBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "heiInfantFeedingNoDisaggregationBase", + "alias": "hmds" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmds.reporting_month" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmds.location" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmds.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmds.location_id" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] + { + "type": "derived_column", + "alias": "EBF_at_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.EBF_at_6_months)" + } }, - "dynamicJsonQueryGenerationDirectives": { + { + "type": "derived_column", + "alias": "ERF_at_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.ERF_at_6_months)" + } + }, + { + "type": "derived_column", + "alias": "MF_at_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.MF_at_6_months)" + } + }, + { + "type": "derived_column", + "alias": "BF_at_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.BF_at_12_months)" + } + }, + { + "type": "derived_column", + "alias": "Not_BF_at_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.Not_BF_at_12_months)" + } + }, + { + "type": "derived_column", + "alias": "BF_at_18_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.BF_at_18_months)" + } + }, + { + "type": "derived_column", + "alias": "Not_BF_at_18_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmds.Not_BF_at_18_months)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["hmds.reporting_month", "hmds.location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { "patientListGenerator": { - "useTemplate": "hei-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + "useTemplate": "hei-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" + } + }, + "skipParams": [] } + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hei-infant-feeding-no-disaggregation-base.json b/app/reporting-framework/json-reports/hei-infant-feeding-no-disaggregation-base.json index a1841da49..17ade9e5f 100644 --- a/app/reporting-framework/json-reports/hei-infant-feeding-no-disaggregation-base.json +++ b/app/reporting-framework/json-reports/hei-infant-feeding-no-disaggregation-base.json @@ -1,144 +1,129 @@ { - "name": "heiInfantFeedingNoDisaggregationBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hei_monthly_report_dataset", - "alias": "hmd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "hmd.location_id = l.location_id" - - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias":"person_id", - "column":"hmd.person_id" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmd.clinic" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"l.uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmd.location_id" - }, - { - "type": "simple_column", - "alias":"reporting_month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "simple_column", - "alias":"month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "derived_column", - "alias": "EBF_at_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 6 AND hmd.age_in_months = 6,1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "ERF_at_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 18 AND hmd.age_in_months = 6,1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "MF_at_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 5 AND hmd.age_in_months = 6,1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "BF_at_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 9 AND hmd.age_in_months = 12,1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "Not_BF_at_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 17 AND hmd.age_in_months = 12,1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "BF_at_18_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 9 AND hmd.age_in_months = 18,1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "Not_BF_at_18_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmd.infant_feeding_method_this_month = 17 AND hmd.age_in_months = 18,1,null)" - } - - - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.location_id in (?)", - "parameterName": "locations" - } - ] + "name": "heiInfantFeedingNoDisaggregationBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hei_monthly_report_dataset", + "alias": "hmd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "hmd.location_id = l.location_id" + } } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmd.person_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmd.clinic" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmd.location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "simple_column", + "alias": "month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "derived_column", + "alias": "EBF_at_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 6 AND hmd.age_in_months = 6,1,null)" + } + }, + { + "type": "derived_column", + "alias": "ERF_at_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 18 AND hmd.age_in_months = 6,1,null)" + } + }, + { + "type": "derived_column", + "alias": "MF_at_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 5 AND hmd.age_in_months = 6,1,null)" + } + }, + { + "type": "derived_column", + "alias": "BF_at_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 9 AND hmd.age_in_months = 12,1,null)" + } + }, + { + "type": "derived_column", + "alias": "Not_BF_at_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 17 AND hmd.age_in_months = 12,1,null)" + } + }, + { + "type": "derived_column", + "alias": "BF_at_18_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 9 AND hmd.age_in_months = 18,1,null)" + } + }, + { + "type": "derived_column", + "alias": "Not_BF_at_18_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmd.infant_feeding_method_this_month = 17 AND hmd.age_in_months = 18,1,null)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.location_id in (?)", + "parameterName": "locations" + } + ] + } } diff --git a/app/reporting-framework/json-reports/hei-infant-testing-aggregate.json b/app/reporting-framework/json-reports/hei-infant-testing-aggregate.json index 5527d23fd..fe1c64662 100644 --- a/app/reporting-framework/json-reports/hei-infant-testing-aggregate.json +++ b/app/reporting-framework/json-reports/hei-infant-testing-aggregate.json @@ -1,128 +1,122 @@ { - "name": "heiInfantTestingAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "heiInfantTestingBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "heiInfantTestingBase", - "alias": "hmds" - } - ], - "columns": [ - - { - "type": "simple_column", - "alias":"reporting_month", - "column":"hmds.reporting_month" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmds.location" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmds.location_id" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"hmds.location_uuid" - }, - { - "type": "derived_column", - "alias":"initial_pcr_less_than_8_wks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.initial_pcr_less_than_8_wks)" - } - }, - { - "type": "derived_column", - "alias":"initial_pcr_8_wks_to_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.initial_pcr_8_wks_to_12_months)" - } - }, - { - "type": "derived_column", - "alias":"initial_pcr_less_than_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.initial_pcr_less_than_12_months)" - } - }, - { - "type": "derived_column", - "alias":"second_pcr_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.second_pcr_6_months)" - } - }, - { - "type": "derived_column", - "alias":"third_pcr_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.third_pcr_12_months)" - } - }, - { - "type": "derived_column", - "alias":"antibody_at_18_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.antibody_at_18_months)" - } - }, - { - "type": "derived_column", - "alias":"antibody_post_18_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.antibody_post_18_months)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "hmds.reporting_month", - "hmds.location_id" - ], - "excludeParam": "excludeParam" + "name": "heiInfantTestingAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "heiInfantTestingBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "heiInfantTestingBase", + "alias": "hmds" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmds.reporting_month" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmds.location" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmds.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmds.location_uuid" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] + { + "type": "derived_column", + "alias": "initial_pcr_less_than_8_wks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.initial_pcr_less_than_8_wks)" + } }, - "dynamicJsonQueryGenerationDirectives": { + { + "type": "derived_column", + "alias": "initial_pcr_8_wks_to_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.initial_pcr_8_wks_to_12_months)" + } + }, + { + "type": "derived_column", + "alias": "initial_pcr_less_than_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.initial_pcr_less_than_12_months)" + } + }, + { + "type": "derived_column", + "alias": "second_pcr_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.second_pcr_6_months)" + } + }, + { + "type": "derived_column", + "alias": "third_pcr_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.third_pcr_12_months)" + } + }, + { + "type": "derived_column", + "alias": "antibody_at_18_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.antibody_at_18_months)" + } + }, + { + "type": "derived_column", + "alias": "antibody_post_18_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.antibody_post_18_months)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["hmds.reporting_month", "hmds.location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { "patientListGenerator": { - "useTemplate": "hei-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + "useTemplate": "hei-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" + } + }, + "skipParams": [] } + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hei-infant-testing-base.json b/app/reporting-framework/json-reports/hei-infant-testing-base.json index b3f55b133..a3ebcb23b 100644 --- a/app/reporting-framework/json-reports/hei-infant-testing-base.json +++ b/app/reporting-framework/json-reports/hei-infant-testing-base.json @@ -1,138 +1,137 @@ { - "name": "heiInfantTestingBase", - "version": "1.0", - "tag": "hei_infant_testing_base", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hei_monthly_report_dataset", - "alias": "hmd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "hmd.location_id = l.location_id" - - } - }, - { - "table": "etl.flat_hei_summary", - "alias": "fhs", - "join": { - "type": "LEFT", - "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_clinical_datetime_hiv IS NULL" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias":"person_id", - "column":"hmd.person_id" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmd.clinic" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"l.uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmd.location_id" - }, - { - "type": "simple_column", - "alias":"reporting_month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "simple_column", - "alias":"month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "derived_column", - "alias": "initial_pcr_less_than_8_wks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.initial_pcr_this_month = 1 AND hmd.age_in_months < 2 ,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "initial_pcr_8_wks_to_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.initial_pcr_this_month = 1 AND hmd.age_in_months between 2 and 12,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "initial_pcr_less_than_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.initial_pcr_this_month = 1 AND hmd.age_in_months < 12,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "second_pcr_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.second_pcr_this_month = 1 AND hmd.age_in_months = 6,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "third_pcr_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.third_pcr_this_month = 1 AND hmd.age_in_months = 12,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "antibody_at_18_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.initial_antibody_screening_this_month = 1 AND hmd.age_in_months = 18,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "antibody_post_18_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.initial_antibody_screening_this_month = 1 AND hmd.age_in_months > 18,1,NULL)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.location_id in (?)", - "parameterName": "locations" - } - ] + "name": "heiInfantTestingBase", + "version": "1.0", + "tag": "hei_infant_testing_base", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hei_monthly_report_dataset", + "alias": "hmd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "hmd.location_id = l.location_id" + } + }, + { + "table": "etl.flat_hei_summary", + "alias": "fhs", + "join": { + "type": "LEFT", + "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_clinical_datetime_hiv IS NULL" + } } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmd.person_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmd.clinic" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmd.location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "simple_column", + "alias": "month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "derived_column", + "alias": "initial_pcr_less_than_8_wks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.initial_pcr_this_month = 1 AND hmd.age_in_months < 2 ,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "initial_pcr_8_wks_to_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.initial_pcr_this_month = 1 AND hmd.age_in_months between 2 and 12,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "initial_pcr_less_than_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.initial_pcr_this_month = 1 AND hmd.age_in_months < 12,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "second_pcr_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.second_pcr_this_month = 1 AND hmd.age_in_months = 6,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "third_pcr_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.third_pcr_this_month = 1 AND hmd.age_in_months = 12,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "antibody_at_18_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.initial_antibody_screening_this_month = 1 AND hmd.age_in_months = 18,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "antibody_post_18_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.initial_antibody_screening_this_month = 1 AND hmd.age_in_months > 18,1,NULL)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.location_id in (?)", + "parameterName": "locations" + } + ] + } } diff --git a/app/reporting-framework/json-reports/hei-mother-aggregate.json b/app/reporting-framework/json-reports/hei-mother-aggregate.json index e3ec42927..32929554d 100644 --- a/app/reporting-framework/json-reports/hei-mother-aggregate.json +++ b/app/reporting-framework/json-reports/hei-mother-aggregate.json @@ -1,104 +1,98 @@ { - "name": "heiMotherAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "heiMotherBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "heiMotherBase", - "alias": "hmds" - } - ], - "columns": [ - - { - "type": "simple_column", - "alias":"reporting_month", - "column":"hmds.reporting_month" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmds.location" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmds.location_id" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"hmds.location_uuid" - }, - { - "type": "derived_column", - "alias":"known_positive_first_anc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.known_positive_first_anc)" - } - }, - { - "type": "derived_column", - "alias":"positive_results_anc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.positive_results_anc)" - } - }, - { - "type": "derived_column", - "alias":"on_haart_first_anc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.on_haart_first_anc)" - } - }, - { - "type": "derived_column", - "alias":"start_haart_anc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.start_haart_anc)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "hmds.reporting_month", - "hmds.location_id" - ], - "excludeParam": "excludeParam" + "name": "heiMotherAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "heiMotherBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "heiMotherBase", + "alias": "hmds" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmds.reporting_month" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmds.location" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] + { + "type": "simple_column", + "alias": "location_id", + "column": "hmds.location_id" }, - "dynamicJsonQueryGenerationDirectives": { + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmds.location_uuid" + }, + { + "type": "derived_column", + "alias": "known_positive_first_anc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.known_positive_first_anc)" + } + }, + { + "type": "derived_column", + "alias": "positive_results_anc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.positive_results_anc)" + } + }, + { + "type": "derived_column", + "alias": "on_haart_first_anc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.on_haart_first_anc)" + } + }, + { + "type": "derived_column", + "alias": "start_haart_anc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.start_haart_anc)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["hmds.reporting_month", "hmds.location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { "patientListGenerator": { - "useTemplate": "hei-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + "useTemplate": "hei-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" + } + }, + "skipParams": [] } + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hei-mother-base.json b/app/reporting-framework/json-reports/hei-mother-base.json index 17a8edfd4..b353e66ce 100644 --- a/app/reporting-framework/json-reports/hei-mother-base.json +++ b/app/reporting-framework/json-reports/hei-mother-base.json @@ -1,122 +1,113 @@ { - "name": "heiMotherBase", - "version": "1.0", - "tag": "hei_mother_base", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "fhs.location_id = l.location_id" - - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias":"person_id", - "column":"fhs.person_id" - }, - { - "type": "simple_column", - "alias":"location", - "column":"l.name" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"l.uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"fhs.location_id" - }, - { - "type": "simple_column", - "alias":"reporting_month", - "column":"DATE_FORMAT(fhs.encounter_datetime,'%Y-%m')" - }, - { - "type": "simple_column", - "alias":"month", - "column":"DATE_FORMAT(fhs.encounter_datetime,'%Y-%m')" - }, - { - "type": "derived_column", - "alias": "known_positive_first_anc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(DATE(fhs.enrollment_date) < DATE(fhs.encounter_datetime),1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "positive_results_anc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(DATE(fhs.enrollment_date) >= DATE(fhs.encounter_datetime),1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "on_haart_first_anc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(DATE(fhs.arv_start_date) < DATE(fhs.encounter_datetime),1,null)" - } - - - }, - { - "type": "derived_column", - "alias": "start_haart_anc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(DATE(fhs.arv_start_date) >= DATE(fhs.encounter_datetime),1,null)" - } - - - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fhs.encounter_datetime) <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fhs.encounter_datetime) >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.prev_anc_visit_date IS NULL" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.anc_visit_date IS NOT NULL" - } - ] + "name": "heiMotherBase", + "version": "1.0", + "tag": "hei_mother_base", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "fhs.location_id = l.location_id" + } } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "fhs.person_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "fhs.location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "DATE_FORMAT(fhs.encounter_datetime,'%Y-%m')" + }, + { + "type": "simple_column", + "alias": "month", + "column": "DATE_FORMAT(fhs.encounter_datetime,'%Y-%m')" + }, + { + "type": "derived_column", + "alias": "known_positive_first_anc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(DATE(fhs.enrollment_date) < DATE(fhs.encounter_datetime),1,null)" + } + }, + { + "type": "derived_column", + "alias": "positive_results_anc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(DATE(fhs.enrollment_date) >= DATE(fhs.encounter_datetime),1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_haart_first_anc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(DATE(fhs.arv_start_date) < DATE(fhs.encounter_datetime),1,null)" + } + }, + { + "type": "derived_column", + "alias": "start_haart_anc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(DATE(fhs.arv_start_date) >= DATE(fhs.encounter_datetime),1,null)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fhs.encounter_datetime) <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fhs.encounter_datetime) >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.prev_anc_visit_date IS NULL" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.anc_visit_date IS NOT NULL" + } + ] + } } diff --git a/app/reporting-framework/json-reports/hei-original-cohort-aggregate.json b/app/reporting-framework/json-reports/hei-original-cohort-aggregate.json index 29dac8982..c65d49360 100644 --- a/app/reporting-framework/json-reports/hei-original-cohort-aggregate.json +++ b/app/reporting-framework/json-reports/hei-original-cohort-aggregate.json @@ -1,96 +1,90 @@ { - "name": "heiOriginalCohortAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "heiOriginalCohortBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "heiOriginalCohortBase", - "alias": "hmds" - } - ], - "columns": [ - - { - "type": "simple_column", - "alias":"reporting_month", - "column":"hmds.reporting_month" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmds.location" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmds.location_id" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"hmds.location_uuid" - }, - { - "type": "derived_column", - "alias":"original_cohort_", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.original_cohort_)" - } - }, - { - "type": "derived_column", - "alias":"transfer_out_", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.transfer_out_)" - } - }, - { - "type": "derived_column", - "alias":"pair_net_cohort", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.pair_net_cohort)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "hmds.reporting_month", - "hmds.location_id" - ], - "excludeParam": "excludeParam" + "name": "heiOriginalCohortAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "heiOriginalCohortBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "heiOriginalCohortBase", + "alias": "hmds" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmds.reporting_month" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmds.location" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] + { + "type": "simple_column", + "alias": "location_id", + "column": "hmds.location_id" }, - "dynamicJsonQueryGenerationDirectives": { + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmds.location_uuid" + }, + { + "type": "derived_column", + "alias": "original_cohort_", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.original_cohort_)" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.transfer_out_)" + } + }, + { + "type": "derived_column", + "alias": "pair_net_cohort", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.pair_net_cohort)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["hmds.reporting_month", "hmds.location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { "patientListGenerator": { - "useTemplate": "hei-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + "useTemplate": "hei-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" + } + }, + "skipParams": [] } + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hei-original-cohort-base.json b/app/reporting-framework/json-reports/hei-original-cohort-base.json index 73e29bf22..09d48579e 100644 --- a/app/reporting-framework/json-reports/hei-original-cohort-base.json +++ b/app/reporting-framework/json-reports/hei-original-cohort-base.json @@ -1,159 +1,158 @@ { - "name": "heiOriginalCohortBase", - "version": "1.0", - "tag": "hei_original_cohort_base", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hei_monthly_report_dataset", - "alias": "hmd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "hmd.enrollment_location_id = l.location_id" - - } - }, - { - "table": "etl.flat_hei_summary", - "alias": "fhs", - "join": { - "type": "LEFT", - "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_encounter_datetime_hiv IS NULL" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias":"person_id", - "column":"hmd.person_id" - }, - { - "type": "simple_column", - "alias":"location", - "column":"l.name" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"l.uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmd.enrollment_location_id" - }, - { - "type": "simple_column", - "alias":"reporting_month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "simple_column", - "alias":"month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "derived_column", - "alias": "original_cohort_", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.person_id,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "transfer_out_", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(fhs.transfer_out = 1,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "pair_net_cohort", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(fhs.transfer_out IS NULL,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "status", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "(hmd.death_date <= DATE_FORMAT(endDate, '%Y-%m-01') IS NULL AND hmd.mother_alive_this_month = 1 AND hmd.mother_alive_on_child_enrollment = 1 AND ((hmd.retention_status = 'active' AND hmd.hei_outcome_this_month IS NULL) OR hei_outcome_this_month IS NOT NULL))", - "value": "ACTIVE" - }, - { - "condition": "hmd.death_date IS NOT NULL", - "value": "DEAD_B" - }, - { - "condition": "hmd.mother_alive_on_child_enrollment = 1 AND hmd.mother_alive_this_month = 2", - "value": "DEAD_M" - }, - { - "condition": "hmd.retention_status = 'ltfu' AND hei_outcome_this_month IS NULL", - "value": "LTFU" - }, - { - "condition": "hmd.mother_alive_on_child_enrollment = 2", - "value": "INVALID" - }, - { - "condition": "else", - "value": null - } - ] - } - }, - { - "type": "derived_column", - "alias": "status_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (hmd.death_date IS NOT NULL) THEN DATE_FORMAT(hmd.death_date,'%Y-%m-%d') WHEN (hmd.mother_alive_on_child_enrollment = 1 AND hmd.mother_alive_this_month = 2) THEN 'DEAD_M' WHEN (hmd.mother_alive_on_child_enrollment = 2) THEN '-' ELSE DATE_FORMAT(hmd.rtc_date,'%Y-%m-%d') END" - } - }, - { - "type": "derived_column", - "alias": "has_status", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"1" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.enrollment_location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.age_in_months = 24" - } + "name": "heiOriginalCohortBase", + "version": "1.0", + "tag": "hei_original_cohort_base", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hei_monthly_report_dataset", + "alias": "hmd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "hmd.enrollment_location_id = l.location_id" + } + }, + { + "table": "etl.flat_hei_summary", + "alias": "fhs", + "join": { + "type": "LEFT", + "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_encounter_datetime_hiv IS NULL" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmd.person_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmd.enrollment_location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "simple_column", + "alias": "month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "derived_column", + "alias": "original_cohort_", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.person_id,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.transfer_out = 1,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "pair_net_cohort", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.transfer_out IS NULL,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "status", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "(hmd.death_date <= DATE_FORMAT(endDate, '%Y-%m-01') IS NULL AND hmd.mother_alive_this_month = 1 AND hmd.mother_alive_on_child_enrollment = 1 AND ((hmd.retention_status = 'active' AND hmd.hei_outcome_this_month IS NULL) OR hei_outcome_this_month IS NOT NULL))", + "value": "ACTIVE" + }, + { + "condition": "hmd.death_date IS NOT NULL", + "value": "DEAD_B" + }, + { + "condition": "hmd.mother_alive_on_child_enrollment = 1 AND hmd.mother_alive_this_month = 2", + "value": "DEAD_M" + }, + { + "condition": "hmd.retention_status = 'ltfu' AND hei_outcome_this_month IS NULL", + "value": "LTFU" + }, + { + "condition": "hmd.mother_alive_on_child_enrollment = 2", + "value": "INVALID" + }, + { + "condition": "else", + "value": null + } ] + } + }, + { + "type": "derived_column", + "alias": "status_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (hmd.death_date IS NOT NULL) THEN DATE_FORMAT(hmd.death_date,'%Y-%m-%d') WHEN (hmd.mother_alive_on_child_enrollment = 1 AND hmd.mother_alive_this_month = 2) THEN 'DEAD_M' WHEN (hmd.mother_alive_on_child_enrollment = 2) THEN '-' ELSE DATE_FORMAT(hmd.rtc_date,'%Y-%m-%d') END" + } + }, + { + "type": "derived_column", + "alias": "has_status", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.enrollment_location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.age_in_months = 24" + } + ] + } } diff --git a/app/reporting-framework/json-reports/hei-program-outcome-aggregate.json b/app/reporting-framework/json-reports/hei-program-outcome-aggregate.json index 2cef136bf..5f28c67fe 100644 --- a/app/reporting-framework/json-reports/hei-program-outcome-aggregate.json +++ b/app/reporting-framework/json-reports/hei-program-outcome-aggregate.json @@ -1,120 +1,114 @@ { - "name": "heiProgramOutcomeAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "heiProgramOutcomeBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "heiProgramOutcomeBase", - "alias": "hmds" - } - ], - "columns": [ - - { - "type": "simple_column", - "alias":"reporting_month", - "column":"hmds.reporting_month" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmds.location" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmds.location_id" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"hmds.location_uuid" - }, - { - "type": "derived_column", - "alias":"infected_24_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.infected_24_months)" - } - }, - { - "type": "derived_column", - "alias":"uninfected_24_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.uninfected_24_months)" - } - }, - { - "type": "derived_column", - "alias":"unknown_outcome", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.unknown_outcome)" - } - }, - { - "type": "derived_column", - "alias":"original_cohort", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.original_cohort)" - } - }, - { - "type": "derived_column", - "alias":"transfer_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.transfer_in)" - } - }, - { - "type": "derived_column", - "alias":"net_cohort_hei_24_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.net_cohort_hei_24_months)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "hmds.reporting_month", - "hmds.location_id" - ], - "excludeParam": "excludeParam" + "name": "heiProgramOutcomeAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "heiProgramOutcomeBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "heiProgramOutcomeBase", + "alias": "hmds" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmds.reporting_month" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmds.location" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmds.location_id" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmds.location_uuid" }, - "dynamicJsonQueryGenerationDirectives": { + { + "type": "derived_column", + "alias": "infected_24_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.infected_24_months)" + } + }, + { + "type": "derived_column", + "alias": "uninfected_24_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.uninfected_24_months)" + } + }, + { + "type": "derived_column", + "alias": "unknown_outcome", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.unknown_outcome)" + } + }, + { + "type": "derived_column", + "alias": "original_cohort", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.original_cohort)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.transfer_in)" + } + }, + { + "type": "derived_column", + "alias": "net_cohort_hei_24_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.net_cohort_hei_24_months)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["hmds.reporting_month", "hmds.location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { "patientListGenerator": { - "useTemplate": "hei-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + "useTemplate": "hei-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" + } + }, + "skipParams": [] } + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hei-program-outcome-base.json b/app/reporting-framework/json-reports/hei-program-outcome-base.json index e3185014b..0bff946bd 100644 --- a/app/reporting-framework/json-reports/hei-program-outcome-base.json +++ b/app/reporting-framework/json-reports/hei-program-outcome-base.json @@ -1,187 +1,186 @@ { - "name": "heiProgramOutcomeBase", - "version": "1.0", - "tag": "hei_program_outcome_base", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hei_monthly_report_dataset", - "alias": "hmd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "hmd.location_id = l.location_id" - - } - }, - { - "table": "etl.flat_hei_summary", - "alias": "fhs", - "join": { - "type": "LEFT", - "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_clinical_datetime_hiv IS NULL AND fhs.is_clinical_encounter = 1" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias":"person_id", - "column":"hmd.person_id" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmd.clinic" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"l.uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmd.location_id" - }, - { - "type": "simple_column", - "alias":"reporting_month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "simple_column", - "alias":"month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "derived_column", - "alias": "infected_24_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.hei_outcome_this_month = 6,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "uninfected_24_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.hei_outcome_this_month = 5,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "unknown_outcome", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.hei_outcome_this_month in (1,2,3,4) OR hmd.hei_outcome_this_month IS NULL,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "original_cohort", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.enrollment_location_id in ({locations}),1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "transfer_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(transfer_in_this_month = 1 AND hmd.enrollment_location_id NOT IN ({locations}),1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "net_cohort_hei_24_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.person_id, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "status", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmd.hei_outcome_this_month = 6", - "value": "INFECTED" - }, - { - "condition": "hmd.hei_outcome_this_month = 5", - "value": "UNINFECTED" - }, - { - "condition": "(hmd.hei_outcome_this_month = 3 OR TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0) AND hmd.infection_status_this_month = 1", - "value": "UNINFECTED DEAD" - }, - { - "condition": "(hmd.hei_outcome_this_month = 3 OR TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0) AND hmd.infection_status_this_month = 2", - "value": "INFECTED DEAD" - }, - { - "condition": "hmd.hei_outcome_this_month = 2 OR (hmd.hei_outcome_this_month IS NULL AND TIMESTAMPDIFF(DAY, fhs.rtc_date, CURDATE()) > 0)", - "value": "LTFU" - }, - { - "condition": "hmd.hei_outcome_this_month = 1", - "value": "TRANSFER OUT" - }, - { - "condition": "else", - "value": null - } - ] - } - }, - { - "type": "derived_column", - "alias": "status_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN hmd.hei_outcome_this_month in (3,5,6) then DATE_FORMAT(hmd.hiv_dna_pcr_date,'%Y-%m-%d') WHEN hmd.hei_outcome_this_month = 1 then DATE_FORMAT(hmd.transfer_out_date,'%Y-%m-%d') WHEN (hmd.hei_outcome_this_month = 2 OR (hmd.hei_outcome_this_month IS NULL AND TIMESTAMPDIFF(DAY, fhs.rtc_date, CURDATE()) > 0)) THEN DATE_FORMAT(hmd.rtc_date,'%Y-%m-%d') ELSE NULL END" - } - }, - { - "type": "derived_column", - "alias": "has_status", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"1" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.age_in_months = 24" - } + "name": "heiProgramOutcomeBase", + "version": "1.0", + "tag": "hei_program_outcome_base", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hei_monthly_report_dataset", + "alias": "hmd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "hmd.location_id = l.location_id" + } + }, + { + "table": "etl.flat_hei_summary", + "alias": "fhs", + "join": { + "type": "LEFT", + "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_clinical_datetime_hiv IS NULL AND fhs.is_clinical_encounter = 1" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmd.person_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmd.clinic" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmd.location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "simple_column", + "alias": "month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "derived_column", + "alias": "infected_24_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.hei_outcome_this_month = 6,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "uninfected_24_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.hei_outcome_this_month = 5,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "unknown_outcome", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.hei_outcome_this_month in (1,2,3,4) OR hmd.hei_outcome_this_month IS NULL,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "original_cohort", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.enrollment_location_id in ({locations}),1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(transfer_in_this_month = 1 AND hmd.enrollment_location_id NOT IN ({locations}),1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "net_cohort_hei_24_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.person_id, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "status", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmd.hei_outcome_this_month = 6", + "value": "INFECTED" + }, + { + "condition": "hmd.hei_outcome_this_month = 5", + "value": "UNINFECTED" + }, + { + "condition": "(hmd.hei_outcome_this_month = 3 OR TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0) AND hmd.infection_status_this_month = 1", + "value": "UNINFECTED DEAD" + }, + { + "condition": "(hmd.hei_outcome_this_month = 3 OR TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0) AND hmd.infection_status_this_month = 2", + "value": "INFECTED DEAD" + }, + { + "condition": "hmd.hei_outcome_this_month = 2 OR (hmd.hei_outcome_this_month IS NULL AND TIMESTAMPDIFF(DAY, fhs.rtc_date, CURDATE()) > 0)", + "value": "LTFU" + }, + { + "condition": "hmd.hei_outcome_this_month = 1", + "value": "TRANSFER OUT" + }, + { + "condition": "else", + "value": null + } ] + } + }, + { + "type": "derived_column", + "alias": "status_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN hmd.hei_outcome_this_month in (3,5,6) then DATE_FORMAT(hmd.hiv_dna_pcr_date,'%Y-%m-%d') WHEN hmd.hei_outcome_this_month = 1 then DATE_FORMAT(hmd.transfer_out_date,'%Y-%m-%d') WHEN (hmd.hei_outcome_this_month = 2 OR (hmd.hei_outcome_this_month IS NULL AND TIMESTAMPDIFF(DAY, fhs.rtc_date, CURDATE()) > 0)) THEN DATE_FORMAT(hmd.rtc_date,'%Y-%m-%d') ELSE NULL END" + } + }, + { + "type": "derived_column", + "alias": "has_status", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.age_in_months = 24" + } + ] + } } diff --git a/app/reporting-framework/json-reports/hei-report-patient-list-template.json b/app/reporting-framework/json-reports/hei-report-patient-list-template.json index a0d1798da..70984485f 100644 --- a/app/reporting-framework/json-reports/hei-report-patient-list-template.json +++ b/app/reporting-framework/json-reports/hei-report-patient-list-template.json @@ -1,133 +1,133 @@ { - "name": "hei-report-patient_list_template", - "version": "1.0", - "tag": "hei_report_patient_list_template", - "description": "HEI Report Patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pa.person_id" - } - }, - { - "table": "etl.flat_hei_summary", - "alias": "hs", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = hs.person_id AND hs.next_encounter_datetime_hiv IS NULL" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "derived_column", - "alias": "birth_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(t1.birthdate, '%Y-%m-%d')" - } - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(hs.date_enrolled, '%Y-%m-%d')" - } - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "hei-report-patient_list_template", + "version": "1.0", + "tag": "hei_report_patient_list_template", + "description": "HEI Report Patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pa.person_id" + } + }, + { + "table": "etl.flat_hei_summary", + "alias": "hs", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = hs.person_id AND hs.next_encounter_datetime_hiv IS NULL" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "derived_column", + "alias": "birth_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(t1.birthdate, '%Y-%m-%d')" + } + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(hs.date_enrolled, '%Y-%m-%d')" + } + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/hei-retention-pairs-aggregate.json b/app/reporting-framework/json-reports/hei-retention-pairs-aggregate.json index 70b46ef92..ea512128e 100644 --- a/app/reporting-framework/json-reports/hei-retention-pairs-aggregate.json +++ b/app/reporting-framework/json-reports/hei-retention-pairs-aggregate.json @@ -1,120 +1,114 @@ { - "name": "heiRetentionPairsAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "heiRetentionPairsBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "heiRetentionPairsBase", - "alias": "hmds" - } - ], - "columns": [ - - { - "type": "simple_column", - "alias":"reporting_month", - "column":"hmds.reporting_month" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmds.location" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmds.location_id" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"hmds.location_uuid" - }, - { - "type": "derived_column", - "alias":"mother_baby_pairs_24_months_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.mother_baby_pairs_24_months_active)" - } - }, - { - "type": "derived_column", - "alias":"dead_b", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.dead_b)" - } - }, - { - "type": "derived_column", - "alias":"dead_m", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.dead_m)" - } - }, - { - "type": "derived_column", - "alias":"invalid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.invalid)" - } - }, - { - "type": "derived_column", - "alias":"ltfu_", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.ltfu_)" - } - }, - { - "type": "derived_column", - "alias":"transfer_in_", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.transfer_in_)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "hmds.reporting_month", - "hmds.location_id" - ], - "excludeParam": "excludeParam" + "name": "heiRetentionPairsAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "heiRetentionPairsBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "heiRetentionPairsBase", + "alias": "hmds" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmds.reporting_month" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmds.location" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmds.location_id" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmds.location_uuid" }, - "dynamicJsonQueryGenerationDirectives": { + { + "type": "derived_column", + "alias": "mother_baby_pairs_24_months_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.mother_baby_pairs_24_months_active)" + } + }, + { + "type": "derived_column", + "alias": "dead_b", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.dead_b)" + } + }, + { + "type": "derived_column", + "alias": "dead_m", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.dead_m)" + } + }, + { + "type": "derived_column", + "alias": "invalid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.invalid)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.ltfu_)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.transfer_in_)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["hmds.reporting_month", "hmds.location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { "patientListGenerator": { - "useTemplate": "hei-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + "useTemplate": "hei-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" + } + }, + "skipParams": [] } + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hei-retention-pairs-base.json b/app/reporting-framework/json-reports/hei-retention-pairs-base.json index d7b910eb1..0d0126e1a 100644 --- a/app/reporting-framework/json-reports/hei-retention-pairs-base.json +++ b/app/reporting-framework/json-reports/hei-retention-pairs-base.json @@ -1,134 +1,133 @@ { - "name": "heiRetentionPairsBase", - "version": "1.0", - "tag": "hei_retention_pairs_base", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hei_monthly_report_dataset", - "alias": "hmd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "hmd.location_id = l.location_id" - - } - }, - { - "table": "etl.flat_hei_summary", - "alias": "fhs", - "join": { - "type": "LEFT", - "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_clinical_datetime_hiv IS NULL AND fhs.is_clinical_encounter = 1" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias":"person_id", - "column":"hmd.person_id" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmd.clinic" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"l.uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmd.location_id" - }, - { - "type": "simple_column", - "alias":"reporting_month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "simple_column", - "alias":"month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "derived_column", - "alias": "mother_baby_pairs_24_months_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.death_date <= date_format(endDate,'%Y-%m-01') IS NULL AND hmd.mother_alive_this_month = 1 AND hmd.mother_alive_on_child_enrollment = 1 AND ((hmd.retention_status = 'active' AND hmd.hei_outcome_this_month IS NULL) OR hei_outcome_this_month IS NOT NULL),1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "dead_b", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.death_date IS NOT NULL ,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "dead_m", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.mother_alive_on_child_enrollment = 1 AND hmd.mother_alive_this_month = 2 ,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "invalid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.mother_alive_on_child_enrollment = 2 ,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.retention_status = 'ltfu' AND hei_outcome_this_month IS NULL,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "transfer_in_", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(fhs.transfer_in = 1,1,NULL)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.age_in_months = 24" - } - ] + "name": "heiRetentionPairsBase", + "version": "1.0", + "tag": "hei_retention_pairs_base", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hei_monthly_report_dataset", + "alias": "hmd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "hmd.location_id = l.location_id" + } + }, + { + "table": "etl.flat_hei_summary", + "alias": "fhs", + "join": { + "type": "LEFT", + "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_clinical_datetime_hiv IS NULL AND fhs.is_clinical_encounter = 1" + } } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmd.person_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmd.clinic" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmd.location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "simple_column", + "alias": "month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "derived_column", + "alias": "mother_baby_pairs_24_months_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.death_date <= date_format(endDate,'%Y-%m-01') IS NULL AND hmd.mother_alive_this_month = 1 AND hmd.mother_alive_on_child_enrollment = 1 AND ((hmd.retention_status = 'active' AND hmd.hei_outcome_this_month IS NULL) OR hei_outcome_this_month IS NOT NULL),1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "dead_b", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.death_date IS NOT NULL ,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "dead_m", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.mother_alive_on_child_enrollment = 1 AND hmd.mother_alive_this_month = 2 ,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "invalid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.mother_alive_on_child_enrollment = 2 ,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.retention_status = 'ltfu' AND hei_outcome_this_month IS NULL,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.transfer_in = 1,1,NULL)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.age_in_months = 24" + } + ] + } } diff --git a/app/reporting-framework/json-reports/hei-unknown-program-outcome-aggregate.json b/app/reporting-framework/json-reports/hei-unknown-program-outcome-aggregate.json index 41bab3c9f..ffac0c121 100644 --- a/app/reporting-framework/json-reports/hei-unknown-program-outcome-aggregate.json +++ b/app/reporting-framework/json-reports/hei-unknown-program-outcome-aggregate.json @@ -1,104 +1,98 @@ { - "name": "heiUknownProgramOutcomeAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "heiUknownProgramOutcomeBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "heiUknownProgramOutcomeBase", - "alias": "hmds" - } - ], - "columns": [ - - { - "type": "simple_column", - "alias":"reporting_month", - "column":"hmds.reporting_month" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmds.location" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmds.location_id" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"hmds.location_uuid" - }, - { - "type": "derived_column", - "alias":"ltfu_uo", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.ltfu_uo)" - } - }, - { - "type": "derived_column", - "alias":"uninfected_died_uo", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.uninfected_died_uo)" - } - }, - { - "type": "derived_column", - "alias":"infected_died_uo", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.infected_died_uo)" - } - }, - { - "type": "derived_column", - "alias":"transfer_out_uo", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"COUNT(hmds.transfer_out_uo)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "hmds.reporting_month", - "hmds.location_id" - ], - "excludeParam": "excludeParam" + "name": "heiUknownProgramOutcomeAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "heiUknownProgramOutcomeBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "heiUknownProgramOutcomeBase", + "alias": "hmds" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmds.reporting_month" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmds.location" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] + { + "type": "simple_column", + "alias": "location_id", + "column": "hmds.location_id" }, - "dynamicJsonQueryGenerationDirectives": { + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmds.location_uuid" + }, + { + "type": "derived_column", + "alias": "ltfu_uo", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.ltfu_uo)" + } + }, + { + "type": "derived_column", + "alias": "uninfected_died_uo", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.uninfected_died_uo)" + } + }, + { + "type": "derived_column", + "alias": "infected_died_uo", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.infected_died_uo)" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_uo", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(hmds.transfer_out_uo)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["hmds.reporting_month", "hmds.location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { "patientListGenerator": { - "useTemplate": "hei-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + "useTemplate": "hei-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" + } + }, + "skipParams": [] } + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hei-unknown-program-outcome-base.json b/app/reporting-framework/json-reports/hei-unknown-program-outcome-base.json index e7ac1a490..9fed4bd84 100644 --- a/app/reporting-framework/json-reports/hei-unknown-program-outcome-base.json +++ b/app/reporting-framework/json-reports/hei-unknown-program-outcome-base.json @@ -1,161 +1,157 @@ { - "name": "heiUnknownProgramOutcomeBase", - "version": "1.0", - "tag": "hei_unknown_program_outcome_base", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hei_monthly_report_dataset", - "alias": "hmd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "hmd.location_id = l.location_id" - - } - }, - { - "table": "etl.flat_hei_summary", - "alias": "fhs", - "join": { - "type": "LEFT", - "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_clinical_datetime_hiv IS NULL" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias":"person_id", - "column":"hmd.person_id" - }, - { - "type": "simple_column", - "alias":"location", - "column":"hmd.clinic" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"l.uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmd.location_id" - }, - { - "type": "simple_column", - "alias":"reporting_month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "simple_column", - "alias":"month", - "column":"DATE_FORMAT(hmd.endDate,'%Y-%m')" - }, - { - "type": "derived_column", - "alias": "ltfu_uo", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmd.hei_outcome_this_month = 2", - "value": 1 - }, - { - "condition": "hmd.hei_outcome_this_month IS NULL AND TIMESTAMPDIFF(DAY, fhs.rtc_date, CURDATE()) > 0", - "value": 1 - } - ] - } - - }, - { - "type": "derived_column", - "alias": "transfer_out_uo", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"IF(hmd.hei_outcome_this_month = 1 AND hmd.enrollment_location_id IN ({locations}),1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "uninfected_died_uo", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmd.hei_outcome_this_month = 3 AND hmd.infection_status_this_month = 1", - "value": 1 - }, - { - "condition": "TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0 AND hmd.infection_status_this_month = 1", - "value": 1 - } - ] - } - - }, - { - "type": "derived_column", - "alias": "infected_died_uo", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmd.hei_outcome_this_month = 3 AND hmd.infection_status_this_month = 2", - "value": 1 - }, - { - "condition": "TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0 AND hmd.infection_status_this_month = 2", - "value": 1 - } - ] - } - - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.endDate <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.location_id in (?)", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.gender in ?", - "parameterName": "genders" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.age_in_months = 24" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmd.hei_outcome_this_month in (1,2,3,4) OR hmd.hei_outcome_this_month IS NULL" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.death_date IS NULL OR TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0" - } + "name": "heiUnknownProgramOutcomeBase", + "version": "1.0", + "tag": "hei_unknown_program_outcome_base", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hei_monthly_report_dataset", + "alias": "hmd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "hmd.location_id = l.location_id" + } + }, + { + "table": "etl.flat_hei_summary", + "alias": "fhs", + "join": { + "type": "LEFT", + "joinCondition": "hmd.person_id = fhs.person_id AND fhs.next_clinical_datetime_hiv IS NULL" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "hmd.person_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmd.clinic" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmd.location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "simple_column", + "alias": "month", + "column": "DATE_FORMAT(hmd.endDate,'%Y-%m')" + }, + { + "type": "derived_column", + "alias": "ltfu_uo", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmd.hei_outcome_this_month = 2", + "value": 1 + }, + { + "condition": "hmd.hei_outcome_this_month IS NULL AND TIMESTAMPDIFF(DAY, fhs.rtc_date, CURDATE()) > 0", + "value": 1 + } + ] + } + }, + { + "type": "derived_column", + "alias": "transfer_out_uo", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmd.hei_outcome_this_month = 1 AND hmd.enrollment_location_id IN ({locations}),1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "uninfected_died_uo", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmd.hei_outcome_this_month = 3 AND hmd.infection_status_this_month = 1", + "value": 1 + }, + { + "condition": "TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0 AND hmd.infection_status_this_month = 1", + "value": 1 + } + ] + } + }, + { + "type": "derived_column", + "alias": "infected_died_uo", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmd.hei_outcome_this_month = 3 AND hmd.infection_status_this_month = 2", + "value": 1 + }, + { + "condition": "TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0 AND hmd.infection_status_this_month = 2", + "value": 1 + } ] + } } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.endDate <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.location_id in (?)", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.gender in ?", + "parameterName": "genders" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.age_in_months = 24" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmd.hei_outcome_this_month in (1,2,3,4) OR hmd.hei_outcome_this_month IS NULL" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.death_date IS NULL OR TIMESTAMPDIFF(DAY, fhs.death_date, endDate) >= 0" + } + ] + } } diff --git a/app/reporting-framework/json-reports/hiv-latest-clinical-encounter-date-base.json b/app/reporting-framework/json-reports/hiv-latest-clinical-encounter-date-base.json index 7e9935a77..2be111837 100644 --- a/app/reporting-framework/json-reports/hiv-latest-clinical-encounter-date-base.json +++ b/app/reporting-framework/json-reports/hiv-latest-clinical-encounter-date-base.json @@ -3,57 +3,54 @@ "version": "1.0", "tag": "", "description": "", - "uses": [ - ], + "uses": [], "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "m" - } + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "m" + } ], "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "m.person_id" + }, + { + "type": "derived_column", + "alias": "latest_encounter_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " MAX(m.encounter_datetime)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "date(m.encounter_datetime) <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "m.encounter_type not in (21,99999)", + "parameterName": "" + }, { - "type": "simple_column", - "alias": "person_id", - "column": "m.person_id" + "filterType": "tableColumns", + "conditionExpression": "m.is_clinical_encounter = 1", + "parameterName": "" }, { - "type": "derived_column", - "alias": "latest_encounter_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " MAX(m.encounter_datetime)" - } + "filterType": "tableColumns", + "conditionExpression": "m.location_uuid in (?)", + "parameterName": "locationUuids" } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "date(m.encounter_datetime) <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "m.encounter_type not in (21,99999)", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "m.is_clinical_encounter = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "m.location_uuid in (?)", - "parameterName": "locationUuids" - } - ] + ] }, "groupBy": { - "columns": [ - "m.person_id" - ] + "columns": ["m.person_id"] + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hiv-monthly-summary-aggregate.json b/app/reporting-framework/json-reports/hiv-monthly-summary-aggregate.json index daad7759e..e7cd910cd 100644 --- a/app/reporting-framework/json-reports/hiv-monthly-summary-aggregate.json +++ b/app/reporting-framework/json-reports/hiv-monthly-summary-aggregate.json @@ -1,523 +1,532 @@ { - "name": "hivMonthlySummaryDataSetAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "hivMonthlySummaryDataSetBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "hivMonthlySummaryDataSetBase", - "alias": "hmsd" - } - ], + "name": "hivMonthlySummaryDataSetAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "hivMonthlySummaryDataSetBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "hivMonthlySummaryDataSetBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "hmsd.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "hmsd.month" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmsd.reporting_month" + }, + { + "type": "derived_column", + "alias": "patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct hmsd.person_id)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_arvs,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_arvs_first_line,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_arvs_second_line,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "newly_on_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.newly_on_second_line,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_third_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_arvs_third_line,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.vl_done_past_year,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_relative_to_end_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.vl_done_past_year_relative_to_end_date,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "no_vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.no_vl_done_past_year,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "on_second_line_not_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_second_line_not_suppressed,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "not_on_arvs_cd4_lte_500", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.not_on_arvs_cd4_lte_500,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.vl_done_past_year_lte_1000,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.vl_done_this_encounter,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.vl_done_this_encounter_lte_1000,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.vl_done_this_encounter_gt_1000,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "vl_ordered", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.vl_ordered,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.pending_vl_order,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order_no_result_after_4_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.pending_vl_order_no_result_after_4_weeks,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_arvs_lte_26_weeks,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_arvs_lte_52_weeks,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_arvs_lte_52_weeks_and_have_vl,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.pregnant_and_on_arvs,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "pregnant", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.pregnant_and_on_arvs,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "pregnant_and_on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.pregnant_and_on_arvs,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.virally_suppressed,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.virally_suppressed_in_past_year,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "viral_load_resulted_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.viral_load_resulted_in_past_year,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.not_virally_suppressed_in_past_year,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "perc_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.virally_suppressed_in_past_year)/count(hmsd.viral_load_resulted_in_past_year)" + } + }, + { + "type": "derived_column", + "alias": "perc_not_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.not_virally_suppressed_in_past_year)/count(hmsd.viral_load_resulted_in_past_year)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.on_arvs)/count(hmsd.patients)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arv_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.on_arvs_first_line)/count(hmsd.on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arv_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.on_arvs_second_line)/count(hmsd.on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "perc_with_pending_viral_load", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.pending_vl_order)/count(hmsd.on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arvs_lte_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.on_arvs_lte_26_weeks)/count(hmsd.on_arvs)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_gt_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_arvs_gt_26_weeks,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arvs_gt_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.on_arvs_gt_26_weeks)/count(hmsd.patients)" + } + }, + { + "type": "derived_column", + "alias": "perc_ART_pats_screened_for_TB_receiving_TB_medication", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.num_ART_pats_screened_for_tb_started_TB)/count(hmsd.num_ART_pats_screened_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "num_new_ART_pats_screened_for_tb_started_TB_this_period", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.num_new_ART_pats_screened_for_tb_started_TB_this_period,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "num_previous_ART_pats_screened_for_tb_started_TB", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.num_previous_ART_pats_screened_for_tb_started_TB,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "num_ART_pats_screened_for_tb_started_TB", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.num_ART_pats_screened_for_tb_started_TB,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.on_arvs,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.vl_done_past_year_gt_1000,hmsd.person_id,null))" + } + }, + { + "type": "derived_column", + "alias": "num_ART_patients_completed_6mths_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.num_ART_patients_completed_6mths_IPT)" + } + }, + { + "type": "derived_column", + "alias": "num_ART_patients_newly_started_IPT_less_6mths", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.num_ART_patients_newly_started_IPT_less_6mths)" + } + }, + { + "type": "derived_column", + "alias": "num_ART_pats_screened_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.num_ART_pats_screened_for_tb,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "num_ART_patients_newly_started_IPT_this_period_less_6mths", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.num_ART_patients_newly_started_IPT_this_period_less_6mths,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "num_ART_patients_newly_started_IPT_previous_period_less_6mths", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.num_ART_patients_newly_started_IPT_previous_period_less_6mths,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "num_patients_currently_on_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.num_patients_currently_on_IPT,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "ever_started_on_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.ever_started_on_IPT,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "newly_started_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.newly_started_IPT,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "num_patients_newly_enrolled_newly_started_on_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.num_patients_newly_enrolled_newly_started_on_IPT,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "num_patients_stopped_on_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.num_patients_stopped_on_IPT,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_from_non_Ampath_site", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.transfer_in_from_non_Ampath_site,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_from_Ampath_site", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.transfer_in_from_Ampath_site,hmsd.person_id,0))" + } + }, + { + "type": "derived_column", + "alias": "transfer_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct if(hmsd.transfer_in,hmsd.person_id,0))" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["encounter_year", "encounter_month"], + "excludeParam": "excludeParam" + }, + "orderBy": { + "orderByParam": "orderByParam", "columns": [ - { - "type": "simple_column", - "alias":"location", - "column":"hmsd.location" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"hmsd.location_id" - }, - { - "type": "simple_column", - "alias":"encounter_datetime", - "column":"hmsd.encounter_datetime" - }, - { - "type": "simple_column", - "alias":"month", - "column":"hmsd.month" - }, - { - "type": "simple_column", - "alias":"reporting_month", - "column":"hmsd.reporting_month" - }, - { - "type": "derived_column", - "alias": "patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct hmsd.person_id)" - } - }, - { - "type": "derived_column", - "alias":"on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.on_arvs,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.on_arvs_first_line,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.on_arvs_second_line,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"newly_on_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.newly_on_second_line,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_third_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.on_arvs_third_line,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.vl_done_past_year,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_relative_to_end_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.vl_done_past_year_relative_to_end_date,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"no_vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.no_vl_done_past_year,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"on_second_line_not_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.on_second_line_not_suppressed,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"not_on_arvs_cd4_lte_500", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.not_on_arvs_cd4_lte_500,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"vl_done_past_year_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.vl_done_past_year_lte_1000,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"vl_done_this_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.vl_done_this_encounter,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"vl_done_this_encounter_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.vl_done_this_encounter_lte_1000,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"vl_done_this_encounter_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.vl_done_this_encounter_gt_1000,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"vl_ordered", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.vl_ordered,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"pending_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.pending_vl_order,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"pending_vl_order_no_result_after_4_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.pending_vl_order_no_result_after_4_weeks,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_lte_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.on_arvs_lte_26_weeks,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_lte_52_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.on_arvs_lte_52_weeks,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_lte_52_weeks_and_have_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.on_arvs_lte_52_weeks_and_have_vl,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.pregnant_and_on_arvs,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"pregnant", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.pregnant_and_on_arvs,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"pregnant_and_on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.pregnant_and_on_arvs,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.virally_suppressed,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.virally_suppressed_in_past_year,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"viral_load_resulted_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.viral_load_resulted_in_past_year,hmsd.person_id,0))" - } - - }, - { - "type": "derived_column", - "alias":"not_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.not_virally_suppressed_in_past_year,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"perc_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(hmsd.virally_suppressed_in_past_year)/count(hmsd.viral_load_resulted_in_past_year)" - } - }, - { - "type": "derived_column", - "alias":"perc_not_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(hmsd.not_virally_suppressed_in_past_year)/count(hmsd.viral_load_resulted_in_past_year)" - } - }, - { - "type": "derived_column", - "alias":"perc_on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(hmsd.on_arvs)/count(hmsd.patients)" - } - }, - { - "type": "derived_column", - "alias":"perc_on_arv_first_line", - "expressionType": "simple_expression", - "expressionOptions": {"expression":"count(hmsd.on_arvs_first_line)/count(hmsd.on_arvs)"} - }, - { - "type": "derived_column", - "alias":"perc_on_arv_second_line", - "expressionType": "simple_expression", - "expressionOptions": {"expression":"count(hmsd.on_arvs_second_line)/count(hmsd.on_arvs)"} - }, - { - "type": "derived_column", - "alias":"perc_with_pending_viral_load", - "expressionType": "simple_expression", - "expressionOptions": {"expression":"count(hmsd.pending_vl_order)/count(hmsd.on_arvs)"} - }, - { - "type": "derived_column", - "alias":"perc_on_arvs_lte_6_months", - "expressionType": "simple_expression", - "expressionOptions": {"expression":"count(hmsd.on_arvs_lte_26_weeks)/count(hmsd.on_arvs)"} - }, - { - "type": "derived_column", - "alias":"on_arvs_gt_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.on_arvs_gt_26_weeks,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"perc_on_arvs_gt_6_months", - "expressionType": "simple_expression", - "expressionOptions": {"expression":"count(hmsd.on_arvs_gt_26_weeks)/count(hmsd.patients)"} - }, - { - "type": "derived_column", - "alias":"perc_ART_pats_screened_for_TB_receiving_TB_medication", - "expressionType": "simple_expression", - "expressionOptions": {"expression":"count(hmsd.num_ART_pats_screened_for_tb_started_TB)/count(hmsd.num_ART_pats_screened_for_tb)"} - }, - { - "type": "derived_column", - "alias":"num_new_ART_pats_screened_for_tb_started_TB_this_period", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.num_new_ART_pats_screened_for_tb_started_TB_this_period,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"num_previous_ART_pats_screened_for_tb_started_TB", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.num_previous_ART_pats_screened_for_tb_started_TB,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"num_ART_pats_screened_for_tb_started_TB", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.num_ART_pats_screened_for_tb_started_TB,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.on_arvs,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"vl_done_past_year_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.vl_done_past_year_gt_1000,hmsd.person_id,null))" - } - }, - { - "type": "derived_column", - "alias":"num_ART_patients_completed_6mths_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(hmsd.num_ART_patients_completed_6mths_IPT)" - } - }, - { - "type": "derived_column", - "alias":"num_ART_patients_newly_started_IPT_less_6mths", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(hmsd.num_ART_patients_newly_started_IPT_less_6mths)" - } - }, - { - "type": "derived_column", - "alias":"num_ART_pats_screened_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"count(distinct if(hmsd.num_ART_pats_screened_for_tb,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"num_ART_patients_newly_started_IPT_this_period_less_6mths", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.num_ART_patients_newly_started_IPT_this_period_less_6mths,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"num_ART_patients_newly_started_IPT_previous_period_less_6mths", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.num_ART_patients_newly_started_IPT_previous_period_less_6mths,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"num_patients_currently_on_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.num_patients_currently_on_IPT,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"ever_started_on_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.ever_started_on_IPT,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"newly_started_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.newly_started_IPT,hmsd.person_id,0))" - - } - }, - { - "type": "derived_column", - "alias":"num_patients_newly_enrolled_newly_started_on_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.num_patients_newly_enrolled_newly_started_on_IPT,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"num_patients_stopped_on_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.num_patients_stopped_on_IPT,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"transfer_in_from_non_Ampath_site", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.transfer_in_from_non_Ampath_site,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"transfer_in_from_Ampath_site", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.transfer_in_from_Ampath_site,hmsd.person_id,0))" - } - }, - { - "type": "derived_column", - "alias":"transfer_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct if(hmsd.transfer_in,hmsd.person_id,0))" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "encounter_year", - "encounter_month" - ], - "excludeParam": "excludeParam" - }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [{ - "column": "encounter_year", - "order": "asc" - }, - { - "column": "encounter_month", - "order": "asc" - }] - }, - "dynamicJsonQueryGenerationDirectives": { + { + "column": "encounter_year", + "order": "asc" + }, + { + "column": "encounter_month", + "order": "asc" + } + ] + }, + "dynamicJsonQueryGenerationDirectives": { "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": ["gender"] + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" + } + }, + "skipParams": ["gender"] } + } } -} \ No newline at end of file diff --git a/app/reporting-framework/json-reports/hiv-monthly-summary-dataset-base.json b/app/reporting-framework/json-reports/hiv-monthly-summary-dataset-base.json index cc73f417f..89673d71e 100644 --- a/app/reporting-framework/json-reports/hiv-monthly-summary-dataset-base.json +++ b/app/reporting-framework/json-reports/hiv-monthly-summary-dataset-base.json @@ -1,529 +1,526 @@ { - "name": "hivMonthlySummaryDataSetBase", - "version": "1.0", - "tag": "hiv_monthly_summary_dataset_base", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs" - }, - { - "table": "etl.dates", - "alias": "dts", - "join": { - "type": "INNER", - "joinCondition": "is_clinical_encounter=1 and encounter_datetime <= dts.endDate and coalesce(fhs.death_date, out_of_care) is null" - } - }, - { - "table": "amrs.location", - "alias": "lct", - "join": { - "type": "INNER", - "joinCondition": "fhs.location_uuid = lct.uuid" - } - }, - { - "table": "amrs.person", - "alias": "t4", - "join": { - "type": "INNER", - "joinCondition": "fhs.person_id = t4.person_id" - } - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "on_arvs_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"cur_arv_line=1" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "cur_arv_line=2 and coalesce(transfer_out, out_of_care) is null" - } - }, - { - "type": "derived_column", - "alias":"newly_on_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "cur_arv_line =2 and (arv_start_date between '{startDate}' and '{endDate}')" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_third_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"cur_arv_line>2" - } - }, - { - "type": "derived_column", - "alias":"vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_relative_to_end_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "timestampdiff(week,vl_1_date,'{endDate}') <= 52" - } - }, - { - "type": "derived_column", - "alias":"no_vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "cur_arv_line is not null and (vl_1_date is null or timestampdiff(week,vl_1_date,encounter_datetime) >= 52)" - - } - }, - { - "type": "derived_column", - "alias":"on_second_line_not_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"vl_1 > 1000 and cur_arv_line =2" - } - }, - { - "type": "derived_column", - "alias":"not_on_arvs_cd4_lte_500", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"arv_start_date is null and cd4_1 < 500" - } - }, - { - "type": "derived_column", - "alias":"vl_done_past_year_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" - } - }, - { - "type": "derived_column", - "alias":"vl_done_this_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"vl_resulted >= 0 and vl_resulted_date=date(encounter_datetime)" - } - }, - { - "type": "derived_column", - "alias":"vl_done_this_encounter_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"vl_resulted <= 1000 and vl_resulted_date = date(encounter_datetime)" - } - }, - { - "type": "derived_column", - "alias":"vl_done_this_encounter_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "vl_resulted > 1000 and vl_resulted_date = date(encounter_datetime)" - } - }, - { - "type": "derived_column", - "alias":"vl_ordered", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"date(vl_order_date)=date(encounter_datetime)" - } - }, - { - "type": "derived_column", - "alias":"pending_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"timestampdiff(week,vl_order_date,encounter_datetime) >= 0 and vl_1_date < vl_order_date" - } - }, - { - "type": "derived_column", - "alias":"pending_vl_order_no_result_after_4_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"timestampdiff(week,vl_order_date,encounter_datetime) >= 4 and vl_1_date < vl_order_date" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_lte_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"timestampdiff(week,arv_start_date,encounter_datetime) <= 26" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_lte_52_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_lte_52_weeks_and_have_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" - } - }, - { - "type": "derived_column", - "alias":"pregnant", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"edd > encounter_datetime" - } - }, - { - "type": "derived_column", - "alias":"pregnant_and_on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"edd > encounter_datetime and cur_arv_line is not null" - } - }, - { - "type": "derived_column", - "alias":"virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and timestampdiff(day, date(vl_1_date), date(dts.endDate)) <= 365 and vl_1 < 1000" - } - }, - { - "type": "derived_column", - "alias":"virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - } - }, - { - "type": "derived_column", - "alias":"viral_load_resulted_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "vl_1 is not null and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - } - - }, - { - "type": "derived_column", - "alias":"not_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "vl_1> 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - } - }, - { - "type": "derived_column", - "alias":"on_arvs_gt_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) > 26" - } - }, - { - "type": "derived_column", - "alias":"num_new_ART_pats_screened_for_tb_started_TB_this_period", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "tb_screen is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(fhs.death_date, out_of_care) is null and arv_start_date>= '{startDate}' and arv_start_date<= '{endDate}'" - } - }, - { - "type": "derived_column", - "alias":"num_previous_ART_pats_screened_for_tb_started_TB", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "tb_screen is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(fhs.death_date, out_of_care) is null and arv_start_date< '{startDate}'" - } - }, - { - "type": "derived_column", - "alias":"num_ART_pats_screened_for_tb_started_TB", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "tb_screen is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(fhs.death_date, out_of_care) is null" - } - }, - { - "type": "derived_column", - "alias": "on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"cur_arv_line is not null" - } - }, - { - "type": "derived_column", - "alias":"vl_done_past_year_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 > 1000" - } - }, - { - "type": "derived_column", - "alias":"num_ART_patients_completed_6mths_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"round(datediff(encounter_datetime,ipt_start_date)/30.5) >= 6 or round(datediff(ipt_stop_date,ipt_start_date)/30.5) >= 6 and (coalesce(fhs.death_date, out_of_care) is null)" - } - }, - { - "type": "derived_column", - "alias":"num_ART_patients_newly_started_IPT_less_6mths", - "expressionType": "simple_expression", - "expressionOptions": { - "expression":"ipt_start_date is not null or ipt_stop_date is not null and ipt_start_date >= DATE_ADD('{startDate}', INTERVAL -6 month) and (coalesce(fhs.death_date, out_of_care) is null) " - } - }, - + "name": "hivMonthlySummaryDataSetBase", + "version": "1.0", + "tag": "hiv_monthly_summary_dataset_base", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs" + }, + { + "table": "etl.dates", + "alias": "dts", + "join": { + "type": "INNER", + "joinCondition": "is_clinical_encounter=1 and encounter_datetime <= dts.endDate and coalesce(fhs.death_date, out_of_care) is null" + } + }, + { + "table": "amrs.location", + "alias": "lct", + "join": { + "type": "INNER", + "joinCondition": "fhs.location_uuid = lct.uuid" + } + }, + { + "table": "amrs.person", + "alias": "t4", + "join": { + "type": "INNER", + "joinCondition": "fhs.person_id = t4.person_id" + } + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "on_arvs_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "cur_arv_line=1" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "cur_arv_line=2 and coalesce(transfer_out, out_of_care) is null" + } + }, + { + "type": "derived_column", + "alias": "newly_on_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "cur_arv_line =2 and (arv_start_date between '{startDate}' and '{endDate}')" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_third_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "cur_arv_line>2" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_relative_to_end_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,vl_1_date,'{endDate}') <= 52" + } + }, + { + "type": "derived_column", + "alias": "no_vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "cur_arv_line is not null and (vl_1_date is null or timestampdiff(week,vl_1_date,encounter_datetime) >= 52)" + } + }, + { + "type": "derived_column", + "alias": "on_second_line_not_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "vl_1 > 1000 and cur_arv_line =2" + } + }, + { + "type": "derived_column", + "alias": "not_on_arvs_cd4_lte_500", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "arv_start_date is null and cd4_1 < 500" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "vl_resulted >= 0 and vl_resulted_date=date(encounter_datetime)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "vl_resulted <= 1000 and vl_resulted_date = date(encounter_datetime)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "vl_resulted > 1000 and vl_resulted_date = date(encounter_datetime)" + } + }, + { + "type": "derived_column", + "alias": "vl_ordered", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date(vl_order_date)=date(encounter_datetime)" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 0 and vl_1_date < vl_order_date" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order_no_result_after_4_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 4 and vl_1_date < vl_order_date" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 26" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" + } + }, + { + "type": "derived_column", + "alias": "pregnant", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "edd > encounter_datetime" + } + }, + { + "type": "derived_column", + "alias": "pregnant_and_on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "edd > encounter_datetime and cur_arv_line is not null" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and timestampdiff(day, date(vl_1_date), date(dts.endDate)) <= 365 and vl_1 < 1000" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + } + }, + { + "type": "derived_column", + "alias": "viral_load_resulted_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "vl_1 is not null and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "vl_1> 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_gt_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) > 26" + } + }, + { + "type": "derived_column", + "alias": "num_new_ART_pats_screened_for_tb_started_TB_this_period", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "tb_screen is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(fhs.death_date, out_of_care) is null and arv_start_date>= '{startDate}' and arv_start_date<= '{endDate}'" + } + }, + { + "type": "derived_column", + "alias": "num_previous_ART_pats_screened_for_tb_started_TB", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "tb_screen is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(fhs.death_date, out_of_care) is null and arv_start_date< '{startDate}'" + } + }, + { + "type": "derived_column", + "alias": "num_ART_pats_screened_for_tb_started_TB", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "tb_screen is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(fhs.death_date, out_of_care) is null" + } + }, + { + "type": "derived_column", + "alias": "on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "cur_arv_line is not null" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 > 1000" + } + }, + { + "type": "derived_column", + "alias": "num_ART_patients_completed_6mths_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "round(datediff(encounter_datetime,ipt_start_date)/30.5) >= 6 or round(datediff(ipt_stop_date,ipt_start_date)/30.5) >= 6 and (coalesce(fhs.death_date, out_of_care) is null)" + } + }, + { + "type": "derived_column", + "alias": "num_ART_patients_newly_started_IPT_less_6mths", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "ipt_start_date is not null or ipt_stop_date is not null and ipt_start_date >= DATE_ADD('{startDate}', INTERVAL -6 month) and (coalesce(fhs.death_date, out_of_care) is null) " + } + }, - { - "type": "derived_column", - "alias":"num_ART_pats_screened_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "tb_screen is not null and cur_arv_line is not null and coalesce(fhs.death_date, out_of_care) is null" - } - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "extract(year from (from_days(datediff(now(),t4.birthdate)))) >= 15", - "value": "15_and_above" - }, - { - "condition": "else", - "value": "below_15" - } - ] - } - }, - { - "type": "derived_column", - "alias":"num_ART_patients_newly_started_IPT_this_period_less_6mths", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "ipt_start_date is not null or ipt_stop_date is not null and ipt_start_date >= '{startDate}'" - } - }, - { - "type": "derived_column", - "alias":"num_ART_patients_newly_started_IPT_previous_period_less_6mths", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "ipt_start_date is not null or ipt_stop_date is not null and ipt_start_date < '{startDate}'" - } - }, - { - "type": "derived_column", - "alias":"num_patients_currently_on_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "coalesce(fhs.death_date, out_of_care) is null and ipt_start_date is not null and ipt_stop_date is null" - } - }, - { - "type": "derived_column", - "alias":"ever_started_on_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "ipt_start_date is not null" - } - }, - { - "type": "derived_column", - "alias":"newly_started_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date(ipt_start_date) between '{startDate}' and '{endDate}'" - } - }, - { - "type": "derived_column", - "alias":"num_patients_newly_enrolled_newly_started_on_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "coalesce(fhs.death_date, out_of_care) is null and ipt_start_date is not null and '{startDate}'<=enrollment_date and enrollment_date<='{endDate}'" - } - }, - { - "type": "derived_column", - "alias":"num_patients_stopped_on_IPT", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "coalesce(fhs.death_date, out_of_care) is null and fhs.ipt_stop_date is not null and '{startDate}'<=ipt_stop_date<='{endDate}'" - } - }, - { - "type": "derived_column", - "alias":"transfer_in_from_non_Ampath_site", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "fhs.transfer_in=1287 and (fhs.encounter_datetime between DATE_FORMAT(dts.endDate, '%Y-%m-01') and dts.endDate)" - } - }, - { - "type": "derived_column", - "alias":"transfer_in_from_Ampath_site", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "fhs.transfer_in=1286 and (fhs.encounter_datetime between DATE_FORMAT(dts.endDate, '%Y-%m-01') and dts.endDate)" - } - }, - { - "type": "derived_column", - "alias":"transfer_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when date(fhs.hiv_start_date) between DATE_FORMAT(dts.endDate, '%Y-%m-01') and dts.endDate then null when fhs.transfer_in is not null and (fhs.encounter_datetime between DATE_FORMAT(dts.endDate, '%Y-%m-01') and dts.endDate) then 1 else null end" - } - }, - { - "type": "derived_column", - "alias":"encounter_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "MONTH(fhs.encounter_datetime)" - } - }, - { - "type": "derived_column", - "alias":"reporting_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(fhs.encounter_datetime, '%m/%Y')" - } - }, - { - "type": "derived_column", - "alias":"encounter_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "YEAR(fhs.encounter_datetime)" - } - }, - { - "type": "simple_column", - "alias":"location", - "column":"lct.name" - }, - { - "type": "simple_column", - "alias":"location_uuid", - "column":"fhs.location_uuid" - }, - { - "type": "simple_column", - "alias":"location_id", - "column":"fhs.location_id" - }, - { - "type": "simple_column", - "alias":"encounter_datetime", - "column":"fhs.encounter_datetime" - }, - { - "type": "simple_column", - "alias":"month", - "column":"fhs.encounter_datetime" - }, - { - "type": "simple_column", - "alias":"person_id", - "column":"t4.person_id" - }, - { - "type": "simple_column", - "alias":"gender", - "column":"t4.gender" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "fhs.encounter_datetime <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.encounter_datetime >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.location_id in ?", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "round(datediff(fhs.encounter_datetime,t4.birthdate)/365) >= 0", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "round(datediff(fhs.encounter_datetime,t4.birthdate)/365) <= 120", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t4.gender in ?", - "parameterName": "gender" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.is_clinical_encounter = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "coalesce(fhs.death_date, out_of_care) is null", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(fhs.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= dts.endDate)", - "parameterName": "" - } + { + "type": "derived_column", + "alias": "num_ART_pats_screened_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "tb_screen is not null and cur_arv_line is not null and coalesce(fhs.death_date, out_of_care) is null" + } + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "extract(year from (from_days(datediff(now(),t4.birthdate)))) >= 15", + "value": "15_and_above" + }, + { + "condition": "else", + "value": "below_15" + } ] + } + }, + { + "type": "derived_column", + "alias": "num_ART_patients_newly_started_IPT_this_period_less_6mths", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "ipt_start_date is not null or ipt_stop_date is not null and ipt_start_date >= '{startDate}'" + } + }, + { + "type": "derived_column", + "alias": "num_ART_patients_newly_started_IPT_previous_period_less_6mths", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "ipt_start_date is not null or ipt_stop_date is not null and ipt_start_date < '{startDate}'" + } + }, + { + "type": "derived_column", + "alias": "num_patients_currently_on_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "coalesce(fhs.death_date, out_of_care) is null and ipt_start_date is not null and ipt_stop_date is null" + } + }, + { + "type": "derived_column", + "alias": "ever_started_on_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "ipt_start_date is not null" + } + }, + { + "type": "derived_column", + "alias": "newly_started_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date(ipt_start_date) between '{startDate}' and '{endDate}'" + } + }, + { + "type": "derived_column", + "alias": "num_patients_newly_enrolled_newly_started_on_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "coalesce(fhs.death_date, out_of_care) is null and ipt_start_date is not null and '{startDate}'<=enrollment_date and enrollment_date<='{endDate}'" + } + }, + { + "type": "derived_column", + "alias": "num_patients_stopped_on_IPT", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "coalesce(fhs.death_date, out_of_care) is null and fhs.ipt_stop_date is not null and '{startDate}'<=ipt_stop_date<='{endDate}'" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_from_non_Ampath_site", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "fhs.transfer_in=1287 and (fhs.encounter_datetime between DATE_FORMAT(dts.endDate, '%Y-%m-01') and dts.endDate)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_from_Ampath_site", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "fhs.transfer_in=1286 and (fhs.encounter_datetime between DATE_FORMAT(dts.endDate, '%Y-%m-01') and dts.endDate)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when date(fhs.hiv_start_date) between DATE_FORMAT(dts.endDate, '%Y-%m-01') and dts.endDate then null when fhs.transfer_in is not null and (fhs.encounter_datetime between DATE_FORMAT(dts.endDate, '%Y-%m-01') and dts.endDate) then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "encounter_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "MONTH(fhs.encounter_datetime)" + } + }, + { + "type": "derived_column", + "alias": "reporting_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(fhs.encounter_datetime, '%m/%Y')" + } + }, + { + "type": "derived_column", + "alias": "encounter_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "YEAR(fhs.encounter_datetime)" + } + }, + { + "type": "simple_column", + "alias": "location", + "column": "lct.name" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "fhs.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "fhs.location_id" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "fhs.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "fhs.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t4.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t4.gender" } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "fhs.encounter_datetime <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.encounter_datetime >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.location_id in ?", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "round(datediff(fhs.encounter_datetime,t4.birthdate)/365) >= 0", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "round(datediff(fhs.encounter_datetime,t4.birthdate)/365) <= 120", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t4.gender in ?", + "parameterName": "gender" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.is_clinical_encounter = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "coalesce(fhs.death_date, out_of_care) is null", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(fhs.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= dts.endDate)", + "parameterName": "" + } + ] + } } diff --git a/app/reporting-framework/json-reports/hiv-summary-aggregate.json b/app/reporting-framework/json-reports/hiv-summary-aggregate.json index 3de4bbbd7..c2dcbbe73 100644 --- a/app/reporting-framework/json-reports/hiv-summary-aggregate.json +++ b/app/reporting-framework/json-reports/hiv-summary-aggregate.json @@ -1,568 +1,564 @@ { - "name": "hivSummaryBaseAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "hivSummaryBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "hivSummaryBase", - "alias": "hsb" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct person_id)" - } - }, - { - "type": "derived_column", - "alias": "on_tdf_3tc_efv_400", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_tdf_3tc_efv_400, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_tdf_3tc_efv_600", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_tdf_3tc_efv_600, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_tdf_3tc_dtg", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_tdf_3tc_dtg, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_first_line, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_second_line, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "newly_on_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(newly_on_second_line, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_third_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_third_line, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_done_past_year, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "no_vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(no_vl_done_past_year, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_second_line_not_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_second_line_not_suppressed, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_on_arvs_cd4_lte_500", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(not_on_arvs_cd4_lte_500, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_done_past_year_lte_1000, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_done_past_year_gt_1000, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_done_this_encounter, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_done_this_encounter_lte_1000, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_done_this_encounter_gt_1000, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_ordered", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_ordered, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(pending_vl_order, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_order_no_result_after_4_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(pending_vl_order_no_result_after_4_weeks, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_lte_26_weeks, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_lte_52_weeks, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks_and_have_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_lte_52_weeks_and_have_vl, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_lte_52_weeks_and_have_vl_lte_1000, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_modern_contraception, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_short_term_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_short_term_modern_contraception, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_long_term_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_long_term_modern_contraception, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(not_on_modern_contraception, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_short_term_modern_contraception_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_short_term_modern_contraception_pnc, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_long_term_modern_contraception_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_long_term_modern_contraception_pnc, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_modern_contraception_pnc, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_on_modern_contraception_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(not_on_modern_contraception_pnc, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "in_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(in_pnc, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_art_and_not_on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_art_and_not_on_modern_contraception, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(started_modern_contraception, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "pregnant", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(pregnant, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "pregnant_and_on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(pregnant_and_on_arvs, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(newly_enrolled, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_care_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(enrolled_in_care_total, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(virally_suppressed, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(virally_suppressed_in_past_year, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "viral_load_resulted_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(viral_load_resulted_in_past_year, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(not_virally_suppressed_in_past_year, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_gt_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_gt_26_weeks, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "perc_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(virally_suppressed_in_past_year, hsb.person_id))/count(distinct concat(viral_load_resulted_in_past_year, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "perc_not_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(not_virally_suppressed_in_past_year, hsb.person_id)) / count(distinct concat(viral_load_resulted_in_past_year, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs, hsb.person_id)) / count(distinct person_id)" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arv_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_first_line, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arv_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_second_line, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arv_third_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_third_line, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "perc_with_pending_viral_load", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(pending_vl_order, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arvs_lte_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_lte_26_weeks, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "perc_on_arvs_gt_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(on_arvs_gt_26_weeks, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "patients_with_vl_result", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(patients_with_vl_result, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "transfer_in_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(transfer_in_patients, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_relative_to_end_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_done_past_year_relative_to_end_date, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "late_scheduled_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(late_scheduled_visits, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_suppressed_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_suppressed_patients, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "vl_unsuppressed_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(vl_unsuppressed_patients, hsb.person_id))" - } - }, - { - "type": "derived_column", - "alias": "early_scheduled_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(early_scheduled_visits, hsb.person_id))" - } - }, - { - "type": "simple_column", - "alias": "location", - "column": "location" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hsb.location_id" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "hsb.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "month", - "column": "hsb.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "month", - "column": "date_format(encounter_datetime, '%m/%Y')" - }, - { - "type": "simple_column", - "alias": "reporting_month", - "column": "reporting_month" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "location_uuid" - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [ - "gender" - ] + "name": "hivSummaryBaseAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "hivSummaryBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "hivSummaryBase", + "alias": "hsb" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct person_id)" + } + }, + { + "type": "derived_column", + "alias": "on_tdf_3tc_efv_400", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_tdf_3tc_efv_400, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_tdf_3tc_efv_600", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_tdf_3tc_efv_600, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_tdf_3tc_dtg", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_tdf_3tc_dtg, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_first_line, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_second_line, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "newly_on_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(newly_on_second_line, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_third_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_third_line, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_done_past_year, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "no_vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(no_vl_done_past_year, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_second_line_not_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_second_line_not_suppressed, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "not_on_arvs_cd4_lte_500", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(not_on_arvs_cd4_lte_500, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_done_past_year_lte_1000, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_done_past_year_gt_1000, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_done_this_encounter, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_done_this_encounter_lte_1000, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_done_this_encounter_gt_1000, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_ordered", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_ordered, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(pending_vl_order, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order_no_result_after_4_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(pending_vl_order_no_result_after_4_weeks, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_lte_26_weeks, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_lte_52_weeks, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_lte_52_weeks_and_have_vl, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_lte_52_weeks_and_have_vl_lte_1000, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_modern_contraception, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_short_term_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_short_term_modern_contraception, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_long_term_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_long_term_modern_contraception, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "not_on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(not_on_modern_contraception, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_short_term_modern_contraception_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_short_term_modern_contraception_pnc, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_long_term_modern_contraception_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_long_term_modern_contraception_pnc, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_modern_contraception_pnc, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "not_on_modern_contraception_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(not_on_modern_contraception_pnc, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "in_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(in_pnc, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_art_and_not_on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_art_and_not_on_modern_contraception, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(started_modern_contraception, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "pregnant", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(pregnant, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "pregnant_and_on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(pregnant_and_on_arvs, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(newly_enrolled, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_care_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(enrolled_in_care_total, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(virally_suppressed, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(virally_suppressed_in_past_year, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "viral_load_resulted_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(viral_load_resulted_in_past_year, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(not_virally_suppressed_in_past_year, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_gt_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_gt_26_weeks, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "perc_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(virally_suppressed_in_past_year, hsb.person_id))/count(distinct concat(viral_load_resulted_in_past_year, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "perc_not_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(not_virally_suppressed_in_past_year, hsb.person_id)) / count(distinct concat(viral_load_resulted_in_past_year, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs, hsb.person_id)) / count(distinct person_id)" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arv_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_first_line, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arv_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_second_line, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arv_third_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_third_line, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "perc_with_pending_viral_load", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(pending_vl_order, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arvs_lte_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_lte_26_weeks, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "perc_on_arvs_gt_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(on_arvs_gt_26_weeks, hsb.person_id)) / count(distinct concat(on_arvs, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "patients_with_vl_result", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(patients_with_vl_result, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(transfer_in_patients, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_relative_to_end_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_done_past_year_relative_to_end_date, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "late_scheduled_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(late_scheduled_visits, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_suppressed_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_suppressed_patients, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "vl_unsuppressed_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(vl_unsuppressed_patients, hsb.person_id))" + } + }, + { + "type": "derived_column", + "alias": "early_scheduled_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(early_scheduled_visits, hsb.person_id))" + } + }, + { + "type": "simple_column", + "alias": "location", + "column": "location" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hsb.location_id" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "hsb.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "hsb.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "date_format(encounter_datetime, '%m/%Y')" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "reporting_month" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "location_uuid" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + }, + "skipParams": ["gender"] } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/hiv-summary-base.json b/app/reporting-framework/json-reports/hiv-summary-base.json index 5fabb7d42..198edc546 100644 --- a/app/reporting-framework/json-reports/hiv-summary-base.json +++ b/app/reporting-framework/json-reports/hiv-summary-base.json @@ -1,532 +1,532 @@ { - "name": "hivSummaryBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = fhs.location_id" - } - }, - { - "table": "amrs.person", - "alias": "p", - "join": { - "type": "INNER", - "joinCondition": "fhs.person_id = p.person_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "fhs.person_id" - }, - { - "type": "derived_column", - "alias": "on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.cur_arv_line is not null,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.cur_arv_line=1,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.cur_arv_line=2,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_tdf_3tc_efv_400", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.cur_arv_meds REGEXP '(802.*633.*628)|(802.*628.*633)|(628.*802.*633)|(628.*633.*802)|(633.*802.*628)|(633.*628.*802)' AND fhs.cur_arv_drugs LIKE '%6964=598%', 1, NULL) " - } - }, - { - "type": "derived_column", - "alias": "on_tdf_3tc_efv_600", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.cur_arv_meds REGEXP '(802.*633.*628)|(802.*628.*633)|(628.*802.*633)|(628.*633.*802)|(633.*802.*628)|(633.*628.*802)' AND fhs.cur_arv_drugs LIKE '%6964=38%', 1, NULL) " - } - }, - { - "type": "derived_column", - "alias": "on_tdf_3tc_dtg", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.cur_arv_meds REGEXP '(802.*9759.*628)|(802.*628.*9759)|(628.*802.*9759)|(628.*9759.*802)|(9759.*802.*628)|(9759.*628.*802)',1,NULL) " - } - }, - { - "type": "derived_column", - "alias": "newly_on_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.cur_arv_line=2 and fhs.arv_start_date between '{startDate}' and '{endDate}',1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_third_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.cur_arv_line>2,1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_relative_to_end_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.vl_1_date,'{endDate}') <= 52,1,null)" - } - }, - { - "type": "derived_column", - "alias": "no_vl_done_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.cur_arv_line is not null and (fhs.vl_1_date is null or timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) >= 52),1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_second_line_not_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_1 > 1000 and fhs.cur_arv_line =2,1,null)" - } - }, - { - "type": "derived_column", - "alias": "not_on_arvs_cd4_lte_500", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.arv_start_date is null and fhs.cd4_1 < 500,1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52 and fhs.vl_1 <= 1000,1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_past_year_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52 and fhs.vl_1 > 1000,1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_resulted >= 0 and fhs.vl_resulted_date=date(fhs.encounter_datetime),1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_resulted <= 1000 and fhs.vl_resulted_date = date(fhs.encounter_datetime),1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_done_this_encounter_gt_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_resulted > 1000 and fhs.vl_resulted_date = date(fhs.encounter_datetime),1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_ordered", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(date(fhs.vl_order_date)=date(fhs.encounter_datetime),1,null)" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.vl_order_date,fhs.encounter_datetime) >= 0 and fhs.vl_1_date < fhs.vl_order_date,1,null)" - } - }, - { - "type": "derived_column", - "alias": "pending_vl_order_no_result_after_4_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.vl_order_date,fhs.encounter_datetime) >= 4 and fhs.vl_1_date < fhs.vl_order_date,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) <= 26,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) <= 52,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks_and_have_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) <= 52 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) <= 52 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52 and fhs.vl_1 <= 1000,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method IN (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817)),1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_short_term_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.contraceptive_method is not null AND fhs.contraceptive_method in (190,780,907,6218,6217,5841,6717,6718,6725,8134,5274,8300),1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_long_term_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817),1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_short_term_modern_contraception_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method is not null AND fhs.contraceptive_method in (190,780,907,6218,6217,5841,6717,6718,6725,8134,5274,8300), 1, null)" - } - }, - { - "type": "derived_column", - "alias": "on_long_term_modern_contraception_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817), 1, null)" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method IN (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817) AND fhs.visit_type in (68, 55, 52, 18), 1, null)" - } - }, - { - "type": "derived_column", - "alias": "not_on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((fhs.contraceptive_method IS NULL or fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277)),1,null)" - } - }, - { - "type": "derived_column", - "alias": "not_on_modern_contraception_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((fhs.contraceptive_method IS NULL or fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277)) AND fhs.visit_type in (68, 55, 52, 18) ,1,null)" - } - }, - { - "type": "derived_column", - "alias": "in_pnc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.visit_type in (68, 55, 52, 18) ,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_art_and_not_on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((fhs.contraceptive_method IS NULL OR fhs.contraceptive_method = 1107) and fhs.cur_arv_line is not null,1,null)" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(date(fhs.modern_contraceptive_method_start_date) between '{startDate}' and '{endDate}',1,null)" - } - }, - { - "type": "derived_column", - "alias": "pregnant", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.is_pregnant is not null,1,null)" - } - }, - { - "type": "derived_column", - "alias": "pregnant_and_on_arvs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.is_pregnant is not null and fhs.cur_arv_line is not null,1,null)" - } - }, - { - "type": "derived_column", - "alias": "pregnant_and_started_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.is_pregnant is not null and date(fhs.arv_first_regimen_start_date) between '{startDate}' and '{endDate}',1,null)" - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.is_clinical_encounter=1 and fhs.prev_clinical_datetime_hiv is null,1,null)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_care_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((date(fhs.prev_clinical_datetime_hiv) between '{startDate}' and '{endDate}' or fhs.prev_clinical_datetime_hiv is null) and date(fhs.enrollment_date) between '{startDate}' and '{endDate}',1,null)" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_1 < 1000 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" - } - }, - { - "type": "derived_column", - "alias": "patients_with_vl_result", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_1_date between '{startDate}' and '{endDate}',1,null)" - } - }, - { - "type": "derived_column", - "alias": "virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_1 < 1000 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" - } - }, - { - "type": "derived_column", - "alias": "viral_load_resulted_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_1 is not null and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" - } - }, - { - "type": "derived_column", - "alias": "not_virally_suppressed_in_past_year", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_1> 1000 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" - } - }, - { - "type": "derived_column", - "alias": "on_arvs_gt_26_weeks", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) > 26,1,null)" - } - }, - { - "type": "derived_column", - "alias": "transfer_in_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.transfer_in is not null,1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_suppressed_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_1_date between '{startDate}' and '{endDate}' and fhs.vl_1 < 100,1,null)" - } - }, - { - "type": "derived_column", - "alias": "vl_unsuppressed_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(fhs.vl_1_date between '{startDate}' and '{endDate}' and fhs.vl_1 >= 1000,1,null)" - } - }, - { - "type": "derived_column", - "alias": "early_scheduled_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((date(fhs.encounter_datetime) < date(fhs.prev_rtc_date)) and fhs.encounter_datetime between '{startDate}' and '{endDate}',1,null)" - } - }, - { - "type": "derived_column", - "alias": "late_scheduled_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if((date(fhs.encounter_datetime) > date(fhs.prev_rtc_date)) and fhs.encounter_datetime between '{startDate}' and '{endDate}',1,null)" - } - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "fhs.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "fhs.location_uuid" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "fhs.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "month", - "column": "fhs.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "reporting_month", - "column": "date_format(fhs.encounter_datetime, '%m/%Y')" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fhs.encounter_datetime) >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fhs.encounter_datetime) <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.location_uuid in ?", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "round(datediff(fhs.encounter_datetime,p.birthdate)/365) >= ?", - "parameterName": "startAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "round(datediff(fhs.encounter_datetime,p.birthdate)/365) <= ?", - "parameterName": "endAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "p.gender in ?", - "parameterName": "gender" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.is_clinical_encounter = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "coalesce(fhs.death_date, fhs.out_of_care) is null", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "(fhs.next_clinical_datetime_hiv is null or DATE(fhs.next_clinical_datetime_hiv) > ?)", - "parameterName": "endDate" - } - ] + "name": "hivSummaryBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = fhs.location_id" + } + }, + { + "table": "amrs.person", + "alias": "p", + "join": { + "type": "INNER", + "joinCondition": "fhs.person_id = p.person_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "fhs.person_id" + }, + { + "type": "derived_column", + "alias": "on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.cur_arv_line is not null,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.cur_arv_line=1,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.cur_arv_line=2,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_tdf_3tc_efv_400", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.cur_arv_meds REGEXP '(802.*633.*628)|(802.*628.*633)|(628.*802.*633)|(628.*633.*802)|(633.*802.*628)|(633.*628.*802)' AND fhs.cur_arv_drugs LIKE '%6964=598%', 1, NULL) " + } + }, + { + "type": "derived_column", + "alias": "on_tdf_3tc_efv_600", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.cur_arv_meds REGEXP '(802.*633.*628)|(802.*628.*633)|(628.*802.*633)|(628.*633.*802)|(633.*802.*628)|(633.*628.*802)' AND fhs.cur_arv_drugs LIKE '%6964=38%', 1, NULL) " + } + }, + { + "type": "derived_column", + "alias": "on_tdf_3tc_dtg", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.cur_arv_meds REGEXP '(802.*9759.*628)|(802.*628.*9759)|(628.*802.*9759)|(628.*9759.*802)|(9759.*802.*628)|(9759.*628.*802)',1,NULL) " + } + }, + { + "type": "derived_column", + "alias": "newly_on_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.cur_arv_line=2 and fhs.arv_start_date between '{startDate}' and '{endDate}',1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_third_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.cur_arv_line>2,1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_relative_to_end_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.vl_1_date,'{endDate}') <= 52,1,null)" + } + }, + { + "type": "derived_column", + "alias": "no_vl_done_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.cur_arv_line is not null and (fhs.vl_1_date is null or timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) >= 52),1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_second_line_not_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_1 > 1000 and fhs.cur_arv_line =2,1,null)" + } + }, + { + "type": "derived_column", + "alias": "not_on_arvs_cd4_lte_500", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.arv_start_date is null and fhs.cd4_1 < 500,1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52 and fhs.vl_1 <= 1000,1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_past_year_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52 and fhs.vl_1 > 1000,1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_resulted >= 0 and fhs.vl_resulted_date=date(fhs.encounter_datetime),1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_resulted <= 1000 and fhs.vl_resulted_date = date(fhs.encounter_datetime),1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_done_this_encounter_gt_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_resulted > 1000 and fhs.vl_resulted_date = date(fhs.encounter_datetime),1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_ordered", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(date(fhs.vl_order_date)=date(fhs.encounter_datetime),1,null)" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.vl_order_date,fhs.encounter_datetime) >= 0 and fhs.vl_1_date < fhs.vl_order_date,1,null)" + } + }, + { + "type": "derived_column", + "alias": "pending_vl_order_no_result_after_4_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.vl_order_date,fhs.encounter_datetime) >= 4 and fhs.vl_1_date < fhs.vl_order_date,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) <= 26,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) <= 52,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) <= 52 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) <= 52 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52 and fhs.vl_1 <= 1000,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method IN (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817)),1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_short_term_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.contraceptive_method is not null AND fhs.contraceptive_method in (190,780,907,6218,6217,5841,6717,6718,6725,8134,5274,8300),1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_long_term_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817),1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_short_term_modern_contraception_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method is not null AND fhs.contraceptive_method in (190,780,907,6218,6217,5841,6717,6718,6725,8134,5274,8300), 1, null)" + } + }, + { + "type": "derived_column", + "alias": "on_long_term_modern_contraception_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817), 1, null)" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method IN (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817) AND fhs.visit_type in (68, 55, 52, 18), 1, null)" + } + }, + { + "type": "derived_column", + "alias": "not_on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((fhs.contraceptive_method IS NULL or fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277)),1,null)" + } + }, + { + "type": "derived_column", + "alias": "not_on_modern_contraception_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((fhs.contraceptive_method IS NULL or fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277)) AND fhs.visit_type in (68, 55, 52, 18) ,1,null)" + } + }, + { + "type": "derived_column", + "alias": "in_pnc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.visit_type in (68, 55, 52, 18) ,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_art_and_not_on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((fhs.contraceptive_method IS NULL OR fhs.contraceptive_method = 1107) and fhs.cur_arv_line is not null,1,null)" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(date(fhs.modern_contraceptive_method_start_date) between '{startDate}' and '{endDate}',1,null)" + } + }, + { + "type": "derived_column", + "alias": "pregnant", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.is_pregnant is not null,1,null)" + } + }, + { + "type": "derived_column", + "alias": "pregnant_and_on_arvs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.is_pregnant is not null and fhs.cur_arv_line is not null,1,null)" + } + }, + { + "type": "derived_column", + "alias": "pregnant_and_started_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.is_pregnant is not null and date(fhs.arv_first_regimen_start_date) between '{startDate}' and '{endDate}',1,null)" + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.is_clinical_encounter=1 and fhs.prev_clinical_datetime_hiv is null,1,null)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_care_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((date(fhs.prev_clinical_datetime_hiv) between '{startDate}' and '{endDate}' or fhs.prev_clinical_datetime_hiv is null) and date(fhs.enrollment_date) between '{startDate}' and '{endDate}',1,null)" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_1 < 1000 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" + } + }, + { + "type": "derived_column", + "alias": "patients_with_vl_result", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_1_date between '{startDate}' and '{endDate}',1,null)" + } + }, + { + "type": "derived_column", + "alias": "virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_1 < 1000 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" + } + }, + { + "type": "derived_column", + "alias": "viral_load_resulted_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_1 is not null and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" + } + }, + { + "type": "derived_column", + "alias": "not_virally_suppressed_in_past_year", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_1> 1000 and timestampdiff(week,fhs.vl_1_date,fhs.encounter_datetime) <= 52,1,null)" + } + }, + { + "type": "derived_column", + "alias": "on_arvs_gt_26_weeks", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(timestampdiff(week,fhs.arv_start_date,fhs.encounter_datetime) > 26,1,null)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.transfer_in is not null,1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_suppressed_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_1_date between '{startDate}' and '{endDate}' and fhs.vl_1 < 100,1,null)" + } + }, + { + "type": "derived_column", + "alias": "vl_unsuppressed_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(fhs.vl_1_date between '{startDate}' and '{endDate}' and fhs.vl_1 >= 1000,1,null)" + } + }, + { + "type": "derived_column", + "alias": "early_scheduled_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((date(fhs.encounter_datetime) < date(fhs.prev_rtc_date)) and fhs.encounter_datetime between '{startDate}' and '{endDate}',1,null)" + } + }, + { + "type": "derived_column", + "alias": "late_scheduled_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if((date(fhs.encounter_datetime) > date(fhs.prev_rtc_date)) and fhs.encounter_datetime between '{startDate}' and '{endDate}',1,null)" + } + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "fhs.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "fhs.location_uuid" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "fhs.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "fhs.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "date_format(fhs.encounter_datetime, '%m/%Y')" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fhs.encounter_datetime) >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fhs.encounter_datetime) <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.location_uuid in ?", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "round(datediff(fhs.encounter_datetime,p.birthdate)/365) >= ?", + "parameterName": "startAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "round(datediff(fhs.encounter_datetime,p.birthdate)/365) <= ?", + "parameterName": "endAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "p.gender in ?", + "parameterName": "gender" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.is_clinical_encounter = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "coalesce(fhs.death_date, fhs.out_of_care) is null", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "(fhs.next_clinical_datetime_hiv is null or DATE(fhs.next_clinical_datetime_hiv) > ?)", + "parameterName": "endDate" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/labs-and-imaging-dataset-base.json b/app/reporting-framework/json-reports/labs-and-imaging-dataset-base.json index 618974341..c1051e3e0 100644 --- a/app/reporting-framework/json-reports/labs-and-imaging-dataset-base.json +++ b/app/reporting-framework/json-reports/labs-and-imaging-dataset-base.json @@ -1,69 +1,71 @@ { - "name": "flatLabsAndImagingDataSetbase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_labs_and_imaging", - "alias": "t1" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_uuid", - "column": "t1.uuid" - }, - { - "type": "simple_column", - "alias": "vl_error_order_date", - "column": "t1.test_datetime" - }, - { - "type": "derived_column", - "alias": "ordered_vl_has_error", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when vl_error= 1 then 1 else 0 end" - } - }, - { - "type": "simple_column", - "alias": "gene_expert_image", - "column": "t1.gene_expert_image" - }, - { - "type": "simple_column", - "alias": "dst_image", - "column": "t1.dst_image" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.uuid = ?", - "parameterName": "patientUuid" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t1.test_datetime < ?", - "parameterName": "referenceDate" - } - ] + "name": "flatLabsAndImagingDataSetbase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_labs_and_imaging", + "alias": "t1" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_uuid", + "column": "t1.uuid" + }, + { + "type": "simple_column", + "alias": "vl_error_order_date", + "column": "t1.test_datetime" + }, + { + "type": "derived_column", + "alias": "ordered_vl_has_error", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when vl_error= 1 then 1 else 0 end" + } }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [{ - "column": "test_datetime", - "order": "desc" - }] - }, - "paging": { - "offSetParam":"offSetParam", - "limitParam": "limitParam" - } -} \ No newline at end of file + { + "type": "simple_column", + "alias": "gene_expert_image", + "column": "t1.gene_expert_image" + }, + { + "type": "simple_column", + "alias": "dst_image", + "column": "t1.dst_image" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.uuid = ?", + "parameterName": "patientUuid" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t1.test_datetime < ?", + "parameterName": "referenceDate" + } + ] + }, + "orderBy": { + "orderByParam": "orderByParam", + "columns": [ + { + "column": "test_datetime", + "order": "desc" + } + ] + }, + "paging": { + "offSetParam": "offSetParam", + "limitParam": "limitParam" + } +} diff --git a/app/reporting-framework/json-reports/labs-report-aggregate.json b/app/reporting-framework/json-reports/labs-report-aggregate.json index 36e443165..ca750adf1 100644 --- a/app/reporting-framework/json-reports/labs-report-aggregate.json +++ b/app/reporting-framework/json-reports/labs-report-aggregate.json @@ -1,103 +1,103 @@ { - "name": "labsReportAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "labsReportBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "labsReportBase", - "alias": "t1" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "derived_column", - "alias": "needs_vl_in_period", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct needs_vl_in_period)" - } - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t1.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t1.location_uuid" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "t1.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "month", - "column": "MONTH(encounter_datetime)" - }, - { - "type": "simple_column", - "alias": "reporting_month", - "column": "date_format(t1.encounter_datetime, '%m/%Y')" - }, - { - "type": "simple_column", - "alias": "year", - "column": "YEAR(encounter_datetime)" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "location_uuid in ?", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "coalesce(t1.death_date, out_of_care) is null", - "parameterName": "" - } - ] + "name": "labsReportAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "labsReportBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "labsReportBase", + "alias": "t1" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "derived_column", + "alias": "needs_vl_in_period", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct needs_vl_in_period)" + } + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patients-requiring-viral-load-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "location_id", + "column": "t1.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t1.location_uuid" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "t1.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "MONTH(encounter_datetime)" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "date_format(t1.encounter_datetime, '%m/%Y')" + }, + { + "type": "simple_column", + "alias": "year", + "column": "YEAR(encounter_datetime)" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "location_uuid in ?", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "coalesce(t1.death_date, out_of_care) is null", + "parameterName": "" + } + ] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patients-requiring-viral-load-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/labs-report-base.json b/app/reporting-framework/json-reports/labs-report-base.json index 9baa4ec68..20605b344 100644 --- a/app/reporting-framework/json-reports/labs-report-base.json +++ b/app/reporting-framework/json-reports/labs-report-base.json @@ -1,146 +1,146 @@ { - "name": "labsReportBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "t2" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "t2.location_uuid = l.uuid" - } - }, - { - "table": "amrs.person", - "alias": "t3", - "join": { - "type": "INNER", - "joinCondition": "t3.person_id = t2.person_id" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t2.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "LEFT", - "joinCondition": "t2.encounter_type = et.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t2.person_id = pa.person_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t2.person_id" - }, - { - "type": "derived_column", - "alias": "needs_vl_in_period", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(case when (t2.cur_arv_meds is not null and t2.vl_1 > 1000) and (timestampdiff(day,t2.vl_1_date, '{endDate}') >= 90) then true when (timestampdiff(month,t2.arv_start_date, '{endDate}') <= 12) and (t2.vl_1_date is null or timestampdiff(month,t2.vl_1_date, '{endDate}') >= 6) and (timestampdiff(month,t2.arv_start_date, '{endDate}')>=6) then true when (timestampdiff(month,t2.arv_start_date, '{endDate}') >= 12) and (t2.vl_1_date is null or timestampdiff(month,t2.vl_1_date, '{endDate}') >= 12) then true else false end,1,0)" - } - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t2.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t2.location_uuid" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "t2.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "month", - "column": "MONTH(t2.encounter_datetime)" - }, - { - "type": "simple_column", - "alias": "reporting_month", - "column": "date_format(t2.encounter_datetime, '%m/%Y')" - }, - { - "type": "simple_column", - "alias": "year", - "column": "YEAR(t2.encounter_datetime)" - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(t2.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(t2.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" - }, - { - "type": "simple_column", - "alias": "cur_meds", - "column": "t2.cur_arv_meds" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "(t2.next_clinical_datetime_hiv is null or date(t2.next_clinical_datetime_hiv) > ?)", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.location_uuid in ?", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": "coalesce(t2.death_date, t2.out_of_care) is null", - "parameterName": "" - } - ] + "name": "labsReportBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "t2" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "t2.location_uuid = l.uuid" + } + }, + { + "table": "amrs.person", + "alias": "t3", + "join": { + "type": "INNER", + "joinCondition": "t3.person_id = t2.person_id" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t2.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "LEFT", + "joinCondition": "t2.encounter_type = et.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t2.person_id = pa.person_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t2.person_id" + }, + { + "type": "derived_column", + "alias": "needs_vl_in_period", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(case when (t2.cur_arv_meds is not null and t2.vl_1 > 1000) and (timestampdiff(day,t2.vl_1_date, '{endDate}') >= 90) then true when (timestampdiff(month,t2.arv_start_date, '{endDate}') <= 12) and (t2.vl_1_date is null or timestampdiff(month,t2.vl_1_date, '{endDate}') >= 6) and (timestampdiff(month,t2.arv_start_date, '{endDate}')>=6) then true when (timestampdiff(month,t2.arv_start_date, '{endDate}') >= 12) and (t2.vl_1_date is null or timestampdiff(month,t2.vl_1_date, '{endDate}') >= 12) then true else false end,1,0)" + } + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "t2.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t2.location_uuid" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "t2.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "month", + "column": "MONTH(t2.encounter_datetime)" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "date_format(t2.encounter_datetime, '%m/%Y')" + }, + { + "type": "simple_column", + "alias": "year", + "column": "YEAR(t2.encounter_datetime)" + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(t2.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(t2.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" + }, + { + "type": "simple_column", + "alias": "cur_meds", + "column": "t2.cur_arv_meds" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "(t2.next_clinical_datetime_hiv is null or date(t2.next_clinical_datetime_hiv) > ?)", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.location_uuid in ?", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": "coalesce(t2.death_date, t2.out_of_care) is null", + "parameterName": "" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/ltfus-surge-baseline-aggregate.json b/app/reporting-framework/json-reports/ltfus-surge-baseline-aggregate.json index 691bbb8ce..23f6f88bd 100644 --- a/app/reporting-framework/json-reports/ltfus-surge-baseline-aggregate.json +++ b/app/reporting-framework/json-reports/ltfus-surge-baseline-aggregate.json @@ -1,71 +1,67 @@ { - "name": "LtfuSurgeBaselineAggregateReport", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "surgeBaselineReport", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [ - { - "dataSet": "surgeBaselineReport", - "alias": "lsb" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "lsb.location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "lsb.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "lsb.location" - }, - { - "type": "derived_column", - "alias": "is_ltfu_surge_baseline", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(lsb.is_ltfu_surge_baseline)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_uuid" - ], - "excludeParam": "excludeParam" + "name": "LtfuSurgeBaselineAggregateReport", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "surgeBaselineReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "surgeBaselineReport", + "alias": "lsb" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "lsb.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "lsb.location_id" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "join_location" - ] + { + "type": "simple_column", + "alias": "location", + "column": "lsb.location" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "is_ltfu_surge_baseline", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(lsb.is_ltfu_surge_baseline)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_uuid"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "join_location"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/ltfus-surge-baseline-base.json b/app/reporting-framework/json-reports/ltfus-surge-baseline-base.json index 91dad0a88..812275853 100644 --- a/app/reporting-framework/json-reports/ltfus-surge-baseline-base.json +++ b/app/reporting-framework/json-reports/ltfus-surge-baseline-base.json @@ -1,143 +1,143 @@ { - "name": "surgeBaselineReport", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.surge_weekly_report_dataset_frozen", - "alias": "lsbr" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = lsbr.baseline_location" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "lsbr.person_id" - }, - { - "type": "simple_column", - "alias": "is_ltfu_surge_baseline", - "column": "lsbr.is_ltfu_surge_baseline" - }, - { - "type": "simple_column", - "alias": "baseline_location", - "column": "lsbr.baseline_location" - }, - { - "type": "simple_column", - "alias": "transfer_out_date", - "column": "lsbr.transfer_out_date" - }, - { - "type": "simple_column", - "alias": "week_patient_became_active", - "column": "lsbr.week_patient_became_active" - }, - { - "type": "simple_column", - "alias": "clinical_visit_num", - "column": "lsbr.clinical_visit_num" - }, - { - "type": "simple_column", - "alias": "days_since_rtc_date", - "column": "lsbr.days_since_rtc_date" - }, - { - "type": "simple_column", - "alias": "status", - "column": "lsbr.status" - }, - { - "type": "simple_column", - "alias": "prev_status", - "column": "lsbr.prev_status" - }, - { - "type": "simple_column", - "alias": "cur_status", - "column": "lsbr.cur_status" - }, - { - "type": "simple_column", - "alias": "death_date", - "column": "lsbr.death_date" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_location_id", - "column": "lsbr.arv_first_regimen_location_id" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen", - "column": "lsbr.arv_first_regimen" - }, - { - "type": "simple_column", - "alias": "active_to_ltfu_count", - "column": "lsbr.active_to_ltfu_count" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_names", - "column": "lsbr.arv_first_regimen_names" - }, - { - "type": "simple_column", - "alias": "age", - "column": "lsbr.age" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "lsbr.gender" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "l.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "year_week = ? ", - "parameterName": "year_week" - }, - { - "filterType": "tableColumns", - "conditionExpression": " l.uuid in ?", - "parameterName": "locationUuids" - }, - { - "filterType": "tableColumns", - "conditionExpression": " lsbr.is_ltfu_surge_baseline = 1", - "parameterName": "" - } - ] + "name": "surgeBaselineReport", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.surge_weekly_report_dataset_frozen", + "alias": "lsbr" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = lsbr.baseline_location" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "lsbr.person_id" + }, + { + "type": "simple_column", + "alias": "is_ltfu_surge_baseline", + "column": "lsbr.is_ltfu_surge_baseline" + }, + { + "type": "simple_column", + "alias": "baseline_location", + "column": "lsbr.baseline_location" + }, + { + "type": "simple_column", + "alias": "transfer_out_date", + "column": "lsbr.transfer_out_date" + }, + { + "type": "simple_column", + "alias": "week_patient_became_active", + "column": "lsbr.week_patient_became_active" + }, + { + "type": "simple_column", + "alias": "clinical_visit_num", + "column": "lsbr.clinical_visit_num" + }, + { + "type": "simple_column", + "alias": "days_since_rtc_date", + "column": "lsbr.days_since_rtc_date" + }, + { + "type": "simple_column", + "alias": "status", + "column": "lsbr.status" + }, + { + "type": "simple_column", + "alias": "prev_status", + "column": "lsbr.prev_status" + }, + { + "type": "simple_column", + "alias": "cur_status", + "column": "lsbr.cur_status" + }, + { + "type": "simple_column", + "alias": "death_date", + "column": "lsbr.death_date" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_location_id", + "column": "lsbr.arv_first_regimen_location_id" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen", + "column": "lsbr.arv_first_regimen" + }, + { + "type": "simple_column", + "alias": "active_to_ltfu_count", + "column": "lsbr.active_to_ltfu_count" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_names", + "column": "lsbr.arv_first_regimen_names" + }, + { + "type": "simple_column", + "alias": "age", + "column": "lsbr.age" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "lsbr.gender" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "l.location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "year_week = ? ", + "parameterName": "year_week" + }, + { + "filterType": "tableColumns", + "conditionExpression": " l.uuid in ?", + "parameterName": "locationUuids" + }, + { + "filterType": "tableColumns", + "conditionExpression": " lsbr.is_ltfu_surge_baseline = 1", + "parameterName": "" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/lung-cancer-daily-screening-summary-aggregate.json b/app/reporting-framework/json-reports/lung-cancer-daily-screening-summary-aggregate.json index 7f8565df5..1afc51edf 100644 --- a/app/reporting-framework/json-reports/lung-cancer-daily-screening-summary-aggregate.json +++ b/app/reporting-framework/json-reports/lung-cancer-daily-screening-summary-aggregate.json @@ -1,237 +1,237 @@ { - "name": "lungCancerDailySummaryAggregate", - "version": "1.0", - "tag": "lung_cancer_summary_aggregate", - "uses": [ - { - "name": "lungCancerMonthlySummaryBase", - "version": "1.0", - "type": "dataset_def" + "name": "lungCancerDailySummaryAggregate", + "version": "1.0", + "tag": "lung_cancer_summary_aggregate", + "uses": [ + { + "name": "lungCancerMonthlySummaryBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "lungCancerMonthlySummaryBase", + "alias": "lcsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_name", + "column": "location_name" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "location_uuid" + }, + { + "type": "derived_column", + "alias": "encounter_datetime", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(lcsd.encounter_datetime, '%d-%m-%Y')" } - ], - "sources": [ - { - "dataSet": "lungCancerMonthlySummaryBase", - "alias": "lcsd" + }, + + { + "type": "derived_column", + "alias": "total_lung_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(person_id)" } - ], + }, + { + "type": "derived_column", + "alias": "walk_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(walk_in)" + } + }, + { + "type": "derived_column", + "alias": "referred_from_clinic", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(referred_from_clinic)" + } + }, + { + "type": "derived_column", + "alias": "cigarette_smoking", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(cigarette_smoking)" + } + }, + { + "type": "derived_column", + "alias": "tobacco_use", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(tobacco_use)" + } + }, + { + "type": "derived_column", + "alias": "chemical_exposure", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(chemical_exposure)" + } + }, + { + "type": "derived_column", + "alias": "asbestos_exposure", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(asbestos_exposure)" + } + }, + { + "type": "derived_column", + "alias": "hiv_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hiv_positive)" + } + }, + { + "type": "derived_column", + "alias": "hiv_negative", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hiv_negative)" + } + }, + { + "type": "derived_column", + "alias": "hiv_status_unknown", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hiv_status_unknown)" + } + }, + { + "type": "derived_column", + "alias": "previously_treated_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(previously_treated_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "not_previously_treated_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(not_previously_treated_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "normal_xray_results", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(normal_xray_results)" + } + }, + { + "type": "derived_column", + "alias": "abnormal_xray_results", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(abnormal_xray_results)" + } + }, + { + "type": "derived_column", + "alias": "indication_of_lung_mass_from_ct_findings", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(indication_of_lung_mass_from_ct_findings)" + } + }, + { + "type": "derived_column", + "alias": "indication_of_mediastinal_mass_from_ct_findings", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(indication_of_mediastinal_mass_from_ct_findings)" + } + }, + { + "type": "derived_column", + "alias": "indication_of_pleural_mass_from_ct_findings", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(indication_of_pleural_mass_from_ct_findings)" + } + }, + { + "type": "derived_column", + "alias": "biopsy_done", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(biopsy_done)" + } + }, + { + "type": "derived_column", + "alias": "biopsy_not_done", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(biopsy_not_done)" + } + }, + { + "type": "derived_column", + "alias": "non_cancer_respiratory_disease", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(non_cancer_respiratory_disease)" + } + }, + { + "type": "derived_column", + "alias": "non_small_cell_lung_cancer", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(non_small_cell_lung_cancer)" + } + }, + { + "type": "derived_column", + "alias": "small_cell_lung_cancer", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(small_cell_lung_cancer)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", "columns": [ - { - "type": "simple_column", - "alias": "location_name", - "column": "location_name" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "location_uuid" - }, - { - "type": "derived_column", - "alias": "encounter_datetime", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(lcsd.encounter_datetime, '%d-%m-%Y')" - } - }, - - { - "type": "derived_column", - "alias": "total_lung_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(person_id)" - } - }, - { - "type": "derived_column", - "alias": "walk_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(walk_in)" - } - }, - { - "type": "derived_column", - "alias": "referred_from_clinic", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(referred_from_clinic)" - } - }, - { - "type": "derived_column", - "alias": "cigarette_smoking", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(cigarette_smoking)" - } - }, - { - "type": "derived_column", - "alias": "tobacco_use", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(tobacco_use)" - } - }, - { - "type": "derived_column", - "alias": "chemical_exposure", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(chemical_exposure)" - } - }, - { - "type": "derived_column", - "alias": "asbestos_exposure", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(asbestos_exposure)" - } - }, - { - "type": "derived_column", - "alias": "hiv_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hiv_positive)" - } - }, - { - "type": "derived_column", - "alias": "hiv_negative", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hiv_negative)" - } - }, - { - "type": "derived_column", - "alias": "hiv_status_unknown", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hiv_status_unknown)" - } - }, - { - "type": "derived_column", - "alias": "previously_treated_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(previously_treated_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "not_previously_treated_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(not_previously_treated_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "normal_xray_results", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(normal_xray_results)" - } - }, - { - "type": "derived_column", - "alias": "abnormal_xray_results", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(abnormal_xray_results)" - } - }, - { - "type": "derived_column", - "alias": "indication_of_lung_mass_from_ct_findings", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(indication_of_lung_mass_from_ct_findings)" - } - }, - { - "type": "derived_column", - "alias": "indication_of_mediastinal_mass_from_ct_findings", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(indication_of_mediastinal_mass_from_ct_findings)" - } - }, - { - "type": "derived_column", - "alias": "indication_of_pleural_mass_from_ct_findings", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(indication_of_pleural_mass_from_ct_findings)" - } - }, - { - "type": "derived_column", - "alias": "biopsy_done", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(biopsy_done)" - } - }, - { - "type": "derived_column", - "alias": "biopsy_not_done", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(biopsy_not_done)" - } - }, - { - "type": "derived_column", - "alias": "non_cancer_respiratory_disease", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(non_cancer_respiratory_disease)" - } - }, - { - "type": "derived_column", - "alias": "non_small_cell_lung_cancer", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(non_small_cell_lung_cancer)" - } - }, - { - "type": "derived_column", - "alias": "small_cell_lung_cancer", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(small_cell_lung_cancer)" - } - } + "location_id", + "date_format(lcsd.encounter_datetime, '%d-%m-%Y')" ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id", - "date_format(lcsd.encounter_datetime, '%d-%m-%Y')" - ], - "excludeParam": "excludeParam" - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "lung_cancer_patient_list_template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "lung_cancer_patient_list_template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/lung-cancer-monthly-screening-summary-aggregate.json b/app/reporting-framework/json-reports/lung-cancer-monthly-screening-summary-aggregate.json index 3f8cb9f1b..a72a3425f 100644 --- a/app/reporting-framework/json-reports/lung-cancer-monthly-screening-summary-aggregate.json +++ b/app/reporting-framework/json-reports/lung-cancer-monthly-screening-summary-aggregate.json @@ -1,238 +1,238 @@ { - "name": "lungCancerMonthlySummaryAggregate", - "version": "1.0", - "tag": "lung_cancer_summary_aggregate", - "uses": [ - { - "name": "lungCancerMonthlySummaryBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "lungCancerMonthlySummaryBase", - "alias": "lcsd" - } - ], + "name": "lungCancerMonthlySummaryAggregate", + "version": "1.0", + "tag": "lung_cancer_summary_aggregate", + "uses": [ + { + "name": "lungCancerMonthlySummaryBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "lungCancerMonthlySummaryBase", + "alias": "lcsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_name", + "column": "location_name" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "location_uuid" + }, + { + "type": "derived_column", + "alias": "encounter_datetime", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(lcsd.encounter_datetime, '%m-%Y')" + } + }, + + { + "type": "derived_column", + "alias": "total_lung_screened", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(person_id)" + } + }, + { + "type": "derived_column", + "alias": "walk_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(walk_in)" + } + }, + { + "type": "derived_column", + "alias": "referred_from_clinic", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(referred_from_clinic)" + } + }, + { + "type": "derived_column", + "alias": "cigarette_smoking", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(cigarette_smoking)" + } + }, + { + "type": "derived_column", + "alias": "uses_tobacco", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(uses_tobacco)" + } + }, + { + "type": "derived_column", + "alias": "chemical_exposure", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(chemical_exposure)" + } + }, + { + "type": "derived_column", + "alias": "asbestos_exposure", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(asbestos_exposure)" + } + }, + { + "type": "derived_column", + "alias": "hiv_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hiv_positive)" + } + }, + { + "type": "derived_column", + "alias": "hiv_negative", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hiv_negative)" + } + }, + { + "type": "derived_column", + "alias": "hiv_status_unknown", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hiv_status_unknown)" + } + }, + { + "type": "derived_column", + "alias": "previously_treated_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(previously_treated_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "not_previously_treated_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(not_previously_treated_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "normal_xray_results", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(normal_xray_results)" + } + }, + { + "type": "derived_column", + "alias": "abnormal_xray_results", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(abnormal_xray_results)" + } + }, + { + "type": "derived_column", + "alias": "biopsy_done", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(biopsy_done)" + } + }, + { + "type": "derived_column", + "alias": "biopsy_not_done", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(biopsy_not_done)" + } + }, + { + "type": "derived_column", + "alias": "indication_of_lung_mass_from_ct_findings", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(indication_of_lung_mass_from_ct_findings)" + } + }, + { + "type": "derived_column", + "alias": "indication_of_mediastinal_mass_from_ct_findings", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(indication_of_mediastinal_mass_from_ct_findings)" + } + }, + { + "type": "derived_column", + "alias": "indication_of_pleural_mass_from_ct_findings", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(indication_of_pleural_mass_from_ct_findings)" + } + }, + { + "type": "derived_column", + "alias": "non_cancer_respiratory_disease", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(non_cancer_respiratory_disease)" + } + }, + { + "type": "derived_column", + "alias": "non_small_cell_lung_cancer", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(non_small_cell_lung_cancer)" + } + }, + { + "type": "derived_column", + "alias": "small_cell_lung_cancer", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(small_cell_lung_cancer)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", "columns": [ - { - "type": "simple_column", - "alias": "location_name", - "column": "location_name" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "location_uuid" - }, - { - "type": "derived_column", - "alias": "encounter_datetime", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(lcsd.encounter_datetime, '%m-%Y')" - } - }, - - { - "type": "derived_column", - "alias": "total_lung_screened", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(person_id)" - } - }, - { - "type": "derived_column", - "alias": "walk_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(walk_in)" - } - }, - { - "type": "derived_column", - "alias": "referred_from_clinic", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(referred_from_clinic)" - } - }, - { - "type": "derived_column", - "alias": "cigarette_smoking", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(cigarette_smoking)" - } - }, - { - "type": "derived_column", - "alias": "uses_tobacco", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(uses_tobacco)" - } - }, - { - "type": "derived_column", - "alias": "chemical_exposure", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(chemical_exposure)" - } - }, - { - "type": "derived_column", - "alias": "asbestos_exposure", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(asbestos_exposure)" - } - }, - { - "type": "derived_column", - "alias": "hiv_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hiv_positive)" - } - }, - { - "type": "derived_column", - "alias": "hiv_negative", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hiv_negative)" - } - }, - { - "type": "derived_column", - "alias": "hiv_status_unknown", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hiv_status_unknown)" - } - }, - { - "type": "derived_column", - "alias": "previously_treated_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(previously_treated_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "not_previously_treated_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(not_previously_treated_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "normal_xray_results", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(normal_xray_results)" - } - }, - { - "type": "derived_column", - "alias": "abnormal_xray_results", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(abnormal_xray_results)" - } - }, - { - "type": "derived_column", - "alias": "biopsy_done", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(biopsy_done)" - } - }, - { - "type": "derived_column", - "alias": "biopsy_not_done", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(biopsy_not_done)" - } - }, - { - "type": "derived_column", - "alias": "indication_of_lung_mass_from_ct_findings", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(indication_of_lung_mass_from_ct_findings)" - } - }, - { - "type": "derived_column", - "alias": "indication_of_mediastinal_mass_from_ct_findings", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(indication_of_mediastinal_mass_from_ct_findings)" - } - }, - { - "type": "derived_column", - "alias": "indication_of_pleural_mass_from_ct_findings", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(indication_of_pleural_mass_from_ct_findings)" - } - }, - { - "type": "derived_column", - "alias": "non_cancer_respiratory_disease", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(non_cancer_respiratory_disease)" - } - }, - { - "type": "derived_column", - "alias": "non_small_cell_lung_cancer", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(non_small_cell_lung_cancer)" - } - }, - { - "type": "derived_column", - "alias": "small_cell_lung_cancer", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(small_cell_lung_cancer)" - } - } + "location_id", + "year(lcsd.encounter_datetime)", + "month(lcsd.encounter_datetime)" ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id", - "year(lcsd.encounter_datetime)", - "month(lcsd.encounter_datetime)" - ], - "excludeParam": "excludeParam" - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "lung_cancer_patient_list_template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "lung_cancer_patient_list_template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/lung-cancer-patient-list-template.json b/app/reporting-framework/json-reports/lung-cancer-patient-list-template.json index deeda5582..51882a018 100644 --- a/app/reporting-framework/json-reports/lung-cancer-patient-list-template.json +++ b/app/reporting-framework/json-reports/lung-cancer-patient-list-template.json @@ -1,100 +1,100 @@ { - "name": "lung_cancer_patient_list_template", - "version": "1.0", - "tag": "lung_cancer_patient_list_template", - "description": "lung Cancer patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "INNER", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0)" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "t1.birthdate" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "hiv_status", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when hiv_status=1 then 'HIV Negative' when hiv_status=2 then 'HIV Positive' when hiv_status=3 then 'Unknown' else NULL end" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "simple_column", - "alias": "given_name", - "column": "person_name.given_name" - }, - { - "type": "simple_column", - "alias": "family_name", - "column": "person_name.family_name" - }, - { - "type": "simple_column", - "alias": "middle_name", - "column": "person_name.middle_name" - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "lung_cancer_patient_list_template", + "version": "1.0", + "tag": "lung_cancer_patient_list_template", + "description": "lung Cancer patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "INNER", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0)" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "t1.birthdate" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "hiv_status", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when hiv_status=1 then 'HIV Negative' when hiv_status=2 then 'HIV Positive' when hiv_status=3 then 'Unknown' else NULL end" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "simple_column", + "alias": "given_name", + "column": "person_name.given_name" + }, + { + "type": "simple_column", + "alias": "family_name", + "column": "person_name.family_name" + }, + { + "type": "simple_column", + "alias": "middle_name", + "column": "person_name.middle_name" + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/lung-cancer-treatment-patient-list-template.json b/app/reporting-framework/json-reports/lung-cancer-treatment-patient-list-template.json index aba838f65..0ef9a86c0 100644 --- a/app/reporting-framework/json-reports/lung-cancer-treatment-patient-list-template.json +++ b/app/reporting-framework/json-reports/lung-cancer-treatment-patient-list-template.json @@ -1,107 +1,108 @@ { - "name": "lung_cancer_treatment_patient_list_template", - "version": "1.0", - "tag": "lung_cancer_treatment_patient_list_template", - "description": "Lung Cancer Treatment patient list template", - "sources": [{ - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "INNER", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL OR person_name.voided = 0)" - } - }, - { - "table": "amrs.person", - "alias": "person", - "join": { - "type": "inner", - "joinCondition": "flct.person_id = person.person_id and (person.voided is null OR person.voided = 0)" - - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL OR id.voided = 0)" - } - } - ], - "columns": [{ - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "t1.birthdate" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "hiv_status", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when hiv_status=1 then 'HIV Negative' when hiv_status=2 then 'HIV Positive' when hiv_status=3 then 'Unknown' else NULL end" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "simple_column", - "alias": "given_name", - "column": "person_name.given_name" - }, - { - "type": "simple_column", - "alias": "family_name", - "column": "person_name.family_name" - }, - { - "type": "simple_column", - "alias": "middle_name", - "column": "person_name.middle_name" - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - } - ], - "groupBy": { - "columns": ["t1.person_id"] + "name": "lung_cancer_treatment_patient_list_template", + "version": "1.0", + "tag": "lung_cancer_treatment_patient_list_template", + "description": "Lung Cancer Treatment patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "INNER", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL OR person_name.voided = 0)" + } + }, + { + "table": "amrs.person", + "alias": "person", + "join": { + "type": "inner", + "joinCondition": "flct.person_id = person.person_id and (person.voided is null OR person.voided = 0)" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL OR id.voided = 0)" + } } + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "t1.birthdate" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "hiv_status", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when hiv_status=1 then 'HIV Negative' when hiv_status=2 then 'HIV Positive' when hiv_status=3 then 'Unknown' else NULL end" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "simple_column", + "alias": "given_name", + "column": "person_name.given_name" + }, + { + "type": "simple_column", + "alias": "family_name", + "column": "person_name.family_name" + }, + { + "type": "simple_column", + "alias": "middle_name", + "column": "person_name.middle_name" + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } } diff --git a/app/reporting-framework/json-reports/lung-cancer-treatment-summary-base.json b/app/reporting-framework/json-reports/lung-cancer-treatment-summary-base.json index b1ccd3594..85f2da2de 100644 --- a/app/reporting-framework/json-reports/lung-cancer-treatment-summary-base.json +++ b/app/reporting-framework/json-reports/lung-cancer-treatment-summary-base.json @@ -3,7 +3,8 @@ "version": "1.0", "tag": "lung_cancer_treatment_summary_base", "uses": [], - "sources": [{ + "sources": [ + { "table": "etl.flat_lung_cancer_treatment", "alias": "flct" }, @@ -64,7 +65,8 @@ } } ], - "columns": [{ + "columns": [ + { "type": "simple_column", "alias": "person_id", "column": "flct.person_id" @@ -301,7 +303,8 @@ ], "filters": { "conditionJoinOperator": "and", - "conditions": [{ + "conditions": [ + { "filterType": "tableColumns", "conditionExpression": "flct.age >= ?", "parameterName": "startAge" @@ -349,4 +352,4 @@ "DATE_FORMAT(flct.encounter_datetime, '%D-%M-%Y')" ] } -} \ No newline at end of file +} diff --git a/app/reporting-framework/json-reports/main-dataset-aggregate-age-disaggregation.json b/app/reporting-framework/json-reports/main-dataset-aggregate-age-disaggregation.json index c1ea93f70..f61ecdcb5 100755 --- a/app/reporting-framework/json-reports/main-dataset-aggregate-age-disaggregation.json +++ b/app/reporting-framework/json-reports/main-dataset-aggregate-age-disaggregation.json @@ -1,216 +1,207 @@ { - "name": "mainDatasetAggregateAgeDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "mainDataSetBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "mainDataSetBase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "current_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_on_art)" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "enrolled_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.enrolled_this_month)" - } - }, - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "derived_column", - "alias": "pre_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.pre_art)" - } - }, - { - "type": "derived_column", - "alias": "current_in_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_in_care)" - } - }, - { - "type": "derived_column", - "alias": "active_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.active_on_art)" - } - }, - { - "type": "derived_column", - "alias": "on_ctx_prophylaxis", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_ctx_prophylaxis)" - } - }, - { - "type": "derived_column", - "alias": "screened_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.screened_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_this_visit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_this_visit_this_month)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_positive)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_positive)" - } - }, - { - "type": "derived_column", - "alias": "started_ipt", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_ipt)" - } - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.completed_ipt_past_12_months)" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_modern_contraception)" - } - }, - { - "type": "derived_column", - "alias": "f_gte_18_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.f_gte_18_visits)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "age_range", - "location_id" - ], - "excludeParam": "excludeParam" - }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "gender", - "join_location" - ], - "joinColumnParam": "joinColumnParam", - "disaggregationColumns": [ - "age_range" - ] - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "name": "mainDatasetAggregateAgeDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "mainDataSetBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "mainDataSetBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "current_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_on_art)" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "enrolled_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.enrolled_this_month)" + } + }, + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "derived_column", + "alias": "pre_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.pre_art)" + } + }, + { + "type": "derived_column", + "alias": "current_in_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_in_care)" + } + }, + { + "type": "derived_column", + "alias": "active_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.active_on_art)" + } + }, + { + "type": "derived_column", + "alias": "on_ctx_prophylaxis", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_ctx_prophylaxis)" + } + }, + { + "type": "derived_column", + "alias": "screened_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.screened_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_this_visit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_this_visit_this_month)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_positive)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_positive)" + } + }, + { + "type": "derived_column", + "alias": "started_ipt", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_ipt)" + } + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.completed_ipt_past_12_months)" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_modern_contraception)" + } + }, + { + "type": "derived_column", + "alias": "f_gte_18_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.f_gte_18_visits)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["age_range", "location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "gender", "join_location"], + "joinColumnParam": "joinColumnParam", + "disaggregationColumns": ["age_range"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/main-dataset-aggregate-age15-disaggregation.json b/app/reporting-framework/json-reports/main-dataset-aggregate-age15-disaggregation.json index 326e3de8d..56ed258c0 100755 --- a/app/reporting-framework/json-reports/main-dataset-aggregate-age15-disaggregation.json +++ b/app/reporting-framework/json-reports/main-dataset-aggregate-age15-disaggregation.json @@ -1,200 +1,191 @@ { - "name": "mainDatasetAggregateAge15Disaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "mainDataSetBaseAge15", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "mainDataSetBaseAge15", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "enrolled_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.enrolled_this_month)" - } - }, - { - "type": "derived_column", - "alias": "pre_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.pre_art)" - } - }, - { - "type": "derived_column", - "alias": "current_in_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_in_care)" - } - }, - { - "type": "derived_column", - "alias": "active_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.active_on_art)" - } - }, - { - "type": "derived_column", - "alias": "on_ctx_prophylaxis", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_ctx_prophylaxis)" - } - }, - { - "type": "derived_column", - "alias": "screened_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.screened_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_this_visit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_this_visit_this_month)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_positive)" - } - }, - { - "type": "derived_column", - "alias": "started_ipt", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_ipt)" - } - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.completed_ipt_past_12_months)" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_modern_contraception)" - } - }, - { - "type": "derived_column", - "alias": "f_gte_18_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.f_gte_18_visits)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "age_range", - "location_id" - ], - "excludeParam": "excludeParam" - }, - "transFormDirectives": { - "joinColumn": "location_id", - "joinColumnParam": "joinColumnParam", - "skipColumns": [ - "location_uuid", - "gender", - "join_location" - ], - "disaggregationColumns": [ - "age_range" - ] - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "name": "mainDatasetAggregateAge15Disaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "mainDataSetBaseAge15", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "mainDataSetBaseAge15", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "enrolled_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.enrolled_this_month)" + } + }, + { + "type": "derived_column", + "alias": "pre_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.pre_art)" + } + }, + { + "type": "derived_column", + "alias": "current_in_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_in_care)" + } + }, + { + "type": "derived_column", + "alias": "active_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.active_on_art)" + } + }, + { + "type": "derived_column", + "alias": "on_ctx_prophylaxis", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_ctx_prophylaxis)" + } + }, + { + "type": "derived_column", + "alias": "screened_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.screened_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_this_visit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_this_visit_this_month)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_positive)" + } + }, + { + "type": "derived_column", + "alias": "started_ipt", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_ipt)" + } + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.completed_ipt_past_12_months)" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_modern_contraception)" + } + }, + { + "type": "derived_column", + "alias": "f_gte_18_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.f_gte_18_visits)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["age_range", "location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "joinColumnParam": "joinColumnParam", + "skipColumns": ["location_uuid", "gender", "join_location"], + "disaggregationColumns": ["age_range"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/main-dataset-aggregate-age18-disaggregation.json b/app/reporting-framework/json-reports/main-dataset-aggregate-age18-disaggregation.json index 14029899b..cd1006cc3 100755 --- a/app/reporting-framework/json-reports/main-dataset-aggregate-age18-disaggregation.json +++ b/app/reporting-framework/json-reports/main-dataset-aggregate-age18-disaggregation.json @@ -1,200 +1,191 @@ { - "name": "mainDatasetAggregateAgeDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "mainDataSetBaseAge18", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "mainDataSetBaseAge18", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "enrolled_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.enrolled_this_month)" - } - }, - { - "type": "derived_column", - "alias": "pre_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.pre_art)" - } - }, - { - "type": "derived_column", - "alias": "current_in_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_in_care)" - } - }, - { - "type": "derived_column", - "alias": "active_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.active_on_art)" - } - }, - { - "type": "derived_column", - "alias": "on_ctx_prophylaxis", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_ctx_prophylaxis)" - } - }, - { - "type": "derived_column", - "alias": "screened_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.screened_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_this_visit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_this_visit_this_month)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_positive)" - } - }, - { - "type": "derived_column", - "alias": "started_ipt", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_ipt)" - } - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.completed_ipt_past_12_months)" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_modern_contraception)" - } - }, - { - "type": "derived_column", - "alias": "f_gte_18_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.f_gte_18_visits)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "age_range", - "location_id" - ], - "excludeParam": "excludeParam" - }, - "transFormDirectives": { - "joinColumn": "location_id", - "joinColumnParam": "joinColumnParam", - "skipColumns": [ - "location_uuid", - "gender", - "join_location" - ], - "disaggregationColumns": [ - "age_range" - ] - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "name": "mainDatasetAggregateAgeDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "mainDataSetBaseAge18", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "mainDataSetBaseAge18", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "enrolled_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.enrolled_this_month)" + } + }, + { + "type": "derived_column", + "alias": "pre_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.pre_art)" + } + }, + { + "type": "derived_column", + "alias": "current_in_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_in_care)" + } + }, + { + "type": "derived_column", + "alias": "active_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.active_on_art)" + } + }, + { + "type": "derived_column", + "alias": "on_ctx_prophylaxis", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_ctx_prophylaxis)" + } + }, + { + "type": "derived_column", + "alias": "screened_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.screened_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_this_visit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_this_visit_this_month)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_positive)" + } + }, + { + "type": "derived_column", + "alias": "started_ipt", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_ipt)" + } + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.completed_ipt_past_12_months)" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_modern_contraception)" + } + }, + { + "type": "derived_column", + "alias": "f_gte_18_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.f_gte_18_visits)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["age_range", "location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "joinColumnParam": "joinColumnParam", + "skipColumns": ["location_uuid", "gender", "join_location"], + "disaggregationColumns": ["age_range"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/main-dataset-aggregate-bluecard.json b/app/reporting-framework/json-reports/main-dataset-aggregate-bluecard.json index dbfbd8d03..be5456c13 100755 --- a/app/reporting-framework/json-reports/main-dataset-aggregate-bluecard.json +++ b/app/reporting-framework/json-reports/main-dataset-aggregate-bluecard.json @@ -1,216 +1,206 @@ { - "name": "mainDatasetAggregateBlueCard", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "mainDataSetBaseBlueCard", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "mainDataSetBaseBlueCard", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "current_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_on_art)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.enrolled_this_month)" - } - }, - { - "type": "derived_column", - "alias": "pre_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.pre_art)" - } - }, - { - "type": "derived_column", - "alias": "current_in_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_in_care)" - } - }, - { - "type": "derived_column", - "alias": "active_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.active_on_art)" - } - }, - { - "type": "derived_column", - "alias": "art_revisit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.art_revisit_this_month)" - } - }, - { - "type": "derived_column", - "alias": "on_ctx_prophylaxis", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_ctx_prophylaxis)" - } - }, - { - "type": "derived_column", - "alias": "screened_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.screened_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_this_visit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_this_visit_this_month)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_positive)" - } - }, - { - "type": "derived_column", - "alias": "started_ipt", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_ipt)" - } - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.completed_ipt_past_12_months)" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_modern_contraception)" - } - }, - { - "type": "derived_column", - "alias": "f_gte_18_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.f_gte_18_visits)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "gender", - "age_range", - "location_id" - ], - "excludeParam": "excludeParam" - }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "join_location" - ], - "disaggregationColumns": [ - "gender", - "age_range" - ] - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "name": "mainDatasetAggregateBlueCard", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "mainDataSetBaseBlueCard", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "mainDataSetBaseBlueCard", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "current_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_on_art)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.enrolled_this_month)" + } + }, + { + "type": "derived_column", + "alias": "pre_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.pre_art)" + } + }, + { + "type": "derived_column", + "alias": "current_in_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_in_care)" + } + }, + { + "type": "derived_column", + "alias": "active_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.active_on_art)" + } + }, + { + "type": "derived_column", + "alias": "art_revisit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.art_revisit_this_month)" + } + }, + { + "type": "derived_column", + "alias": "on_ctx_prophylaxis", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_ctx_prophylaxis)" + } + }, + { + "type": "derived_column", + "alias": "screened_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.screened_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_this_visit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_this_visit_this_month)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_positive)" + } + }, + { + "type": "derived_column", + "alias": "started_ipt", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_ipt)" + } + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.completed_ipt_past_12_months)" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_modern_contraception)" + } + }, + { + "type": "derived_column", + "alias": "f_gte_18_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.f_gte_18_visits)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["gender", "age_range", "location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "join_location"], + "disaggregationColumns": ["gender", "age_range"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/main-dataset-aggregate-no-disaggregation.json b/app/reporting-framework/json-reports/main-dataset-aggregate-no-disaggregation.json index efbf61f0f..ed162d932 100755 --- a/app/reporting-framework/json-reports/main-dataset-aggregate-no-disaggregation.json +++ b/app/reporting-framework/json-reports/main-dataset-aggregate-no-disaggregation.json @@ -1,422 +1,415 @@ { - "name": "mainDatasetAggregateNoDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "mainDataSetBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "mainDataSetBase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "enrolled_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.enrolled_this_month)" - } - }, - { - "type": "derived_column", - "alias": "pre_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.pre_art)" - } - }, - { - "type": "derived_column", - "alias": "started_art_pregnant", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_art_pregnant)" - } - }, - { - "type": "derived_column", - "alias": "art_revisit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.art_revisit_this_month)" - } - }, - { - "type": "derived_column", - "alias": "started_art_and_has_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_art_and_has_tb)" - } - }, - { - "type": "derived_column", - "alias": "current_in_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_in_care)" - } - }, - { - "type": "derived_column", - "alias": "active_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.active_on_art)" - } - }, - { - "type": "derived_column", - "alias": "on_ctx_prophylaxis", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_ctx_prophylaxis)" - } - }, - { - "type": "derived_column", - "alias": "screened_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.screened_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_this_visit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_this_visit_this_month)" - } - }, - { - "type": "derived_column", - "alias": "current_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_on_art)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_positive)" - } - }, - { - "type": "derived_column", - "alias": "started_ipt", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_ipt)" - } - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.completed_ipt_past_12_months)" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_modern_contraception)" - } - }, - { - "type": "derived_column", - "alias": "f_gte_18_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.f_gte_18_visits)" - } - }, - { - "type": "derived_column", - "alias": "scheduled_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.scheduled_visits)" - } - }, - { - "type": "derived_column", - "alias": "unscheduled_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.unscheduled_visits)" - } - }, - { - "type": "derived_column", - "alias": "total_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.total_visits)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_art_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_on_art_this_month)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_vl_suppressed_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_vl_suppressed_this_month)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_active_on_art_12_month_cohort_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_active_on_art_12_month_cohort_this_month)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_presumed_tb_positive_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_presumed_tb_positive_this_month)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_started_tb_tx_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_started_tb_tx_this_month)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_tb_tx_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_on_tb_tx_this_month)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_completed_tb_tx", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_completed_tb_tx)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_stopped_tb_tx", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_stopped_tb_tx)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_tb_tx_transferred_out", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_on_tb_tx_transferred_out)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_tb_tx_ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_on_tb_tx_ltfu)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_tb_tx_dead", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_on_tb_tx_dead)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_modern_contraception_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_on_modern_contraception_this_month)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_country_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_country_this_month)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_county_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_county_this_month)" - } - }, - { - "type": "derived_column", - "alias": "travelled_outside_last_3_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.travelled_outside_last_3_months)" - } - }, - { - "type": "derived_column", - "alias": "travelled_outside_last_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.travelled_outside_last_6_months)" - } - }, - { - "type": "derived_column", - "alias": "travelled_outside_last_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.travelled_outside_last_12_months)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_this_month_kenya", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_this_month_kenya)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_this_month_uganda", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_this_month_uganda)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_this_month_other", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_this_month_other)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.is_cross_border_this_month)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" - }, - "transFormDirectives": { - "joinColumn": "location_id", - "joinColumnParam": "joinColumnParam", - "skipColumns": [ - "location_uuid", - "gender", - "age_range", - "join_location" - ], - "disaggregationColumns": [] - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "name": "mainDatasetAggregateNoDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "mainDataSetBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "mainDataSetBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "enrolled_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.enrolled_this_month)" + } + }, + { + "type": "derived_column", + "alias": "pre_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.pre_art)" + } + }, + { + "type": "derived_column", + "alias": "started_art_pregnant", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_art_pregnant)" + } + }, + { + "type": "derived_column", + "alias": "art_revisit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.art_revisit_this_month)" + } + }, + { + "type": "derived_column", + "alias": "started_art_and_has_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_art_and_has_tb)" + } + }, + { + "type": "derived_column", + "alias": "current_in_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_in_care)" + } + }, + { + "type": "derived_column", + "alias": "active_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.active_on_art)" + } + }, + { + "type": "derived_column", + "alias": "on_ctx_prophylaxis", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_ctx_prophylaxis)" + } + }, + { + "type": "derived_column", + "alias": "screened_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.screened_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_this_visit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_this_visit_this_month)" + } + }, + { + "type": "derived_column", + "alias": "current_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_on_art)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_positive)" + } + }, + { + "type": "derived_column", + "alias": "started_ipt", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_ipt)" + } + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.completed_ipt_past_12_months)" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_modern_contraception)" + } + }, + { + "type": "derived_column", + "alias": "f_gte_18_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.f_gte_18_visits)" + } + }, + { + "type": "derived_column", + "alias": "scheduled_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.scheduled_visits)" + } + }, + { + "type": "derived_column", + "alias": "unscheduled_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.unscheduled_visits)" + } + }, + { + "type": "derived_column", + "alias": "total_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.total_visits)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_art_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_on_art_this_month)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_vl_suppressed_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_vl_suppressed_this_month)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_active_on_art_12_month_cohort_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_active_on_art_12_month_cohort_this_month)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_presumed_tb_positive_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_presumed_tb_positive_this_month)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_started_tb_tx_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_started_tb_tx_this_month)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_tb_tx_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_on_tb_tx_this_month)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_completed_tb_tx", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_completed_tb_tx)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_stopped_tb_tx", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_stopped_tb_tx)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_tb_tx_transferred_out", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_on_tb_tx_transferred_out)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_tb_tx_ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_on_tb_tx_ltfu)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_tb_tx_dead", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_on_tb_tx_dead)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_modern_contraception_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_on_modern_contraception_this_month)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_country_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_country_this_month)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_county_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_county_this_month)" + } + }, + { + "type": "derived_column", + "alias": "travelled_outside_last_3_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.travelled_outside_last_3_months)" + } + }, + { + "type": "derived_column", + "alias": "travelled_outside_last_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.travelled_outside_last_6_months)" + } + }, + { + "type": "derived_column", + "alias": "travelled_outside_last_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.travelled_outside_last_12_months)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_this_month_kenya", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_this_month_kenya)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_this_month_uganda", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_this_month_uganda)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_this_month_other", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_this_month_other)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.is_cross_border_this_month)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "joinColumnParam": "joinColumnParam", + "skipColumns": ["location_uuid", "gender", "age_range", "join_location"], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/main-dataset-aggregate.json b/app/reporting-framework/json-reports/main-dataset-aggregate.json index 4278245cd..2597a9b0b 100755 --- a/app/reporting-framework/json-reports/main-dataset-aggregate.json +++ b/app/reporting-framework/json-reports/main-dataset-aggregate.json @@ -1,216 +1,206 @@ { - "name": "mainDatasetAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "mainDataSetBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "mainDataSetBase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "current_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_on_art)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.enrolled_this_month)" - } - }, - { - "type": "derived_column", - "alias": "pre_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.pre_art)" - } - }, - { - "type": "derived_column", - "alias": "current_in_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.current_in_care)" - } - }, - { - "type": "derived_column", - "alias": "active_on_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.active_on_art)" - } - }, - { - "type": "derived_column", - "alias": "on_ctx_prophylaxis", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_ctx_prophylaxis)" - } - }, - { - "type": "derived_column", - "alias": "screened_for_tb", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.screened_for_tb)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_this_visit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_this_visit_this_month)" - } - }, - { - "type": "derived_column", - "alias": "tb_screened_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.tb_screened_positive)" - } - }, - { - "type": "derived_column", - "alias": "started_ipt", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_ipt)" - } - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.completed_ipt_past_12_months)" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.condoms_provided)" - } - }, - { - "type": "derived_column", - "alias": "on_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_modern_contraception)" - } - }, - { - "type": "derived_column", - "alias": "art_revisit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.art_revisit_this_month)" - } - }, - { - "type": "derived_column", - "alias": "f_gte_18_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.f_gte_18_visits)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "gender", - "age_range", - "location_id" - ], - "excludeParam": "excludeParam" - }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "join_location" - ], - "disaggregationColumns": [ - "gender", - "age_range" - ] - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "name": "mainDatasetAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "mainDataSetBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "mainDataSetBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "current_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_on_art)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.enrolled_this_month)" + } + }, + { + "type": "derived_column", + "alias": "pre_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.pre_art)" + } + }, + { + "type": "derived_column", + "alias": "current_in_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.current_in_care)" + } + }, + { + "type": "derived_column", + "alias": "active_on_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.active_on_art)" + } + }, + { + "type": "derived_column", + "alias": "on_ctx_prophylaxis", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_ctx_prophylaxis)" + } + }, + { + "type": "derived_column", + "alias": "screened_for_tb", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.screened_for_tb)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_this_visit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_this_visit_this_month)" + } + }, + { + "type": "derived_column", + "alias": "tb_screened_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.tb_screened_positive)" + } + }, + { + "type": "derived_column", + "alias": "started_ipt", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_ipt)" + } + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.completed_ipt_past_12_months)" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.condoms_provided)" + } + }, + { + "type": "derived_column", + "alias": "on_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_modern_contraception)" + } + }, + { + "type": "derived_column", + "alias": "art_revisit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.art_revisit_this_month)" + } + }, + { + "type": "derived_column", + "alias": "f_gte_18_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.f_gte_18_visits)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["gender", "age_range", "location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "join_location"], + "disaggregationColumns": ["gender", "age_range"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/main-dataset-base-age15.json b/app/reporting-framework/json-reports/main-dataset-base-age15.json index 7a6b7537e..4eacd8a55 100755 --- a/app/reporting-framework/json-reports/main-dataset-base-age15.json +++ b/app/reporting-framework/json-reports/main-dataset-base-age15.json @@ -1,224 +1,224 @@ { - "name": "mainDataSetBaseAge15", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hmsd.cur_arv_meds" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "cur_regimen_arv_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "hmsd.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmsd.age >= 15", - "value": "older_than_15" - }, - { - "condition": "else", - "value": "below_15_years" - } - ] - } - }, - { - "type": "simple_column", - "alias": "enrolled_this_month", - "column": "hmsd.enrolled_this_month" - }, - { - "type": "simple_column", - "alias": "current_in_care", - "column": "hmsd.active_in_care_this_month" - }, - { - "type": "simple_column", - "alias": "pre_art", - "column": "hmsd.is_pre_art_this_month" - }, - { - "type": "simple_column", - "alias": "active_on_art", - "column": "hmsd.on_art_this_month" - }, - { - "type": "simple_column", - "alias": "on_ctx_prophylaxis", - "column": "hmsd.on_pcp_prophylaxis_this_month" - }, - { - "type": "simple_column", - "alias": "screened_for_tb", - "column": "hmsd.tb_screened_active_this_month" - }, - { - "type": "simple_column", - "alias": "tb_screened_this_visit_this_month", - "column": "hmsd.tb_screened_this_visit_this_month" - }, - { - "type": "simple_column", - "alias": "tb_screened_positive", - "column": "hmsd.presumed_tb_positive_this_month" - }, - { - "type": "derived_column", - "alias": "screened_for_cervical_ca", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "0" - } - }, - { - "type": "simple_column", - "alias": "started_ipt", - "column": "hmsd.started_ipt_this_month" - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "completed_ipt_past_12_months" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "condoms_provided_this_month" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "started_modern_contraception_this_month" - } - }, - { - "type": "simple_column", - "alias": "on_modern_contraception", - "column": "hmsd.on_modern_contraception_this_month" - }, - { - "type": "simple_column", - "alias": "f_gte_18_visits", - "column": "hmsd.f_18_and_older_this_month" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.location_id in ?", - "parameterName": "locations" - } + "name": "mainDataSetBaseAge15", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hmsd.cur_arv_meds" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "cur_regimen_arv_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "hmsd.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmsd.age >= 15", + "value": "older_than_15" + }, + { + "condition": "else", + "value": "below_15_years" + } ] + } + }, + { + "type": "simple_column", + "alias": "enrolled_this_month", + "column": "hmsd.enrolled_this_month" + }, + { + "type": "simple_column", + "alias": "current_in_care", + "column": "hmsd.active_in_care_this_month" + }, + { + "type": "simple_column", + "alias": "pre_art", + "column": "hmsd.is_pre_art_this_month" + }, + { + "type": "simple_column", + "alias": "active_on_art", + "column": "hmsd.on_art_this_month" + }, + { + "type": "simple_column", + "alias": "on_ctx_prophylaxis", + "column": "hmsd.on_pcp_prophylaxis_this_month" + }, + { + "type": "simple_column", + "alias": "screened_for_tb", + "column": "hmsd.tb_screened_active_this_month" + }, + { + "type": "simple_column", + "alias": "tb_screened_this_visit_this_month", + "column": "hmsd.tb_screened_this_visit_this_month" + }, + { + "type": "simple_column", + "alias": "tb_screened_positive", + "column": "hmsd.presumed_tb_positive_this_month" + }, + { + "type": "derived_column", + "alias": "screened_for_cervical_ca", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "0" + } + }, + { + "type": "simple_column", + "alias": "started_ipt", + "column": "hmsd.started_ipt_this_month" + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "completed_ipt_past_12_months" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "condoms_provided_this_month" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "started_modern_contraception_this_month" + } + }, + { + "type": "simple_column", + "alias": "on_modern_contraception", + "column": "hmsd.on_modern_contraception_this_month" + }, + { + "type": "simple_column", + "alias": "f_gte_18_visits", + "column": "hmsd.f_18_and_older_this_month" } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/main-dataset-base-age18.json b/app/reporting-framework/json-reports/main-dataset-base-age18.json index 61016ff28..1365baf94 100755 --- a/app/reporting-framework/json-reports/main-dataset-base-age18.json +++ b/app/reporting-framework/json-reports/main-dataset-base-age18.json @@ -1,224 +1,224 @@ { - "name": "mainDataSetBaseAge18", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hmsd.cur_arv_meds" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "cur_regimen_arv_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "hmsd.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmsd.age >= 18", - "value": "18_and_above" - }, - { - "condition": "else", - "value": "below_18" - } - ] - } - }, - { - "type": "simple_column", - "alias": "enrolled_this_month", - "column": "hmsd.enrolled_this_month" - }, - { - "type": "simple_column", - "alias": "current_in_care", - "column": "hmsd.active_in_care_this_month" - }, - { - "type": "simple_column", - "alias": "pre_art", - "column": "hmsd.is_pre_art_this_month" - }, - { - "type": "simple_column", - "alias": "active_on_art", - "column": "hmsd.on_art_this_month" - }, - { - "type": "simple_column", - "alias": "on_ctx_prophylaxis", - "column": "hmsd.on_pcp_prophylaxis_this_month" - }, - { - "type": "simple_column", - "alias": "screened_for_tb", - "column": "hmsd.tb_screened_active_this_month" - }, - { - "type": "simple_column", - "alias": "tb_screened_this_visit_this_month", - "column": "hmsd.tb_screened_this_visit_this_month" - }, - { - "type": "simple_column", - "alias": "tb_screened_positive", - "column": "hmsd.presumed_tb_positive_this_month" - }, - { - "type": "derived_column", - "alias": "screened_for_cervical_ca", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "0" - } - }, - { - "type": "simple_column", - "alias": "started_ipt", - "column": "hmsd.started_ipt_this_month" - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "completed_ipt_past_12_months" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "condoms_provided_this_month" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "started_modern_contraception_this_month" - } - }, - { - "type": "simple_column", - "alias": "on_modern_contraception", - "column": "hmsd.on_modern_contraception_this_month" - }, - { - "type": "simple_column", - "alias": "f_gte_18_visits", - "column": "hmsd.f_18_and_older_this_month" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.location_id in ?", - "parameterName": "locations" - } + "name": "mainDataSetBaseAge18", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hmsd.cur_arv_meds" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "cur_regimen_arv_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "hmsd.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmsd.age >= 18", + "value": "18_and_above" + }, + { + "condition": "else", + "value": "below_18" + } ] + } + }, + { + "type": "simple_column", + "alias": "enrolled_this_month", + "column": "hmsd.enrolled_this_month" + }, + { + "type": "simple_column", + "alias": "current_in_care", + "column": "hmsd.active_in_care_this_month" + }, + { + "type": "simple_column", + "alias": "pre_art", + "column": "hmsd.is_pre_art_this_month" + }, + { + "type": "simple_column", + "alias": "active_on_art", + "column": "hmsd.on_art_this_month" + }, + { + "type": "simple_column", + "alias": "on_ctx_prophylaxis", + "column": "hmsd.on_pcp_prophylaxis_this_month" + }, + { + "type": "simple_column", + "alias": "screened_for_tb", + "column": "hmsd.tb_screened_active_this_month" + }, + { + "type": "simple_column", + "alias": "tb_screened_this_visit_this_month", + "column": "hmsd.tb_screened_this_visit_this_month" + }, + { + "type": "simple_column", + "alias": "tb_screened_positive", + "column": "hmsd.presumed_tb_positive_this_month" + }, + { + "type": "derived_column", + "alias": "screened_for_cervical_ca", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "0" + } + }, + { + "type": "simple_column", + "alias": "started_ipt", + "column": "hmsd.started_ipt_this_month" + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "completed_ipt_past_12_months" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "condoms_provided_this_month" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "started_modern_contraception_this_month" + } + }, + { + "type": "simple_column", + "alias": "on_modern_contraception", + "column": "hmsd.on_modern_contraception_this_month" + }, + { + "type": "simple_column", + "alias": "f_gte_18_visits", + "column": "hmsd.f_18_and_older_this_month" } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/main-dataset-base-blue-card.json b/app/reporting-framework/json-reports/main-dataset-base-blue-card.json index ba9f79ae0..0daf47f95 100755 --- a/app/reporting-framework/json-reports/main-dataset-base-blue-card.json +++ b/app/reporting-framework/json-reports/main-dataset-base-blue-card.json @@ -1,237 +1,237 @@ { - "name": "mainDataSetBaseBlueCard", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hmsd.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "cur_regimen_arv_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "hmsd.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmsd.age < 15", - "value": "below_15_years" - }, - { - "condition": "hmsd.age >= 15", - "value": "older_than_15" - } - ] - } - }, - { - "type": "simple_column", - "alias": "enrolled_this_month", - "column": "hmsd.enrolled_this_month" - }, - { - "type": "simple_column", - "alias": "current_in_care", - "column": "hmsd.active_in_care_this_month" - }, - { - "type": "simple_column", - "alias": "pre_art", - "column": "hmsd.is_pre_art_this_month" - }, - { - "type": "simple_column", - "alias": "active_on_art", - "column": "hmsd.on_art_this_month" - }, - { - "type": "derived_column", - "alias": "art_revisit_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when art_revisit_this_month=1 and status = 'active' then 1 else null end" - } - }, - { - "type": "simple_column", - "alias": "on_ctx_prophylaxis", - "column": "hmsd.on_pcp_prophylaxis_this_month" - }, - { - "type": "simple_column", - "alias": "current_on_art", - "column": "hmsd.on_art_this_month" - }, - { - "type": "simple_column", - "alias": "screened_for_tb", - "column": "hmsd.tb_screened_active_this_month" - }, - { - "type": "simple_column", - "alias": "tb_screened_this_visit_this_month", - "column": "hmsd.tb_screened_this_visit_this_month" - }, - { - "type": "simple_column", - "alias": "tb_screened_positive", - "column": "hmsd.presumed_tb_positive_this_month" - }, - { - "type": "derived_column", - "alias": "screened_for_cervical_ca", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "0" - } - }, - { - "type": "simple_column", - "alias": "started_ipt", - "column": "hmsd.started_ipt_this_month" - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "completed_ipt_past_12_months" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "condoms_provided_this_month" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "started_modern_contraception_this_month" - } - }, - { - "type": "simple_column", - "alias": "on_modern_contraception", - "column": "hmsd.on_modern_contraception_this_month" - }, - { - "type": "simple_column", - "alias": "f_gte_18_visits", - "column": "hmsd.f_18_and_older_this_month" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.location_id in ?", - "parameterName": "locations" - } + "name": "mainDataSetBaseBlueCard", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hmsd.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "cur_regimen_arv_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "hmsd.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmsd.age < 15", + "value": "below_15_years" + }, + { + "condition": "hmsd.age >= 15", + "value": "older_than_15" + } ] + } + }, + { + "type": "simple_column", + "alias": "enrolled_this_month", + "column": "hmsd.enrolled_this_month" + }, + { + "type": "simple_column", + "alias": "current_in_care", + "column": "hmsd.active_in_care_this_month" + }, + { + "type": "simple_column", + "alias": "pre_art", + "column": "hmsd.is_pre_art_this_month" + }, + { + "type": "simple_column", + "alias": "active_on_art", + "column": "hmsd.on_art_this_month" + }, + { + "type": "derived_column", + "alias": "art_revisit_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when art_revisit_this_month=1 and status = 'active' then 1 else null end" + } + }, + { + "type": "simple_column", + "alias": "on_ctx_prophylaxis", + "column": "hmsd.on_pcp_prophylaxis_this_month" + }, + { + "type": "simple_column", + "alias": "current_on_art", + "column": "hmsd.on_art_this_month" + }, + { + "type": "simple_column", + "alias": "screened_for_tb", + "column": "hmsd.tb_screened_active_this_month" + }, + { + "type": "simple_column", + "alias": "tb_screened_this_visit_this_month", + "column": "hmsd.tb_screened_this_visit_this_month" + }, + { + "type": "simple_column", + "alias": "tb_screened_positive", + "column": "hmsd.presumed_tb_positive_this_month" + }, + { + "type": "derived_column", + "alias": "screened_for_cervical_ca", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "0" + } + }, + { + "type": "simple_column", + "alias": "started_ipt", + "column": "hmsd.started_ipt_this_month" + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "completed_ipt_past_12_months" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "condoms_provided_this_month" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "started_modern_contraception_this_month" + } + }, + { + "type": "simple_column", + "alias": "on_modern_contraception", + "column": "hmsd.on_modern_contraception_this_month" + }, + { + "type": "simple_column", + "alias": "f_gte_18_visits", + "column": "hmsd.f_18_and_older_this_month" } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/main-dataset-base.json b/app/reporting-framework/json-reports/main-dataset-base.json index 07e1bc461..1c1b34a6c 100755 --- a/app/reporting-framework/json-reports/main-dataset-base.json +++ b/app/reporting-framework/json-reports/main-dataset-base.json @@ -1,444 +1,443 @@ { - "name": "mainDataSetBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hmsd.cur_arv_meds" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "cur_regimen_arv_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "hmsd.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmsd.age < 1", - "value": "0_to_1" - }, - { - "condition": "hmsd.age between 1 and 9", - "value": "1_to_9" - }, - { - "condition": "hmsd.age between 10 and 14", - "value": "10_to_14" - }, - { - "condition": "hmsd.age between 15 and 19", - "value": "15_to_19" - }, - { - "condition": "hmsd.age between 20 and 24", - "value": "20_to_24" - }, - { - "condition": "else", - "value": "older_than_24" - } - ] - } - }, - { - "type": "simple_column", - "alias": "enrolled_this_month", - "column": "hmsd.enrolled_this_month" - }, - { - "type": "simple_column", - "alias": "art_revisit_this_month", - "column": "hmsd.art_revisit_this_month" - }, - { - "type": "simple_column", - "alias": "current_in_care", - "column": "hmsd.active_in_care_this_month" - }, - { - "type": "simple_column", - "alias": "pre_art", - "column": "hmsd.is_pre_art_this_month" - }, - { - "type": "simple_column", - "alias": "started_art_pregnant", - "column": "hmsd.is_pregnant_and_started_art_this_month" - }, - { - "type": "simple_column", - "alias": "started_art_and_has_tb", - "column": "hmsd.on_tb_tx_and_started_art_this_month" - }, - { - "type": "simple_column", - "alias": "active_on_art", - "column": "hmsd.on_art_this_month" - }, - { - "type": "simple_column", - "alias": "on_ctx_prophylaxis", - "column": "hmsd.on_pcp_prophylaxis_this_month" - }, - { - "type": "simple_column", - "alias": "current_on_art", - "column": "hmsd.on_art_this_month" - }, - { - "type": "simple_column", - "alias": "screened_for_tb", - "column": "hmsd.tb_screened_active_this_month" - }, - { - "type": "simple_column", - "alias": "tb_screened_this_visit_this_month", - "column": "hmsd.tb_screened_this_visit_this_month" - }, - { - "type": "simple_column", - "alias": "tb_screened_positive", - "column": "hmsd.presumed_tb_positive_this_month" - }, - { - "type": "derived_column", - "alias": "screened_for_cervical_ca", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "0" - } - }, - { - "type": "simple_column", - "alias": "started_ipt", - "column": "hmsd.started_ipt_this_month" - }, - { - "type": "derived_column", - "alias": "completed_ipt_past_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "completed_ipt_past_12_months" - } - }, - { - "type": "derived_column", - "alias": "condoms_provided", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "condoms_provided_this_month" - } - }, - { - "type": "derived_column", - "alias": "started_modern_contraception", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "started_modern_contraception_this_month" - } - }, - { - "type": "simple_column", - "alias": "on_modern_contraception", - "column": "hmsd.on_modern_contraception_this_month" - }, - { - "type": "simple_column", - "alias": "scheduled_visits", - "column": "hmsd.scheduled_this_month" - }, - { - "type": "simple_column", - "alias": "unscheduled_visits", - "column": "hmsd.unscheduled_this_month" - }, - { - "type": "simple_column", - "alias": "total_visits", - "column": "hmsd.visit_this_month" - }, - { - "type": "simple_column", - "alias": "f_gte_18_visits", - "column": "hmsd.f_18_and_older_this_month" - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_art_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.art_revisit_this_month = 1 and hmsd.is_cross_border_this_month = 1 , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_vl_suppressed_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.is_suppressed_this_month = 1 and hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_active_on_art_12_month_cohort_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.active_on_art_12_month_cohort_this_month = 1 and hmsd.is_cross_border_this_month = 1 , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_presumed_tb_positive_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.presumed_tb_positive_this_month = 1 and hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_started_tb_tx_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.started_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_tb_tx_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.on_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 and status = 'active' , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_completed_tb_tx", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.tb_tx_end_date is not null , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_stopped_tb_tx", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.tb_tx_stop_date is not null , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_tb_tx_transferred_out", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.on_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 and status = 'transfer_out' , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_tb_tx_ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.on_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 and ( status = 'defaulter' or status = 'ltfu'), 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_tb_tx_dead", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.on_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 and status = 'dead', 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_on_modern_contraception_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.on_modern_contraception_this_month = 1 and hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active', 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_country_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.is_cross_border_country_this_month = 1 and hmsd.status = 'active' , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_county_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.is_cross_border_county_this_month = 1 and hmsd.status = 'active' , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "travelled_outside_last_3_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.travelled_outside_last_3_months = 1 and hmsd.status = 'active' , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "travelled_outside_last_6_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.travelled_outside_last_6_months = 1 and hmsd.status = 'active' , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "travelled_outside_last_12_months", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.travelled_outside_last_12_months = 1 and hmsd.status = 'active' , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_this_month_kenya", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' and hmsd.country_of_residence = 11197, 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_this_month_uganda", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' and hmsd.country_of_residence = 11118, 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_this_month_other", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' and hmsd.country_of_residence is null , 1 , 0)" - } - }, - { - "type": "derived_column", - "alias": "is_cross_border_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active', 1 , 0)" - } - } - - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.location_id in ?", - "parameterName": "locations" - } + "name": "mainDataSetBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hmsd.cur_arv_meds" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "cur_regimen_arv_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "hmsd.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmsd.age < 1", + "value": "0_to_1" + }, + { + "condition": "hmsd.age between 1 and 9", + "value": "1_to_9" + }, + { + "condition": "hmsd.age between 10 and 14", + "value": "10_to_14" + }, + { + "condition": "hmsd.age between 15 and 19", + "value": "15_to_19" + }, + { + "condition": "hmsd.age between 20 and 24", + "value": "20_to_24" + }, + { + "condition": "else", + "value": "older_than_24" + } ] + } + }, + { + "type": "simple_column", + "alias": "enrolled_this_month", + "column": "hmsd.enrolled_this_month" + }, + { + "type": "simple_column", + "alias": "art_revisit_this_month", + "column": "hmsd.art_revisit_this_month" + }, + { + "type": "simple_column", + "alias": "current_in_care", + "column": "hmsd.active_in_care_this_month" + }, + { + "type": "simple_column", + "alias": "pre_art", + "column": "hmsd.is_pre_art_this_month" + }, + { + "type": "simple_column", + "alias": "started_art_pregnant", + "column": "hmsd.is_pregnant_and_started_art_this_month" + }, + { + "type": "simple_column", + "alias": "started_art_and_has_tb", + "column": "hmsd.on_tb_tx_and_started_art_this_month" + }, + { + "type": "simple_column", + "alias": "active_on_art", + "column": "hmsd.on_art_this_month" + }, + { + "type": "simple_column", + "alias": "on_ctx_prophylaxis", + "column": "hmsd.on_pcp_prophylaxis_this_month" + }, + { + "type": "simple_column", + "alias": "current_on_art", + "column": "hmsd.on_art_this_month" + }, + { + "type": "simple_column", + "alias": "screened_for_tb", + "column": "hmsd.tb_screened_active_this_month" + }, + { + "type": "simple_column", + "alias": "tb_screened_this_visit_this_month", + "column": "hmsd.tb_screened_this_visit_this_month" + }, + { + "type": "simple_column", + "alias": "tb_screened_positive", + "column": "hmsd.presumed_tb_positive_this_month" + }, + { + "type": "derived_column", + "alias": "screened_for_cervical_ca", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "0" + } + }, + { + "type": "simple_column", + "alias": "started_ipt", + "column": "hmsd.started_ipt_this_month" + }, + { + "type": "derived_column", + "alias": "completed_ipt_past_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "completed_ipt_past_12_months" + } + }, + { + "type": "derived_column", + "alias": "condoms_provided", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "condoms_provided_this_month" + } + }, + { + "type": "derived_column", + "alias": "started_modern_contraception", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "started_modern_contraception_this_month" + } + }, + { + "type": "simple_column", + "alias": "on_modern_contraception", + "column": "hmsd.on_modern_contraception_this_month" + }, + { + "type": "simple_column", + "alias": "scheduled_visits", + "column": "hmsd.scheduled_this_month" + }, + { + "type": "simple_column", + "alias": "unscheduled_visits", + "column": "hmsd.unscheduled_this_month" + }, + { + "type": "simple_column", + "alias": "total_visits", + "column": "hmsd.visit_this_month" + }, + { + "type": "simple_column", + "alias": "f_gte_18_visits", + "column": "hmsd.f_18_and_older_this_month" + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_art_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.art_revisit_this_month = 1 and hmsd.is_cross_border_this_month = 1 , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_vl_suppressed_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.is_suppressed_this_month = 1 and hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_active_on_art_12_month_cohort_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.active_on_art_12_month_cohort_this_month = 1 and hmsd.is_cross_border_this_month = 1 , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_presumed_tb_positive_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.presumed_tb_positive_this_month = 1 and hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_started_tb_tx_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.started_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_tb_tx_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.on_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 and status = 'active' , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_completed_tb_tx", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.tb_tx_end_date is not null , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_stopped_tb_tx", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.tb_tx_stop_date is not null , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_tb_tx_transferred_out", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.on_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 and status = 'transfer_out' , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_tb_tx_ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.on_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 and ( status = 'defaulter' or status = 'ltfu'), 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_tb_tx_dead", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.on_tb_tx_this_month = 1 and hmsd.is_cross_border_this_month = 1 and status = 'dead', 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_on_modern_contraception_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.on_modern_contraception_this_month = 1 and hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active', 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_country_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.is_cross_border_country_this_month = 1 and hmsd.status = 'active' , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_county_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.is_cross_border_county_this_month = 1 and hmsd.status = 'active' , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "travelled_outside_last_3_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.travelled_outside_last_3_months = 1 and hmsd.status = 'active' , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "travelled_outside_last_6_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.travelled_outside_last_6_months = 1 and hmsd.status = 'active' , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "travelled_outside_last_12_months", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.travelled_outside_last_12_months = 1 and hmsd.status = 'active' , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_this_month_kenya", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' and hmsd.country_of_residence = 11197, 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_this_month_uganda", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' and hmsd.country_of_residence = 11118, 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_this_month_other", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active' and hmsd.country_of_residence is null , 1 , 0)" + } + }, + { + "type": "derived_column", + "alias": "is_cross_border_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(hmsd.is_cross_border_this_month = 1 and hmsd.status = 'active', 1 , 0)" + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/medical-history-dataset-base.json b/app/reporting-framework/json-reports/medical-history-dataset-base.json index 071352cc2..ad1ffb85f 100644 --- a/app/reporting-framework/json-reports/medical-history-dataset-base.json +++ b/app/reporting-framework/json-reports/medical-history-dataset-base.json @@ -1,86 +1,83 @@ { - "name": "medicalHistoryDataSetBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "t1" - }, - { - "table": "amrs.person", - "alias": "t2", - "join": { - "type": "INNER", - "joinCondition": "t1.person_id=t2.person_id" - } - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "encounter_datetime", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(t1.encounter_datetime,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "previous_vl_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(t1.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias":"current_regimen", - "column": "t1.cur_arv_meds" - }, - { - "type": "simple_column", - "alias":"previous_regimen", - "column": "t1.prev_arv_meds" - }, - { - "type": "simple_column", - "alias":"previous_vl", - "column": "t1.vl_1" - }, - { - "type": "simple_column", - "alias":"previous_vl_date", - "column": "DATE_FORMAT(t1.vl_1_date,'%d-%m-%Y')" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t2.uuid = ?", - "parameterName": "patientUuid" - } - ] + "name": "medicalHistoryDataSetBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "t1" + }, + { + "table": "amrs.person", + "alias": "t2", + "join": { + "type": "INNER", + "joinCondition": "t1.person_id=t2.person_id" + } + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "encounter_datetime", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(t1.encounter_datetime,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "previous_vl_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(t1.vl_1_date,'%d-%m-%Y')" + } }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "cur_arv_meds", - "prev_arv_meds" - ], - "excludeParam": "excludeParam" + { + "type": "simple_column", + "alias": "current_regimen", + "column": "t1.cur_arv_meds" }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [ - { - "column": "t1.encounter_datetime", - "order": "desc" - } - ] + { + "type": "simple_column", + "alias": "previous_regimen", + "column": "t1.prev_arv_meds" + }, + { + "type": "simple_column", + "alias": "previous_vl", + "column": "t1.vl_1" + }, + { + "type": "simple_column", + "alias": "previous_vl_date", + "column": "DATE_FORMAT(t1.vl_1_date,'%d-%m-%Y')" } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t2.uuid = ?", + "parameterName": "patientUuid" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["cur_arv_meds", "prev_arv_meds"], + "excludeParam": "excludeParam" + }, + "orderBy": { + "orderByParam": "orderByParam", + "columns": [ + { + "column": "t1.encounter_datetime", + "order": "desc" + } + ] + } } diff --git a/app/reporting-framework/json-reports/moh-408.json b/app/reporting-framework/json-reports/moh-408.json index 297091cdd..ef6bf13ec 100644 --- a/app/reporting-framework/json-reports/moh-408.json +++ b/app/reporting-framework/json-reports/moh-408.json @@ -1,11 +1,11 @@ { - "reports": [ - "heiInfantFeedingAggregate", - "heiInfantFeedingNoDisaggregationAggregate", - "heiInfantTestingAggregate", - "heiRetentionPairsAggregate", - "heiProgramOutcomeAggregate", - "heiUknownProgramOutcomeAggregate", - "heiOriginalCohortAggregate" - ] -} \ No newline at end of file + "reports": [ + "heiInfantFeedingAggregate", + "heiInfantFeedingNoDisaggregationAggregate", + "heiInfantTestingAggregate", + "heiRetentionPairsAggregate", + "heiProgramOutcomeAggregate", + "heiUknownProgramOutcomeAggregate", + "heiOriginalCohortAggregate" + ] +} diff --git a/app/reporting-framework/json-reports/moh-731-bluecard.json b/app/reporting-framework/json-reports/moh-731-bluecard.json index b003eca83..5369fd87e 100755 --- a/app/reporting-framework/json-reports/moh-731-bluecard.json +++ b/app/reporting-framework/json-reports/moh-731-bluecard.json @@ -1,14 +1,14 @@ { - "reports": [ - "mainDatasetAggregate", - "mainDatasetAggregateBlueCard", - "regimenDataSetAggregate", - "retentionDataSetAggregate", - "mainDatasetAggregateNoDisaggregation", - "StartingARTAggregationAge15", - "StartingARTDisaggregationAge15", - "pepDatasetAggregate", - "everOnARTAggregate", - "everOnARTDisaggregation" - ] -} \ No newline at end of file + "reports": [ + "mainDatasetAggregate", + "mainDatasetAggregateBlueCard", + "regimenDataSetAggregate", + "retentionDataSetAggregate", + "mainDatasetAggregateNoDisaggregation", + "StartingARTAggregationAge15", + "StartingARTDisaggregationAge15", + "pepDatasetAggregate", + "everOnARTAggregate", + "everOnARTDisaggregation" + ] +} diff --git a/app/reporting-framework/json-reports/moh-731-greencard.json b/app/reporting-framework/json-reports/moh-731-greencard.json index be64c333a..e786ffbb1 100755 --- a/app/reporting-framework/json-reports/moh-731-greencard.json +++ b/app/reporting-framework/json-reports/moh-731-greencard.json @@ -1,15 +1,15 @@ { - "reports": [ - "mainDatasetAggregate", - "regimenDataSetAggregate", - "retentionDataSetAggregate", - "mainDatasetAggregateNoDisaggregation", - "mainDatasetAggregateAgeDisaggregation", - "mainDatasetAggregateAge15Disaggregation", - "StartingARTAggregationAgeGreen", - "StartingARTDisaggregationAgeGreen", - "StartingARTDisaggregationAgeOnlyGreen", - "mainDatasetAggregateAge18Disaggregation", - "pepDatasetAggregate" - ] -} \ No newline at end of file + "reports": [ + "mainDatasetAggregate", + "regimenDataSetAggregate", + "retentionDataSetAggregate", + "mainDatasetAggregateNoDisaggregation", + "mainDatasetAggregateAgeDisaggregation", + "mainDatasetAggregateAge15Disaggregation", + "StartingARTAggregationAgeGreen", + "StartingARTDisaggregationAgeGreen", + "StartingARTDisaggregationAgeOnlyGreen", + "mainDatasetAggregateAge18Disaggregation", + "pepDatasetAggregate" + ] +} diff --git a/app/reporting-framework/json-reports/next-drug-pickup-encounter.base.json b/app/reporting-framework/json-reports/next-drug-pickup-encounter.base.json index 47517e977..1e93e191c 100644 --- a/app/reporting-framework/json-reports/next-drug-pickup-encounter.base.json +++ b/app/reporting-framework/json-reports/next-drug-pickup-encounter.base.json @@ -1,46 +1,44 @@ { - "name": "nextDrugPickupEncounterBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_appointment", - "alias": "fa" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "next_drugpickup_date", - "column": "MIN(fa.encounter_datetime)" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "fa.person_id" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "fa.encounter_datetime" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "fa.encounter_type = 186" - } - ] + "name": "nextDrugPickupEncounterBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_appointment", + "alias": "fa" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "next_drugpickup_date", + "column": "MIN(fa.encounter_datetime)" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "fa.person_id" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "fa.person_id" - ], - "excludeParam": "excludeParam" + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "fa.encounter_datetime" } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "fa.encounter_type = 186" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["fa.person_id"], + "excludeParam": "excludeParam" + } } diff --git a/app/reporting-framework/json-reports/ovc-in-hei-dataset-aggregate.json b/app/reporting-framework/json-reports/ovc-in-hei-dataset-aggregate.json index ce7c1c3e9..b4e24c89d 100644 --- a/app/reporting-framework/json-reports/ovc-in-hei-dataset-aggregate.json +++ b/app/reporting-framework/json-reports/ovc-in-hei-dataset-aggregate.json @@ -1,138 +1,133 @@ { - "name": "ovcInHeiDatasetAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "ovcInHeiDatasetBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "ovcInHeiDatasetBase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "derived_column", - "alias": "active_and_eligible_for_ovc_hei", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.active_and_eligible_for_ovc)" - } - }, - { - "type": "derived_column", - "alias": "inactive_and_eligible_for_ovc_hei", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.inactive_and_eligible_for_ovc)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_ovc_this_month_hei", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.enrolled_in_ovc_this_month)" - } - }, - { - "type": "derived_column", - "alias": "ovc_non_enrolment_declined_hei", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.ovc_non_enrolment_declined)" - } - }, - { - "type": "derived_column", - "alias": "ovc_non_enrolment_out_of_catchment_area_hei", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.ovc_non_enrolment_out_of_catchment_area)" - } - }, - { - "type": "derived_column", - "alias": "ovc_non_enrolment_undocumented_hei", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.ovc_non_enrolment_undocumented_hei)" - } - }, - { - "type": "derived_column", - "alias": "newly_exited_from_ovc_this_month_hei", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.newly_exited_from_ovc_this_month_hei)" - } - }, - { - "type": "derived_column", - "alias": "exited_from_ovc_this_month_hei", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.exited_from_ovc_this_month_hei)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" + "name": "ovcInHeiDatasetAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "ovcInHeiDatasetBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "ovcInHeiDatasetBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" }, - "transFormDirectives": { - "joinColumn": "location_id", - "joinColumnParam": "joinColumnParam", - "skipColumns": [ - "location_uuid", - "join_location" - ], - "disaggregationColumns": [] + { + "type": "derived_column", + "alias": "active_and_eligible_for_ovc_hei", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.active_and_eligible_for_ovc)" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "ovc-in-hei-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "inactive_and_eligible_for_ovc_hei", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.inactive_and_eligible_for_ovc)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_ovc_this_month_hei", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.enrolled_in_ovc_this_month)" + } + }, + { + "type": "derived_column", + "alias": "ovc_non_enrolment_declined_hei", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.ovc_non_enrolment_declined)" + } + }, + { + "type": "derived_column", + "alias": "ovc_non_enrolment_out_of_catchment_area_hei", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.ovc_non_enrolment_out_of_catchment_area)" + } + }, + { + "type": "derived_column", + "alias": "ovc_non_enrolment_undocumented_hei", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.ovc_non_enrolment_undocumented_hei)" + } + }, + { + "type": "derived_column", + "alias": "newly_exited_from_ovc_this_month_hei", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.newly_exited_from_ovc_this_month_hei)" + } + }, + { + "type": "derived_column", + "alias": "exited_from_ovc_this_month_hei", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.exited_from_ovc_this_month_hei)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "joinColumnParam": "joinColumnParam", + "skipColumns": ["location_uuid", "join_location"], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "ovc-in-hei-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/ovc-in-hei-dataset-base.json b/app/reporting-framework/json-reports/ovc-in-hei-dataset-base.json index 520dada56..c38e70f49 100644 --- a/app/reporting-framework/json-reports/ovc-in-hei-dataset-base.json +++ b/app/reporting-framework/json-reports/ovc-in-hei-dataset-base.json @@ -1,134 +1,134 @@ { - "name": "ovcInHeiDatasetBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hei_monthly_report_dataset", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "simple_column", - "alias": "status", - "column": "hmsd.retention_status" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "active_and_eligible_for_ovc", - "column": "hmsd.active_and_eligible_for_ovc" - }, - { - "type": "simple_column", - "alias": "inactive_and_eligible_for_ovc", - "column": "hmsd.inactive_and_eligible_for_ovc" - }, - { - "type": "simple_column", - "alias": "enrolled_in_ovc_this_month", - "column": "hmsd.enrolled_in_ovc_this_month" - }, - { - "type": "simple_column", - "alias": "ovc_non_enrolment_out_of_catchment_area", - "column": "hmsd.ovc_non_enrolment_out_of_catchment_area" - }, - { - "type": "simple_column", - "alias": "ovc_non_enrolment_declined", - "column": "hmsd.ovc_non_enrolment_declined" - }, - { - "type": "simple_column", - "alias": "newly_exited_from_ovc_this_month_hei", - "column": "hmsd.newly_exited_from_ovc_this_month" - }, - { - "type": "simple_column", - "alias": "exited_from_ovc_this_month_hei", - "column": "hmsd.exited_from_ovc_this_month" - }, - { - "type": "derived_column", - "alias": "ovc_non_enrolment_undocumented_hei", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmsd.active_and_eligible_for_ovc = 1 and (hmsd.enrolled_in_ovc_this_month is null or hmsd.enrolled_in_ovc_this_month = 0 ) and hmsd.ovc_non_enrolment_declined <> 1 and hmsd.ovc_non_enrolment_out_of_catchment_area <> 1, 1,0)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.location_id in ?", - "parameterName": "locations" - } - ] + "name": "ovcInHeiDatasetBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hei_monthly_report_dataset", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "simple_column", + "alias": "status", + "column": "hmsd.retention_status" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "active_and_eligible_for_ovc", + "column": "hmsd.active_and_eligible_for_ovc" + }, + { + "type": "simple_column", + "alias": "inactive_and_eligible_for_ovc", + "column": "hmsd.inactive_and_eligible_for_ovc" + }, + { + "type": "simple_column", + "alias": "enrolled_in_ovc_this_month", + "column": "hmsd.enrolled_in_ovc_this_month" + }, + { + "type": "simple_column", + "alias": "ovc_non_enrolment_out_of_catchment_area", + "column": "hmsd.ovc_non_enrolment_out_of_catchment_area" + }, + { + "type": "simple_column", + "alias": "ovc_non_enrolment_declined", + "column": "hmsd.ovc_non_enrolment_declined" + }, + { + "type": "simple_column", + "alias": "newly_exited_from_ovc_this_month_hei", + "column": "hmsd.newly_exited_from_ovc_this_month" + }, + { + "type": "simple_column", + "alias": "exited_from_ovc_this_month_hei", + "column": "hmsd.exited_from_ovc_this_month" + }, + { + "type": "derived_column", + "alias": "ovc_non_enrolment_undocumented_hei", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmsd.active_and_eligible_for_ovc = 1 and (hmsd.enrolled_in_ovc_this_month is null or hmsd.enrolled_in_ovc_this_month = 0 ) and hmsd.ovc_non_enrolment_declined <> 1 and hmsd.ovc_non_enrolment_out_of_catchment_area <> 1, 1,0)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/ovc-in-hei-patient-list-template.json b/app/reporting-framework/json-reports/ovc-in-hei-patient-list-template.json index 8e0933acc..ba2e948d3 100644 --- a/app/reporting-framework/json-reports/ovc-in-hei-patient-list-template.json +++ b/app/reporting-framework/json-reports/ovc-in-hei-patient-list-template.json @@ -1,176 +1,175 @@ { - "name": "ovc-in-hei-patient-list-template", - "version": "1.0", - "tag": "ovc-in-hei-patient-list-template", - "description": "OVC Patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "etl.flat_hei_summary", - "alias": "fh", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "LEFT", - "joinCondition": "fh.encounter_type = et.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pa.person_id" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "ovc_id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = ovc_id.patient_id AND (ovc_id.voided IS NULL || ovc_id.voided = 0) AND ovc_id.identifier_type = 43" - } - } - - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "ovc_identifier", - "column": "ovc_id.identifier" - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(fh.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" - }, - { - "type": "derived_column", - "alias": "exit_reason", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "fh.ovc_exit_reason = 8204", - "value": "Graduated" - }, - { - "condition": "fh.ovc_exit_reason = 11292", - "value": "Attrition" - }, - { - "condition": "fh.ovc_exit_reason = 10119", - "value": "Transfer out" - }, - { - "condition": "fh.ovc_exit_reason = 8640", - "value": "Wrong enrollment" - } - ] - } - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - }, - { - "type": "simple_column", - "alias": "county", - "column": "pa.address1" - }, - { - "type": "simple_column", - "alias": "sub_county", - "column": "pa.address2" - }, - { - "type": "simple_column", - "alias": "ward", - "column": "pa.address7" - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "ovc-in-hei-patient-list-template", + "version": "1.0", + "tag": "ovc-in-hei-patient-list-template", + "description": "OVC Patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "etl.flat_hei_summary", + "alias": "fh", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "LEFT", + "joinCondition": "fh.encounter_type = et.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pa.person_id" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "ovc_id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = ovc_id.patient_id AND (ovc_id.voided IS NULL || ovc_id.voided = 0) AND ovc_id.identifier_type = 43" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "ovc_identifier", + "column": "ovc_id.identifier" + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(fh.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" + }, + { + "type": "derived_column", + "alias": "exit_reason", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "fh.ovc_exit_reason = 8204", + "value": "Graduated" + }, + { + "condition": "fh.ovc_exit_reason = 11292", + "value": "Attrition" + }, + { + "condition": "fh.ovc_exit_reason = 10119", + "value": "Transfer out" + }, + { + "condition": "fh.ovc_exit_reason = 8640", + "value": "Wrong enrollment" + } + ] + } + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + }, + { + "type": "simple_column", + "alias": "county", + "column": "pa.address1" + }, + { + "type": "simple_column", + "alias": "sub_county", + "column": "pa.address2" + }, + { + "type": "simple_column", + "alias": "ward", + "column": "pa.address7" + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/ovc-in-hiv-dataset-aggregate.json b/app/reporting-framework/json-reports/ovc-in-hiv-dataset-aggregate.json index 0dca535e4..3b75c8b2c 100644 --- a/app/reporting-framework/json-reports/ovc-in-hiv-dataset-aggregate.json +++ b/app/reporting-framework/json-reports/ovc-in-hiv-dataset-aggregate.json @@ -1,159 +1,154 @@ { - "name": "ovcInHivDatasetAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "ovcInHivDatasetBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "ovcInHivDatasetBase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "derived_column", - "alias": "on_art_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.on_art_this_month)" - } - }, - { - "type": "derived_column", - "alias": "active_in_care_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.active_in_care_this_month)" - } - }, - { - "type": "derived_column", - "alias": "active_and_eligible_for_ovc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.active_and_eligible_for_ovc)" - } - }, - { - "type": "derived_column", - "alias": "inactive_and_eligible_for_ovc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.inactive_and_eligible_for_ovc)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_ovc_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.enrolled_in_ovc_this_month)" - } - }, - { - "type": "derived_column", - "alias": "ovc_non_enrolment_declined", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.ovc_non_enrolment_declined)" - } - }, - { - "type": "derived_column", - "alias": "ovc_non_enrolment_out_of_catchment_area", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.ovc_non_enrolment_out_of_catchment_area)" - } - }, - { - "type": "derived_column", - "alias": "ovc_non_enrolment_undocumented", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.ovc_non_enrolment_undocumented)" - } - }, - { - "type": "derived_column", - "alias": "newly_exited_from_ovc_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.newly_exited_from_ovc_this_month)" - } - }, - { - "type": "derived_column", - "alias": "exited_from_ovc_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.exited_from_ovc_this_month)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" + "name": "ovcInHivDatasetAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "ovcInHivDatasetBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "ovcInHivDatasetBase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" }, - "transFormDirectives": { - "joinColumn": "location_id", - "joinColumnParam": "joinColumnParam", - "skipColumns": [ - "location_uuid", - "join_location" - ], - "disaggregationColumns": [] + { + "type": "derived_column", + "alias": "on_art_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.on_art_this_month)" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "ovc-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "active_in_care_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.active_in_care_this_month)" + } + }, + { + "type": "derived_column", + "alias": "active_and_eligible_for_ovc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.active_and_eligible_for_ovc)" + } + }, + { + "type": "derived_column", + "alias": "inactive_and_eligible_for_ovc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.inactive_and_eligible_for_ovc)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_ovc_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.enrolled_in_ovc_this_month)" + } + }, + { + "type": "derived_column", + "alias": "ovc_non_enrolment_declined", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.ovc_non_enrolment_declined)" + } + }, + { + "type": "derived_column", + "alias": "ovc_non_enrolment_out_of_catchment_area", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.ovc_non_enrolment_out_of_catchment_area)" + } + }, + { + "type": "derived_column", + "alias": "ovc_non_enrolment_undocumented", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.ovc_non_enrolment_undocumented)" + } + }, + { + "type": "derived_column", + "alias": "newly_exited_from_ovc_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.newly_exited_from_ovc_this_month)" + } + }, + { + "type": "derived_column", + "alias": "exited_from_ovc_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.exited_from_ovc_this_month)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "joinColumnParam": "joinColumnParam", + "skipColumns": ["location_uuid", "join_location"], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "ovc-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/ovc-in-hiv-dataset-base.json b/app/reporting-framework/json-reports/ovc-in-hiv-dataset-base.json index 10054e711..5c26e770f 100644 --- a/app/reporting-framework/json-reports/ovc-in-hiv-dataset-base.json +++ b/app/reporting-framework/json-reports/ovc-in-hiv-dataset-base.json @@ -1,180 +1,180 @@ { - "name": "ovcInHivDatasetBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "status", - "column": "hmsd.status" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hmsd.cur_arv_meds" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "hmsd.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "enrolled_this_month", - "column": "hmsd.enrolled_this_month" - }, - { - "type": "simple_column", - "alias": "on_art_this_month", - "column": "hmsd.on_art_this_month" - }, - { - "type": "simple_column", - "alias": "active_in_care_this_month", - "column": "hmsd.active_in_care_this_month" - }, - { - "type": "simple_column", - "alias": "active_and_eligible_for_ovc", - "column": "hmsd.active_and_eligible_for_ovc" - }, - { - "type": "simple_column", - "alias": "inactive_and_eligible_for_ovc", - "column": "hmsd.inactive_and_eligible_for_ovc" - }, - { - "type": "simple_column", - "alias": "enrolled_in_ovc_this_month", - "column": "hmsd.enrolled_in_ovc_this_month" - }, - { - "type": "simple_column", - "alias": "ovc_non_enrolment_declined", - "column": "hmsd.ovc_non_enrolment_declined" - }, - { - "type": "simple_column", - "alias": "ovc_non_enrolment_out_of_catchment_area", - "column": "hmsd.ovc_non_enrolment_out_of_catchment_area" - }, - { - "type": "simple_column", - "alias": "newly_exited_from_ovc_this_month", - "column": "hmsd.newly_exited_from_ovc_this_month" - }, - { - "type": "simple_column", - "alias": "exited_from_ovc_this_month", - "column": "hmsd.exited_from_ovc_this_month" - }, - { - "type": "derived_column", - "alias": "ovc_non_enrolment_undocumented", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hmsd.active_and_eligible_for_ovc = 1 and (hmsd.enrolled_in_ovc_this_month is null or hmsd.enrolled_in_ovc_this_month = 0 ) and hmsd.ovc_non_enrolment_declined <> 1 and hmsd.ovc_non_enrolment_out_of_catchment_area <> 1, 1,0)" - } - }, - { - "type": "simple_column", - "alias": "due_for_vl_this_month", - "column": "hmsd.due_for_vl_this_month" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.location_id in ?", - "parameterName": "locations" - } - ] + "name": "ovcInHivDatasetBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "status", + "column": "hmsd.status" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hmsd.cur_arv_meds" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "hmsd.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "enrolled_this_month", + "column": "hmsd.enrolled_this_month" + }, + { + "type": "simple_column", + "alias": "on_art_this_month", + "column": "hmsd.on_art_this_month" + }, + { + "type": "simple_column", + "alias": "active_in_care_this_month", + "column": "hmsd.active_in_care_this_month" + }, + { + "type": "simple_column", + "alias": "active_and_eligible_for_ovc", + "column": "hmsd.active_and_eligible_for_ovc" + }, + { + "type": "simple_column", + "alias": "inactive_and_eligible_for_ovc", + "column": "hmsd.inactive_and_eligible_for_ovc" + }, + { + "type": "simple_column", + "alias": "enrolled_in_ovc_this_month", + "column": "hmsd.enrolled_in_ovc_this_month" + }, + { + "type": "simple_column", + "alias": "ovc_non_enrolment_declined", + "column": "hmsd.ovc_non_enrolment_declined" + }, + { + "type": "simple_column", + "alias": "ovc_non_enrolment_out_of_catchment_area", + "column": "hmsd.ovc_non_enrolment_out_of_catchment_area" + }, + { + "type": "simple_column", + "alias": "newly_exited_from_ovc_this_month", + "column": "hmsd.newly_exited_from_ovc_this_month" + }, + { + "type": "simple_column", + "alias": "exited_from_ovc_this_month", + "column": "hmsd.exited_from_ovc_this_month" + }, + { + "type": "derived_column", + "alias": "ovc_non_enrolment_undocumented", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hmsd.active_and_eligible_for_ovc = 1 and (hmsd.enrolled_in_ovc_this_month is null or hmsd.enrolled_in_ovc_this_month = 0 ) and hmsd.ovc_non_enrolment_declined <> 1 and hmsd.ovc_non_enrolment_out_of_catchment_area <> 1, 1,0)" + } + }, + { + "type": "simple_column", + "alias": "due_for_vl_this_month", + "column": "hmsd.due_for_vl_this_month" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/ovc-patient-list-template.json b/app/reporting-framework/json-reports/ovc-patient-list-template.json index 009c97431..6f2bb5e9f 100644 --- a/app/reporting-framework/json-reports/ovc-patient-list-template.json +++ b/app/reporting-framework/json-reports/ovc-patient-list-template.json @@ -1,181 +1,180 @@ { - "name": "ovc-patient-list-template", - "version": "1.0", - "tag": "ovc-patient-list-template", - "description": "OVC Patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fh", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "LEFT", - "joinCondition": "fh.encounter_type = et.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pa.person_id" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "ovc_id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = ovc_id.patient_id AND (ovc_id.voided IS NULL || ovc_id.voided = 0) AND ovc_id.identifier_type = 43" - } - } - - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "ovc_identifier", - "column": "ovc_id.identifier" - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(fh.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" - }, - { - "type": "derived_column", - "alias": "exit_reason", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "fh.ovc_exit_reason = 8204", - "value": "Graduated" - }, - { - "condition": "fh.ovc_exit_reason = 11292", - "value": "Attrition" - }, - { - "condition": "fh.ovc_exit_reason = 10119", - "value": "Transfer out" - }, - { - "condition": "fh.ovc_exit_reason = 8640", - "value": "Wrong enrollment" - } - ] - } - }, - { - "type": "simple_column", - "alias": "disclosure_status", - "column": "fh.hiv_status_disclosed" - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - }, - { - "type": "simple_column", - "alias": "county", - "column": "pa.address1" - }, - { - "type": "simple_column", - "alias": "sub_county", - "column": "pa.address2" - }, - { - "type": "simple_column", - "alias": "ward", - "column": "pa.address7" - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "ovc-patient-list-template", + "version": "1.0", + "tag": "ovc-patient-list-template", + "description": "OVC Patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fh", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "LEFT", + "joinCondition": "fh.encounter_type = et.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pa.person_id" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "ovc_id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = ovc_id.patient_id AND (ovc_id.voided IS NULL || ovc_id.voided = 0) AND ovc_id.identifier_type = 43" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "ovc_identifier", + "column": "ovc_id.identifier" + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(fh.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" + }, + { + "type": "derived_column", + "alias": "exit_reason", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "fh.ovc_exit_reason = 8204", + "value": "Graduated" + }, + { + "condition": "fh.ovc_exit_reason = 11292", + "value": "Attrition" + }, + { + "condition": "fh.ovc_exit_reason = 10119", + "value": "Transfer out" + }, + { + "condition": "fh.ovc_exit_reason = 8640", + "value": "Wrong enrollment" + } + ] + } + }, + { + "type": "simple_column", + "alias": "disclosure_status", + "column": "fh.hiv_status_disclosed" + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + }, + { + "type": "simple_column", + "alias": "county", + "column": "pa.address1" + }, + { + "type": "simple_column", + "alias": "sub_county", + "column": "pa.address2" + }, + { + "type": "simple_column", + "alias": "ward", + "column": "pa.address7" + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/ovc-report.json b/app/reporting-framework/json-reports/ovc-report.json index 650ff8876..a9c0637aa 100644 --- a/app/reporting-framework/json-reports/ovc-report.json +++ b/app/reporting-framework/json-reports/ovc-report.json @@ -1,6 +1,3 @@ { - "reports": [ - "ovcInHivDatasetAggregate", - "ovcInHeiDatasetAggregate" - ] -} \ No newline at end of file + "reports": ["ovcInHivDatasetAggregate", "ovcInHeiDatasetAggregate"] +} diff --git a/app/reporting-framework/json-reports/patient-daily-care-status.json b/app/reporting-framework/json-reports/patient-daily-care-status.json index 5b0253621..4d1cb3c1a 100644 --- a/app/reporting-framework/json-reports/patient-daily-care-status.json +++ b/app/reporting-framework/json-reports/patient-daily-care-status.json @@ -1,43 +1,42 @@ { - "name": "patient_daily_care_status", - "version": "1.0", - "tag": "patient_daily_care_status", - "description": "Patient Daily Care Status", - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "t1" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "patient_daily_care_status", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN TIMESTAMPDIFF(DAY, IF(rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)),'{referenceDate}') <= 90 AND transfer_out IS NULL AND COALESCE(death_date, out_of_care) IS NULL THEN 'active' WHEN TIMESTAMPDIFF(DAY, IF(rtc_date, rtc_date, DATE_ADD(encounter_datetime, INTERVAL 30 DAY)), '{referenceDate}') > 90 THEN 'ltfu' WHEN transfer_out IS NOT NULL AND COALESCE(death_date) IS NULL THEN 'transfered_out' END" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.uuid = ?", - "parameterName": "patient_uuid" - }, - { - "filterType": "tableColumns", - "conditionExpression": "is_clinical_encounter = 1", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "next_clinical_datetime_hiv IS NULL", - "parameterName": "" - } - ] + "name": "patient_daily_care_status", + "version": "1.0", + "tag": "patient_daily_care_status", + "description": "Patient Daily Care Status", + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "t1" } - -} \ No newline at end of file + ], + "columns": [ + { + "type": "derived_column", + "alias": "patient_daily_care_status", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN TIMESTAMPDIFF(DAY, IF(rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)),'{referenceDate}') <= 90 AND transfer_out IS NULL AND COALESCE(death_date, out_of_care) IS NULL THEN 'active' WHEN TIMESTAMPDIFF(DAY, IF(rtc_date, rtc_date, DATE_ADD(encounter_datetime, INTERVAL 30 DAY)), '{referenceDate}') > 90 THEN 'ltfu' WHEN transfer_out IS NOT NULL AND COALESCE(death_date) IS NULL THEN 'transfered_out' END" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.uuid = ?", + "parameterName": "patient_uuid" + }, + { + "filterType": "tableColumns", + "conditionExpression": "is_clinical_encounter = 1", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "next_clinical_datetime_hiv IS NULL", + "parameterName": "" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/patient-flow.json b/app/reporting-framework/json-reports/patient-flow.json index 19acd0a9b..2ca5972d1 100644 --- a/app/reporting-framework/json-reports/patient-flow.json +++ b/app/reporting-framework/json-reports/patient-flow.json @@ -1,299 +1,297 @@ { - "name": "patientFlow", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "amrs.visit", - "alias": "t1" - }, - { - "table": "amrs.encounter", - "alias": "t4", - "join": { - "type": "LEFT", - "joinCondition": "t1.visit_id=t4.visit_id" - } - }, - { - "table": "amrs.person_name", - "alias": "t2", - "join": { - "type": "LEFT", - "joinCondition": "t1.patient_id = t2.person_id and (t2.voided is null || t2.voided = 0)" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "t3", - "join": { - "type": "LEFT", - "joinCondition": "t1.patient_id = t3.patient_id" - } - }, - { - "table": "amrs.person", - "alias": "t5", - "join": { - "type": "LEFT", - "joinCondition": "t1.patient_id = t5.person_id" - } - }, - { - "table": "amrs.encounter_provider", - "alias": "t6", - "join": { - "type": "LEFT", - "joinCondition": "t4.encounter_id=t6.encounter_id" - } - }, - { - "table": "amrs.provider", - "alias": "t7", - "join": { - "type": "LEFT", - "joinCondition": "t7.provider_id = t6.provider_id" - } - }, - { - "table": "amrs.encounter_type", - "alias": "t9", - "join": { - "type": "LEFT", - "joinCondition": "t9.encounter_type_id=t4.encounter_type" - } - }, - { - "table": "etl.clinical_encounter_type_map", - "alias": "t13", - "join": { - "type": "LEFT", - "joinCondition": "t9.encounter_type_id= t13.encounter_type" - } - }, - { - "table": "amrs.person_name", - "alias": "t8", - "join": { - "type": "LEFT", - "joinCondition": "t7.person_id = t8.person_id and (t8.voided is null || t8.voided = 0)" - } - }, - { - "table": "amrs.users", - "alias": "t10", - "join": { - "type": "LEFT", - "joinCondition": "t1.creator = t10.user_id" - } - }, - { - "table": "amrs.person_name", - "alias": "t11", - "join": { - "type": "LEFT", - "joinCondition": "t10.person_id = t11.person_id and (t11.voided is null || t11.voided = 0)" - } - }, - { - "table": "amrs.location", - "alias": "t12", - "join": { - "type": "LEFT", - "joinCondition": "t1.location_id = t12.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "visit_id", - "column": "t1.visit_id" - }, - { - "type": "simple_column", - "alias": "visit_start", - "column": "t1.date_started" - }, - { - "type": "derived_column", - "alias": "triaged", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when t4.encounter_type=110 then t4.encounter_datetime else null end" - } - }, - { - "type": "derived_column", - "alias": "time_to_be_triaged", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when t4.encounter_type=110 then TIMESTAMPDIFF(MINUTE,t1.date_started,t4.encounter_datetime) else null end" - } - }, - { - "type": "derived_column", - "alias": "seen_by_clinician", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when t13.is_clinical = 1 then t4.encounter_datetime else null end" - } - }, - { - "type": "simple_column", - "alias": "visit_end", - "column": "t1.date_stopped" - }, - { - "type": "simple_column", - "alias": "creator", - "column": "t1.creator" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "t4.encounter_type" - }, - { - "type": "simple_column", - "alias": "encounter_type_name", - "column": "t9.name" - }, - { - "type": "simple_column", - "alias": "encounter_start", - "column": "t4.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "encounter_end", - "column": "t4.date_created" - }, - { - "type": "simple_column", - "alias": "patient_id", - "column": "t1.patient_id" - }, - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t5.uuid" - }, - { - "type": "simple_column", - "alias": "given_name", - "column": "t2.given_name" - }, - { - "type": "simple_column", - "alias": "middle_name", - "column": "t2.middle_name" - }, - { - "type": "simple_column", - "alias": "family_name", - "column": "t2.family_name" - }, - { - "type": "simple_column", - "alias": "identifiers", - "column": "group_concat(distinct t3.identifier)" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t7.person_id" - }, - { - "type": "simple_column", - "alias": "visit_person_id", - "column": "t10.person_id" - }, - { - "type": "simple_column", - "alias": "provider_given_name", - "column": "t8.given_name" - }, - { - "type": "simple_column", - "alias": "provider_middle_name", - "column": "t8.middle_name" - }, - { - "type": "simple_column", - "alias": "provider_family_name", - "column": "t8.family_name" - }, - { - "type": "simple_column", - "alias": "Visit_creator", - "column": "t10.creator" - }, - { - "type": "simple_column", - "alias": "visit_start_given_name", - "column": "t11.given_name" - }, - { - "type": "simple_column", - "alias": "visit_start_middle_name", - "column": "t11.middle_name" - }, - { - "type": "simple_column", - "alias": "visit_start_family_name", - "column": "t11.family_name" - }, - { - "type": "simple_column", - "alias": "location", - "column": "t12.name" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t12.location_id" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "date(t1.date_started) = ?", - "parameterName": "dateStarted" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t1.location_id in ?", - "parameterName": "locations" - } - ] - }, - "orderBy":{ - "orderByParam": "orderByParam", - "columns": [ - { - "column": "t1.date_started", - "order": "asc" - }, - { - "column": "gender", - "order": "t1.visit_id" - }, - { - "column": "t4.date_created", - "order": "asc" - } - ] - }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "t4.encounter_id" - ], - "excludeParam": "excludeParam" + "name": "patientFlow", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "amrs.visit", + "alias": "t1" + }, + { + "table": "amrs.encounter", + "alias": "t4", + "join": { + "type": "LEFT", + "joinCondition": "t1.visit_id=t4.visit_id" + } + }, + { + "table": "amrs.person_name", + "alias": "t2", + "join": { + "type": "LEFT", + "joinCondition": "t1.patient_id = t2.person_id and (t2.voided is null || t2.voided = 0)" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "t3", + "join": { + "type": "LEFT", + "joinCondition": "t1.patient_id = t3.patient_id" + } + }, + { + "table": "amrs.person", + "alias": "t5", + "join": { + "type": "LEFT", + "joinCondition": "t1.patient_id = t5.person_id" + } + }, + { + "table": "amrs.encounter_provider", + "alias": "t6", + "join": { + "type": "LEFT", + "joinCondition": "t4.encounter_id=t6.encounter_id" + } + }, + { + "table": "amrs.provider", + "alias": "t7", + "join": { + "type": "LEFT", + "joinCondition": "t7.provider_id = t6.provider_id" + } + }, + { + "table": "amrs.encounter_type", + "alias": "t9", + "join": { + "type": "LEFT", + "joinCondition": "t9.encounter_type_id=t4.encounter_type" + } + }, + { + "table": "etl.clinical_encounter_type_map", + "alias": "t13", + "join": { + "type": "LEFT", + "joinCondition": "t9.encounter_type_id= t13.encounter_type" + } + }, + { + "table": "amrs.person_name", + "alias": "t8", + "join": { + "type": "LEFT", + "joinCondition": "t7.person_id = t8.person_id and (t8.voided is null || t8.voided = 0)" + } + }, + { + "table": "amrs.users", + "alias": "t10", + "join": { + "type": "LEFT", + "joinCondition": "t1.creator = t10.user_id" + } + }, + { + "table": "amrs.person_name", + "alias": "t11", + "join": { + "type": "LEFT", + "joinCondition": "t10.person_id = t11.person_id and (t11.voided is null || t11.voided = 0)" + } + }, + { + "table": "amrs.location", + "alias": "t12", + "join": { + "type": "LEFT", + "joinCondition": "t1.location_id = t12.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "visit_id", + "column": "t1.visit_id" + }, + { + "type": "simple_column", + "alias": "visit_start", + "column": "t1.date_started" + }, + { + "type": "derived_column", + "alias": "triaged", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t4.encounter_type=110 then t4.encounter_datetime else null end" + } + }, + { + "type": "derived_column", + "alias": "time_to_be_triaged", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t4.encounter_type=110 then TIMESTAMPDIFF(MINUTE,t1.date_started,t4.encounter_datetime) else null end" + } + }, + { + "type": "derived_column", + "alias": "seen_by_clinician", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when t13.is_clinical = 1 then t4.encounter_datetime else null end" + } + }, + { + "type": "simple_column", + "alias": "visit_end", + "column": "t1.date_stopped" + }, + { + "type": "simple_column", + "alias": "creator", + "column": "t1.creator" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "t4.encounter_type" + }, + { + "type": "simple_column", + "alias": "encounter_type_name", + "column": "t9.name" + }, + { + "type": "simple_column", + "alias": "encounter_start", + "column": "t4.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "encounter_end", + "column": "t4.date_created" + }, + { + "type": "simple_column", + "alias": "patient_id", + "column": "t1.patient_id" + }, + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t5.uuid" + }, + { + "type": "simple_column", + "alias": "given_name", + "column": "t2.given_name" + }, + { + "type": "simple_column", + "alias": "middle_name", + "column": "t2.middle_name" + }, + { + "type": "simple_column", + "alias": "family_name", + "column": "t2.family_name" + }, + { + "type": "simple_column", + "alias": "identifiers", + "column": "group_concat(distinct t3.identifier)" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t7.person_id" + }, + { + "type": "simple_column", + "alias": "visit_person_id", + "column": "t10.person_id" + }, + { + "type": "simple_column", + "alias": "provider_given_name", + "column": "t8.given_name" + }, + { + "type": "simple_column", + "alias": "provider_middle_name", + "column": "t8.middle_name" + }, + { + "type": "simple_column", + "alias": "provider_family_name", + "column": "t8.family_name" + }, + { + "type": "simple_column", + "alias": "Visit_creator", + "column": "t10.creator" + }, + { + "type": "simple_column", + "alias": "visit_start_given_name", + "column": "t11.given_name" + }, + { + "type": "simple_column", + "alias": "visit_start_middle_name", + "column": "t11.middle_name" + }, + { + "type": "simple_column", + "alias": "visit_start_family_name", + "column": "t11.family_name" + }, + { + "type": "simple_column", + "alias": "location", + "column": "t12.name" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "t12.location_id" } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "date(t1.date_started) = ?", + "parameterName": "dateStarted" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t1.location_id in ?", + "parameterName": "locations" + } + ] + }, + "orderBy": { + "orderByParam": "orderByParam", + "columns": [ + { + "column": "t1.date_started", + "order": "asc" + }, + { + "column": "gender", + "order": "t1.visit_id" + }, + { + "column": "t4.date_created", + "order": "asc" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["t4.encounter_id"], + "excludeParam": "excludeParam" + } +} diff --git a/app/reporting-framework/json-reports/patient-gain-lose-dataset-1.json b/app/reporting-framework/json-reports/patient-gain-lose-dataset-1.json index 8bf398144..1b5943563 100644 --- a/app/reporting-framework/json-reports/patient-gain-lose-dataset-1.json +++ b/app/reporting-framework/json-reports/patient-gain-lose-dataset-1.json @@ -1,66 +1,66 @@ { - "name": "patientGainLoseDatasetOne", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hiv_monthly_report_dataset_frozen", - "alias": "t2" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t2.person_id" - }, - { - "type": "simple_column", - "alias": "starting_month", - "column": "t2.endDate" - }, - { - "type": "simple_column", - "alias": "starting_status", - "column": "t2.status" - }, - { - "type": "derived_column", - "alias": "on_art_starting", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "(IF(t2.status = 'active' AND cur_arv_meds is not null, 1, 0))" - } - }, - { - "type": "derived_column", - "alias": "not_on_art_starting", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "(IF(t2.status = 'active' AND cur_arv_meds is null, 1, 0))" - } - }, - { - "type": "simple_column", - "alias": "starting_location_uuid", - "column": "t2.location_uuid" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t2.location_uuid = ?", - "parameterName": "locationUuid" - }, - { - "filterType": "tableColumns", - "conditionExpression": "t2.endDate = ?", - "parameterName": "startingMonth" - } - ] + "name": "patientGainLoseDatasetOne", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hiv_monthly_report_dataset_frozen", + "alias": "t2" } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t2.person_id" + }, + { + "type": "simple_column", + "alias": "starting_month", + "column": "t2.endDate" + }, + { + "type": "simple_column", + "alias": "starting_status", + "column": "t2.status" + }, + { + "type": "derived_column", + "alias": "on_art_starting", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "(IF(t2.status = 'active' AND cur_arv_meds is not null, 1, 0))" + } + }, + { + "type": "derived_column", + "alias": "not_on_art_starting", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "(IF(t2.status = 'active' AND cur_arv_meds is null, 1, 0))" + } + }, + { + "type": "simple_column", + "alias": "starting_location_uuid", + "column": "t2.location_uuid" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t2.location_uuid = ?", + "parameterName": "locationUuid" + }, + { + "filterType": "tableColumns", + "conditionExpression": "t2.endDate = ?", + "parameterName": "startingMonth" + } + ] + } } diff --git a/app/reporting-framework/json-reports/patient-gain-lose-dataset-2.json b/app/reporting-framework/json-reports/patient-gain-lose-dataset-2.json index 93d4f188d..026f79b08 100644 --- a/app/reporting-framework/json-reports/patient-gain-lose-dataset-2.json +++ b/app/reporting-framework/json-reports/patient-gain-lose-dataset-2.json @@ -1,99 +1,99 @@ { - "name": "patientGainLoseDatasetTwo", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hiv_monthly_report_dataset_frozen", - "alias": "t1" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "ending_month", - "column": "t1.endDate" - }, - { - "type": "derived_column", - "alias": "ending_status", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when location_uuid = '{locationUuid}' then status else null end" - } - }, - { - "type": "simple_column", - "alias": "ending_location_uuid", - "column": "t1.location_uuid" - }, - { - "type": "derived_column", - "alias": "on_art_ending", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "(IF(t1.location_uuid = '{locationUuid}' AND t1.status = 'active' AND cur_arv_meds IS NOT NULL, 1, 0))" - } - }, - { - "type": "derived_column", - "alias": "not_on_art_ending", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "(IF(t1.location_uuid = '{locationUuid}' AND t1.status = 'active' AND cur_arv_meds IS NULL, 1, 0))" - } - }, - { - "type": "simple_column", - "alias": "transfer_in_date", - "column": "t1.transfer_in_date" - }, - { - "type": "simple_column", - "alias": "transfer_in_location_id", - "column": "t1.transfer_in_location_id" - }, - { - "type": "simple_column", - "alias": "transfer_out_date", - "column": "t1.transfer_out_date" - }, - { - "type": "simple_column", - "alias": "transfer_out_location_id", - "column": "t1.transfer_out_location_id" - }, - { - "type": "simple_column", - "alias": "death_date", - "column": "t1.death_date" - }, - { - "type": "simple_column", - "alias": "enrollment_date", - "column": "t1.enrollment_date" - }, - { - "type": "simple_column", - "alias": "person_uuid", - "column": "t1.person_uuid" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.endDate = ?", - "parameterName": "endingMonth" - } - ] + "name": "patientGainLoseDatasetTwo", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hiv_monthly_report_dataset_frozen", + "alias": "t1" } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "ending_month", + "column": "t1.endDate" + }, + { + "type": "derived_column", + "alias": "ending_status", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when location_uuid = '{locationUuid}' then status else null end" + } + }, + { + "type": "simple_column", + "alias": "ending_location_uuid", + "column": "t1.location_uuid" + }, + { + "type": "derived_column", + "alias": "on_art_ending", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "(IF(t1.location_uuid = '{locationUuid}' AND t1.status = 'active' AND cur_arv_meds IS NOT NULL, 1, 0))" + } + }, + { + "type": "derived_column", + "alias": "not_on_art_ending", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "(IF(t1.location_uuid = '{locationUuid}' AND t1.status = 'active' AND cur_arv_meds IS NULL, 1, 0))" + } + }, + { + "type": "simple_column", + "alias": "transfer_in_date", + "column": "t1.transfer_in_date" + }, + { + "type": "simple_column", + "alias": "transfer_in_location_id", + "column": "t1.transfer_in_location_id" + }, + { + "type": "simple_column", + "alias": "transfer_out_date", + "column": "t1.transfer_out_date" + }, + { + "type": "simple_column", + "alias": "transfer_out_location_id", + "column": "t1.transfer_out_location_id" + }, + { + "type": "simple_column", + "alias": "death_date", + "column": "t1.death_date" + }, + { + "type": "simple_column", + "alias": "enrollment_date", + "column": "t1.enrollment_date" + }, + { + "type": "simple_column", + "alias": "person_uuid", + "column": "t1.person_uuid" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.endDate = ?", + "parameterName": "endingMonth" + } + ] + } } diff --git a/app/reporting-framework/json-reports/patient-gain-loses-aggregate.json b/app/reporting-framework/json-reports/patient-gain-loses-aggregate.json index cd7dc6705..42f2b9089 100644 --- a/app/reporting-framework/json-reports/patient-gain-loses-aggregate.json +++ b/app/reporting-framework/json-reports/patient-gain-loses-aggregate.json @@ -1,194 +1,195 @@ { - "name": "patientGainLosesAggregateReport", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "patientGainLosesBaseReport", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [ - { - "dataSet": "patientGainLosesBaseReport", - "alias": "pgl" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "on_art_starting", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(on_art_starting)" - } - }, - { - "type": "derived_column", - "alias": "not_on_art_starting", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(not_on_art_starting)" - } - }, - { - "type": "derived_column", - "alias": "on_art_ending", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(on_art_ending)" - } - }, - { - "type": "derived_column", - "alias": "not_on_art_ending", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(not_on_art_ending)" - } - }, - { - "type": "derived_column", - "alias": "starting_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(starting_active)" - } - }, - { - "type": "derived_column", - "alias": "still_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(still_active)" - } - }, - { - "type": "derived_column", - "alias": "starting_not_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(starting_not_active)" - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(newly_enrolled)" - } - }, - { - "type": "derived_column", - "alias": "transferred_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(transferred_in)" - } - }, - { - "type": "derived_column", - "alias": "return_to_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(return_to_care)" - } - }, - { - "type": "derived_column", - "alias": "gained_other", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(gained_other)" - } - }, - { - "type": "derived_column", - "alias": "transfer_out", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(transfer_out)" - } - }, - { - "type": "derived_column", - "alias": "transfer_out_undocumented", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(transfer_out_undocumented)" - } - }, - { - "type": "derived_column", - "alias": "transfer_out_documented", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(transfer_out_documented)" - } - }, - { - "type": "derived_column", - "alias": "lost_other", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(lost_other)" - } - }, - { - "type": "derived_column", - "alias": "ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(ltfu)" - } - }, - { - "type": "derived_column", - "alias": "dead", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(dead)" - } - }, - { - "type": "derived_column", - "alias": "ending_not_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(ending_not_active)" - } - }, - { - "type": "derived_column", - "alias": "ending_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(ending_active)" - } - }, - { - "type": "derived_column", - "alias": "total_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(*)" - } - } - ], - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "name": "patientGainLosesAggregateReport", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "patientGainLosesBaseReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "patientGainLosesBaseReport", + "alias": "pgl" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "on_art_starting", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(on_art_starting)" + } + }, + { + "type": "derived_column", + "alias": "not_on_art_starting", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(not_on_art_starting)" + } + }, + { + "type": "derived_column", + "alias": "on_art_ending", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(on_art_ending)" + } + }, + { + "type": "derived_column", + "alias": "not_on_art_ending", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(not_on_art_ending)" + } + }, + { + "type": "derived_column", + "alias": "starting_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(starting_active)" + } + }, + { + "type": "derived_column", + "alias": "still_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(still_active)" + } + }, + { + "type": "derived_column", + "alias": "starting_not_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(starting_not_active)" + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(newly_enrolled)" + } + }, + { + "type": "derived_column", + "alias": "transferred_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(transferred_in)" + } + }, + { + "type": "derived_column", + "alias": "return_to_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(return_to_care)" + } + }, + { + "type": "derived_column", + "alias": "gained_other", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(gained_other)" + } + }, + { + "type": "derived_column", + "alias": "transfer_out", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(transfer_out)" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_undocumented", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(transfer_out_undocumented)" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_documented", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(transfer_out_documented)" + } + }, + { + "type": "derived_column", + "alias": "lost_other", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(lost_other)" + } + }, + { + "type": "derived_column", + "alias": "ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(ltfu)" + } + }, + { + "type": "derived_column", + "alias": "dead", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(dead)" + } + }, + { + "type": "derived_column", + "alias": "ending_not_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(ending_not_active)" + } + }, + { + "type": "derived_column", + "alias": "ending_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(ending_active)" + } + }, + { + "type": "derived_column", + "alias": "total_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(*)" + } + } + ], + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } + } } diff --git a/app/reporting-framework/json-reports/patient-gain-loses-base.json b/app/reporting-framework/json-reports/patient-gain-loses-base.json index 627897672..5af85ed78 100644 --- a/app/reporting-framework/json-reports/patient-gain-loses-base.json +++ b/app/reporting-framework/json-reports/patient-gain-loses-base.json @@ -1,259 +1,259 @@ { - "name": "patientGainLosesBaseReport", - "version": "1.0", - "tag": "patient-gain-loses", - "description": "Patient gains and loses", - "uses": [ - { - "name": "patientGainLoseDatasetOne", - "version": "1.0", - "type": "dataset_def1" - }, - { - "name": "patientGainLoseDatasetTwo", - "version": "1.0", - "type": "dataset_def2" - } - ], - "sources": [ - { - "dataSet": "patientGainLoseDatasetTwo", - "alias": "t3" - }, - { - "dataSet": "patientGainLoseDatasetOne", - "alias": "t4", - "join": { - "type": "LEFT", - "joinCondition": "t4.person_id = t3.person_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t3.person_id" - }, - { - "type": "simple_column", - "alias": "person_uuid", - "column": "person_uuid" - }, - { - "type": "simple_column", - "alias": "starting_month", - "column": "starting_month" - }, - { - "type": "simple_column", - "alias": "ending_month", - "column": "ending_month" - }, - { - "type": "simple_column", - "alias": "starting_status", - "column": "starting_status" - }, - { - "type": "simple_column", - "alias": "ending_status", - "column": "ending_status" - }, - { - "type": "simple_column", - "alias": "starting_location_uuid", - "column": "t4.starting_location_uuid" - }, - { - "type": "simple_column", - "alias": "ending_location_uuid", - "column": "t3.ending_location_uuid" - }, - { - "type": "simple_column", - "alias": "on_art_starting", - "column": "t4.on_art_starting" - }, - { - "type": "simple_column", - "alias": "not_on_art_starting", - "column": "t4.not_on_art_starting" - }, - { - "type": "simple_column", - "alias": "on_art_ending", - "column": "t3.on_art_ending" - }, - { - "type": "simple_column", - "alias": "not_on_art_ending", - "column": "t3.not_on_art_ending" - }, - { - "type": "derived_column", - "alias": "starting_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "(IF(starting_status = 'active', 1, 0))" - } - }, - { - "type": "derived_column", - "alias": "ending_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "(IF(ending_status = 'active', 1, 0))" - } - }, - { - "type": "derived_column", - "alias": "starting_not_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "transferred_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND t3.transfer_in_date >= '{startingMonth}' AND t3.transfer_in_date <= '{endingMonth}' THEN 1 ELSE 0 END " - } - }, - { - "type": "derived_column", - "alias": "return_to_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND t3.transfer_in_date >= '{startingMonth}' AND t3.transfer_in_date <= '{endingMonth}' THEN 1 ELSE 0 END ) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 AND (starting_status = 'ltfu' OR starting_status = 'defaulter') THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "gained_other", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND t3.transfer_in_date >= '{startingMonth}' AND t3.transfer_in_date <= '{endingMonth}' THEN 1 ELSE 0 END ) = 0 AND ((IF(starting_status = 'active', 1, 0))) = 0 AND (CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND t3.transfer_in_date >= '{startingMonth}' AND t3.transfer_in_date <= '{endingMonth}' THEN 1 ELSE 0 END ) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 AND (starting_status = 'ltfu' OR starting_status = 'defaulter') THEN 1 ELSE 0 END) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "transfer_out", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "ending_not_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "transfer_out_documented", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 1 AND (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND t3.transfer_out_date IS NOT NULL THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "transfer_out_undocumented", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 1 AND (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND t3.transfer_out_date IS NULL THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "dead", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND ending_status = 'dead' THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND (ending_status = 'ltfu' OR ending_status = 'defaulter') THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "lost_other", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND ending_status = 'dead' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND (ending_status = 'ltfu' OR ending_status = 'defaulter') THEN 1 ELSE 0 END) = 0 THEN 1 ELSE 0 END" - } - }, - { - "type": "derived_column", - "alias": "still_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 1 AND t3.ending_location_uuid = t4.starting_location_uuid THEN 1 ELSE 0 END" - } - }, - { - "type": "simple_column", - "alias": "transfer_in_date", - "column": "t3.transfer_in_date" - }, - { - "type": "simple_column", - "alias": "transfer_in_location_id", - "column": "t3.transfer_in_location_id" - }, - { - "type": "simple_column", - "alias": "transfer_out_date", - "column": "t3.transfer_out_date" - }, - { - "type": "simple_column", - "alias": "transfer_out_location_id", - "column": "t3.transfer_out_location_id" - }, - { - "type": "simple_column", - "alias": "death_date", - "column": "t3.death_date" - }, - { - "type": "simple_column", - "alias": "enrollment_date", - "column": "t3.enrollment_date" - } - ], - "filters": { - "conditionJoinOperator": "AND", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "", - "parameterName": "endingMonth" - }, - { - "filterType": "tableColumns", - "conditionExpression": "", - "parameterName": "startingMonth" - } - ] + "name": "patientGainLosesBaseReport", + "version": "1.0", + "tag": "patient-gain-loses", + "description": "Patient gains and loses", + "uses": [ + { + "name": "patientGainLoseDatasetOne", + "version": "1.0", + "type": "dataset_def1" + }, + { + "name": "patientGainLoseDatasetTwo", + "version": "1.0", + "type": "dataset_def2" } + ], + "sources": [ + { + "dataSet": "patientGainLoseDatasetTwo", + "alias": "t3" + }, + { + "dataSet": "patientGainLoseDatasetOne", + "alias": "t4", + "join": { + "type": "LEFT", + "joinCondition": "t4.person_id = t3.person_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t3.person_id" + }, + { + "type": "simple_column", + "alias": "person_uuid", + "column": "person_uuid" + }, + { + "type": "simple_column", + "alias": "starting_month", + "column": "starting_month" + }, + { + "type": "simple_column", + "alias": "ending_month", + "column": "ending_month" + }, + { + "type": "simple_column", + "alias": "starting_status", + "column": "starting_status" + }, + { + "type": "simple_column", + "alias": "ending_status", + "column": "ending_status" + }, + { + "type": "simple_column", + "alias": "starting_location_uuid", + "column": "t4.starting_location_uuid" + }, + { + "type": "simple_column", + "alias": "ending_location_uuid", + "column": "t3.ending_location_uuid" + }, + { + "type": "simple_column", + "alias": "on_art_starting", + "column": "t4.on_art_starting" + }, + { + "type": "simple_column", + "alias": "not_on_art_starting", + "column": "t4.not_on_art_starting" + }, + { + "type": "simple_column", + "alias": "on_art_ending", + "column": "t3.on_art_ending" + }, + { + "type": "simple_column", + "alias": "not_on_art_ending", + "column": "t3.not_on_art_ending" + }, + { + "type": "derived_column", + "alias": "starting_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "(IF(starting_status = 'active', 1, 0))" + } + }, + { + "type": "derived_column", + "alias": "ending_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "(IF(ending_status = 'active', 1, 0))" + } + }, + { + "type": "derived_column", + "alias": "starting_not_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "transferred_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND t3.transfer_in_date >= '{startingMonth}' AND t3.transfer_in_date <= '{endingMonth}' THEN 1 ELSE 0 END " + } + }, + { + "type": "derived_column", + "alias": "return_to_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND t3.transfer_in_date >= '{startingMonth}' AND t3.transfer_in_date <= '{endingMonth}' THEN 1 ELSE 0 END ) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 AND (starting_status = 'ltfu' OR starting_status = 'defaulter') THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "gained_other", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND t3.transfer_in_date >= '{startingMonth}' AND t3.transfer_in_date <= '{endingMonth}' THEN 1 ELSE 0 END ) = 0 AND ((IF(starting_status = 'active', 1, 0))) = 0 AND (CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END) = 1 AND t3.enrollment_date >= '{startingMonth}' AND t3.enrollment_date <= '{endingMonth}' THEN 1 ELSE 0 END) = 0 AND t3.transfer_in_date >= '{startingMonth}' AND t3.transfer_in_date <= '{endingMonth}' THEN 1 ELSE 0 END ) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 AND (starting_status = 'ltfu' OR starting_status = 'defaulter') THEN 1 ELSE 0 END) = 0 AND ((IF(ending_status = 'active', 1, 0))) = 1 THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "transfer_out", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "ending_not_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_documented", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 1 AND (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND t3.transfer_out_date IS NOT NULL THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_undocumented", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 1 AND (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND t3.transfer_out_date IS NULL THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "dead", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND ending_status = 'dead' THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND (ending_status = 'ltfu' OR ending_status = 'defaulter') THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "lost_other", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND ending_status = 'dead' THEN 1 ELSE 0 END) = 0 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND (CASE WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND starting_location_uuid != ending_location_uuid THEN 1 WHEN (CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 0 THEN 1 ELSE 0 END) = 1 AND ending_status = 'transfer_out' THEN 1 ELSE 0 END) = 0 AND (ending_status = 'ltfu' OR ending_status = 'defaulter') THEN 1 ELSE 0 END) = 0 THEN 1 ELSE 0 END" + } + }, + { + "type": "derived_column", + "alias": "still_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CASE WHEN ((IF(starting_status = 'active', 1, 0))) = 1 AND ((IF(ending_status = 'active', 1, 0))) = 1 AND t3.ending_location_uuid = t4.starting_location_uuid THEN 1 ELSE 0 END" + } + }, + { + "type": "simple_column", + "alias": "transfer_in_date", + "column": "t3.transfer_in_date" + }, + { + "type": "simple_column", + "alias": "transfer_in_location_id", + "column": "t3.transfer_in_location_id" + }, + { + "type": "simple_column", + "alias": "transfer_out_date", + "column": "t3.transfer_out_date" + }, + { + "type": "simple_column", + "alias": "transfer_out_location_id", + "column": "t3.transfer_out_location_id" + }, + { + "type": "simple_column", + "alias": "death_date", + "column": "t3.death_date" + }, + { + "type": "simple_column", + "alias": "enrollment_date", + "column": "t3.enrollment_date" + } + ], + "filters": { + "conditionJoinOperator": "AND", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "", + "parameterName": "endingMonth" + }, + { + "filterType": "tableColumns", + "conditionExpression": "", + "parameterName": "startingMonth" + } + ] + } } diff --git a/app/reporting-framework/json-reports/patient-list-frozen-template.json b/app/reporting-framework/json-reports/patient-list-frozen-template.json index a4aad06a9..95d1d913d 100644 --- a/app/reporting-framework/json-reports/patient-list-frozen-template.json +++ b/app/reporting-framework/json-reports/patient-list-frozen-template.json @@ -1,153 +1,152 @@ { - "name": "patient_list_frozen_template", - "version": "1.0", - "tag": "patient_list_frozen_template", - "description": "Patient list frozen template, for use against the hiv monthly frozen table", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fh", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "LEFT", - "joinCondition": "fh.encounter_type = et.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pa.person_id" - } - } - - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(fh.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "latest_vl", - "column": "fh.vl_1" - }, - { - "type": "simple_column", - "alias": "latest_vl_date", - "column": "date_format(fh.vl_1_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" - }, - { - "type": "simple_column", - "alias": "cur_meds", - "column": "fh.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "fh.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "previous_vl", - "column": "fh.vl_2" - }, - { - "type": "simple_column", - "alias": "previous_vl_date", - "column": "date_format(fh.vl_2_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "patient_list_frozen_template", + "version": "1.0", + "tag": "patient_list_frozen_template", + "description": "Patient list frozen template, for use against the hiv monthly frozen table", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fh", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "LEFT", + "joinCondition": "fh.encounter_type = et.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pa.person_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(fh.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "latest_vl", + "column": "fh.vl_1" + }, + { + "type": "simple_column", + "alias": "latest_vl_date", + "column": "date_format(fh.vl_1_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" + }, + { + "type": "simple_column", + "alias": "cur_meds", + "column": "fh.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "fh.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "previous_vl", + "column": "fh.vl_2" + }, + { + "type": "simple_column", + "alias": "previous_vl_date", + "column": "date_format(fh.vl_2_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/patient-list-prep-template.json b/app/reporting-framework/json-reports/patient-list-prep-template.json index 16934c034..d97f1c454 100644 --- a/app/reporting-framework/json-reports/patient-list-prep-template.json +++ b/app/reporting-framework/json-reports/patient-list-prep-template.json @@ -1,163 +1,162 @@ { - "name": "patient_list_prep_template", - "version": "1.0", - "tag": "patient_list_prep_template", - "description": "", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fh", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "LEFT", - "joinCondition": "fh.encounter_type = et.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pa.person_id" - } - } - - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(fh.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - }, - { - "type": "simple_column", - "alias": "latest_vl", - "column": "fh.vl_1" - }, - { - "type": "simple_column", - "alias": "latest_vl_date", - "column": "fh.vl_1_date" - }, - { - "type": "simple_column", - "alias": "previous_vl", - "column": "fh.vl_2" - }, - { - "type": "simple_column", - "alias": "previous_vl_date", - "column": "fh.vl_2_date" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_start_date", - "column": "fh.arv_first_regimen_start_date" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen", - "column": "fh.arv_first_regimen" - }, - { - "type": "simple_column", - "alias": "cur_meds", - "column": "fh.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "fh.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "patient_list_prep_template", + "version": "1.0", + "tag": "patient_list_prep_template", + "description": "", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fh", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "LEFT", + "joinCondition": "fh.encounter_type = et.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pa.person_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(fh.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + }, + { + "type": "simple_column", + "alias": "latest_vl", + "column": "fh.vl_1" + }, + { + "type": "simple_column", + "alias": "latest_vl_date", + "column": "fh.vl_1_date" + }, + { + "type": "simple_column", + "alias": "previous_vl", + "column": "fh.vl_2" + }, + { + "type": "simple_column", + "alias": "previous_vl_date", + "column": "fh.vl_2_date" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_start_date", + "column": "fh.arv_first_regimen_start_date" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen", + "column": "fh.arv_first_regimen" + }, + { + "type": "simple_column", + "alias": "cur_meds", + "column": "fh.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "fh.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/patient-list-schedules-template.json b/app/reporting-framework/json-reports/patient-list-schedules-template.json index c6da0d56c..a8b30e1d1 100644 --- a/app/reporting-framework/json-reports/patient-list-schedules-template.json +++ b/app/reporting-framework/json-reports/patient-list-schedules-template.json @@ -1,178 +1,178 @@ { - "name": "patient_list_schedules_template", - "version": "1.0", - "tag": "patient_list_schedules_template", - "description": "Patient list schedules template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fh", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "LEFT", - "joinCondition": "fh.encounter_type = et.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pa.person_id" - } - }, - { - "table": "amrs.visit_type", - "alias": "vt", - "join": { - "type": "LEFT", - "joinCondition": "t2.visit_type_id = vt.visit_type_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "t1.birthdate" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(fh.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "latest_vl", - "column": "fh.vl_1" - }, - { - "type": "simple_column", - "alias": "latest_vl_date", - "column": "date_format(fh.vl_1_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" - }, - { - "type": "simple_column", - "alias": "visit_type", - "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(vt.name, ''))" - }, - { - "type": "simple_column", - "alias": "cur_meds", - "column": "fh.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "previous_vl", - "column": "fh.vl_2" - }, - { - "type": "simple_column", - "alias": "previous_vl_date", - "column": "date_format(fh.vl_2_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "patient_list_schedules_template", + "version": "1.0", + "tag": "patient_list_schedules_template", + "description": "Patient list schedules template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fh", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "LEFT", + "joinCondition": "fh.encounter_type = et.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pa.person_id" + } + }, + { + "table": "amrs.visit_type", + "alias": "vt", + "join": { + "type": "LEFT", + "joinCondition": "t2.visit_type_id = vt.visit_type_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "t1.birthdate" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(fh.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "latest_vl", + "column": "fh.vl_1" + }, + { + "type": "simple_column", + "alias": "latest_vl_date", + "column": "date_format(fh.vl_1_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" + }, + { + "type": "simple_column", + "alias": "visit_type", + "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(vt.name, ''))" + }, + { + "type": "simple_column", + "alias": "cur_meds", + "column": "fh.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "previous_vl", + "column": "fh.vl_2" + }, + { + "type": "simple_column", + "alias": "previous_vl_date", + "column": "date_format(fh.vl_2_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/patient-list-template.json b/app/reporting-framework/json-reports/patient-list-template.json index a971ee35b..d69c15c2d 100755 --- a/app/reporting-framework/json-reports/patient-list-template.json +++ b/app/reporting-framework/json-reports/patient-list-template.json @@ -1,165 +1,165 @@ { - "name": "patient_list_template", - "version": "1.0", - "tag": "patient_list_template", - "description": "Patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fh", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "LEFT", - "joinCondition": "fh.encounter_type = et.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pa.person_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "t1.birthdate" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(fh.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "latest_vl", - "column": "fh.vl_1" - }, - { - "type": "simple_column", - "alias": "latest_vl_date", - "column": "date_format(fh.vl_1_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" - }, - { - "type": "simple_column", - "alias": "cur_meds", - "column": "fh.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "previous_vl", - "column": "fh.vl_2" - }, - { - "type": "simple_column", - "alias": "previous_vl_date", - "column": "date_format(fh.vl_2_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "patient_list_template", + "version": "1.0", + "tag": "patient_list_template", + "description": "Patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fh", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "LEFT", + "joinCondition": "fh.encounter_type = et.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pa.person_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "t1.birthdate" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(fh.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "latest_vl", + "column": "fh.vl_1" + }, + { + "type": "simple_column", + "alias": "latest_vl_date", + "column": "date_format(fh.vl_1_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" + }, + { + "type": "simple_column", + "alias": "cur_meds", + "column": "fh.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "previous_vl", + "column": "fh.vl_2" + }, + { + "type": "simple_column", + "alias": "previous_vl_date", + "column": "date_format(fh.vl_2_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/patient-list-with-contacts-template.json b/app/reporting-framework/json-reports/patient-list-with-contacts-template.json index e50d76b6e..05fedc800 100755 --- a/app/reporting-framework/json-reports/patient-list-with-contacts-template.json +++ b/app/reporting-framework/json-reports/patient-list-with-contacts-template.json @@ -1,165 +1,165 @@ { - "name": "patient_list_with_contacts_template", - "version": "1.0", - "tag": "patient_list_template", - "description": "Patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fh", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999, 21)" - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "LEFT", - "joinCondition": "fh.encounter_type = et.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pa.person_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "t1.birthdate" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(fh.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "latest_vl", - "column": "fh.vl_1" - }, - { - "type": "simple_column", - "alias": "latest_vl_date", - "column": "date_format(fh.vl_1_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" - }, - { - "type": "simple_column", - "alias": "cur_meds", - "column": "fh.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "previous_vl", - "column": "fh.vl_2" - }, - { - "type": "simple_column", - "alias": "previous_vl_date", - "column": "date_format(fh.vl_2_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "patient_list_with_contacts_template", + "version": "1.0", + "tag": "patient_list_template", + "description": "Patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fh", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999, 21)" + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "LEFT", + "joinCondition": "fh.encounter_type = et.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pa.person_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "t1.birthdate" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(fh.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "latest_vl", + "column": "fh.vl_1" + }, + { + "type": "simple_column", + "alias": "latest_vl_date", + "column": "date_format(fh.vl_1_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" + }, + { + "type": "simple_column", + "alias": "cur_meds", + "column": "fh.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "previous_vl", + "column": "fh.vl_2" + }, + { + "type": "simple_column", + "alias": "previous_vl_date", + "column": "date_format(fh.vl_2_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/patient-program-cohort.json b/app/reporting-framework/json-reports/patient-program-cohort.json index 4cb1a5357..3c22f35e6 100644 --- a/app/reporting-framework/json-reports/patient-program-cohort.json +++ b/app/reporting-framework/json-reports/patient-program-cohort.json @@ -1,43 +1,43 @@ { - "name": "patientProgramCohort", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "amrs.patient_program", - "alias": "pp" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "patient_id" - }, - { - "type": "derived_column", - "alias": "programs", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "GROUP_CONCAT(DISTINCT program_id SEPARATOR ',')" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": " voided = 0", - "parameterName": "" - } - ] + "name": "patientProgramCohort", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "amrs.patient_program", + "alias": "pp" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "patient_id" }, - "groupBy": { - "groupParam": "groupByParam", - "columns":["patient_id"], - "excludeParam": "excludeParam" + { + "type": "derived_column", + "alias": "programs", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "GROUP_CONCAT(DISTINCT program_id SEPARATOR ',')" + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": " voided = 0", + "parameterName": "" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["patient_id"], + "excludeParam": "excludeParam" + } +} diff --git a/app/reporting-framework/json-reports/patients-requiring-viral-load-template.json b/app/reporting-framework/json-reports/patients-requiring-viral-load-template.json index cf29fe6fb..e36b719bc 100644 --- a/app/reporting-framework/json-reports/patients-requiring-viral-load-template.json +++ b/app/reporting-framework/json-reports/patients-requiring-viral-load-template.json @@ -1,198 +1,197 @@ { - "name": "patient_requiring_viral_load_template", - "version": "1.0", - "tag": "patient_requiring_viral_load_template", - "description": "Patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "INNER", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contact", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contact.person_id AND (contact.voided IS NULL || contact.voided = 0) AND contact.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhsh", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = fhsh.person_id AND fhsh.next_clinical_location_id IS NULL AND fhsh.encounter_type NOT IN (99999) " - } - }, - { - "table": "amrs.encounter_type", - "alias": "ety", - "join": { - "type": "LEFT", - "joinCondition": "fhsh.encounter_type = ety.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pad", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pad.person_id" - } - } - - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "t1.birthdate" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "derived_column", - "alias": "has_pending_vl_test", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when (timestampdiff(day,t2.vl_order_date,now()) between 0 and 14) and (t2.vl_1_date is null or t2.vl_order_date > t2.vl_1_date) then true else false end" - } - }, - { - "type": "derived_column", - "alias": "current_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t2.vl_1 " - } - }, - { - "type": "derived_column", - "alias": "current_vl_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(t2.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "last_vl_order_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(t2.vl_order_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "days_since_last_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "timestampdiff(day, t2.vl_order_date, now())" - } - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contact.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(fhsh.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "latest_vl", - "column": "fhsh.vl_1" - }, - { - "type": "simple_column", - "alias": "latest_vl_date", - "column": "date_format(fhsh.vl_1_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(fhsh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(ety.name, ''))" - }, - { - "type": "simple_column", - "alias": "cur_meds", - "column": "fhsh.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "previous_vl", - "column": "fhsh.vl_2" - }, - { - "type": "simple_column", - "alias": "previous_vl_date", - "column": "date_format(fhsh.vl_2_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pad.address3" - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "patient_requiring_viral_load_template", + "version": "1.0", + "tag": "patient_requiring_viral_load_template", + "description": "Patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "INNER", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contact", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contact.person_id AND (contact.voided IS NULL || contact.voided = 0) AND contact.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhsh", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = fhsh.person_id AND fhsh.next_clinical_location_id IS NULL AND fhsh.encounter_type NOT IN (99999) " + } + }, + { + "table": "amrs.encounter_type", + "alias": "ety", + "join": { + "type": "LEFT", + "joinCondition": "fhsh.encounter_type = ety.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pad", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pad.person_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "t1.birthdate" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "derived_column", + "alias": "has_pending_vl_test", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when (timestampdiff(day,t2.vl_order_date,now()) between 0 and 14) and (t2.vl_1_date is null or t2.vl_order_date > t2.vl_1_date) then true else false end" + } + }, + { + "type": "derived_column", + "alias": "current_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t2.vl_1 " + } + }, + { + "type": "derived_column", + "alias": "current_vl_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(t2.vl_1_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "last_vl_order_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(t2.vl_order_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "days_since_last_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(day, t2.vl_order_date, now())" + } + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contact.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(fhsh.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "latest_vl", + "column": "fhsh.vl_1" + }, + { + "type": "simple_column", + "alias": "latest_vl_date", + "column": "date_format(fhsh.vl_1_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(fhsh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(ety.name, ''))" + }, + { + "type": "simple_column", + "alias": "cur_meds", + "column": "fhsh.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "previous_vl", + "column": "fhsh.vl_2" + }, + { + "type": "simple_column", + "alias": "previous_vl_date", + "column": "date_format(fhsh.vl_2_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pad.address3" + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/patint-change-status-tracker-aggregate.json b/app/reporting-framework/json-reports/patint-change-status-tracker-aggregate.json index 3be849ad7..484abafab 100644 --- a/app/reporting-framework/json-reports/patint-change-status-tracker-aggregate.json +++ b/app/reporting-framework/json-reports/patint-change-status-tracker-aggregate.json @@ -1,126 +1,124 @@ { - "name": "patintChangeStatusTrackerDataSetbase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "patintChangeStatusTrackerDataSetbase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "patintChangeStatusTrackerDataSetbase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "total_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hmsd.person_id)" - } - }, - { - "type": "derived_column", - "alias": "active_in_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hmsd.active_in_care)" - } - }, - { - "type": "derived_column", - "alias": "active_return", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hmsd.active_return)" - } - }, - { - "type": "derived_column", - "alias": "LTFU", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hmsd.LTFU)" - } - }, - { - "type": "derived_column", - "alias": "deaths", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hmsd.deaths)" - } - }, - { - "type": "derived_column", - "alias": "transfer_out_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hmsd.transfer_out_patients)" - } - }, - { - "type": "derived_column", - "alias": "new_enrollments", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hmsd.new_enrollments)" - } - }, - { - "type": "derived_column", - "alias": "transfer_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(hmsd.transfer_in)" - } - }, - { - "type": "simple_column", - "alias": "reporting_date", - "column": "hmsd.reporting_date" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "reporting_month", - "column": "hmsd.reporting_month" - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "reporting_date" - ], - "excludeParam": "excludeParam" + "name": "patintChangeStatusTrackerDataSetbase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "patintChangeStatusTrackerDataSetbase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "patintChangeStatusTrackerDataSetbase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "total_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.person_id)" + } + }, + { + "type": "derived_column", + "alias": "active_in_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.active_in_care)" + } + }, + { + "type": "derived_column", + "alias": "active_return", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.active_return)" + } + }, + { + "type": "derived_column", + "alias": "LTFU", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.LTFU)" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "deaths", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.deaths)" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.transfer_out_patients)" + } + }, + { + "type": "derived_column", + "alias": "new_enrollments", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.new_enrollments)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(hmsd.transfer_in)" + } + }, + { + "type": "simple_column", + "alias": "reporting_date", + "column": "hmsd.reporting_date" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "reporting_month", + "column": "hmsd.reporting_month" + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["reporting_date"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/patint-change-status-tracker-base.json b/app/reporting-framework/json-reports/patint-change-status-tracker-base.json index 4575f8023..f90b690ee 100644 --- a/app/reporting-framework/json-reports/patint-change-status-tracker-base.json +++ b/app/reporting-framework/json-reports/patint-change-status-tracker-base.json @@ -1,142 +1,142 @@ { - "name": "patintChangeStatusTrackerDataSetbase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.hiv_monthly_report_dataset_frozen", - "alias": "fhs" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = fhs.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "fhs.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "fhs.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "fhs.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "fhs.age" - }, - { - "type": "derived_column", - "alias": "active_in_care", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when status='active' then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "active_return", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when status='active' and art_revisit_this_month = 1 then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "LTFU", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when status='ltfu' then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "deaths", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when status='dead' then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "transfer_out_patients", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when status='transfer_out' then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "new_enrollments", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when enrolled_this_month=1 then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "transfer_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "case when transfer_in_this_month = 1 then 1 else null end" - } - }, - { - "type": "derived_column", - "alias": "reporting_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(fhs.endDate, '%m/%Y') " - } - }, - { - "type": "simple_column", - "alias": "reporting_date", - "column": "fhs.endDate" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "fhs.location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "fhs.location_id" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "endDate <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.location_id in ?", - "parameterName": "locations" - } - ] + "name": "patintChangeStatusTrackerDataSetbase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.hiv_monthly_report_dataset_frozen", + "alias": "fhs" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = fhs.location_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "fhs.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "fhs.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "fhs.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "fhs.age" + }, + { + "type": "derived_column", + "alias": "active_in_care", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when status='active' then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "active_return", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when status='active' and art_revisit_this_month = 1 then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "LTFU", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when status='ltfu' then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "deaths", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when status='dead' then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_patients", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when status='transfer_out' then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "new_enrollments", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when enrolled_this_month=1 then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "transfer_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "case when transfer_in_this_month = 1 then 1 else null end" + } + }, + { + "type": "derived_column", + "alias": "reporting_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(fhs.endDate, '%m/%Y') " + } + }, + { + "type": "simple_column", + "alias": "reporting_date", + "column": "fhs.endDate" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "fhs.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "fhs.location_id" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "endDate <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/pep-dataset-aggregate.json b/app/reporting-framework/json-reports/pep-dataset-aggregate.json index 726ceaa2a..142ad0e67 100755 --- a/app/reporting-framework/json-reports/pep-dataset-aggregate.json +++ b/app/reporting-framework/json-reports/pep-dataset-aggregate.json @@ -1,121 +1,117 @@ { - "name": "pepDatasetAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [{ - "name": "pepDataSetbase", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [{ - "dataSet": "pepDataSetbase", - "alias": "hmsd" - }], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "derived_column", - "alias": "total_hiv_exposed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(hmsd.total_hiv_exposed, hmsd.person_id))" - } - - }, - { - "type": "derived_column", - "alias": "hiv_exposed_occupational", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(hmsd.hiv_exposed_occupational,hmsd.person_id))" - } - - }, - { - "type": "derived_column", - "alias": "hiv_exposed_non_occupational", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(hmsd.hiv_exposed_non_occupational,hmsd.person_id))" - } - - }, - { - "type": "derived_column", - "alias": "total_started_PEP", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(hmsd.total_started_PEP,hmsd.person_id))" - } - - }, - { - "type": "derived_column", - "alias": "started_PEP_occupational", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat( hmsd.started_PEP_occupational,hmsd.person_id))" - } - - }, - { - "type": "derived_column", - "alias": "started_PEP_non_occupational", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct concat(hmsd.started_PEP_non_occupational,hmsd.person_id))" - } - - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" + "name": "pepDatasetAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "pepDataSetbase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "pepDataSetbase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" }, - "transFormDirectives": { - "joinColumn": "location_id", - "joinColumnParam": "joinColumnParam", - "skipColumns": ["join_location"], - "disaggregationColumns": [] + { + "type": "derived_column", + "alias": "total_hiv_exposed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(hmsd.total_hiv_exposed, hmsd.person_id))" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "hiv_exposed_occupational", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(hmsd.hiv_exposed_occupational,hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "hiv_exposed_non_occupational", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(hmsd.hiv_exposed_non_occupational,hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "total_started_PEP", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(hmsd.total_started_PEP,hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "started_PEP_occupational", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat( hmsd.started_PEP_occupational,hmsd.person_id))" + } + }, + { + "type": "derived_column", + "alias": "started_PEP_non_occupational", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct concat(hmsd.started_PEP_non_occupational,hmsd.person_id))" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "joinColumnParam": "joinColumnParam", + "skipColumns": ["join_location"], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/pep-dataset-base.json b/app/reporting-framework/json-reports/pep-dataset-base.json index 2534f3b91..9471638a1 100755 --- a/app/reporting-framework/json-reports/pep-dataset-base.json +++ b/app/reporting-framework/json-reports/pep-dataset-base.json @@ -1,111 +1,111 @@ { - "name": "pepDataSetbase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_pep_summary", - "alias": "pep" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = pep.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_id", - "column": "pep.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "pep.person_id" - }, - { - "type": "derived_column", - "alias": "total_hiv_exposed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hiv_exposed_occupational is not null,1,null)" - } - }, - { - "type": "derived_column", - "alias": "hiv_exposed_occupational", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hiv_exposed_occupational=1,1,null)" - } - }, - { - "type": "derived_column", - "alias": "hiv_exposed_non_occupational", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hiv_exposed_occupational=0,1,null)" - } - }, - { - "type": "derived_column", - "alias": "total_started_PEP", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hiv_exposed_occupational is not null and date(pep_start_date) between '{startDate}' and '{endDate}',1,null)" - } - }, - { - "type": "derived_column", - "alias": "started_PEP_occupational", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hiv_exposed_occupational=1 and date(pep_start_date) between '{startDate}' and '{endDate}',1,null)" - } - }, - { - "type": "derived_column", - "alias": "started_PEP_non_occupational", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if(hiv_exposed_occupational=0 and date(pep_start_date) between '{startDate}' and '{endDate}',1,null)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "pep.encounter_datetime <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "pep.encounter_datetime >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "pep.location_id in ?", - "parameterName": "locations" - } - ] + "name": "pepDataSetbase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_pep_summary", + "alias": "pep" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = pep.location_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_id", + "column": "pep.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "pep.person_id" + }, + { + "type": "derived_column", + "alias": "total_hiv_exposed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hiv_exposed_occupational is not null,1,null)" + } + }, + { + "type": "derived_column", + "alias": "hiv_exposed_occupational", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hiv_exposed_occupational=1,1,null)" + } + }, + { + "type": "derived_column", + "alias": "hiv_exposed_non_occupational", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hiv_exposed_occupational=0,1,null)" + } + }, + { + "type": "derived_column", + "alias": "total_started_PEP", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hiv_exposed_occupational is not null and date(pep_start_date) between '{startDate}' and '{endDate}',1,null)" + } + }, + { + "type": "derived_column", + "alias": "started_PEP_occupational", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hiv_exposed_occupational=1 and date(pep_start_date) between '{startDate}' and '{endDate}',1,null)" + } + }, + { + "type": "derived_column", + "alias": "started_PEP_non_occupational", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if(hiv_exposed_occupational=0 and date(pep_start_date) between '{startDate}' and '{endDate}',1,null)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "pep.encounter_datetime <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "pep.encounter_datetime >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "pep.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/prep-aggregate-report.json b/app/reporting-framework/json-reports/prep-aggregate-report.json index ed9221810..08ee5be05 100644 --- a/app/reporting-framework/json-reports/prep-aggregate-report.json +++ b/app/reporting-framework/json-reports/prep-aggregate-report.json @@ -1,111 +1,107 @@ { - "name": "prepAggregateReport", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "prepBaseReport", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [ - { - "dataSet": "prepBaseReport", - "alias": "prep" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "prep.location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "prep.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "prep.location" - }, - { - "type": "derived_column", - "alias": "active_on_prep_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(active_on_prep_this_week)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_prep_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(enrolled_in_prep_this_week)" - } - }, - { - "type": "derived_column", - "alias": "prep_ltfu_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(prep_ltfu_this_week)" - } - }, - { - "type": "derived_column", - "alias": "prep_discontinued_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(prep_discontinued_this_week)" - } - }, - { - "type": "derived_column", - "alias": "prep_defaulter_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(prep_defaulter_this_week)" - } - }, - { - "type": "derived_column", - "alias": "prev_on_prep_and_turned_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(prev_on_prep_and_turned_positive)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_uuid" - ], - "excludeParam": "excludeParam" + "name": "prepAggregateReport", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "prepBaseReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "prepBaseReport", + "alias": "prep" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "prep.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "prep.location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "prep.location" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "join_location" - ] + { + "type": "derived_column", + "alias": "active_on_prep_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(active_on_prep_this_week)" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "prep-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "enrolled_in_prep_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(enrolled_in_prep_this_week)" + } + }, + { + "type": "derived_column", + "alias": "prep_ltfu_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(prep_ltfu_this_week)" + } + }, + { + "type": "derived_column", + "alias": "prep_discontinued_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(prep_discontinued_this_week)" + } + }, + { + "type": "derived_column", + "alias": "prep_defaulter_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(prep_defaulter_this_week)" + } + }, + { + "type": "derived_column", + "alias": "prev_on_prep_and_turned_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(prev_on_prep_and_turned_positive)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_uuid"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "join_location"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "prep-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/prep-base-report.json b/app/reporting-framework/json-reports/prep-base-report.json index 9ef39a2a9..553bac53b 100644 --- a/app/reporting-framework/json-reports/prep-base-report.json +++ b/app/reporting-framework/json-reports/prep-base-report.json @@ -1,179 +1,176 @@ { - "name": "prepBaseReport", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "prepDatasetReport", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "table": "etl.prep_weekly_report_dataset_v1_1", - "alias": "prep" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = prep.location_id" - } - }, - { - "table": "etl.flat_prep_summary_v1_1", - "alias": "t2", - "join": { - "type": "LEFT", - "joinCondition": "prep.person_id = t2.person_id" - } - }, - { - "dataSet": "prepDatasetReport", - "alias": "t3", - "join": { - "type": "LEFT", - "joinCondition": "t2.person_id = t3.person_id" - } - }, - { - "table": "etl.flat_prep_summary_v1_1", - "alias": "t4", - "join": { - "type": "LEFT", - "joinCondition": "t3.person_id = t4.person_id AND t3.latest_encounter_datetime = t4.encounter_datetime" - } - }, - { - "table": "amrs.encounter_type", - "alias": "t5", - "join": { - "type": "LEFT", - "joinCondition": "t4.encounter_type = t5.encounter_type_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "l.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "active_on_prep_this_week", - "column": "prep.active_on_prep_this_week" - }, - { - "type": "simple_column", - "alias": "enrolled_in_prep_this_week", - "column": "prep.enrolled_in_prep_this_week" - }, - { - "type": "simple_column", - "alias": "prep_ltfu_this_week", - "column": "prep.prep_ltfu_this_week" - }, - { - "type": "simple_column", - "alias": "prep_discontinued_this_week", - "column": "prep.prep_discontinued_this_week" - }, - { - "type": "simple_column", - "alias": "prep_defaulter_this_week", - "column": "prep.prep_defaulter_this_week" - }, - { - "type": "simple_column", - "alias": "prev_on_prep_and_turned_positive", - "column": "prep.prev_on_prep_and_turned_positive" - }, - { - "type": "simple_column", - "alias": "status", - "column": "prep.status" - }, - { - "type": "simple_column", - "alias": "age", - "column": "prep.age" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "prep.gender" - }, - { - "type": "simple_column", - "alias": "enrollment_date", - "column": "date_format(t4.enrollment_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(t4.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(t5.name, ''))" - }, - { - "type": "simple_column", - "alias": "prev_rtc_date", - "column": "date_format(t4.prev_rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "encounter_date", - "column": "date_format(t4.encounter_datetime, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "rtc_date", - "column": "date_format(t4.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "days_since_rtc_date", - "column": "prep.days_since_rtc_date" - }, - { - "type": "simple_column", - "alias": "death_date", - "column": "date_format(t4.death_date, '%Y-%m-%d')" - } - - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "week = ? ", - "parameterName": "year_week" - }, - { - "filterType": "tableColumns", - "conditionExpression": "l.uuid in ?", - "parameterName": "locationUuids" - } - ] - }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "t2.person_id" - ], - "excludeParam": "excludeParam" + "name": "prepBaseReport", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "prepDatasetReport", + "version": "1.0", + "type": "dataset_def" } -} \ No newline at end of file + ], + "sources": [ + { + "table": "etl.prep_weekly_report_dataset_v1_1", + "alias": "prep" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = prep.location_id" + } + }, + { + "table": "etl.flat_prep_summary_v1_1", + "alias": "t2", + "join": { + "type": "LEFT", + "joinCondition": "prep.person_id = t2.person_id" + } + }, + { + "dataSet": "prepDatasetReport", + "alias": "t3", + "join": { + "type": "LEFT", + "joinCondition": "t2.person_id = t3.person_id" + } + }, + { + "table": "etl.flat_prep_summary_v1_1", + "alias": "t4", + "join": { + "type": "LEFT", + "joinCondition": "t3.person_id = t4.person_id AND t3.latest_encounter_datetime = t4.encounter_datetime" + } + }, + { + "table": "amrs.encounter_type", + "alias": "t5", + "join": { + "type": "LEFT", + "joinCondition": "t4.encounter_type = t5.encounter_type_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "l.location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "active_on_prep_this_week", + "column": "prep.active_on_prep_this_week" + }, + { + "type": "simple_column", + "alias": "enrolled_in_prep_this_week", + "column": "prep.enrolled_in_prep_this_week" + }, + { + "type": "simple_column", + "alias": "prep_ltfu_this_week", + "column": "prep.prep_ltfu_this_week" + }, + { + "type": "simple_column", + "alias": "prep_discontinued_this_week", + "column": "prep.prep_discontinued_this_week" + }, + { + "type": "simple_column", + "alias": "prep_defaulter_this_week", + "column": "prep.prep_defaulter_this_week" + }, + { + "type": "simple_column", + "alias": "prev_on_prep_and_turned_positive", + "column": "prep.prev_on_prep_and_turned_positive" + }, + { + "type": "simple_column", + "alias": "status", + "column": "prep.status" + }, + { + "type": "simple_column", + "alias": "age", + "column": "prep.age" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "prep.gender" + }, + { + "type": "simple_column", + "alias": "enrollment_date", + "column": "date_format(t4.enrollment_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(t4.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(t5.name, ''))" + }, + { + "type": "simple_column", + "alias": "prev_rtc_date", + "column": "date_format(t4.prev_rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "encounter_date", + "column": "date_format(t4.encounter_datetime, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "rtc_date", + "column": "date_format(t4.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "days_since_rtc_date", + "column": "prep.days_since_rtc_date" + }, + { + "type": "simple_column", + "alias": "death_date", + "column": "date_format(t4.death_date, '%Y-%m-%d')" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "week = ? ", + "parameterName": "year_week" + }, + { + "filterType": "tableColumns", + "conditionExpression": "l.uuid in ?", + "parameterName": "locationUuids" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["t2.person_id"], + "excludeParam": "excludeParam" + } +} diff --git a/app/reporting-framework/json-reports/prep-dataset-report.json b/app/reporting-framework/json-reports/prep-dataset-report.json index d0985bd31..8e46c95c0 100644 --- a/app/reporting-framework/json-reports/prep-dataset-report.json +++ b/app/reporting-framework/json-reports/prep-dataset-report.json @@ -1,41 +1,39 @@ { - "name": "prepDatasetReport", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_prep_summary_v1_1", - "alias": "t3" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t3.person_id" - }, - { - "type": "simple_column", - "alias": "latest_encounter_datetime", - "column": "MAX(t3.encounter_datetime )" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t3.encounter_type in (1,2,3,4,10,14,15,17,19,26,32,33,34,47,105,106,112,113,114,117,120,127,128,138,140,153,154,158,162,163, 186, 133, 134)" - } - ] + "name": "prepDatasetReport", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_prep_summary_v1_1", + "alias": "t3" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t3.person_id" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "t3.person_id" - ], - "excludeParam": "excludeParam" + { + "type": "simple_column", + "alias": "latest_encounter_datetime", + "column": "MAX(t3.encounter_datetime )" } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t3.encounter_type in (1,2,3,4,10,14,15,17,19,26,32,33,34,47,105,106,112,113,114,117,120,127,128,138,140,153,154,158,162,163, 186, 133, 134)" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["t3.person_id"], + "excludeParam": "excludeParam" + } } diff --git a/app/reporting-framework/json-reports/prep-monthly-breastfeeding-disaggregation.json b/app/reporting-framework/json-reports/prep-monthly-breastfeeding-disaggregation.json index e4a866c10..88c7f6a51 100644 --- a/app/reporting-framework/json-reports/prep-monthly-breastfeeding-disaggregation.json +++ b/app/reporting-framework/json-reports/prep-monthly-breastfeeding-disaggregation.json @@ -1,72 +1,64 @@ { - "name": "prepMonthlySummaryBreastFeedingDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "prepMonthlySummaryBaseReport", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "prepMonthlySummaryBaseReport", - "alias": "t5" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t5.location_uuid" - }, - { - "type": "simple_column", - "alias": "is_breastfeeding", - "column": "t5.is_breastfeeding" - }, - { - "type": "derived_column", - "alias": "active_on_prep_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t5.active_on_prep_this_month)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "is_breastfeeding", - "location_uuid" - ], - "excludeParam": "excludeParam" + "name": "prepMonthlySummaryBreastFeedingDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "prepMonthlySummaryBaseReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "prepMonthlySummaryBaseReport", + "alias": "t5" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t5.location_uuid" }, - "transFormDirectives": { - "joinColumn": "location_uuid", - "skipColumns": [ - "location_uuid", - "join_location" - ], - "disaggregationColumns": [ - "is_breastfeeding" - ] + { + "type": "simple_column", + "alias": "is_breastfeeding", + "column": "t5.is_breastfeeding" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "prep-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + { + "type": "derived_column", + "alias": "active_on_prep_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t5.active_on_prep_this_month)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["is_breastfeeding", "location_uuid"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_uuid", + "skipColumns": ["location_uuid", "join_location"], + "disaggregationColumns": ["is_breastfeeding"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "prep-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + }, + "skipParams": [] } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/prep-monthly-newly-enrolled-breastfeeding-disaggregation.json b/app/reporting-framework/json-reports/prep-monthly-newly-enrolled-breastfeeding-disaggregation.json index d1209fca7..c63e2d489 100644 --- a/app/reporting-framework/json-reports/prep-monthly-newly-enrolled-breastfeeding-disaggregation.json +++ b/app/reporting-framework/json-reports/prep-monthly-newly-enrolled-breastfeeding-disaggregation.json @@ -1,72 +1,64 @@ { - "name": "prepMonthlyNewlyEnrolledBreastFeedingDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "prepMonthlySummaryBaseReport", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "prepMonthlySummaryBaseReport", - "alias": "t5" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t5.location_uuid" - }, - { - "type": "simple_column", - "alias": "newly_enrolled_breastfeeding", - "column": "t5.newly_enrolled_breastfeeding" - }, - { - "type": "derived_column", - "alias": "enrolled_in_prep_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t5.enrolled_in_prep_this_month)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "newly_enrolled_breastfeeding", - "location_uuid" - ], - "excludeParam": "excludeParam" + "name": "prepMonthlyNewlyEnrolledBreastFeedingDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "prepMonthlySummaryBaseReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "prepMonthlySummaryBaseReport", + "alias": "t5" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t5.location_uuid" }, - "transFormDirectives": { - "joinColumn": "location_uuid", - "skipColumns": [ - "location_uuid", - "join_location" - ], - "disaggregationColumns": [ - "newly_enrolled_breastfeeding" - ] + { + "type": "simple_column", + "alias": "newly_enrolled_breastfeeding", + "column": "t5.newly_enrolled_breastfeeding" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "prep-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + { + "type": "derived_column", + "alias": "enrolled_in_prep_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t5.enrolled_in_prep_this_month)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["newly_enrolled_breastfeeding", "location_uuid"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_uuid", + "skipColumns": ["location_uuid", "join_location"], + "disaggregationColumns": ["newly_enrolled_breastfeeding"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "prep-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + }, + "skipParams": [] } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/prep-monthly-newly-enrolled-pregnancy-disaggregation.json b/app/reporting-framework/json-reports/prep-monthly-newly-enrolled-pregnancy-disaggregation.json index 6e75ba023..3f80d76ec 100644 --- a/app/reporting-framework/json-reports/prep-monthly-newly-enrolled-pregnancy-disaggregation.json +++ b/app/reporting-framework/json-reports/prep-monthly-newly-enrolled-pregnancy-disaggregation.json @@ -1,72 +1,64 @@ { - "name": "prepMonthlyNewlyEnrolledPregnancyDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "prepMonthlySummaryBaseReport", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "prepMonthlySummaryBaseReport", - "alias": "t5" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t5.location_uuid" - }, - { - "type": "simple_column", - "alias": "newly_enrolled_pregnant", - "column": "t5.newly_enrolled_pregnant" - }, - { - "type": "derived_column", - "alias": "enrolled_in_prep_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t5.enrolled_in_prep_this_month)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "newly_enrolled_pregnant", - "location_uuid" - ], - "excludeParam": "excludeParam" + "name": "prepMonthlyNewlyEnrolledPregnancyDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "prepMonthlySummaryBaseReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "prepMonthlySummaryBaseReport", + "alias": "t5" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t5.location_uuid" }, - "transFormDirectives": { - "joinColumn": "location_uuid", - "skipColumns": [ - "location_uuid", - "join_location" - ], - "disaggregationColumns": [ - "newly_enrolled_pregnant" - ] + { + "type": "simple_column", + "alias": "newly_enrolled_pregnant", + "column": "t5.newly_enrolled_pregnant" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "prep-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + { + "type": "derived_column", + "alias": "enrolled_in_prep_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t5.enrolled_in_prep_this_month)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["newly_enrolled_pregnant", "location_uuid"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_uuid", + "skipColumns": ["location_uuid", "join_location"], + "disaggregationColumns": ["newly_enrolled_pregnant"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "prep-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + }, + "skipParams": [] } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/prep-monthly-population-type-disaggregation.json b/app/reporting-framework/json-reports/prep-monthly-population-type-disaggregation.json index 0106ee653..edc011ad0 100644 --- a/app/reporting-framework/json-reports/prep-monthly-population-type-disaggregation.json +++ b/app/reporting-framework/json-reports/prep-monthly-population-type-disaggregation.json @@ -1,71 +1,64 @@ { - "name": "prepMonthlySummaryPopulationTypeDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "prepMonthlySummaryBaseReport", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "prepMonthlySummaryBaseReport", - "alias": "t5" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t5.location_uuid" - }, - { - "type": "simple_column", - "alias": "population_type", - "column": "t5.population_type" - }, - { - "type": "derived_column", - "alias": "active_on_prep_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t5.active_on_prep_this_month)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "population_type", - "location_uuid" - ], - "excludeParam": "excludeParam" + "name": "prepMonthlySummaryPopulationTypeDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "prepMonthlySummaryBaseReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "prepMonthlySummaryBaseReport", + "alias": "t5" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t5.location_uuid" }, - "transFormDirectives": { - "joinColumn": "location_uuid", - "skipColumns": [ - "location_uuid" - ], - "disaggregationColumns": [ - "population_type" - ] + { + "type": "simple_column", + "alias": "population_type", + "column": "t5.population_type" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "prep-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + { + "type": "derived_column", + "alias": "active_on_prep_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t5.active_on_prep_this_month)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["population_type", "location_uuid"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_uuid", + "skipColumns": ["location_uuid"], + "disaggregationColumns": ["population_type"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "prep-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + }, + "skipParams": [] } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/prep-monthly-pregnancy-disaggregation.json b/app/reporting-framework/json-reports/prep-monthly-pregnancy-disaggregation.json index 3aba74f51..6c0846f16 100644 --- a/app/reporting-framework/json-reports/prep-monthly-pregnancy-disaggregation.json +++ b/app/reporting-framework/json-reports/prep-monthly-pregnancy-disaggregation.json @@ -1,71 +1,64 @@ { - "name": "prepMonthlySummaryPregnancyDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "prepMonthlySummaryBaseReport", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "prepMonthlySummaryBaseReport", - "alias": "t5" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t5.location_uuid" - }, - { - "type": "simple_column", - "alias": "is_pregnant", - "column": "t5.is_pregnant" - }, - { - "type": "derived_column", - "alias": "active_on_prep_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t5.active_on_prep_this_month)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "is_pregnant", - "location_uuid" - ], - "excludeParam": "excludeParam" + "name": "prepMonthlySummaryPregnancyDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "prepMonthlySummaryBaseReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "prepMonthlySummaryBaseReport", + "alias": "t5" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t5.location_uuid" }, - "transFormDirectives": { - "joinColumn": "location_uuid", - "skipColumns": [ - "location_uuid" - ], - "disaggregationColumns": [ - "is_pregnant" - ] + { + "type": "simple_column", + "alias": "is_pregnant", + "column": "t5.is_pregnant" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "prep-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + { + "type": "derived_column", + "alias": "active_on_prep_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t5.active_on_prep_this_month)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["is_pregnant", "location_uuid"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_uuid", + "skipColumns": ["location_uuid"], + "disaggregationColumns": ["is_pregnant"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "prep-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + }, + "skipParams": [] } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/prep-monthly-summary-aggregate.json b/app/reporting-framework/json-reports/prep-monthly-summary-aggregate.json index 7670a46e4..f2175405c 100644 --- a/app/reporting-framework/json-reports/prep-monthly-summary-aggregate.json +++ b/app/reporting-framework/json-reports/prep-monthly-summary-aggregate.json @@ -1,151 +1,149 @@ { - "name": "prepMonthlySummaryNoDisaggregation", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "prepMonthlySummaryBaseReport", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "prepMonthlySummaryBaseReport", - "alias": "t2" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "t2.location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t2.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "t2.location" - }, - { - "type": "derived_column", - "alias": "active_on_prep_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.active_on_prep_this_month)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_in_prep_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.enrolled_in_prep_this_month)" - } - }, - { - "type": "derived_column", - "alias": "cumulative_prep_ltfu_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.cumulative_prep_ltfu_this_month)" - } - }, - { - "type": "derived_column", - "alias": "prep_ltfu_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.prep_ltfu_this_month)" - } - }, - { - "type": "derived_column", - "alias": "prep_discontinued_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.prep_discontinued_this_month)" - } - }, - { - "type": "derived_column", - "alias": "cumulative_prep_discontinued_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.cumulative_prep_discontinued_this_month)" - } - }, - { - "type": "derived_column", - "alias": "prev_on_prep_and_turned_positive", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.prev_on_prep_and_turned_positive)" - } - }, - { - "type": "derived_column", - "alias": "turned_positive_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.turned_positive_this_month)" - } - }, - { - "type": "derived_column", - "alias": "cumulative_turned_positive_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.cumulative_turned_positive_this_month)" - } - }, - { - "type": "derived_column", - "alias": "general_pop_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.general_pop_active)" - } - }, - { - "type": "derived_column", - "alias": "has_hiv_rapid_test_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "SUM(t2.has_hiv_rapid_test_this_month)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_uuid" - ], - "excludeParam": "excludeParam" + "name": "prepMonthlySummaryNoDisaggregation", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "prepMonthlySummaryBaseReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "prepMonthlySummaryBaseReport", + "alias": "t2" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "t2.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "t2.location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "t2.location" + }, + { + "type": "derived_column", + "alias": "active_on_prep_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.active_on_prep_this_month)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_in_prep_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.enrolled_in_prep_this_month)" + } }, - "transFormDirectives": { - "joinColumn": "location_uuid", - "skipColumns": [], - "disaggregationColumns": [] + { + "type": "derived_column", + "alias": "cumulative_prep_ltfu_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.cumulative_prep_ltfu_this_month)" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "prep-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - }, - "skipParams": [] + { + "type": "derived_column", + "alias": "prep_ltfu_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.prep_ltfu_this_month)" + } + }, + { + "type": "derived_column", + "alias": "prep_discontinued_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.prep_discontinued_this_month)" + } + }, + { + "type": "derived_column", + "alias": "cumulative_prep_discontinued_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.cumulative_prep_discontinued_this_month)" + } + }, + { + "type": "derived_column", + "alias": "prev_on_prep_and_turned_positive", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.prev_on_prep_and_turned_positive)" + } + }, + { + "type": "derived_column", + "alias": "turned_positive_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.turned_positive_this_month)" + } + }, + { + "type": "derived_column", + "alias": "cumulative_turned_positive_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.cumulative_turned_positive_this_month)" + } + }, + { + "type": "derived_column", + "alias": "general_pop_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.general_pop_active)" + } + }, + { + "type": "derived_column", + "alias": "has_hiv_rapid_test_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "SUM(t2.has_hiv_rapid_test_this_month)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_uuid"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_uuid", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "prep-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + }, + "skipParams": [] } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/prep-monthly-summary-base.json b/app/reporting-framework/json-reports/prep-monthly-summary-base.json index cf13e53c3..359983c53 100644 --- a/app/reporting-framework/json-reports/prep-monthly-summary-base.json +++ b/app/reporting-framework/json-reports/prep-monthly-summary-base.json @@ -1,279 +1,277 @@ { - "name": "prepMonthlySummaryBaseReport", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "prepLatestClinicalEncounterDate", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "table": "etl.prep_monthly_report_dataset", - "alias": "prep" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = prep.location_id" - } - }, - { - "dataSet": "prepLatestClinicalEncounterDate", - "alias": "latest_enc", - "join": { - "type": "LEFT", - "joinCondition": "latest_enc.person_id = prep.person_id" - } - }, - { - "table": "etl.flat_prep_summary_v1_1", - "alias": "prep_summary", - "join": { - "type": "LEFT", - "joinCondition": "latest_enc.person_id = prep_summary.person_id AND prep_summary.encounter_datetime = latest_enc.latest_encounter_date" - } - }, - { - "table": "amrs.encounter_type", - "alias": "e", - "join": { - "type": "LEFT", - "joinCondition": "prep_summary.encounter_type = e.encounter_type_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "l.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "active_on_prep_this_month", - "column": "prep.active_on_prep_this_month" - }, - { - "type": "simple_column", - "alias": "enrolled_in_prep_this_month", - "column": "prep.enrolled_in_prep_this_month" - }, - { - "type": "simple_column", - "alias": "cumulative_prep_ltfu_this_month", - "column": "prep.cumulative_prep_ltfu_this_month" - }, - { - "type": "simple_column", - "alias": "prep_ltfu_this_month", - "column": "prep.prep_ltfu_this_month" - }, - { - "type": "simple_column", - "alias": "prep_discontinued_this_month", - "column": "prep.prep_discontinued_this_month" - }, - { - "type": "simple_column", - "alias": "cumulative_prep_discontinued_this_month", - "column": "prep.cumulative_prep_discontinued_this_month" - }, - { - "type": "simple_column", - "alias": "prev_on_prep_and_turned_positive", - "column": "prep.prev_on_prep_and_turned_positive" - }, - { - "type": "simple_column", - "alias": "turned_positive_this_month", - "column": "prep.turned_positive_this_month" - }, - { - "type": "simple_column", - "alias": "cumulative_turned_positive_this_month", - "column": "prep.cumulative_turned_positive_this_month" - }, - { - "type": "simple_column", - "alias": "status", - "column": "prep.status" - }, - { - "type": "simple_column", - "alias": "age", - "column": "prep.age" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "prep.gender" - }, - { - "type": "simple_column", - "alias": "days_since_rtc_date", - "column": "prep.days_since_rtc_date" - }, - { - "type": "simple_column", - "alias": "latest_rtc_date", - "column": "date_format(prep_summary.rtc_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "last_appointment", - "column": "CONCAT(COALESCE(DATE_FORMAT(prep_summary.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(e.name, ''))" - }, - { - "type": "simple_column", - "alias": "prev_rtc_date", - "column": "date_format(prep_summary.prev_rtc_date, '%Y-%m-%d')" - }, - { - "type": "derived_column", - "alias": "general_pop_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF((prep.population_type = 3 or prep.population_type = 1 or prep.population_type is null) and active_on_prep_this_month = 1 ,1, 0)" - } - }, - { - "type": "derived_column", - "alias": "population_type", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "prep.population_type = 1", - "value": "discordant" - }, - { - "condition": "prep.population_type = 2", - "value": "priority" - }, - { - "condition": "prep.population_type = 3 or prep.population_type is null", - "value": "general" - }, - { - "condition": "prep.population_type = 4", - "value": "key" - } - ] - } - }, - { - "type": "derived_column", - "alias": "is_breastfeeding", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "prep.is_breastfeeding = 1", - "value": "is_breastfeeding" - }, - { - "condition": "prep.is_breastfeeding = 0", - "value": "not_breastfeeding" - }, - { - "condition": "prep.is_breastfeeding is null", - "value": "unknown" - } - ] - } - }, - { - "type": "derived_column", - "alias": "is_pregnant", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "prep.is_pregnant = 1", - "value": "is_pregnant" - }, - { - "condition": "prep.is_pregnant = 0", - "value": "not_pregnant" - }, - { - "condition": "prep.is_pregnant is null", - "value": "unknown" - } - ] - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled_pregnant", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "prep.is_pregnant = 1 and prep.enrolled_in_prep_this_month = 1", - "value": "is_pregnant" - } - ] - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled_breastfeeding", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "prep.is_breastfeeding = 1 and prep.enrolled_in_prep_this_month = 1", - "value": "is_breastfeeding" - } - ] - } - }, - { - "type": "derived_column", - "alias": "has_hiv_rapid_test_this_month", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF((prep.status = 'active' or prep.status = 'defaulter') and has_hiv_rapid_test_this_month = 1 ,1, 0)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "prep.person_id" - ], - "excludeParam": "excludeParam" + "name": "prepMonthlySummaryBaseReport", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "prepLatestClinicalEncounterDate", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "table": "etl.prep_monthly_report_dataset", + "alias": "prep" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = prep.location_id" + } + }, + { + "dataSet": "prepLatestClinicalEncounterDate", + "alias": "latest_enc", + "join": { + "type": "LEFT", + "joinCondition": "latest_enc.person_id = prep.person_id" + } + }, + { + "table": "etl.flat_prep_summary_v1_1", + "alias": "prep_summary", + "join": { + "type": "LEFT", + "joinCondition": "latest_enc.person_id = prep_summary.person_id AND prep_summary.encounter_datetime = latest_enc.latest_encounter_date" + } + }, + { + "table": "amrs.encounter_type", + "alias": "e", + "join": { + "type": "LEFT", + "joinCondition": "prep_summary.encounter_type = e.encounter_type_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "l.location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "active_on_prep_this_month", + "column": "prep.active_on_prep_this_month" + }, + { + "type": "simple_column", + "alias": "enrolled_in_prep_this_month", + "column": "prep.enrolled_in_prep_this_month" + }, + { + "type": "simple_column", + "alias": "cumulative_prep_ltfu_this_month", + "column": "prep.cumulative_prep_ltfu_this_month" + }, + { + "type": "simple_column", + "alias": "prep_ltfu_this_month", + "column": "prep.prep_ltfu_this_month" + }, + { + "type": "simple_column", + "alias": "prep_discontinued_this_month", + "column": "prep.prep_discontinued_this_month" + }, + { + "type": "simple_column", + "alias": "cumulative_prep_discontinued_this_month", + "column": "prep.cumulative_prep_discontinued_this_month" + }, + { + "type": "simple_column", + "alias": "prev_on_prep_and_turned_positive", + "column": "prep.prev_on_prep_and_turned_positive" + }, + { + "type": "simple_column", + "alias": "turned_positive_this_month", + "column": "prep.turned_positive_this_month" + }, + { + "type": "simple_column", + "alias": "cumulative_turned_positive_this_month", + "column": "prep.cumulative_turned_positive_this_month" }, - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ? ", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "l.uuid in ?", - "parameterName": "locationUuids" - } + { + "type": "simple_column", + "alias": "status", + "column": "prep.status" + }, + { + "type": "simple_column", + "alias": "age", + "column": "prep.age" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "prep.gender" + }, + { + "type": "simple_column", + "alias": "days_since_rtc_date", + "column": "prep.days_since_rtc_date" + }, + { + "type": "simple_column", + "alias": "latest_rtc_date", + "column": "date_format(prep_summary.rtc_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "last_appointment", + "column": "CONCAT(COALESCE(DATE_FORMAT(prep_summary.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(e.name, ''))" + }, + { + "type": "simple_column", + "alias": "prev_rtc_date", + "column": "date_format(prep_summary.prev_rtc_date, '%Y-%m-%d')" + }, + { + "type": "derived_column", + "alias": "general_pop_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF((prep.population_type = 3 or prep.population_type = 1 or prep.population_type is null) and active_on_prep_this_month = 1 ,1, 0)" + } + }, + { + "type": "derived_column", + "alias": "population_type", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "prep.population_type = 1", + "value": "discordant" + }, + { + "condition": "prep.population_type = 2", + "value": "priority" + }, + { + "condition": "prep.population_type = 3 or prep.population_type is null", + "value": "general" + }, + { + "condition": "prep.population_type = 4", + "value": "key" + } ] + } + }, + { + "type": "derived_column", + "alias": "is_breastfeeding", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "prep.is_breastfeeding = 1", + "value": "is_breastfeeding" + }, + { + "condition": "prep.is_breastfeeding = 0", + "value": "not_breastfeeding" + }, + { + "condition": "prep.is_breastfeeding is null", + "value": "unknown" + } + ] + } + }, + { + "type": "derived_column", + "alias": "is_pregnant", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "prep.is_pregnant = 1", + "value": "is_pregnant" + }, + { + "condition": "prep.is_pregnant = 0", + "value": "not_pregnant" + }, + { + "condition": "prep.is_pregnant is null", + "value": "unknown" + } + ] + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled_pregnant", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "prep.is_pregnant = 1 and prep.enrolled_in_prep_this_month = 1", + "value": "is_pregnant" + } + ] + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled_breastfeeding", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "prep.is_breastfeeding = 1 and prep.enrolled_in_prep_this_month = 1", + "value": "is_breastfeeding" + } + ] + } + }, + { + "type": "derived_column", + "alias": "has_hiv_rapid_test_this_month", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF((prep.status = 'active' or prep.status = 'defaulter') and has_hiv_rapid_test_this_month = 1 ,1, 0)" + } } -} \ No newline at end of file + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["prep.person_id"], + "excludeParam": "excludeParam" + }, + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ? ", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "l.uuid in ?", + "parameterName": "locationUuids" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/prep-monthly-summary.json b/app/reporting-framework/json-reports/prep-monthly-summary.json index 99843f65f..5430747c1 100644 --- a/app/reporting-framework/json-reports/prep-monthly-summary.json +++ b/app/reporting-framework/json-reports/prep-monthly-summary.json @@ -1,11 +1,10 @@ - { - "reports": [ - "prepMonthlySummaryNoDisaggregation", - "prepMonthlySummaryPopulationTypeDisaggregation", - "prepMonthlySummaryBreastFeedingDisaggregation", - "prepMonthlySummaryPregnancyDisaggregation", - "prepMonthlyNewlyEnrolledBreastFeedingDisaggregation", - "prepMonthlyNewlyEnrolledPregnancyDisaggregation" - ] -} \ No newline at end of file + "reports": [ + "prepMonthlySummaryNoDisaggregation", + "prepMonthlySummaryPopulationTypeDisaggregation", + "prepMonthlySummaryBreastFeedingDisaggregation", + "prepMonthlySummaryPregnancyDisaggregation", + "prepMonthlyNewlyEnrolledBreastFeedingDisaggregation", + "prepMonthlyNewlyEnrolledPregnancyDisaggregation" + ] +} diff --git a/app/reporting-framework/json-reports/prep-report-patient-list-template.json b/app/reporting-framework/json-reports/prep-report-patient-list-template.json index 0792f5b98..1cbfc239c 100644 --- a/app/reporting-framework/json-reports/prep-report-patient-list-template.json +++ b/app/reporting-framework/json-reports/prep-report-patient-list-template.json @@ -1,240 +1,238 @@ { - "name": "prep-report-patient-list-template", - "version": "1.0", - "tag": "prep-report-patient-list-template", - "description": "Patient list template, for use against the prep summary table", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" - } - }, - { - "table": "etl.flat_prep_summary_v1_1", - "alias": "fps", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = fps.person_id AND fps.next_encounter_datetime IS NULL AND fps.encounter_type NOT IN (99999)" - } - }, - { - "table": "amrs.encounter_type", - "alias": "et", - "join": { - "type": "LEFT", - "joinCondition": "fps.encounter_type = et.encounter_type_id" - } - }, - { - "table": "amrs.person_address", - "alias": "pa", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = pa.person_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "cur_prep_meds", - "column": "fps.cur_prep_meds" - }, - { - "type": "simple_column", - "alias": "cur_prep_meds_names", - "column": "fps.cur_prep_meds_names" - }, - { - "type": "simple_column", - "alias": "inital_prep_start_date", - "column": "fps.inital_prep_start_date" - }, - { - "type": "derived_column", - "alias": "population_type_category", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "fps.sub_population_type = 1", - "value": "MSM" - }, - { - "condition": "fps.sub_population_type = 2", - "value": "MSW" - }, - { - "condition": "fps.sub_population_type = 3", - "value": "FSW" - }, - { - "condition": "fps.sub_population_type = 4", - "value": "IDU" - }, - { - "condition": "fps.sub_population_type = 5", - "value": "TRANS WOMAN" - }, - { - "condition": "fps.sub_population_type = 6", - "value": "TRANS MAN" - }, - { - "condition": "fps.sub_population_type = 7", - "value": "FISHER FOLK" - }, - { - "condition": "fps.sub_population_type = 8", - "value": "CSW" - }, - { - "condition": "fps.sub_population_type = 9", - "value": "DISPLACED PERSONS" - }, - { - "condition": "fps.sub_population_type = 10", - "value": "Military and other" - }, - { - "condition": "fps.sub_population_type = 12", - "value": "TRUCK/LORRY DRIVER" - }, - { - "condition": "fps.sub_population_type = 13", - "value": "NIDU" - } - ] - } - }, - { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" - }, - { - "type": "simple_column", - "alias": "enrollment_date", - "column": "date_format(fps.enrollment_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "days_since_rtc", - "column": "TIMESTAMPDIFF(DAY, prep.rtc_date, curdate())" - }, - { - "type": "simple_column", - "alias": "death_date", - "column": "date_format(fps.death_date, '%Y-%m-%d')" - }, - { - "type": "derived_column", - "alias": "hiv_rapid_test", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "fps.hiv_rapid_test_result = 703", - "value": "Positive" - }, - { - "condition": "fps.hiv_rapid_test_result = 664", - "value": "Negative" - }, - { - "condition": "fps.hiv_rapid_test_result = 1138", - "value": "Indeterminate" - }, - { - "condition": "fps.hiv_rapid_test_result = 1304", - "value": "Poor sample quality" - }, - { - "condition": "fps.hiv_rapid_test_result = 1067", - "value": "Unknown" - } - ] - } - }, - { - "type": "simple_column", - "alias": "rapid_test_date", - "column": "date_format(fps.hiv_rapid_test_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "turned_positive_date", - "column": "date_format(fps.turned_positive_date, '%Y-%m-%d')" - } - ], - "groupBy": { - "columns": [ - "t1.person_id" + "name": "prep-report-patient-list-template", + "version": "1.0", + "tag": "prep-report-patient-list-template", + "description": "Patient list template, for use against the prep summary table", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + } + }, + { + "table": "etl.flat_prep_summary_v1_1", + "alias": "fps", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = fps.person_id AND fps.next_encounter_datetime IS NULL AND fps.encounter_type NOT IN (99999)" + } + }, + { + "table": "amrs.encounter_type", + "alias": "et", + "join": { + "type": "LEFT", + "joinCondition": "fps.encounter_type = et.encounter_type_id" + } + }, + { + "table": "amrs.person_address", + "alias": "pa", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = pa.person_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "cur_prep_meds", + "column": "fps.cur_prep_meds" + }, + { + "type": "simple_column", + "alias": "cur_prep_meds_names", + "column": "fps.cur_prep_meds_names" + }, + { + "type": "simple_column", + "alias": "inital_prep_start_date", + "column": "fps.inital_prep_start_date" + }, + { + "type": "derived_column", + "alias": "population_type_category", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "fps.sub_population_type = 1", + "value": "MSM" + }, + { + "condition": "fps.sub_population_type = 2", + "value": "MSW" + }, + { + "condition": "fps.sub_population_type = 3", + "value": "FSW" + }, + { + "condition": "fps.sub_population_type = 4", + "value": "IDU" + }, + { + "condition": "fps.sub_population_type = 5", + "value": "TRANS WOMAN" + }, + { + "condition": "fps.sub_population_type = 6", + "value": "TRANS MAN" + }, + { + "condition": "fps.sub_population_type = 7", + "value": "FISHER FOLK" + }, + { + "condition": "fps.sub_population_type = 8", + "value": "CSW" + }, + { + "condition": "fps.sub_population_type = 9", + "value": "DISPLACED PERSONS" + }, + { + "condition": "fps.sub_population_type = 10", + "value": "Military and other" + }, + { + "condition": "fps.sub_population_type = 12", + "value": "TRUCK/LORRY DRIVER" + }, + { + "condition": "fps.sub_population_type = 13", + "value": "NIDU" + } + ] + } + }, + { + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" + }, + { + "type": "simple_column", + "alias": "enrollment_date", + "column": "date_format(fps.enrollment_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "days_since_rtc", + "column": "TIMESTAMPDIFF(DAY, prep.rtc_date, curdate())" + }, + { + "type": "simple_column", + "alias": "death_date", + "column": "date_format(fps.death_date, '%Y-%m-%d')" + }, + { + "type": "derived_column", + "alias": "hiv_rapid_test", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "fps.hiv_rapid_test_result = 703", + "value": "Positive" + }, + { + "condition": "fps.hiv_rapid_test_result = 664", + "value": "Negative" + }, + { + "condition": "fps.hiv_rapid_test_result = 1138", + "value": "Indeterminate" + }, + { + "condition": "fps.hiv_rapid_test_result = 1304", + "value": "Poor sample quality" + }, + { + "condition": "fps.hiv_rapid_test_result = 1067", + "value": "Unknown" + } ] + } + }, + { + "type": "simple_column", + "alias": "rapid_test_date", + "column": "date_format(fps.hiv_rapid_test_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "turned_positive_date", + "column": "date_format(fps.turned_positive_date, '%Y-%m-%d')" } -} \ No newline at end of file + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/prep_latest_clinical_encounter_date_base.json b/app/reporting-framework/json-reports/prep_latest_clinical_encounter_date_base.json index 8298648b9..dacacb41b 100644 --- a/app/reporting-framework/json-reports/prep_latest_clinical_encounter_date_base.json +++ b/app/reporting-framework/json-reports/prep_latest_clinical_encounter_date_base.json @@ -1,47 +1,45 @@ { - "name": "prepLatestClinicalEncounterDate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_prep_summary_v1_1", - "alias": "t1" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "latest_encounter_date", - "column": "MAX(t1.encounter_datetime)" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t1.location_id" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t1.is_prep_clinical_encounter = 1", - "parameterName": "" - } - ] + "name": "prepLatestClinicalEncounterDate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_prep_summary_v1_1", + "alias": "t1" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "latest_encounter_date", + "column": "MAX(t1.encounter_datetime)" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "t1.person_id" - ], - "excludeParam": "excludeParam" + { + "type": "simple_column", + "alias": "location_id", + "column": "t1.location_id" } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t1.is_prep_clinical_encounter = 1", + "parameterName": "" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["t1.person_id"], + "excludeParam": "excludeParam" + } } diff --git a/app/reporting-framework/json-reports/referral-aggregate.json b/app/reporting-framework/json-reports/referral-aggregate.json index 797c15134..cbf739af2 100755 --- a/app/reporting-framework/json-reports/referral-aggregate.json +++ b/app/reporting-framework/json-reports/referral-aggregate.json @@ -1,81 +1,78 @@ { - "name": "dataDatasetAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "referralDatasetbase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "referralDatasetbase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "program", - "column": "hmsd.program" - }, - { - "type": "simple_column", - "alias": "programUuids", - "column": "hmsd.programUuids" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "locationUuids", - "column": "hmsd.locationUuids" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "derived_column", - "alias": "counts", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct hmsd.patient_id,hmsd.programUuids)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id", - "program_id" - ], - "excludeParam": "excludeParam" + "name": "dataDatasetAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "referralDatasetbase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "referralDatasetbase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "program", + "column": "hmsd.program" + }, + { + "type": "simple_column", + "alias": "programUuids", + "column": "hmsd.programUuids" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "referral-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "patient_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "locationUuids", + "column": "hmsd.locationUuids" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "derived_column", + "alias": "counts", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct hmsd.patient_id,hmsd.programUuids)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id", "program_id"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "referral-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "patient_id", + "templateColumn": "person_id" } + } } + } } diff --git a/app/reporting-framework/json-reports/referral-patient-list-peer-template.json b/app/reporting-framework/json-reports/referral-patient-list-peer-template.json index f145900de..44175d2f8 100644 --- a/app/reporting-framework/json-reports/referral-patient-list-peer-template.json +++ b/app/reporting-framework/json-reports/referral-patient-list-peer-template.json @@ -1,158 +1,156 @@ { - "name": "referral_patient_list_peer_template", - "version": "1.0", - "tag": "referral_patient_list_peer_template", - "description": "Referral peer patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "INNER", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id = 10" - } - }, - { - "table": "etl.flat_cdm_peer_navigation", - "alias": "peer_navigation", - "join": { - "type": "LEFT", - "joinCondition": "peer_navigation.person_id = t1.person_id" - } - }, - { - "table": "etl.flat_cdm_peer_navigation", - "alias": "peer_initial", - "join": { - "type": "LEFT", - "joinCondition": "peer_initial.person_id = t1.person_id AND peer_initial.encounter_type = 192" - } - } - { - "table": "etl.flat_cdm_peer_navigation", - "alias": "peer_follow_up", - "join": { - "type": "LEFT", - "joinCondition": "peer_follow_up.person_id = t1.person_id AND peer_follow_up.encounter_type = 193" - } - } - - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "t1.birthdate" - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if (contacts.value IS NULL, '', contacts.value)" - } - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "is_referral_complete", - "column": "peer_navigation.is_referal_completed" - }, - { - "type": "simple_column", - "alias": "patient_referal_status", - "column": "peer_navigation.patient_referal_status" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "peer_navigation.encounter_type" - }, - { - "type": "derived_column", - "alias": "initial_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if (peer_initial.encounter_type =192, 1, 0)" - } - }, - { - "type": "derived_column", - "alias": "follow_up_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if (peer_follow_up.encounter_type =193, 1, 0)" - } - } - - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "referral_patient_list_peer_template", + "version": "1.0", + "tag": "referral_patient_list_peer_template", + "description": "Referral peer patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "INNER", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id = 10" + } + }, + { + "table": "etl.flat_cdm_peer_navigation", + "alias": "peer_navigation", + "join": { + "type": "LEFT", + "joinCondition": "peer_navigation.person_id = t1.person_id" + } + }, + { + "table": "etl.flat_cdm_peer_navigation", + "alias": "peer_initial", + "join": { + "type": "LEFT", + "joinCondition": "peer_initial.person_id = t1.person_id AND peer_initial.encounter_type = 192" + } + }, + { + "table": "etl.flat_cdm_peer_navigation", + "alias": "peer_follow_up", + "join": { + "type": "LEFT", + "joinCondition": "peer_follow_up.person_id = t1.person_id AND peer_follow_up.encounter_type = 193" + } } + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "t1.birthdate" + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if (contacts.value IS NULL, '', contacts.value)" + } + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "is_referral_complete", + "column": "peer_navigation.is_referal_completed" + }, + { + "type": "simple_column", + "alias": "patient_referal_status", + "column": "peer_navigation.patient_referal_status" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "peer_navigation.encounter_type" + }, + { + "type": "derived_column", + "alias": "initial_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if (peer_initial.encounter_type =192, 1, 0)" + } + }, + { + "type": "derived_column", + "alias": "follow_up_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if (peer_follow_up.encounter_type =193, 1, 0)" + } + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } } diff --git a/app/reporting-framework/json-reports/referral-patient-list-template.json b/app/reporting-framework/json-reports/referral-patient-list-template.json index c0e98498f..e2b9f8e26 100755 --- a/app/reporting-framework/json-reports/referral-patient-list-template.json +++ b/app/reporting-framework/json-reports/referral-patient-list-template.json @@ -1,109 +1,109 @@ { - "name": "referral_patient_list_template", - "version": "1.0", - "tag": "referral_patient_list_template", - "description": "Referral patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "INNER", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id = 10" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "derived_column", - "alias": "uuid", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "t1.uuid" - } - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "t1.birthdate" - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if (contacts.value IS NULL, '', contacts.value)" - } - }, - { - "type": "derived_column", - "alias": "provider_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(t5.uuid = '731ba72-cf99-4176-9fcd-37cd186400c7' OR t5.uuid ='876a154d-310d-4caf-8b58-be9dbcc7e753' OR t5.uuid ='bd9a8b06-73c7-44a8-928c-5e72247f4c1d' , 1,0)" - } - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - } - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "referral_patient_list_template", + "version": "1.0", + "tag": "referral_patient_list_template", + "description": "Referral patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "INNER", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id = 10" + } } + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "derived_column", + "alias": "uuid", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "t1.uuid" + } + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "t1.birthdate" + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if (contacts.value IS NULL, '', contacts.value)" + } + }, + { + "type": "derived_column", + "alias": "provider_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(t5.uuid = '731ba72-cf99-4176-9fcd-37cd186400c7' OR t5.uuid ='876a154d-310d-4caf-8b58-be9dbcc7e753' OR t5.uuid ='bd9a8b06-73c7-44a8-928c-5e72247f4c1d' , 1,0)" + } + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } } diff --git a/app/reporting-framework/json-reports/referral-peer-aggregate.json b/app/reporting-framework/json-reports/referral-peer-aggregate.json index 28417037a..cbf739af2 100644 --- a/app/reporting-framework/json-reports/referral-peer-aggregate.json +++ b/app/reporting-framework/json-reports/referral-peer-aggregate.json @@ -1,82 +1,78 @@ { - "name": "dataDatasetAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "referralDatasetbase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "referralDatasetbase", - "alias": "hmsd" - } - ], - "columns": [ - - { - "type": "simple_column", - "alias": "program", - "column": "hmsd.program" - }, - { - "type": "simple_column", - "alias": "programUuids", - "column": "hmsd.programUuids" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "locationUuids", - "column": "hmsd.locationUuids" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "derived_column", - "alias": "counts", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(distinct hmsd.patient_id,hmsd.programUuids)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id", - "program_id" - ], - "excludeParam": "excludeParam" + "name": "dataDatasetAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "referralDatasetbase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "referralDatasetbase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "program", + "column": "hmsd.program" + }, + { + "type": "simple_column", + "alias": "programUuids", + "column": "hmsd.programUuids" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "referral-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "patient_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "locationUuids", + "column": "hmsd.locationUuids" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "derived_column", + "alias": "counts", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(distinct hmsd.patient_id,hmsd.programUuids)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id", "program_id"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "referral-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "patient_id", + "templateColumn": "person_id" } + } } + } } diff --git a/app/reporting-framework/json-reports/referral-peer-base.json b/app/reporting-framework/json-reports/referral-peer-base.json index b4b8aacfc..61b020799 100644 --- a/app/reporting-framework/json-reports/referral-peer-base.json +++ b/app/reporting-framework/json-reports/referral-peer-base.json @@ -1,194 +1,191 @@ - { - "name": "referralDataSetbase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - - { - "table": "amrs.patient_program", - "alias": "t3" - }, - { - "table": "etl.patient_referral", - "alias": "t4", - "join": { - "type": "LEFT", - "joinCondition": "t4.patient_program_id = t3.patient_program_id" - } - }, - { - "table": "amrs.program", - "alias": "t5", - "join": { - "type": "INNER", - "joinCondition": "t3.program_id = t5.program_id" - } - }, - { - "table": "amrs.location", - "alias": "t9", - "join": { - "type": "INNER", - "joinCondition": "t3.location_id = t9.location_id" - } - }, - { - "table": "amrs.location", - "alias": "location", - "join": { - "type": "INNER", - "joinCondition": "t4.referred_from_location_id = location.location_id" - } - }, - { - "table": "etl.flat_cdm_peer_navigation", - "alias": "peer_navigation", - "join": { - "type": "LEFT", - "joinCondition": "t3.patient_id = peer_navigation.person_id" - } - }, - { - "table": "etl.flat_cdm_peer_navigation", - "alias": "initial_encounter", - "join": { - "type": "LEFT", - "joinCondition": "t3.patient_id = initial_encounter.person_id and initial_encounter.encounter_type = 192" - } - }, - { - "table": "etl.flat_cdm_peer_navigation", - "alias": "follow_up_encounter", - "join": { - "type": "LEFT", - "joinCondition": "t3.patient_id = follow_up_encounter.person_id and follow_up_encounter.encounter_type = 193 " - } - } + "name": "referralDataSetbase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "amrs.patient_program", + "alias": "t3" + }, + { + "table": "etl.patient_referral", + "alias": "t4", + "join": { + "type": "LEFT", + "joinCondition": "t4.patient_program_id = t3.patient_program_id" + } + }, + { + "table": "amrs.program", + "alias": "t5", + "join": { + "type": "INNER", + "joinCondition": "t3.program_id = t5.program_id" + } + }, + { + "table": "amrs.location", + "alias": "t9", + "join": { + "type": "INNER", + "joinCondition": "t3.location_id = t9.location_id" + } + }, + { + "table": "amrs.location", + "alias": "location", + "join": { + "type": "INNER", + "joinCondition": "t4.referred_from_location_id = location.location_id" + } + }, + { + "table": "etl.flat_cdm_peer_navigation", + "alias": "peer_navigation", + "join": { + "type": "LEFT", + "joinCondition": "t3.patient_id = peer_navigation.person_id" + } + }, + { + "table": "etl.flat_cdm_peer_navigation", + "alias": "initial_encounter", + "join": { + "type": "LEFT", + "joinCondition": "t3.patient_id = initial_encounter.person_id and initial_encounter.encounter_type = 192" + } + }, + { + "table": "etl.flat_cdm_peer_navigation", + "alias": "follow_up_encounter", + "join": { + "type": "LEFT", + "joinCondition": "t3.patient_id = follow_up_encounter.person_id and follow_up_encounter.encounter_type = 193 " + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_id", + "column": "t3.patient_id" + }, + { + "type": "simple_column", + "alias": "program", + "column": "t5.name" + }, + { + "type": "simple_column", + "alias": "programUuids", + "column": "t5.uuid" + }, + { + "type": "simple_column", + "alias": "program_id", + "column": "t5.program_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "t9.name" + }, + { + "type": "simple_column", + "alias": "locationUuids", + "column": "t9.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "t9.location_id" + }, + { + "type": "simple_column", + "alias": "referred_from", + "column": "location.name" + }, + { + "type": "simple_column", + "alias": "date_referred", + "column": "DATE_FORMAT(t4.date_created, '%Y-%m-%d')" + }, + { + "type": "derived_column", + "alias": "review_status", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if (t4.notification_status IS NULL, 'PENDING', 'DONE')" + } + }, + { + "type": "simple_column", + "alias": "is_referal_complete", + "column": "peer_navigation.is_referal_completed" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "peer_navigation.encounter_type" + }, + { + "type": "simple_column", + "alias": "referal_status", + "column": "peer_navigation.patient_referal_status" + }, + { + "type": "simple_column", + "alias": "referral_urgency", + "column": "peer_navigation.referal_urgency" + }, + { + "type": "simple_column", + "alias": "referred_in_or_out", + "column": "peer_navigation.referred_in_or_out" + }, + { + "type": "derived_column", + "alias": "initial_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if (initial_encounter.encounter_type IS NOT NULL,1,0)" + } + }, + { + "type": "derived_column", + "alias": "follow_up_encounter", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "if (follow_up_encounter.encounter_type IS NOT NULL,1,0)" + } + } + ], + "orderBy": { + "orderByParam": "orderByParam", - ], "columns": [ - { - "type": "simple_column", - "alias": "patient_id", - "column": "t3.patient_id" - }, - { - "type": "simple_column", - "alias": "program", - "column": "t5.name" - }, - { - "type": "simple_column", - "alias": "programUuids", - "column": "t5.uuid" - }, - { - "type": "simple_column", - "alias": "program_id", - "column": "t5.program_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "t9.name" - }, - { - "type": "simple_column", - "alias": "locationUuids", - "column": "t9.uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "t9.location_id" - }, - { - "type": "simple_column", - "alias": "referred_from", - "column": "location.name" - }, - { - "type": "simple_column", - "alias": "date_referred", - "column": "DATE_FORMAT(t4.date_created, '%Y-%m-%d')" - }, - { - "type": "derived_column", - "alias": "review_status", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if (t4.notification_status IS NULL, 'PENDING', 'DONE')" - } - }, - { - "type": "simple_column", - "alias": "is_referal_complete", - "column": "peer_navigation.is_referal_completed" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "peer_navigation.encounter_type" - }, - { - "type": "simple_column", - "alias": "referal_status", - "column": "peer_navigation.patient_referal_status" - }, - { - "type": "simple_column", - "alias": "referral_urgency", - "column": "peer_navigation.referal_urgency" - }, - { - "type": "simple_column", - "alias": "referred_in_or_out", - "column": "peer_navigation.referred_in_or_out" - }, - - { - "type": "derived_column", - "alias": "initial_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if (initial_encounter.encounter_type IS NOT NULL,1,0)" - } - }, - { - "type": "derived_column", - "alias": "follow_up_encounter", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "if (follow_up_encounter.encounter_type IS NOT NULL,1,0)" - } - } - ], - "orderBy": { - "orderByParam": "orderByParam", - - - "columns": [{ - "column": "t4.notification_status", - "order": "asc" - }] - }, - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "DATE_FORMAT(t4.date_created, '%Y-%m-%d') >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE_FORMAT(t4.date_created, '%Y-%m-%d') <= ?", - "parameterName": "endDate" - } - ] - } + { + "column": "t4.notification_status", + "order": "asc" + } + ] + }, + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "DATE_FORMAT(t4.date_created, '%Y-%m-%d') >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE_FORMAT(t4.date_created, '%Y-%m-%d') <= ?", + "parameterName": "endDate" + } + ] + } } diff --git a/app/reporting-framework/json-reports/regimen-dataset-aggregate.json b/app/reporting-framework/json-reports/regimen-dataset-aggregate.json index 0b1f3adbb..b22c29dc8 100755 --- a/app/reporting-framework/json-reports/regimen-dataset-aggregate.json +++ b/app/reporting-framework/json-reports/regimen-dataset-aggregate.json @@ -1,95 +1,97 @@ { - "name": "regimenDataSetAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "regimenDataSetbase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "regimenDataSetbase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, { - "type": "simple_column", - "alias": "arv_first_regimen_location_id", - "column": "hmsd.arv_first_regimen_location_id" - }, + "name": "regimenDataSetAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" + "name": "regimenDataSetbase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "regimenDataSetbase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } }, { - "type": "simple_column", - "alias": "age_range", - "disAggregation": "true", - "column": "hmsd.age_range" - }, { - "type": "derived_column", - "alias": "arv_first_regimen", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(*)" - } - }], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "arv_first_regimen_location_id", - "age_range", - "hmsd.gender" - ], - "excludeParam": "excludeParam" + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" }, - "transFormDirectives":{ - "joinColumn":"location_id", - "joinColumnParam": "joinColumnParam", - "disaggregationColumns":["gender","age_range"], - "skipColumns":["arv_first_regimen_location_id","join_location","location_uuid"] + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_location_id", + "column": "hmsd.arv_first_regimen_location_id" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "age_range", + "disAggregation": "true", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "arv_first_regimen", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(*)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["arv_first_regimen_location_id", "age_range", "hmsd.gender"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "joinColumnParam": "joinColumnParam", + "disaggregationColumns": ["gender", "age_range"], + "skipColumns": [ + "arv_first_regimen_location_id", + "join_location", + "location_uuid" + ] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } - + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/regimen-dataset-base.json b/app/reporting-framework/json-reports/regimen-dataset-base.json index 8eb5e982b..48f5c85f2 100755 --- a/app/reporting-framework/json-reports/regimen-dataset-base.json +++ b/app/reporting-framework/json-reports/regimen-dataset-base.json @@ -1,142 +1,142 @@ { - "name": "regimenDataSetbase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hmsd.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_location_id", - "column": "hmsd.arv_first_regimen_location_id" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "cur_regimen_arv_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "hmsd.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmsd.age < 15", - "value": "lt_15" - }, - { - "condition": "hmsd.age >= 15", - "value": "gte_15" - } - ] - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.location_id in ?", - "parameterName": "locations" - } + "name": "regimenDataSetbase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hmsd.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_location_id", + "column": "hmsd.arv_first_regimen_location_id" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "cur_regimen_arv_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "hmsd.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmsd.age < 15", + "value": "lt_15" + }, + { + "condition": "hmsd.age >= 15", + "value": "gte_15" + } ] + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/retention-appointment-adherence-aggregate.json b/app/reporting-framework/json-reports/retention-appointment-adherence-aggregate.json index 32fbdbd97..976c96844 100644 --- a/app/reporting-framework/json-reports/retention-appointment-adherence-aggregate.json +++ b/app/reporting-framework/json-reports/retention-appointment-adherence-aggregate.json @@ -1,93 +1,92 @@ { - "name": "retentionAppointmentAdherenceAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [{ - "name": "retentionAppointmentAdherenceBase", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [{ - "dataSet": "retentionAppointmentAdherenceBase", - "alias": "rb" - }], - "columns": [ - { - "type": "simple_column", - "alias": "location_id", - "column": "rb.location_id" - }, - { - "type": "simple_column", - "alias": "location_name", - "column": "rb.location_name" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "rb.location_uuid" - }, - { - "type": "derived_column", - "alias": "report_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(rb.report_date, '%Y-%m-%d')" - } - }, - { - "type": "derived_column", - "alias": "patients_scheduled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.patients_scheduled)" - } - }, - { - "type": "derived_column", - "alias": "defaulted", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.defaulted)" - } - }, - { - "type": "derived_column", - "alias": "no_attempt_to_contact_28_days_after_rtc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.no_attempt_to_contact_28_days_after_rtc)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id", - "DATE(rb.report_date)" - ], - "excludeParam": "excludeParam" + "name": "retentionAppointmentAdherenceAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "retentionAppointmentAdherenceBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "retentionAppointmentAdherenceBase", + "alias": "rb" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_id", + "column": "rb.location_id" + }, + { + "type": "simple_column", + "alias": "location_name", + "column": "rb.location_name" }, - "transFormDirectives": { - "joinColumn": "report_date", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] + { + "type": "simple_column", + "alias": "location_uuid", + "column": "rb.location_uuid" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "retention-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "report_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(rb.report_date, '%Y-%m-%d')" + } + }, + { + "type": "derived_column", + "alias": "patients_scheduled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.patients_scheduled)" + } + }, + { + "type": "derived_column", + "alias": "defaulted", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.defaulted)" + } + }, + { + "type": "derived_column", + "alias": "no_attempt_to_contact_28_days_after_rtc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.no_attempt_to_contact_28_days_after_rtc)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id", "DATE(rb.report_date)"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "report_date", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "retention-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/retention-appointment-adherence-base.json b/app/reporting-framework/json-reports/retention-appointment-adherence-base.json index a0cb1aa40..35f46005b 100644 --- a/app/reporting-framework/json-reports/retention-appointment-adherence-base.json +++ b/app/reporting-framework/json-reports/retention-appointment-adherence-base.json @@ -1,243 +1,229 @@ { - "name": "retentionAppointmentAdherenceBase", - "version": "1.0", - "tag": "retention_appointment_adherence_base", - "uses": [ - { - "name": "retentionReportCohortBase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "table": "etl.flat_appointment", - "alias": "fa" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "l.location_id = fa.location_id" - - } - }, - { - "table": "amrs.program", - "alias": "pr", - "join": { - "type": "inner", - "joinCondition": "pr.program_id = fa.program_id" - - } - }, - { - "table": "amrs.visit_type", - "alias": "vt", - "join": { - "type": "left", - "joinCondition": "vt.visit_type_id = fa.visit_type_id" - - } - }, - { - "table": "amrs.person", - "alias": "p", - "join": { - "type": "inner", - "joinCondition": "p.person_id = fa.person_id" - - } - }, - { - "table": "etl.flat_appointment", - "alias": "attended_day", - "join": { - "type": "left", - "joinCondition": "attended_day.person_id = fa.person_id AND DATE(attended_day.encounter_datetime) > DATE(fa.encounter_datetime) AND DATE(attended_day.encounter_datetime) <= DATE(fa.rtc_date) AND attended_day.is_clinical = 1" - - } - }, - { - "table": "etl.flat_appointment", - "alias": "next_outreach", - "join": { - "type": "left", - "joinCondition": "next_outreach.person_id = fa.person_id AND next_outreach.encounter_type = 21 AND next_outreach.encounter_datetime > fa.encounter_datetime" - - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs", - "join": { - "type": "left", - "joinCondition": "fhs.person_id = fa.person_id AND fhs.next_encounter_datetime_hiv IS NULL AND fhs.encounter_type NOT IN ('99999')" - - } - }, - { - "table": "etl.flat_appointment", - "alias": "exited", - "join": { - "type": "left", - "joinCondition": "exited.person_id = fa.person_id AND exited.encounter_type IN ('157') AND exited.next_clinical_encounter_datetime IS NULL" - - } - }, - { - "table": "etl.flat_appointment", - "alias": "transfer", - "join": { - "type": "left", - "joinCondition": "transfer.person_id = fa.person_id AND transfer.encounter_type IN ('116') AND transfer.next_clinical_encounter_datetime IS NULL" - - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "fa.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "p.gender" - }, - { - "type": "simple_column", - "alias": "program", - "column": "pr.name" - }, - { - "type": "simple_column", - "alias": "visit_type", - "column": "vt.name" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "timestampdiff(year,p.birthdate,NOW())" - } - }, - { - "type": "simple_column", - "alias": "report_date", - "column": "fa.rtc_date" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "fa.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_name", - "column": "l.name" - }, - { - "type": "derived_column", - "alias": "patients_scheduled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fa.person_id IS NOT NULL , 1 , NULL)" - } - }, - { - "type": "derived_column", - "alias": "defaulted", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(attended_day.person_id IS NULL,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "no_attempt_to_contact_28_days_after_rtc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(TIMESTAMPDIFF(DAY,fa.rtc_date, IF(fa.next_clinical_encounter_datetime IS NOT NULL, fa.next_clinical_encounter_datetime, CURDATE())) >= 28 AND fa.next_clinical_encounter_datetime IS NULL AND next_outreach.encounter_datetime IS NULL , 1, NULL)" - } - } - - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fa.rtc_date) >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fa.rtc_date) <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) >= ?", - "parameterName": "startAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) <= ?", - "parameterName": "endAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "p.gender IN ?", - "parameterName": "genders" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.is_clinical = 1" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.location_id IN ? ", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.program_id IN (1,9,27) " - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.transfer_out_location_id NOT IN (?,9999) OR fhs.transfer_out_location_id IS NULL", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "transfer.person_id IS NULL" - } - ] - }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "fa.person_id", - "DATE(fa.rtc_date)" - ] - }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [{ - "column": "fa.rtc_date", - "order": "asc" - } - - ] - + "name": "retentionAppointmentAdherenceBase", + "version": "1.0", + "tag": "retention_appointment_adherence_base", + "uses": [ + { + "name": "retentionReportCohortBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "table": "etl.flat_appointment", + "alias": "fa" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "l.location_id = fa.location_id" + } + }, + { + "table": "amrs.program", + "alias": "pr", + "join": { + "type": "inner", + "joinCondition": "pr.program_id = fa.program_id" + } + }, + { + "table": "amrs.visit_type", + "alias": "vt", + "join": { + "type": "left", + "joinCondition": "vt.visit_type_id = fa.visit_type_id" + } + }, + { + "table": "amrs.person", + "alias": "p", + "join": { + "type": "inner", + "joinCondition": "p.person_id = fa.person_id" + } + }, + { + "table": "etl.flat_appointment", + "alias": "attended_day", + "join": { + "type": "left", + "joinCondition": "attended_day.person_id = fa.person_id AND DATE(attended_day.encounter_datetime) > DATE(fa.encounter_datetime) AND DATE(attended_day.encounter_datetime) <= DATE(fa.rtc_date) AND attended_day.is_clinical = 1" + } + }, + { + "table": "etl.flat_appointment", + "alias": "next_outreach", + "join": { + "type": "left", + "joinCondition": "next_outreach.person_id = fa.person_id AND next_outreach.encounter_type = 21 AND next_outreach.encounter_datetime > fa.encounter_datetime" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs", + "join": { + "type": "left", + "joinCondition": "fhs.person_id = fa.person_id AND fhs.next_encounter_datetime_hiv IS NULL AND fhs.encounter_type NOT IN ('99999')" + } + }, + { + "table": "etl.flat_appointment", + "alias": "exited", + "join": { + "type": "left", + "joinCondition": "exited.person_id = fa.person_id AND exited.encounter_type IN ('157') AND exited.next_clinical_encounter_datetime IS NULL" + } + }, + { + "table": "etl.flat_appointment", + "alias": "transfer", + "join": { + "type": "left", + "joinCondition": "transfer.person_id = fa.person_id AND transfer.encounter_type IN ('116') AND transfer.next_clinical_encounter_datetime IS NULL" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "fa.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "p.gender" + }, + { + "type": "simple_column", + "alias": "program", + "column": "pr.name" + }, + { + "type": "simple_column", + "alias": "visit_type", + "column": "vt.name" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(year,p.birthdate,NOW())" + } + }, + { + "type": "simple_column", + "alias": "report_date", + "column": "fa.rtc_date" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "fa.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_name", + "column": "l.name" + }, + { + "type": "derived_column", + "alias": "patients_scheduled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fa.person_id IS NOT NULL , 1 , NULL)" + } + }, + { + "type": "derived_column", + "alias": "defaulted", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(attended_day.person_id IS NULL,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "no_attempt_to_contact_28_days_after_rtc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(TIMESTAMPDIFF(DAY,fa.rtc_date, IF(fa.next_clinical_encounter_datetime IS NOT NULL, fa.next_clinical_encounter_datetime, CURDATE())) >= 28 AND fa.next_clinical_encounter_datetime IS NULL AND next_outreach.encounter_datetime IS NULL , 1, NULL)" + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fa.rtc_date) >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fa.rtc_date) <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) >= ?", + "parameterName": "startAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) <= ?", + "parameterName": "endAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "p.gender IN ?", + "parameterName": "genders" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.is_clinical = 1" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.location_id IN ? ", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.program_id IN (1,9,27) " + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.transfer_out_location_id NOT IN (?,9999) OR fhs.transfer_out_location_id IS NULL", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "transfer.person_id IS NULL" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["fa.person_id", "DATE(fa.rtc_date)"] + }, + "orderBy": { + "orderByParam": "orderByParam", + "columns": [ + { + "column": "fa.rtc_date", + "order": "asc" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/retention-dataset-aggregate.json b/app/reporting-framework/json-reports/retention-dataset-aggregate.json index 587ecc95c..e47502fd7 100755 --- a/app/reporting-framework/json-reports/retention-dataset-aggregate.json +++ b/app/reporting-framework/json-reports/retention-dataset-aggregate.json @@ -1,158 +1,156 @@ { - "name": "retentionDataSetAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - { - "name": "retentionDataSetbase", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "retentionDataSetbase", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "derived_column", - "alias": "net_cohort", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(*)" - } - }, - { - "type": "derived_column", - "alias": "active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(active)" - } - }, - { - "type": "derived_column", - "alias": "ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(ltfu)" - } - }, - { - "type": "derived_column", - "alias": "perc_ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(ltfu)/count(*)" - } - }, - { - "type": "derived_column", - "alias": "dead", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(dead)" - } - }, - { - "type": "derived_column", - "alias": "on_tx", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(on_tx)" - } - }, - { - "type": "derived_column", - "alias": "suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(suppressed)" - } - }, - { - "type": "derived_column", - "alias": "total_with_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(total_with_vl)" - } - }, - { - "type": "derived_column", - "alias": "on_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(on_second_line)" - } - }, - { - "type": "derived_column", - "alias": "on_original_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(on_original_first_line)" - } - }, - { - "type": "derived_column", - "alias": "on_alternative_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "count(on_alternative_first_line)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" + "name": "retentionDataSetAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "retentionDataSetbase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "retentionDataSetbase", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "derived_column", + "alias": "net_cohort", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(*)" + } }, - "transFormDirectives":{ - "joinColumn":"location_id", - "joinColumnParam": "joinColumnParam", - "skipColumns":["arv_first_regimen_location_id","join_location"] + { + "type": "derived_column", + "alias": "active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(active)" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(ltfu)" + } + }, + { + "type": "derived_column", + "alias": "perc_ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(ltfu)/count(*)" + } + }, + { + "type": "derived_column", + "alias": "dead", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(dead)" + } + }, + { + "type": "derived_column", + "alias": "on_tx", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(on_tx)" + } + }, + { + "type": "derived_column", + "alias": "suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(suppressed)" + } + }, + { + "type": "derived_column", + "alias": "total_with_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(total_with_vl)" + } + }, + { + "type": "derived_column", + "alias": "on_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(on_second_line)" + } + }, + { + "type": "derived_column", + "alias": "on_original_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(on_original_first_line)" + } + }, + { + "type": "derived_column", + "alias": "on_alternative_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "count(on_alternative_first_line)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "joinColumnParam": "joinColumnParam", + "skipColumns": ["arv_first_regimen_location_id", "join_location"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/retention-dataset-base.json b/app/reporting-framework/json-reports/retention-dataset-base.json index 8fd60d600..f0c1df228 100755 --- a/app/reporting-framework/json-reports/retention-dataset-base.json +++ b/app/reporting-framework/json-reports/retention-dataset-base.json @@ -1,210 +1,210 @@ { - "name": "retentionDataSetbase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hmsd.cur_arv_meds" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "cur_regimen_arv_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "hmsd.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - }, - { - "alias": "net_cohort", - "expressionOptions": { - "expression": "1" - }, - "type": "derived_column", - "expressionType": "simple_expression" - }, - { - "alias": "active", - "expressionOptions": { - "expression": "if(status='active',1,null)" - }, - "type": "derived_column", - "expressionType": "simple_expression" - }, - { - "alias": "ltfu", - "expressionOptions": { - "expression": "if(status='ltfu',1,null)" - }, - "type": "derived_column", - "expressionType": "simple_expression" - }, - { - "alias": "dead", - "expressionOptions": { - "expression": "if(status='dead',1,null)" - }, - "type": "derived_column", - "expressionType": "simple_expression" - }, - { - "alias": "on_tx", - "expressionOptions": { - "expression": "if(on_art_this_month=1,1,null)" - }, - "type": "derived_column", - "expressionType": "simple_expression" - }, - { - "alias": "suppressed", - "expressionOptions": { - "expression": "if(hmsd.vl_1<1000 and vl_in_past_year=1,1,null)" - }, - "type": "derived_column", - "expressionType": "simple_expression" - }, - { - "alias": "total_with_vl", - "expressionOptions": { - "expression": "if(vl_in_past_year=1,1,null)" - }, - "type": "derived_column", - "expressionType": "simple_expression" - }, - { - "type": "derived_column", - "alias": "on_original_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(status = 'active' AND hmsd.cur_arv_line = 1 AND hmsd.arv_first_regimen = hmsd.cur_arv_meds,1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "on_alternative_first_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(status = 'active' AND hmsd.cur_arv_line = 1 AND hmsd.arv_first_regimen <> hmsd.cur_arv_meds,1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "on_second_line", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(status = 'active' AND hmsd.cur_arv_line >= 2,1,NULL)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "status in ('active','ltfu','dead')", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.arv_first_regimen_start_date between date_format(date_sub(endDate,interval 1 year),'%Y-%m-01') and date_sub(endDate,interval 1 year)", - "parameterName": "" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.location_id in ?", - "parameterName": "locations" - } - ] + "name": "retentionDataSetbase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hmsd.cur_arv_meds" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "cur_regimen_arv_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "hmsd.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } + }, + { + "alias": "net_cohort", + "expressionOptions": { + "expression": "1" + }, + "type": "derived_column", + "expressionType": "simple_expression" + }, + { + "alias": "active", + "expressionOptions": { + "expression": "if(status='active',1,null)" + }, + "type": "derived_column", + "expressionType": "simple_expression" + }, + { + "alias": "ltfu", + "expressionOptions": { + "expression": "if(status='ltfu',1,null)" + }, + "type": "derived_column", + "expressionType": "simple_expression" + }, + { + "alias": "dead", + "expressionOptions": { + "expression": "if(status='dead',1,null)" + }, + "type": "derived_column", + "expressionType": "simple_expression" + }, + { + "alias": "on_tx", + "expressionOptions": { + "expression": "if(on_art_this_month=1,1,null)" + }, + "type": "derived_column", + "expressionType": "simple_expression" + }, + { + "alias": "suppressed", + "expressionOptions": { + "expression": "if(hmsd.vl_1<1000 and vl_in_past_year=1,1,null)" + }, + "type": "derived_column", + "expressionType": "simple_expression" + }, + { + "alias": "total_with_vl", + "expressionOptions": { + "expression": "if(vl_in_past_year=1,1,null)" + }, + "type": "derived_column", + "expressionType": "simple_expression" + }, + { + "type": "derived_column", + "alias": "on_original_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(status = 'active' AND hmsd.cur_arv_line = 1 AND hmsd.arv_first_regimen = hmsd.cur_arv_meds,1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "on_alternative_first_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(status = 'active' AND hmsd.cur_arv_line = 1 AND hmsd.arv_first_regimen <> hmsd.cur_arv_meds,1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "on_second_line", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(status = 'active' AND hmsd.cur_arv_line >= 2,1,NULL)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "status in ('active','ltfu','dead')", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.arv_first_regimen_start_date between date_format(date_sub(endDate,interval 1 year),'%Y-%m-01') and date_sub(endDate,interval 1 year)", + "parameterName": "" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/retention-defaulter-tracing-aggregate.json b/app/reporting-framework/json-reports/retention-defaulter-tracing-aggregate.json index edff3ab70..721ea6dfc 100644 --- a/app/reporting-framework/json-reports/retention-defaulter-tracing-aggregate.json +++ b/app/reporting-framework/json-reports/retention-defaulter-tracing-aggregate.json @@ -1,122 +1,121 @@ { - "name": "retentionDefaulterTracingAggregate", - "version": "1.0", - "tag": "retention_defaulter_tracing_aggregate", - "description": "", - "uses": [{ - "name": "retentionDefaulterTracingBase", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [{ - "dataSet": "retentionDefaulterTracingBase", - "alias": "dt" - }], - "columns": [ { - "type": "simple_column", - "alias": "report_date", - "column": "dt.report_date" + "name": "retentionDefaulterTracingAggregate", + "version": "1.0", + "tag": "retention_defaulter_tracing_aggregate", + "description": "", + "uses": [ + { + "name": "retentionDefaulterTracingBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "retentionDefaulterTracingBase", + "alias": "dt" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "report_date", + "column": "dt.report_date" }, { - "type": "simple_column", - "alias": "location_id", - "column": "dt.location_id" + "type": "simple_column", + "alias": "location_id", + "column": "dt.location_id" }, { - "type": "simple_column", - "alias": "location_uuid", - "column": "dt.location_uuid" + "type": "simple_column", + "alias": "location_uuid", + "column": "dt.location_uuid" }, { - "type": "simple_column", - "alias": "location_name", - "column": "dt.location_name" + "type": "simple_column", + "alias": "location_name", + "column": "dt.location_name" }, { - "type": "derived_column", - "alias": "reached_by_phone", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(dt.reached_by_phone)" - } + "type": "derived_column", + "alias": "reached_by_phone", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(dt.reached_by_phone)" + } }, { - "type": "derived_column", - "alias": "not_reached_by_phone", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(dt.not_reached_by_phone)" - } + "type": "derived_column", + "alias": "not_reached_by_phone", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(dt.not_reached_by_phone)" + } }, { - "type": "derived_column", - "alias": "home_visit_found", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(dt.home_visit_found)" - } + "type": "derived_column", + "alias": "home_visit_found", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(dt.home_visit_found)" + } }, { - "type": "derived_column", - "alias": "home_visit_not_found", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(dt.home_visit_not_found)" - } + "type": "derived_column", + "alias": "home_visit_not_found", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(dt.home_visit_not_found)" + } }, { - "type": "derived_column", - "alias": "deceased", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(dt.deceased)" - } + "type": "derived_column", + "alias": "deceased", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(dt.deceased)" + } }, { - "type": "derived_column", - "alias": "self_disengaged", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(dt.self_disengaged)" - } + "type": "derived_column", + "alias": "self_disengaged", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(dt.self_disengaged)" + } }, { - "type": "derived_column", - "alias": "self_transferred_out", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(dt.self_transferred_out)" - } + "type": "derived_column", + "alias": "self_transferred_out", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(dt.self_transferred_out)" + } } - - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "DATE(dt.report_date)", - "dt.location_id" - ], - "excludeParam": "excludeParam" - }, - "transFormDirectives": { - "joinColumn": "report_date", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "retention-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["DATE(dt.report_date)", "dt.location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "report_date", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "retention-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/retention-defaulter-tracing-base.json b/app/reporting-framework/json-reports/retention-defaulter-tracing-base.json index 49925db9d..615f591f7 100644 --- a/app/reporting-framework/json-reports/retention-defaulter-tracing-base.json +++ b/app/reporting-framework/json-reports/retention-defaulter-tracing-base.json @@ -1,208 +1,200 @@ { - "name": "retentionDefaulterTracingBase", - "version": "1.0", - "tag": "retention_defaulter_tracing_base", - "uses": [ - ], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "l.location_id = fhs.location_id" - - } - }, - { - "table": "amrs.person", - "alias": "p", - "join": { - "type": "inner", - "joinCondition": "p.person_id = fhs.person_id" - - } - }, - { - "table": "etl.flat_appointment", - "alias": "fa", - "join": { - "type": "left", - "joinCondition": "fa.person_id = fhs.person_id AND DATE(fa.encounter_datetime) = DATE(fhs.prev_clinical_datetime_hiv)" - - } - }, - { - "table": "amrs.program", - "alias": "pr", - "join": { - "type": "inner", - "joinCondition": "pr.program_id = fa.program_id" - - } - }, - { - "table": "amrs.visit_type", - "alias": "vt", - "join": { - "type": "left", - "joinCondition": "vt.visit_type_id = fa.visit_type_id" - - } - } - ], + "name": "retentionDefaulterTracingBase", + "version": "1.0", + "tag": "retention_defaulter_tracing_base", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "l.location_id = fhs.location_id" + } + }, + { + "table": "amrs.person", + "alias": "p", + "join": { + "type": "inner", + "joinCondition": "p.person_id = fhs.person_id" + } + }, + { + "table": "etl.flat_appointment", + "alias": "fa", + "join": { + "type": "left", + "joinCondition": "fa.person_id = fhs.person_id AND DATE(fa.encounter_datetime) = DATE(fhs.prev_clinical_datetime_hiv)" + } + }, + { + "table": "amrs.program", + "alias": "pr", + "join": { + "type": "inner", + "joinCondition": "pr.program_id = fa.program_id" + } + }, + { + "table": "amrs.visit_type", + "alias": "vt", + "join": { + "type": "left", + "joinCondition": "vt.visit_type_id = fa.visit_type_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "report_date", + "column": "DATE_FORMAT(fhs.encounter_datetime,'%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "l.location_id" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "fhs.person_id" + }, + { + "type": "simple_column", + "alias": "program", + "column": "pr.name" + }, + { + "type": "simple_column", + "alias": "visit_type", + "column": "vt.name" + }, + { + "type": "simple_column", + "alias": "location_name", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "derived_column", + "alias": "reached_by_phone", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.phone_outreach = 1, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "not_reached_by_phone", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.phone_outreach = 2, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "home_visit_found", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.home_outreach = 1, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "home_visit_not_found", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.home_outreach = 2, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "deceased", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.outreach_missed_visit_reason = 159, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "self_disengaged", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.outreach_missed_visit_reason = 9083, 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "self_transferred_out", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fhs.outreach_missed_visit_reason = 1594, 1, NULL)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "fhs.encounter_type = 21" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.location_id IN ?", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "date(fhs.encounter_datetime) <= date(?)", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "date(fhs.encounter_datetime) >= date(?)", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "p.gender in ?", + "parameterName": "genders" + }, + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) >= ?", + "parameterName": "startAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) <= ?", + "parameterName": "endAge" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": [ + "fhs.person_id", + "DATE_FORMAT(fhs.encounter_datetime,'%Y-%m-%d')" + ] + }, + "orderBy": { + "orderByParam": "orderByParam", "columns": [ - { - "type": "simple_column", - "alias": "report_date", - "column": "DATE_FORMAT(fhs.encounter_datetime,'%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "l.location_id" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "fhs.person_id" - }, - { - "type": "simple_column", - "alias": "program", - "column": "pr.name" - }, - { - "type": "simple_column", - "alias": "visit_type", - "column": "vt.name" - }, - { - "type": "simple_column", - "alias": "location_name", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "derived_column", - "alias": "reached_by_phone", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.phone_outreach = 1, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "not_reached_by_phone", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.phone_outreach = 2, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "home_visit_found", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.home_outreach = 1, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "home_visit_not_found", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.home_outreach = 2, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "deceased", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.outreach_missed_visit_reason = 159, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "self_disengaged", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.outreach_missed_visit_reason = 9083, 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "self_transferred_out", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fhs.outreach_missed_visit_reason = 1594, 1, NULL)" - } - } - - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "fhs.encounter_type = 21" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.location_id IN ?", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "date(fhs.encounter_datetime) <= date(?)", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "date(fhs.encounter_datetime) >= date(?)", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "p.gender in ?", - "parameterName": "genders" - }, - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) >= ?", - "parameterName": "startAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) <= ?", - "parameterName": "endAge" - } - ] - }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "fhs.person_id", - "DATE_FORMAT(fhs.encounter_datetime,'%Y-%m-%d')" - ] - }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [{ - "column": "fhs.encounter_datetime", - "order": "asc" - } - - ] - - } -} \ No newline at end of file + { + "column": "fhs.encounter_datetime", + "order": "asc" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/retention-intervention-cohort.json b/app/reporting-framework/json-reports/retention-intervention-cohort.json index 6188f93b1..2981f0ea3 100644 --- a/app/reporting-framework/json-reports/retention-intervention-cohort.json +++ b/app/reporting-framework/json-reports/retention-intervention-cohort.json @@ -1,51 +1,49 @@ { - "name": "retentionInterventionCohort", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "t2" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "t2.person_id" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "t2.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "phone_outreach", - "column": "t2.phone_outreach" - }, - { - "type": "simple_column", - "alias": "home_outreach", - "column": "t2.home_outreach" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "t2.encounter_type = 21" - } - ] + "name": "retentionInterventionCohort", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "t2" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "t2.person_id" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "t2.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "phone_outreach", + "column": "t2.phone_outreach" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "encounter_id" - ], - "excludeParam": "excludeParam" + { + "type": "simple_column", + "alias": "home_outreach", + "column": "t2.home_outreach" } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "t2.encounter_type = 21" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["encounter_id"], + "excludeParam": "excludeParam" + } } diff --git a/app/reporting-framework/json-reports/retention-ltfu-aggregate.json b/app/reporting-framework/json-reports/retention-ltfu-aggregate.json index e101b380a..d1cd35510 100644 --- a/app/reporting-framework/json-reports/retention-ltfu-aggregate.json +++ b/app/reporting-framework/json-reports/retention-ltfu-aggregate.json @@ -1,74 +1,73 @@ { - "name": "retentionLtfuAggregate", - "version": "1.0", - "tag": "retention_ltfu_aggregate", - "description": "", - "uses": [{ - "name": "retentionLtfuBase", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [{ - "dataSet": "retentionLtfuBase", - "alias": "rl" - }], - "columns": [ { - "type": "simple_column", - "alias": "report_date", - "column": "DATE_FORMAT(rl.report_date,'%Y-%m-%d')" + "name": "retentionLtfuAggregate", + "version": "1.0", + "tag": "retention_ltfu_aggregate", + "description": "", + "uses": [ + { + "name": "retentionLtfuBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "retentionLtfuBase", + "alias": "rl" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "report_date", + "column": "DATE_FORMAT(rl.report_date,'%Y-%m-%d')" }, { - "type": "simple_column", - "alias": "location_id", - "column": "rl.location_id" + "type": "simple_column", + "alias": "location_id", + "column": "rl.location_id" }, { - "type": "simple_column", - "alias": "location_uuid", - "column": "rl.location_uuid" + "type": "simple_column", + "alias": "location_uuid", + "column": "rl.location_uuid" }, { - "type": "simple_column", - "alias": "location_name", - "column": "rl.location_name" + "type": "simple_column", + "alias": "location_name", + "column": "rl.location_name" }, { - "type": "derived_column", - "alias": "newly_ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rl.newly_ltfu)" - } + "type": "derived_column", + "alias": "newly_ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rl.newly_ltfu)" + } } - - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "DATE(rl.report_date)", - "rl.location_id" - ], - "excludeParam": "excludeParam" - }, - "transFormDirectives": { - "joinColumn": "report_date", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "retention-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["DATE(rl.report_date)", "rl.location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "report_date", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "retention-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/retention-ltfu-base.json b/app/reporting-framework/json-reports/retention-ltfu-base.json index 8025899a8..79e396e1b 100644 --- a/app/reporting-framework/json-reports/retention-ltfu-base.json +++ b/app/reporting-framework/json-reports/retention-ltfu-base.json @@ -1,219 +1,206 @@ { - "name": "retentionLtfuBase", - "version": "1.0", - "tag": "retention_ltfu_base", - "uses": [ - ], - "sources": [ - { - "table": "etl.flat_appointment", - "alias": "fa" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "l.location_id = fa.location_id" - - } - }, - { - "table": "amrs.program", - "alias": "pr", - "join": { - "type": "inner", - "joinCondition": "pr.program_id = fa.program_id" - - } - }, - { - "table": "amrs.person", - "alias": "p", - "join": { - "type": "inner", - "joinCondition": "p.person_id = fa.person_id" - - } - }, - { - "table": "amrs.visit_type", - "alias": "vt", - "join": { - "type": "left", - "joinCondition": "vt.visit_type_id = fa.visit_type_id" - - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhs", - "join": { - "type": "left", - "joinCondition": "fhs.person_id = fa.person_id AND fhs.next_encounter_datetime_hiv IS NULL AND fhs.encounter_type NOT IN ('99999')" - - } - }, - { - "table": "etl.flat_appointment", - "alias": "exit", - "join": { - "type": "left", - "joinCondition": "exit.person_id = fa.person_id AND exit.encounter_type IN ('157') AND exit.next_clinical_encounter_datetime IS NULL" - - } - }, - { - "table": "etl.flat_appointment", - "alias": "transfer", - "join": { - "type": "left", - "joinCondition": "transfer.person_id = fa.person_id AND transfer.encounter_type IN ('116') AND transfer.next_clinical_encounter_datetime IS NULL" - - } - } - ], + "name": "retentionLtfuBase", + "version": "1.0", + "tag": "retention_ltfu_base", + "uses": [], + "sources": [ + { + "table": "etl.flat_appointment", + "alias": "fa" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "l.location_id = fa.location_id" + } + }, + { + "table": "amrs.program", + "alias": "pr", + "join": { + "type": "inner", + "joinCondition": "pr.program_id = fa.program_id" + } + }, + { + "table": "amrs.person", + "alias": "p", + "join": { + "type": "inner", + "joinCondition": "p.person_id = fa.person_id" + } + }, + { + "table": "amrs.visit_type", + "alias": "vt", + "join": { + "type": "left", + "joinCondition": "vt.visit_type_id = fa.visit_type_id" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhs", + "join": { + "type": "left", + "joinCondition": "fhs.person_id = fa.person_id AND fhs.next_encounter_datetime_hiv IS NULL AND fhs.encounter_type NOT IN ('99999')" + } + }, + { + "table": "etl.flat_appointment", + "alias": "exit", + "join": { + "type": "left", + "joinCondition": "exit.person_id = fa.person_id AND exit.encounter_type IN ('157') AND exit.next_clinical_encounter_datetime IS NULL" + } + }, + { + "table": "etl.flat_appointment", + "alias": "transfer", + "join": { + "type": "left", + "joinCondition": "transfer.person_id = fa.person_id AND transfer.encounter_type IN ('116') AND transfer.next_clinical_encounter_datetime IS NULL" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "fa.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "p.gender" + }, + { + "type": "simple_column", + "alias": "program", + "column": "pr.name" + }, + { + "type": "simple_column", + "alias": "visit_type", + "column": "vt.name" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(year,p.birthdate,NOW())" + } + }, + { + "type": "derived_column", + "alias": "report_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE(DATE_ADD(fa.rtc_date, INTERVAL 90 DAY))" + } + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "fa.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_name", + "column": "l.name" + }, + { + "type": "derived_column", + "alias": "newly_ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(TIMESTAMPDIFF(DAY, fa.rtc_date, IF(fa.next_clinical_encounter_datetime IS NULL, DATE(DATE_ADD(fa.rtc_date , INTERVAL 90 DAY)), fa.next_clinical_encounter_datetime)) = 90, 1, NULL)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fa.rtc_date) >= DATE(DATE_SUB(? , INTERVAL 90 DAY))", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fa.rtc_date) <= DATE(DATE_SUB(? , INTERVAL 90 DAY))", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) >= ?", + "parameterName": "startAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) <= ?", + "parameterName": "endAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "p.gender in ?", + "parameterName": "genders" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.is_clinical = 1" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.location_id IN ? ", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.program_id IN (1,9,27) " + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhs.transfer_out_location_id NOT IN (?,9999) OR fhs.transfer_out_location_id IS NULL", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "p.death_date IS NULL" + }, + { + "filterType": "tableColumns", + "conditionExpression": "exit.person_id IS NULL" + }, + { + "filterType": "tableColumns", + "conditionExpression": "transfer.person_id IS NULL" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.next_clinical_encounter_datetime IS NULL" + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["fa.person_id", "DATE(report_date)"] + }, + "orderBy": { + "orderByParam": "orderByParam", "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "fa.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "p.gender" - }, - { - "type": "simple_column", - "alias": "program", - "column": "pr.name" - }, - { - "type": "simple_column", - "alias": "visit_type", - "column": "vt.name" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "timestampdiff(year,p.birthdate,NOW())" - } - }, - { - "type": "derived_column", - "alias": "report_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE(DATE_ADD(fa.rtc_date, INTERVAL 90 DAY))" - } - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "fa.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_name", - "column": "l.name" - }, - { - "type": "derived_column", - "alias": "newly_ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(TIMESTAMPDIFF(DAY, fa.rtc_date, IF(fa.next_clinical_encounter_datetime IS NULL, DATE(DATE_ADD(fa.rtc_date , INTERVAL 90 DAY)), fa.next_clinical_encounter_datetime)) = 90, 1, NULL)" - } - } - - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fa.rtc_date) >= DATE(DATE_SUB(? , INTERVAL 90 DAY))", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fa.rtc_date) <= DATE(DATE_SUB(? , INTERVAL 90 DAY))", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) >= ?", - "parameterName": "startAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) <= ?", - "parameterName": "endAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "p.gender in ?", - "parameterName": "genders" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.is_clinical = 1" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.location_id IN ? ", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.program_id IN (1,9,27) " - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhs.transfer_out_location_id NOT IN (?,9999) OR fhs.transfer_out_location_id IS NULL", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "p.death_date IS NULL" - }, - { - "filterType": "tableColumns", - "conditionExpression": "exit.person_id IS NULL" - }, - { - "filterType": "tableColumns", - "conditionExpression": "transfer.person_id IS NULL" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.next_clinical_encounter_datetime IS NULL" - } - ] - }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "fa.person_id", - "DATE(report_date)" - ] - }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [{ - "column": "fa.rtc_date", - "order": "asc" - } - - ] - - } -} \ No newline at end of file + { + "column": "fa.rtc_date", + "order": "asc" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/retention-report-latest-cohort-base.json b/app/reporting-framework/json-reports/retention-report-latest-cohort-base.json index 5cb372e6e..0d65e6f93 100644 --- a/app/reporting-framework/json-reports/retention-report-latest-cohort-base.json +++ b/app/reporting-framework/json-reports/retention-report-latest-cohort-base.json @@ -1,79 +1,77 @@ { - "name": "retentionReportLatestCohortBase", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "fhsc" - }, - { - "table": "amrs.encounter_type", - "alias": "e", - "join": { - "type": "INNER", - "joinCondition": "fhsc.encounter_type = e.encounter_type_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "fhsc.person_id" - }, - { - "type": "derived_column", - "alias": "latest_vl_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " vl_1_date" - } - }, - { - "type": "simple_column", - "alias": "current_vl", - "column": "fhsc.vl_1" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "fhsc.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "DATE_FORMAT(fhsc.encounter_datetime,'%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "encounter_type", - "column": "fhsc.encounter_type" - }, - { - "type": "simple_column", - "alias": "encounter_name", - "column": "e.name" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "fhsc.next_clinical_datetime_hiv IS NULL" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fhsc.is_clinical_encounter = 1" - } - ] + "name": "retentionReportLatestCohortBase", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "fhsc" }, - "groupBy": { - "columns": [ - "fhsc.person_id" - ] + { + "table": "amrs.encounter_type", + "alias": "e", + "join": { + "type": "INNER", + "joinCondition": "fhsc.encounter_type = e.encounter_type_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "fhsc.person_id" + }, + { + "type": "derived_column", + "alias": "latest_vl_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " vl_1_date" + } + }, + { + "type": "simple_column", + "alias": "current_vl", + "column": "fhsc.vl_1" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "fhsc.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "DATE_FORMAT(fhsc.encounter_datetime,'%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "encounter_type", + "column": "fhsc.encounter_type" + }, + { + "type": "simple_column", + "alias": "encounter_name", + "column": "e.name" + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "fhsc.next_clinical_datetime_hiv IS NULL" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fhsc.is_clinical_encounter = 1" + } + ] + }, + "groupBy": { + "columns": ["fhsc.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/retention-report-patient-list-template.json b/app/reporting-framework/json-reports/retention-report-patient-list-template.json index 971aac813..a46bfdb7e 100644 --- a/app/reporting-framework/json-reports/retention-report-patient-list-template.json +++ b/app/reporting-framework/json-reports/retention-report-patient-list-template.json @@ -1,181 +1,180 @@ { - "name": "retention_report_patient_list_template", - "version": "1.0", - "tag": "retention_report_patient_list_template", - "description": "Retention Report Patient list template", - "sources": [ - { - "table": "amrs.person", - "alias": "t1" - }, - { - "table": "amrs.person_name", - "alias": "person_name", - "join": { - "type": "INNER", - "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" - } - }, - { - "table": "amrs.patient_identifier", - "alias": "id", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" - } - }, - { - "table": "amrs.person_attribute", - "alias": "contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id = 10" - } - }, - { - "table": "amrs.person_attribute", - "alias": "alternate_contacts", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = alternate_contacts.person_id AND (alternate_contacts.voided IS NULL || alternate_contacts.voided = 0) AND alternate_contacts.person_attribute_type_id = 40" - } - }, - { - "table": "amrs.person_address", - "alias": "address", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = address.person_id AND address.voided = 0" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "hs", - "join": { - "type": "LEFT", - "joinCondition": "t1.person_id = hs.person_id AND hs.next_clinical_datetime_hiv IS NULL AND hs.encounter_type NOT IN('99999')" - } - }, - { - "table": "amrs.encounter_type", - "alias": "encounter_type", - "join": { - "type": "LEFT", - "joinCondition": "hs.encounter_type = encounter_type.encounter_type_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "patient_uuid", - "column": "t1.uuid" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "t1.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "t1.gender" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" - } - }, - { - "type": "derived_column", - "alias": "person_name", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" - } - }, - { - "type": "derived_column", - "alias": "identifiers", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "current_vl", - "column": "hs.vl_1" - }, - { - "type": "derived_column", - "alias": "current_vl_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hs.vl_1_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "previous_vl", - "column": "hs.vl_2" - }, - { - "type": "derived_column", - "alias": "previous_vl_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hs.vl_2_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hs.cur_arv_meds" - }, - { - "type": "derived_column", - "alias": "last_appointment", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "CONCAT(COALESCE(DATE_FORMAT(hs.encounter_datetime,'%Y-%m-%d'), ''),' ', COALESCE(encounter_type.name, ''))" - } - }, - { - "type": "derived_column", - "alias": "latest_rtc_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(hs.rtc_date,'%Y-%m-%d')" - } - }, - { - "type": "derived_column", - "alias": "phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - } - }, - { - "type": "derived_column", - "alias": "alternate_phone_number", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": " GROUP_CONCAT(DISTINCT alternate_contacts.value SEPARATOR ', ')" - } - }, - { - "type": "simple_column", - "alias": "estate", - "column": "address.address3" - } - - ], - "groupBy":{ - "columns":["t1.person_id"] + "name": "retention_report_patient_list_template", + "version": "1.0", + "tag": "retention_report_patient_list_template", + "description": "Retention Report Patient list template", + "sources": [ + { + "table": "amrs.person", + "alias": "t1" + }, + { + "table": "amrs.person_name", + "alias": "person_name", + "join": { + "type": "INNER", + "joinCondition": "t1.person_id = person_name.person_id AND (person_name.voided IS NULL || person_name.voided = 0) AND person_name.preferred = 1" + } + }, + { + "table": "amrs.patient_identifier", + "alias": "id", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = id.patient_id AND (id.voided IS NULL || id.voided = 0)" + } + }, + { + "table": "amrs.person_attribute", + "alias": "contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id = 10" + } + }, + { + "table": "amrs.person_attribute", + "alias": "alternate_contacts", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = alternate_contacts.person_id AND (alternate_contacts.voided IS NULL || alternate_contacts.voided = 0) AND alternate_contacts.person_attribute_type_id = 40" + } + }, + { + "table": "amrs.person_address", + "alias": "address", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = address.person_id AND address.voided = 0" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "hs", + "join": { + "type": "LEFT", + "joinCondition": "t1.person_id = hs.person_id AND hs.next_clinical_datetime_hiv IS NULL AND hs.encounter_type NOT IN('99999')" + } + }, + { + "table": "amrs.encounter_type", + "alias": "encounter_type", + "join": { + "type": "LEFT", + "joinCondition": "hs.encounter_type = encounter_type.encounter_type_id" + } } -} \ No newline at end of file + ], + "columns": [ + { + "type": "simple_column", + "alias": "patient_uuid", + "column": "t1.uuid" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "t1.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "t1.gender" + }, + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "extract(year from (from_days(datediff(now(),t1.birthdate))))" + } + }, + { + "type": "derived_column", + "alias": "person_name", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " CONCAT(COALESCE(person_name.given_name, ''), ' ', COALESCE(person_name.middle_name, ''), ' ', COALESCE(person_name.family_name, ''))" + } + }, + { + "type": "derived_column", + "alias": "identifiers", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT id.identifier SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "current_vl", + "column": "hs.vl_1" + }, + { + "type": "derived_column", + "alias": "current_vl_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hs.vl_1_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "previous_vl", + "column": "hs.vl_2" + }, + { + "type": "derived_column", + "alias": "previous_vl_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hs.vl_2_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hs.cur_arv_meds" + }, + { + "type": "derived_column", + "alias": "last_appointment", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "CONCAT(COALESCE(DATE_FORMAT(hs.encounter_datetime,'%Y-%m-%d'), ''),' ', COALESCE(encounter_type.name, ''))" + } + }, + { + "type": "derived_column", + "alias": "latest_rtc_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(hs.rtc_date,'%Y-%m-%d')" + } + }, + { + "type": "derived_column", + "alias": "phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + } + }, + { + "type": "derived_column", + "alias": "alternate_phone_number", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": " GROUP_CONCAT(DISTINCT alternate_contacts.value SEPARATOR ', ')" + } + }, + { + "type": "simple_column", + "alias": "estate", + "column": "address.address3" + } + ], + "groupBy": { + "columns": ["t1.person_id"] + } +} diff --git a/app/reporting-framework/json-reports/retention-report-visits-aggregate.json b/app/reporting-framework/json-reports/retention-report-visits-aggregate.json index 638918110..56c9dbeba 100644 --- a/app/reporting-framework/json-reports/retention-report-visits-aggregate.json +++ b/app/reporting-framework/json-reports/retention-report-visits-aggregate.json @@ -1,124 +1,124 @@ { - "name": "retentionVisitsAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [{ - "name": "retentionVisitsBase", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [{ - "dataSet": "retentionVisitsBase", - "alias": "rb" - }], - "columns": [{ - "type": "simple_column", - "alias": "location_id", - "column": "rb.location_id" - }, - { - "type": "simple_column", - "alias": "location_name", - "column": "rb.location_name" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "rb.location_uuid" - }, - { - "type": "derived_column", - "alias": "report_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(rb.report_date, '%Y-%m-%d')" - } - }, - { - "type": "derived_column", - "alias": "attended_clinic_on_date_scheduled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.attended_clinic_on_date_scheduled)" - } - }, - { - "type": "derived_column", - "alias": "unscheduled_early_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.unscheduled_early_visits)" - } - }, - { - "type": "derived_column", - "alias": "unscheduled_late_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.unscheduled_late_visits)" - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.newly_enrolled)" - } - }, - { - "type": "derived_column", - "alias": "returned_after_intervention", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.returned_after_intervention)" - } - }, - { - "type": "derived_column", - "alias": "returned_without_intervention", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.returned_without_intervention)" - } - }, - { - "type": "derived_column", - "alias": "transfer_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "COUNT(rb.transfer_in)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id", - "DATE(rb.report_date)" - ], - "excludeParam": "excludeParam" + "name": "retentionVisitsAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "retentionVisitsBase", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "retentionVisitsBase", + "alias": "rb" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_id", + "column": "rb.location_id" + }, + { + "type": "simple_column", + "alias": "location_name", + "column": "rb.location_name" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "rb.location_uuid" + }, + { + "type": "derived_column", + "alias": "report_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(rb.report_date, '%Y-%m-%d')" + } }, - "transFormDirectives": { - "joinColumn": "report_date", - "skipColumns": [ - ], - "disaggregationColumns": [ - ] + { + "type": "derived_column", + "alias": "attended_clinic_on_date_scheduled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.attended_clinic_on_date_scheduled)" + } }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "retention-report-patient-list-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "unscheduled_early_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.unscheduled_early_visits)" + } + }, + { + "type": "derived_column", + "alias": "unscheduled_late_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.unscheduled_late_visits)" + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.newly_enrolled)" + } + }, + { + "type": "derived_column", + "alias": "returned_after_intervention", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.returned_after_intervention)" + } + }, + { + "type": "derived_column", + "alias": "returned_without_intervention", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.returned_without_intervention)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "COUNT(rb.transfer_in)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id", "DATE(rb.report_date)"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "report_date", + "skipColumns": [], + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "retention-report-patient-list-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/retention-report-visits-base.json b/app/reporting-framework/json-reports/retention-report-visits-base.json index 029dc51a4..05f71cbe8 100644 --- a/app/reporting-framework/json-reports/retention-report-visits-base.json +++ b/app/reporting-framework/json-reports/retention-report-visits-base.json @@ -1,256 +1,246 @@ { - "name": "retentionVisitsBase", - "version": "1.0", - "tag": "retention_visits_base", - "uses": [ - { - "name": "retentionInterventionCohort", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "table": "etl.flat_appointment", - "alias": "fa" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "inner", - "joinCondition": "l.location_id = fa.location_id" - - } - }, - { - "table": "amrs.program", - "alias": "pr", - "join": { - "type": "inner", - "joinCondition": "pr.program_id = fa.program_id" - - } - }, - { - "table": "amrs.visit_type", - "alias": "vt", - "join": { - "type": "left", - "joinCondition": "vt.visit_type_id = fa.visit_type_id" - - } - }, - { - "table": "amrs.person", - "alias": "p", - "join": { - "type": "inner", - "joinCondition": "p.person_id = fa.person_id" - - } - }, - { - "dataSet": "retentionInterventionCohort", - "alias": "intervention", - "join": { - "type": "LEFT", - "joinCondition": "intervention.person_id = fa.person_id AND intervention.encounter_datetime > fa.prev_clinical_encounter_datetime AND intervention.encounter_datetime < fa.encounter_datetime" - } - }, - { - "table": "etl.flat_hiv_summary_v15b", - "alias": "transfers", - "join": { - "type": "left", - "joinCondition": "transfers.person_id = fa.person_id AND DATE(transfers.transfer_in_date) = DATE(fa.encounter_datetime) AND transfers.is_clinical_encounter = 1 AND transfers.transfer_in = 1" - - } - }, - { - "table": "etl.flat_appointment", - "alias": "scheduled", - "join": { - "type": "left", - "joinCondition": "scheduled.person_id = fa.person_id AND DATE(scheduled.rtc_date) = DATE(fa.encounter_datetime)" - - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "person_id", - "column": "fa.person_id" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "p.gender" - }, - { - "type": "simple_column", - "alias": "program", - "column": "pr.name" - }, - { - "type": "simple_column", - "alias": "visit_type", - "column": "vt.name" - }, - { - "type": "derived_column", - "alias": "age", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "timestampdiff(year,p.birthdate,NOW())" - } - }, - { - "type": "simple_column", - "alias": "report_date", - "column": "DATE_FORMAT(fa.encounter_datetime,'%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "fa.location_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_name", - "column": "l.name" - }, - { - "type": "derived_column", - "alias": "attended_clinic_on_date_scheduled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(scheduled.person_id IS NOT NULL,1,NULL)" - } - }, - { - "type": "derived_column", - "alias": "unscheduled_early_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF((DATE(fa.encounter_datetime) < DATE(fa.prev_clinical_rtc_date)), 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "unscheduled_late_visits", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF((DATE(fa.encounter_datetime) > DATE(fa.prev_clinical_rtc_date)), 1, NULL)" - } - }, - { - "type": "derived_column", - "alias": "newly_enrolled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(fa.prev_clinical_encounter_datetime IS NULL, 1 , NULL)" - } - }, - { - "type": "derived_column", - "alias": "returned_after_intervention", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "TIMESTAMPDIFF(DAY, fa.prev_clinical_rtc_date, fa.encounter_datetime) >= 1 AND intervention.person_id IS NOT NULL", - "value": 1 - } - ] - } - }, - { - "type": "derived_column", - "alias": "returned_without_intervention", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "TIMESTAMPDIFF(DAY, fa.prev_clinical_rtc_date, fa.encounter_datetime) >= 1 AND intervention.person_id IS NULL", - "value": 1 - } - ] - } - }, - { - "type": "derived_column", - "alias": "transfer_in", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "IF(transfers.person_id IS NOT NULL,1,NULL)" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fa.encounter_datetime) >= ?", - "parameterName": "startDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "DATE(fa.encounter_datetime) <= ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) >= ?", - "parameterName": "startAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) <= ?", - "parameterName": "endAge" - }, - { - "filterType": "tableColumns", - "conditionExpression": "p.gender in ?", - "parameterName": "genders" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.is_clinical = 1" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.location_id IN ? ", - "parameterName": "locations" - }, - { - "filterType": "tableColumns", - "conditionExpression": "fa.program_id IN (1,9,27) " - } - ] + "name": "retentionVisitsBase", + "version": "1.0", + "tag": "retention_visits_base", + "uses": [ + { + "name": "retentionInterventionCohort", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "table": "etl.flat_appointment", + "alias": "fa" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "inner", + "joinCondition": "l.location_id = fa.location_id" + } + }, + { + "table": "amrs.program", + "alias": "pr", + "join": { + "type": "inner", + "joinCondition": "pr.program_id = fa.program_id" + } + }, + { + "table": "amrs.visit_type", + "alias": "vt", + "join": { + "type": "left", + "joinCondition": "vt.visit_type_id = fa.visit_type_id" + } + }, + { + "table": "amrs.person", + "alias": "p", + "join": { + "type": "inner", + "joinCondition": "p.person_id = fa.person_id" + } + }, + { + "dataSet": "retentionInterventionCohort", + "alias": "intervention", + "join": { + "type": "LEFT", + "joinCondition": "intervention.person_id = fa.person_id AND intervention.encounter_datetime > fa.prev_clinical_encounter_datetime AND intervention.encounter_datetime < fa.encounter_datetime" + } + }, + { + "table": "etl.flat_hiv_summary_v15b", + "alias": "transfers", + "join": { + "type": "left", + "joinCondition": "transfers.person_id = fa.person_id AND DATE(transfers.transfer_in_date) = DATE(fa.encounter_datetime) AND transfers.is_clinical_encounter = 1 AND transfers.transfer_in = 1" + } + }, + { + "table": "etl.flat_appointment", + "alias": "scheduled", + "join": { + "type": "left", + "joinCondition": "scheduled.person_id = fa.person_id AND DATE(scheduled.rtc_date) = DATE(fa.encounter_datetime)" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "person_id", + "column": "fa.person_id" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "p.gender" + }, + { + "type": "simple_column", + "alias": "program", + "column": "pr.name" + }, + { + "type": "simple_column", + "alias": "visit_type", + "column": "vt.name" }, - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "fa.person_id", - "fa.encounter_datetime" + { + "type": "derived_column", + "alias": "age", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "timestampdiff(year,p.birthdate,NOW())" + } + }, + { + "type": "simple_column", + "alias": "report_date", + "column": "DATE_FORMAT(fa.encounter_datetime,'%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "fa.location_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_name", + "column": "l.name" + }, + { + "type": "derived_column", + "alias": "attended_clinic_on_date_scheduled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(scheduled.person_id IS NOT NULL,1,NULL)" + } + }, + { + "type": "derived_column", + "alias": "unscheduled_early_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF((DATE(fa.encounter_datetime) < DATE(fa.prev_clinical_rtc_date)), 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "unscheduled_late_visits", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF((DATE(fa.encounter_datetime) > DATE(fa.prev_clinical_rtc_date)), 1, NULL)" + } + }, + { + "type": "derived_column", + "alias": "newly_enrolled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(fa.prev_clinical_encounter_datetime IS NULL, 1 , NULL)" + } + }, + { + "type": "derived_column", + "alias": "returned_after_intervention", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "TIMESTAMPDIFF(DAY, fa.prev_clinical_rtc_date, fa.encounter_datetime) >= 1 AND intervention.person_id IS NOT NULL", + "value": 1 + } ] + } }, - "orderBy": { - "orderByParam": "orderByParam", - "columns": [{ - "column": "fa.encounter_datetime", - "order": "asc" - } - + { + "type": "derived_column", + "alias": "returned_without_intervention", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "TIMESTAMPDIFF(DAY, fa.prev_clinical_rtc_date, fa.encounter_datetime) >= 1 AND intervention.person_id IS NULL", + "value": 1 + } ] - - } -} \ No newline at end of file + } + }, + { + "type": "derived_column", + "alias": "transfer_in", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "IF(transfers.person_id IS NOT NULL,1,NULL)" + } + } + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fa.encounter_datetime) >= ?", + "parameterName": "startDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "DATE(fa.encounter_datetime) <= ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) >= ?", + "parameterName": "startAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "timestampdiff(year,p.birthdate,NOW()) <= ?", + "parameterName": "endAge" + }, + { + "filterType": "tableColumns", + "conditionExpression": "p.gender in ?", + "parameterName": "genders" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.is_clinical = 1" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.location_id IN ? ", + "parameterName": "locations" + }, + { + "filterType": "tableColumns", + "conditionExpression": "fa.program_id IN (1,9,27) " + } + ] + }, + "groupBy": { + "groupParam": "groupByParam", + "columns": ["fa.person_id", "fa.encounter_datetime"] + }, + "orderBy": { + "orderByParam": "orderByParam", + "columns": [ + { + "column": "fa.encounter_datetime", + "order": "asc" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/retention-report/appointment-adherence.json b/app/reporting-framework/json-reports/retention-report/appointment-adherence.json index 4896d0bd5..4d26e8f4a 100644 --- a/app/reporting-framework/json-reports/retention-report/appointment-adherence.json +++ b/app/reporting-framework/json-reports/retention-report/appointment-adherence.json @@ -1,8 +1,8 @@ { - "reports": [ + "reports": [ "retentionAppointmentAdherenceAggregate", "retentionVisitsAggregate", "retentionDefaulterTracingAggregate", "retentionLtfuAggregate" - ] -} \ No newline at end of file + ] +} diff --git a/app/reporting-framework/json-reports/starting-art-aggregation-age-green.json b/app/reporting-framework/json-reports/starting-art-aggregation-age-green.json index 521fbe606..521dd023d 100755 --- a/app/reporting-framework/json-reports/starting-art-aggregation-age-green.json +++ b/app/reporting-framework/json-reports/starting-art-aggregation-age-green.json @@ -1,92 +1,87 @@ { - "name": "StartingARTAggregationAgeGreen", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ { - "name": "StartingARTSetBaseAgeGreen", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [ - { - "dataSet": "StartingARTSetBaseAgeGreen", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "started_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_art)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" + "name": "StartingARTAggregationAgeGreen", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "StartingARTSetBaseAgeGreen", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "StartingARTSetBaseAgeGreen", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "gender", - "age_range", - "join_location" - ], - "joinColumnParam": "joinColumnParam", - "disaggregationColumns": [] + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "started_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_art)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "gender", "age_range", "join_location"], + "joinColumnParam": "joinColumnParam", + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/starting-art-aggregation-age15.json b/app/reporting-framework/json-reports/starting-art-aggregation-age15.json index ab04b03e0..3191cca0a 100755 --- a/app/reporting-framework/json-reports/starting-art-aggregation-age15.json +++ b/app/reporting-framework/json-reports/starting-art-aggregation-age15.json @@ -1,92 +1,87 @@ { - "name": "StartingARTAggregationAge15", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ { - "name": "StartingARTSetBaseAge15", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [ - { - "dataSet": "StartingARTSetBaseAge15", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "started_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_art)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_id" - ], - "excludeParam": "excludeParam" + "name": "StartingARTAggregationAge15", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "StartingARTSetBaseAge15", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "StartingARTSetBaseAge15", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "gender", - "age_range", - "join_location" - ], - "joinColumnParam": "joinColumnParam", - "disaggregationColumns": [] + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "started_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_art)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "gender", "age_range", "join_location"], + "joinColumnParam": "joinColumnParam", + "disaggregationColumns": [] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/starting-art-base-age-green.json b/app/reporting-framework/json-reports/starting-art-base-age-green.json index 0eb10173d..2fd7053c2 100755 --- a/app/reporting-framework/json-reports/starting-art-base-age-green.json +++ b/app/reporting-framework/json-reports/starting-art-base-age-green.json @@ -1,158 +1,158 @@ { - "name": "StartingARTSetBaseAgeGreen", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.arv_first_regimen_location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hmsd.cur_arv_meds" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmsd.age < 1", - "value": "0_to_1" - }, - { - "condition": "hmsd.age between 1 and 9", - "value": "1_to_9" - }, - { - "condition": "hmsd.age between 10 and 14", - "value": "10_to_14" - }, - { - "condition": "hmsd.age between 15 and 19", - "value": "15_to_19" - }, - { - "condition": "hmsd.age between 20 and 24", - "value": "20_to_24" - }, - { - "condition": "else", - "value": "older_than_24" - } - ] - } - }, - { - "type": "simple_column", - "alias": "started_art", - "column": "started_art_this_month" - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "cur_regimen_arv_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "hmsd.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.arv_first_regimen_location_id in ?", - "parameterName": "locations" - } + "name": "StartingARTSetBaseAgeGreen", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.arv_first_regimen_location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hmsd.cur_arv_meds" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmsd.age < 1", + "value": "0_to_1" + }, + { + "condition": "hmsd.age between 1 and 9", + "value": "1_to_9" + }, + { + "condition": "hmsd.age between 10 and 14", + "value": "10_to_14" + }, + { + "condition": "hmsd.age between 15 and 19", + "value": "15_to_19" + }, + { + "condition": "hmsd.age between 20 and 24", + "value": "20_to_24" + }, + { + "condition": "else", + "value": "older_than_24" + } ] + } + }, + { + "type": "simple_column", + "alias": "started_art", + "column": "started_art_this_month" + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "cur_regimen_arv_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "hmsd.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.arv_first_regimen_location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/starting-art-base-age15.json b/app/reporting-framework/json-reports/starting-art-base-age15.json index 75181e415..fa70dc08d 100755 --- a/app/reporting-framework/json-reports/starting-art-base-age15.json +++ b/app/reporting-framework/json-reports/starting-art-base-age15.json @@ -1,146 +1,146 @@ { - "name": "StartingARTSetBaseAge15", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "hmsd" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = hmsd.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "birthdate", - "column": "hmsd.birthdate" - }, - { - "type": "simple_column", - "alias": "age", - "column": "hmsd.age" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "hmsd.person_id" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.arv_first_regimen_location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "hmsd.cur_arv_meds" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "age_range", - "expressionType": "case_statement", - "expressionOptions": { - "caseOptions": [ - { - "condition": "hmsd.age < 1", - "value": "0_to_1" - }, - { - "condition": "hmsd.age between 1 and 9", - "value": "below_15_years" - }, - { - "condition": "else", - "value": "older_than_15" - } - ] - } - }, - { - "type": "simple_column", - "alias": "started_art", - "column": "started_art_this_month" - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" - } - }, - { - "type": "derived_column", - "alias": "cur_regimen_arv_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" - } - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "hmsd.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "vl_1", - "column": "hmsd.vl_1" - }, - { - "type": "derived_column", - "alias": "vl_1_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" - } - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "endDate = ?", - "parameterName": "endDate" - }, - { - "filterType": "tableColumns", - "conditionExpression": "hmsd.arv_first_regimen_location_id in ?", - "parameterName": "locations" - } + "name": "StartingARTSetBaseAge15", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "hmsd" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = hmsd.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "birthdate", + "column": "hmsd.birthdate" + }, + { + "type": "simple_column", + "alias": "age", + "column": "hmsd.age" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "hmsd.person_id" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.arv_first_regimen_location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "hmsd.cur_arv_meds" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.enrollment_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "age_range", + "expressionType": "case_statement", + "expressionOptions": { + "caseOptions": [ + { + "condition": "hmsd.age < 1", + "value": "0_to_1" + }, + { + "condition": "hmsd.age between 1 and 9", + "value": "below_15_years" + }, + { + "condition": "else", + "value": "older_than_15" + } ] + } + }, + { + "type": "simple_column", + "alias": "started_art", + "column": "started_art_this_month" + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_first_regimen_start_date,'%d-%m-%Y')" + } + }, + { + "type": "derived_column", + "alias": "cur_regimen_arv_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.arv_start_date,'%d-%m-%Y')" + } + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "hmsd.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "vl_1", + "column": "hmsd.vl_1" + }, + { + "type": "derived_column", + "alias": "vl_1_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "date_format(hmsd.vl_1_date,'%d-%m-%Y')" + } } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "endDate = ?", + "parameterName": "endDate" + }, + { + "filterType": "tableColumns", + "conditionExpression": "hmsd.arv_first_regimen_location_id in ?", + "parameterName": "locations" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/starting-art-disaggregation-age-green.json b/app/reporting-framework/json-reports/starting-art-disaggregation-age-green.json index f21cd71f9..f60f885de 100755 --- a/app/reporting-framework/json-reports/starting-art-disaggregation-age-green.json +++ b/app/reporting-framework/json-reports/starting-art-disaggregation-age-green.json @@ -1,98 +1,87 @@ { - "name": "StartingARTDisaggregationAgeGreen", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - - { - "name": "StartingARTSetBaseAgeGreen", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "StartingARTSetBaseAgeGreen", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "started_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_art)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "age_range", - "location_id", - "gender" - ], - "excludeParam": "excludeParam" + "name": "StartingARTDisaggregationAgeGreen", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "StartingARTSetBaseAgeGreen", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "StartingARTSetBaseAgeGreen", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "join_location" - ], - "joinColumnParam": "joinColumnParam", - "disaggregationColumns": [ - "age_range", - "gender" - ] + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "started_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_art)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["age_range", "location_id", "gender"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "join_location"], + "joinColumnParam": "joinColumnParam", + "disaggregationColumns": ["age_range", "gender"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/starting-art-disaggregation-age-only-green.json b/app/reporting-framework/json-reports/starting-art-disaggregation-age-only-green.json index 01fd14109..15ad24ee4 100755 --- a/app/reporting-framework/json-reports/starting-art-disaggregation-age-only-green.json +++ b/app/reporting-framework/json-reports/starting-art-disaggregation-age-only-green.json @@ -1,97 +1,87 @@ { - "name": "StartingARTDisaggregationAgeOnlyGreen", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - - { - "name": "StartingARTSetBaseAgeGreen", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "StartingARTSetBaseAgeGreen", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "started_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_art)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "age_range", - "location_id" - ], - "excludeParam": "excludeParam" + "name": "StartingARTDisaggregationAgeOnlyGreen", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "StartingARTSetBaseAgeGreen", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "StartingARTSetBaseAgeGreen", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "join_location", - "gender" - ], - "joinColumnParam": "joinColumnParam", - "disaggregationColumns": [ - "age_range" - ] + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "started_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_art)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["age_range", "location_id"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "join_location", "gender"], + "joinColumnParam": "joinColumnParam", + "disaggregationColumns": ["age_range"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/starting-art-disaggregation-age15.json b/app/reporting-framework/json-reports/starting-art-disaggregation-age15.json index fbdc84281..78f75e6cb 100755 --- a/app/reporting-framework/json-reports/starting-art-disaggregation-age15.json +++ b/app/reporting-framework/json-reports/starting-art-disaggregation-age15.json @@ -1,98 +1,87 @@ { - "name": "StartingARTDisaggregationAge15", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ - - { - "name": "StartingARTSetBaseAge15", - "version": "1.0", - "type": "dataset_def" - } - ], - "sources": [ - { - "dataSet": "StartingARTSetBaseAge15", - "alias": "hmsd" - } - ], - "columns": [ - { - "type": "derived_column", - "alias": "join_location", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "1" - } - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "hmsd.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "hmsd.location" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "hmsd.gender" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "hmsd.location_id" - }, - { - "type": "simple_column", - "alias": "age_range", - "column": "hmsd.age_range" - }, - { - "type": "derived_column", - "alias": "started_art", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(hmsd.started_art)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "age_range", - "location_id", - "gender" - ], - "excludeParam": "excludeParam" + "name": "StartingARTDisaggregationAge15", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "StartingARTSetBaseAge15", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "StartingARTSetBaseAge15", + "alias": "hmsd" + } + ], + "columns": [ + { + "type": "derived_column", + "alias": "join_location", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "1" + } }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "join_location" - ], - "joinColumnParam": "joinColumnParam", - "disaggregationColumns": [ - "age_range", - "gender" - ] + { + "type": "simple_column", + "alias": "location_uuid", + "column": "hmsd.location_uuid" }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "simple_column", + "alias": "location", + "column": "hmsd.location" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "hmsd.gender" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "hmsd.location_id" + }, + { + "type": "simple_column", + "alias": "age_range", + "column": "hmsd.age_range" + }, + { + "type": "derived_column", + "alias": "started_art", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(hmsd.started_art)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["age_range", "location_id", "gender"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "join_location"], + "joinColumnParam": "joinColumnParam", + "disaggregationColumns": ["age_range", "gender"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/surge-daily-report-aggregate.json b/app/reporting-framework/json-reports/surge-daily-report-aggregate.json index 98a2f4ddc..dfcfd32d1 100644 --- a/app/reporting-framework/json-reports/surge-daily-report-aggregate.json +++ b/app/reporting-framework/json-reports/surge-daily-report-aggregate.json @@ -1,426 +1,419 @@ { - "name": "SurgeDailyReportAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ { - "name": "surgeDailyReport", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [ - { - "dataSet": "surgeDailyReport", - "alias": "srb" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "srb.location_uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "srb.location" - }, - { - "type": "derived_column", - "alias": "visit_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(visit_today)" - } - }, - { - "type": "derived_column", - "alias": "appointment_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(appointment_today)" - } - }, - { - "type": "derived_column", - "alias": "scheduled_visit_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(scheduled_visit_today)" - } - }, - { - "type": "derived_column", - "alias": "early_appointment_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(early_appointment_today)" - } - }, - { - "type": "derived_column", - "alias": "late_appointment_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(late_appointment_today)" - } - }, - { - "type": "derived_column", - "alias": "missed_appointment_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(missed_appointment_today)" - } - }, - { - "type": "derived_column", - "alias": "started_art_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(started_art_today)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(enrolled_today)" - } - }, - { - "type": "derived_column", - "alias": "art_revisit_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(art_revisit_today)" - } - }, - { - "type": "derived_column", - "alias": "transfer_in_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(transfer_in_today)" - } - }, - { - "type": "derived_column", - "alias": "transfer_out_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(transfer_out_today)" - } - }, - { - "type": "derived_column", - "alias": "tx2_appointment_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_appointment_today)" - } - }, - { - "type": "derived_column", - "alias": "tx2_visit_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_visit_today)" - } - }, - { - "type": "derived_column", - "alias": "tx2_appointment_honored", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_appointment_honored)" - } - }, - { - "type": "derived_column", - "alias": "tx2_appointment_missed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_appointment_missed)" - } - }, - { - "type": "derived_column", - "alias": "intervention_done_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(intervention_done_today)" - } - }, - { - "type": "derived_column", - "alias": "interventions", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(interventions)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_to_active_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_to_active_today)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_outcome_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_outcome_today)" - } - }, - - - - - - { - "type": "derived_column", - "alias": "dc_eligible_cumulative", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(dc_eligible_cumulative)" - } - }, - { - "type": "derived_column", - "alias": "scheduled_today_and_due_for_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(scheduled_today_and_due_for_vl)" - } - }, - { - "type": "derived_column", - "alias": "unscheduled_today_and_due_for_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(unscheduled_today_and_due_for_vl)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_today_has_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_today_has_vl_order)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_today_dont_have_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_today_dont_have_order)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_today_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_today_active)" - } - }, - { - "type": "derived_column", - "alias": "overdue_for_vl_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(overdue_for_vl_active)" - } - }, - { - "type": "derived_column", - "alias": "is_suppressed_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(is_suppressed_active)" - } - }, - { - "type": "derived_column", - "alias": "is_unsuppressed_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(is_unsuppressed_active)" - } - }, - { - "type": "derived_column", - "alias": "eligible_and_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_and_on_dc)" - } - }, - { - "type": "derived_column", - "alias": "eligible_not_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_not_on_dc)" - } - }, - { - "type": "derived_column", - "alias": "eligible_not_on_dc_and_appointment_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_not_on_dc_and_appointment_today)" - } - }, - { - "type": "derived_column", - "alias": "eligible_not_on_dc_and_unscheduled_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_not_on_dc_and_unscheduled_today)" - } - }, - { - "type": "derived_column", - "alias": "eligible_and_on_dc_and_appointment_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_and_on_dc_and_appointment_today)" - } - }, - { - "type": "derived_column", - "alias": "eligible_and_on_dc_and_unscheduled_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_and_on_dc_and_unscheduled_today)" - } - }, - { - "type": "derived_column", - "alias": "elligible_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(elligible_total)" - } - }, - { - "type": "derived_column", - "alias": "has_vl_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(has_vl_today)" - } - }, - { - "type": "derived_column", - "alias": "tx2_unscheduled_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_unscheduled_today)" - } - }, - { - "type": "derived_column", - "alias": "started_dc_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(started_dc_today)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_outcome_total_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_outcome_total_today)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_death_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_death_today)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_transfer_out_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_transfer_out_today)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_active_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_active_today)" - } - }, - { - "type": "derived_column", - "alias": "defaulters_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(defaulters_today)" - } - }, - { - "type": "derived_column", - "alias": "newly_ltfu_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(newly_ltfu_today)" - } - }, - { - "type": "derived_column", - "alias": "dead_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(dead_today)" - } - }, - { - "type": "derived_column", - "alias": "on_dc_today", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(on_dc_today)" - } - } - - + "name": "SurgeDailyReportAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "surgeDailyReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "surgeDailyReport", + "alias": "srb" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "srb.location_uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "srb.location" + }, + { + "type": "derived_column", + "alias": "visit_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(visit_today)" + } + }, + { + "type": "derived_column", + "alias": "appointment_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(appointment_today)" + } + }, + { + "type": "derived_column", + "alias": "scheduled_visit_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(scheduled_visit_today)" + } + }, + { + "type": "derived_column", + "alias": "early_appointment_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(early_appointment_today)" + } + }, + { + "type": "derived_column", + "alias": "late_appointment_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(late_appointment_today)" + } + }, + { + "type": "derived_column", + "alias": "missed_appointment_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(missed_appointment_today)" + } + }, + { + "type": "derived_column", + "alias": "started_art_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(started_art_today)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(enrolled_today)" + } + }, + { + "type": "derived_column", + "alias": "art_revisit_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(art_revisit_today)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(transfer_in_today)" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(transfer_out_today)" + } + }, + { + "type": "derived_column", + "alias": "tx2_appointment_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_appointment_today)" + } + }, + { + "type": "derived_column", + "alias": "tx2_visit_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_visit_today)" + } + }, + { + "type": "derived_column", + "alias": "tx2_appointment_honored", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_appointment_honored)" + } + }, + { + "type": "derived_column", + "alias": "tx2_appointment_missed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_appointment_missed)" + } + }, + { + "type": "derived_column", + "alias": "intervention_done_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(intervention_done_today)" + } + }, + { + "type": "derived_column", + "alias": "interventions", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(interventions)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_to_active_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_to_active_today)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_outcome_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_outcome_today)" + } + }, - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_uuid" - ], - "excludeParam": "excludeParam" - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + { + "type": "derived_column", + "alias": "dc_eligible_cumulative", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(dc_eligible_cumulative)" + } + }, + { + "type": "derived_column", + "alias": "scheduled_today_and_due_for_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(scheduled_today_and_due_for_vl)" + } + }, + { + "type": "derived_column", + "alias": "unscheduled_today_and_due_for_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(unscheduled_today_and_due_for_vl)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_today_has_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_today_has_vl_order)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_today_dont_have_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_today_dont_have_order)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_today_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_today_active)" + } + }, + { + "type": "derived_column", + "alias": "overdue_for_vl_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(overdue_for_vl_active)" + } + }, + { + "type": "derived_column", + "alias": "is_suppressed_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(is_suppressed_active)" + } + }, + { + "type": "derived_column", + "alias": "is_unsuppressed_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(is_unsuppressed_active)" + } + }, + { + "type": "derived_column", + "alias": "eligible_and_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_and_on_dc)" + } + }, + { + "type": "derived_column", + "alias": "eligible_not_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_not_on_dc)" + } + }, + { + "type": "derived_column", + "alias": "eligible_not_on_dc_and_appointment_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_not_on_dc_and_appointment_today)" + } + }, + { + "type": "derived_column", + "alias": "eligible_not_on_dc_and_unscheduled_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_not_on_dc_and_unscheduled_today)" + } + }, + { + "type": "derived_column", + "alias": "eligible_and_on_dc_and_appointment_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_and_on_dc_and_appointment_today)" + } + }, + { + "type": "derived_column", + "alias": "eligible_and_on_dc_and_unscheduled_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_and_on_dc_and_unscheduled_today)" + } + }, + { + "type": "derived_column", + "alias": "elligible_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(elligible_total)" + } + }, + { + "type": "derived_column", + "alias": "has_vl_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(has_vl_today)" + } + }, + { + "type": "derived_column", + "alias": "tx2_unscheduled_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_unscheduled_today)" + } + }, + { + "type": "derived_column", + "alias": "started_dc_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(started_dc_today)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_outcome_total_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_outcome_total_today)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_death_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_death_today)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_transfer_out_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_transfer_out_today)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_active_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_active_today)" + } + }, + { + "type": "derived_column", + "alias": "defaulters_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(defaulters_today)" + } + }, + { + "type": "derived_column", + "alias": "newly_ltfu_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(newly_ltfu_today)" + } + }, + { + "type": "derived_column", + "alias": "dead_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(dead_today)" + } + }, + { + "type": "derived_column", + "alias": "on_dc_today", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(on_dc_today)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_uuid"], + "excludeParam": "excludeParam" + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/surge-daily-report-base.json b/app/reporting-framework/json-reports/surge-daily-report-base.json index 12badd3a1..155e8c12d 100644 --- a/app/reporting-framework/json-reports/surge-daily-report-base.json +++ b/app/reporting-framework/json-reports/surge-daily-report-base.json @@ -1,659 +1,658 @@ { - "name": "surgeDailyReport", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "etl.surge_daily_report_dataset", - "alias": "sdr" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = sdr.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "_date", - "column": "sdr._date" - }, - { - "type": "simple_column", - "alias": "person_id", - "column": "sdr.person_id" - }, - { - "type": "simple_column", - "alias": "person_uuid", - "column": "sdr.person_uuid" - }, - { - "type": "simple_column", - "alias": "death_date", - "column": "sdr.death_date" - }, - { - "type": "simple_column", - "alias": "encounter_datetime", - "column": "sdr.encounter_datetime" - }, - { - "type": "simple_column", - "alias": "prev_clinical_rtc_date_hiv", - "column": "sdr.prev_clinical_rtc_date_hiv" - }, - { - "type": "simple_column", - "alias": "prev_rtc_date", - "column": "sdr.prev_rtc_date" - }, - { - "type": "simple_column", - "alias": "rtc_date", - "column": "sdr.rtc_date" - }, - + "name": "surgeDailyReport", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "etl.surge_daily_report_dataset", + "alias": "sdr" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = sdr.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "_date", + "column": "sdr._date" + }, + { + "type": "simple_column", + "alias": "person_id", + "column": "sdr.person_id" + }, + { + "type": "simple_column", + "alias": "person_uuid", + "column": "sdr.person_uuid" + }, + { + "type": "simple_column", + "alias": "death_date", + "column": "sdr.death_date" + }, + { + "type": "simple_column", + "alias": "encounter_datetime", + "column": "sdr.encounter_datetime" + }, + { + "type": "simple_column", + "alias": "prev_clinical_rtc_date_hiv", + "column": "sdr.prev_clinical_rtc_date_hiv" + }, + { + "type": "simple_column", + "alias": "prev_rtc_date", + "column": "sdr.prev_rtc_date" + }, + { + "type": "simple_column", + "alias": "rtc_date", + "column": "sdr.rtc_date" + }, - { - "type": "simple_column", - "alias": "visit_today", - "column": "sdr.visit_today" - }, - { - "type": "simple_column", - "alias": "appointment_today", - "column": "sdr.appointment_today" - }, - { - "type": "simple_column", - "alias": "scheduled_visit_today", - "column": "sdr.scheduled_visit_today" - }, - { - "type": "simple_column", - "alias": "early_appointment_today", - "column": "sdr.early_appointment_today" - }, - { - "type": "simple_column", - "alias": "late_appointment_today", - "column": "sdr.late_appointment_today" - }, - { - "type": "simple_column", - "alias": "missed_appointment_today", - "column": "sdr.missed_appointment_today" - }, - { - "type": "simple_column", - "alias": "started_art_today", - "column": "sdr.started_art_today" - }, - { - "type": "simple_column", - "alias": "enrolled_today", - "column": "sdr.enrolled_today" - }, - { - "type": "simple_column", - "alias": "art_revisit_today", - "column": "sdr.art_revisit_today" - }, - { - "type": "simple_column", - "alias": "transfer_in_today", - "column": "sdr.transfer_in_today" - }, - { - "type": "simple_column", - "alias": "transfer_out_today", - "column": "sdr.transfer_out_today" - }, - { - "type": "simple_column", - "alias": "tx2_appointment_today", - "column": "sdr.tx2_appointment_today" - }, - { - "type": "simple_column", - "alias": "tx2_visit_today", - "column": "sdr.tx2_visit_today" - }, - { - "type": "simple_column", - "alias": "tx2_appointment_honored", - "column": "sdr.tx2_appointment_honored" - }, - { - "type": "simple_column", - "alias": "tx2_appointment_missed", - "column": "sdr.tx2_appointment_missed" - }, - { - "type": "simple_column", - "alias": "is_pregnant", - "column": "sdr.is_pregnant" - }, - { - "type": "simple_column", - "alias": "intervention_done_today", - "column": "sdr.intervention_done_today" - }, - { - "type": "simple_column", - "alias": "interventions", - "column": "sdr.interventions" - }, - { - "type": "simple_column", - "alias": "ltfu_to_active_today", - "column": "sdr.ltfu_to_active_today" - }, - { - "type": "simple_column", - "alias": "ltfu_outcome_today", - "column": "sdr.ltfu_outcome_today" - }, - { - "type": "simple_column", - "alias": "dc_eligible_cumulative", - "column": "sdr.dc_eligible_cumulative" - }, - { - "type": "simple_column", - "alias": "scheduled_today_and_due_for_vl", - "column": "sdr.scheduled_today_and_due_for_vl" - }, - { - "type": "simple_column", - "alias": "unscheduled_today_and_due_for_vl", - "column": "sdr.unscheduled_today_and_due_for_vl" - }, - { - "type": "simple_column", - "alias": "due_for_vl_today_has_vl_order", - "column": "sdr.due_for_vl_today_has_vl_order" - }, - { - "type": "simple_column", - "alias": "due_for_vl_today_dont_have_order", - "column": "sdr.due_for_vl_today_dont_have_order" - }, - { - "type": "simple_column", - "alias": "due_for_vl_today_active", - "column": "sdr.due_for_vl_today_active" - }, - { - "type": "simple_column", - "alias": "overdue_for_vl_active", - "column": "sdr.overdue_for_vl_active" - }, - { - "type": "simple_column", - "alias": "is_suppressed_active", - "column": "sdr.is_suppressed_active" - }, - { - "type": "simple_column", - "alias": "is_unsuppressed_active", - "column": "sdr.is_unsuppressed_active" - }, - { - "type": "simple_column", - "alias": "clinical_visit_num", - "column": "sdr.clinical_visit_num" - }, - { - "type": "simple_column", - "alias": "days_since_rtc_date", - "column": "sdr.days_since_rtc_date" - }, - { - "type": "simple_column", - "alias": "status", - "column": "sdr.status" - }, - { - "type": "simple_column", - "alias": "cur_arv_adherence", - "column": "sdr.cur_arv_adherence" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_location_id", - "column": "sdr.arv_first_regimen_location_id" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_names", - "column": "sdr.arv_first_regimen_names" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_start_date", - "column": "sdr.arv_first_regimen_start_date" - }, - { - "type": "simple_column", - "alias": "days_since_starting_arvs", - "column": "sdr.days_since_starting_arvs" - }, - { - "type": "simple_column", - "alias": "enrollment_date", - "column": "sdr.enrollment_date" - }, + { + "type": "simple_column", + "alias": "visit_today", + "column": "sdr.visit_today" + }, + { + "type": "simple_column", + "alias": "appointment_today", + "column": "sdr.appointment_today" + }, + { + "type": "simple_column", + "alias": "scheduled_visit_today", + "column": "sdr.scheduled_visit_today" + }, + { + "type": "simple_column", + "alias": "early_appointment_today", + "column": "sdr.early_appointment_today" + }, + { + "type": "simple_column", + "alias": "late_appointment_today", + "column": "sdr.late_appointment_today" + }, + { + "type": "simple_column", + "alias": "missed_appointment_today", + "column": "sdr.missed_appointment_today" + }, + { + "type": "simple_column", + "alias": "started_art_today", + "column": "sdr.started_art_today" + }, + { + "type": "simple_column", + "alias": "enrolled_today", + "column": "sdr.enrolled_today" + }, + { + "type": "simple_column", + "alias": "art_revisit_today", + "column": "sdr.art_revisit_today" + }, + { + "type": "simple_column", + "alias": "transfer_in_today", + "column": "sdr.transfer_in_today" + }, + { + "type": "simple_column", + "alias": "transfer_out_today", + "column": "sdr.transfer_out_today" + }, + { + "type": "simple_column", + "alias": "tx2_appointment_today", + "column": "sdr.tx2_appointment_today" + }, + { + "type": "simple_column", + "alias": "tx2_visit_today", + "column": "sdr.tx2_visit_today" + }, + { + "type": "simple_column", + "alias": "tx2_appointment_honored", + "column": "sdr.tx2_appointment_honored" + }, + { + "type": "simple_column", + "alias": "tx2_appointment_missed", + "column": "sdr.tx2_appointment_missed" + }, + { + "type": "simple_column", + "alias": "is_pregnant", + "column": "sdr.is_pregnant" + }, + { + "type": "simple_column", + "alias": "intervention_done_today", + "column": "sdr.intervention_done_today" + }, + { + "type": "simple_column", + "alias": "interventions", + "column": "sdr.interventions" + }, + { + "type": "simple_column", + "alias": "ltfu_to_active_today", + "column": "sdr.ltfu_to_active_today" + }, + { + "type": "simple_column", + "alias": "ltfu_outcome_today", + "column": "sdr.ltfu_outcome_today" + }, + { + "type": "simple_column", + "alias": "dc_eligible_cumulative", + "column": "sdr.dc_eligible_cumulative" + }, + { + "type": "simple_column", + "alias": "scheduled_today_and_due_for_vl", + "column": "sdr.scheduled_today_and_due_for_vl" + }, + { + "type": "simple_column", + "alias": "unscheduled_today_and_due_for_vl", + "column": "sdr.unscheduled_today_and_due_for_vl" + }, + { + "type": "simple_column", + "alias": "due_for_vl_today_has_vl_order", + "column": "sdr.due_for_vl_today_has_vl_order" + }, + { + "type": "simple_column", + "alias": "due_for_vl_today_dont_have_order", + "column": "sdr.due_for_vl_today_dont_have_order" + }, + { + "type": "simple_column", + "alias": "due_for_vl_today_active", + "column": "sdr.due_for_vl_today_active" + }, + { + "type": "simple_column", + "alias": "overdue_for_vl_active", + "column": "sdr.overdue_for_vl_active" + }, + { + "type": "simple_column", + "alias": "is_suppressed_active", + "column": "sdr.is_suppressed_active" + }, + { + "type": "simple_column", + "alias": "is_unsuppressed_active", + "column": "sdr.is_unsuppressed_active" + }, + { + "type": "simple_column", + "alias": "clinical_visit_num", + "column": "sdr.clinical_visit_num" + }, + { + "type": "simple_column", + "alias": "days_since_rtc_date", + "column": "sdr.days_since_rtc_date" + }, + { + "type": "simple_column", + "alias": "status", + "column": "sdr.status" + }, + { + "type": "simple_column", + "alias": "cur_arv_adherence", + "column": "sdr.cur_arv_adherence" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_location_id", + "column": "sdr.arv_first_regimen_location_id" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_names", + "column": "sdr.arv_first_regimen_names" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_start_date", + "column": "sdr.arv_first_regimen_start_date" + }, + { + "type": "simple_column", + "alias": "days_since_starting_arvs", + "column": "sdr.days_since_starting_arvs" + }, + { + "type": "simple_column", + "alias": "enrollment_date", + "column": "sdr.enrollment_date" + }, - { - "type": "simple_column", - "alias": "arv_start_date", - "column": "sdr.arv_start_date" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds_names", - "column": "sdr.cur_arv_meds_names" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds_strict", - "column": "sdr.cur_arv_meds_strict" - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "sdr.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "cur_arv_line_strict", - "column": "sdr.cur_arv_line_strict" - }, - { - "type": "simple_column", - "alias": "cur_arv_line_reported", - "column": "sdr.cur_arv_line_reported" - }, - { - "type": "simple_column", - "alias": "transfer_in_location_id", - "column": "sdr.transfer_in_location_id" - }, - { - "type": "simple_column", - "alias": "transfer_in_date", - "column": "sdr.transfer_in_date" - }, - { - "type": "simple_column", - "alias": "transfer_out_location_id", - "column": "sdr.transfer_out_location_id" - }, - { - "type": "simple_column", - "alias": "transfer_out_date", - "column": "sdr.transfer_out_date" - }, - { - "type": "simple_column", - "alias": "tb_tx_start_date", - "column": "sdr.tb_tx_start_date" - }, - { - "type": "simple_column", - "alias": "months_since_tb_tx_start_date", - "column": "sdr.months_since_tb_tx_start_date" - }, - { - "type": "simple_column", - "alias": "prev_status", - "column": "sdr.prev_status" - }, - { - "type": "simple_column", - "alias": "cur_status", - "column": "sdr.cur_status" - }, + { + "type": "simple_column", + "alias": "arv_start_date", + "column": "sdr.arv_start_date" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds_names", + "column": "sdr.cur_arv_meds_names" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds_strict", + "column": "sdr.cur_arv_meds_strict" + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "sdr.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "cur_arv_line_strict", + "column": "sdr.cur_arv_line_strict" + }, + { + "type": "simple_column", + "alias": "cur_arv_line_reported", + "column": "sdr.cur_arv_line_reported" + }, + { + "type": "simple_column", + "alias": "transfer_in_location_id", + "column": "sdr.transfer_in_location_id" + }, + { + "type": "simple_column", + "alias": "transfer_in_date", + "column": "sdr.transfer_in_date" + }, + { + "type": "simple_column", + "alias": "transfer_out_location_id", + "column": "sdr.transfer_out_location_id" + }, + { + "type": "simple_column", + "alias": "transfer_out_date", + "column": "sdr.transfer_out_date" + }, + { + "type": "simple_column", + "alias": "tb_tx_start_date", + "column": "sdr.tb_tx_start_date" + }, + { + "type": "simple_column", + "alias": "months_since_tb_tx_start_date", + "column": "sdr.months_since_tb_tx_start_date" + }, + { + "type": "simple_column", + "alias": "prev_status", + "column": "sdr.prev_status" + }, + { + "type": "simple_column", + "alias": "cur_status", + "column": "sdr.cur_status" + }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "tx2_appointment_today", - "column": "sdr.tx2_appointment_today" - }, - { - "type": "simple_column", - "alias": "tx2_visit_today", - "column": "sdr.tx2_visit_today" - }, - { - "type": "simple_column", - "alias": "tx2_appointment_honored", - "column": "sdr.tx2_appointment_honored" - }, - { - "type": "simple_column", - "alias": "tx2_appointment_missed", - "column": "sdr.tx2_appointment_missed" - }, - { - "type": "simple_column", - "alias": "is_pregnant", - "column": "sdr.is_pregnant" - }, - { - "type": "simple_column", - "alias": "intervention_done_today", - "column": "sdr.intervention_done_today" - }, - { - "type": "simple_column", - "alias": "interventions", - "column": "sdr.interventions" - }, - { - "type": "simple_column", - "alias": "ltfu_to_active_today", - "column": "sdr.ltfu_to_active_today" - }, - { - "type": "simple_column", - "alias": "ltfu_outcome_today", - "column": "sdr.ltfu_outcome_today" - }, - { - "type": "simple_column", - "alias": "dc_eligible_cumulative", - "column": "sdr.dc_eligible_cumulative" - }, - { - "type": "simple_column", - "alias": "scheduled_today_and_due_for_vl", - "column": "sdr.scheduled_today_and_due_for_vl" - }, - { - "type": "simple_column", - "alias": "unscheduled_today_and_due_for_vl", - "column": "sdr.unscheduled_today_and_due_for_vl" - }, - { - "type": "simple_column", - "alias": "due_for_vl_today_has_vl_order", - "column": "sdr.due_for_vl_today_has_vl_order" - }, - { - "type": "simple_column", - "alias": "due_for_vl_today_dont_have_order", - "column": "sdr.due_for_vl_today_dont_have_order" - }, - { - "type": "simple_column", - "alias": "due_for_vl_today_active", - "column": "sdr.due_for_vl_today_active" - }, - { - "type": "simple_column", - "alias": "overdue_for_vl_active", - "column": "sdr.overdue_for_vl_active" - }, - { - "type": "simple_column", - "alias": "is_suppressed_active", - "column": "sdr.is_suppressed_active" - }, - { - "type": "simple_column", - "alias": "is_unsuppressed_active", - "column": "sdr.is_unsuppressed_active" - }, - { - "type": "simple_column", - "alias": "clinical_visit_num", - "column": "sdr.clinical_visit_num" - }, - { - "type": "simple_column", - "alias": "days_since_rtc_date", - "column": "sdr.days_since_rtc_date" - }, - { - "type": "simple_column", - "alias": "status", - "column": "sdr.status" - }, - { - "type": "simple_column", - "alias": "cur_arv_adherence", - "column": "sdr.cur_arv_adherence" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_location_id", - "column": "sdr.arv_first_regimen_location_id" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_names", - "column": "sdr.arv_first_regimen_names" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_start_date", - "column": "sdr.arv_first_regimen_start_date" - }, - { - "type": "simple_column", - "alias": "days_since_starting_arvs", - "column": "sdr.days_since_starting_arvs" - }, - { - "type": "simple_column", - "alias": "enrollment_date", - "column": "sdr.enrollment_date" - }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "tx2_appointment_today", + "column": "sdr.tx2_appointment_today" + }, + { + "type": "simple_column", + "alias": "tx2_visit_today", + "column": "sdr.tx2_visit_today" + }, + { + "type": "simple_column", + "alias": "tx2_appointment_honored", + "column": "sdr.tx2_appointment_honored" + }, + { + "type": "simple_column", + "alias": "tx2_appointment_missed", + "column": "sdr.tx2_appointment_missed" + }, + { + "type": "simple_column", + "alias": "is_pregnant", + "column": "sdr.is_pregnant" + }, + { + "type": "simple_column", + "alias": "intervention_done_today", + "column": "sdr.intervention_done_today" + }, + { + "type": "simple_column", + "alias": "interventions", + "column": "sdr.interventions" + }, + { + "type": "simple_column", + "alias": "ltfu_to_active_today", + "column": "sdr.ltfu_to_active_today" + }, + { + "type": "simple_column", + "alias": "ltfu_outcome_today", + "column": "sdr.ltfu_outcome_today" + }, + { + "type": "simple_column", + "alias": "dc_eligible_cumulative", + "column": "sdr.dc_eligible_cumulative" + }, + { + "type": "simple_column", + "alias": "scheduled_today_and_due_for_vl", + "column": "sdr.scheduled_today_and_due_for_vl" + }, + { + "type": "simple_column", + "alias": "unscheduled_today_and_due_for_vl", + "column": "sdr.unscheduled_today_and_due_for_vl" + }, + { + "type": "simple_column", + "alias": "due_for_vl_today_has_vl_order", + "column": "sdr.due_for_vl_today_has_vl_order" + }, + { + "type": "simple_column", + "alias": "due_for_vl_today_dont_have_order", + "column": "sdr.due_for_vl_today_dont_have_order" + }, + { + "type": "simple_column", + "alias": "due_for_vl_today_active", + "column": "sdr.due_for_vl_today_active" + }, + { + "type": "simple_column", + "alias": "overdue_for_vl_active", + "column": "sdr.overdue_for_vl_active" + }, + { + "type": "simple_column", + "alias": "is_suppressed_active", + "column": "sdr.is_suppressed_active" + }, + { + "type": "simple_column", + "alias": "is_unsuppressed_active", + "column": "sdr.is_unsuppressed_active" + }, + { + "type": "simple_column", + "alias": "clinical_visit_num", + "column": "sdr.clinical_visit_num" + }, + { + "type": "simple_column", + "alias": "days_since_rtc_date", + "column": "sdr.days_since_rtc_date" + }, + { + "type": "simple_column", + "alias": "status", + "column": "sdr.status" + }, + { + "type": "simple_column", + "alias": "cur_arv_adherence", + "column": "sdr.cur_arv_adherence" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_location_id", + "column": "sdr.arv_first_regimen_location_id" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_names", + "column": "sdr.arv_first_regimen_names" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_start_date", + "column": "sdr.arv_first_regimen_start_date" + }, + { + "type": "simple_column", + "alias": "days_since_starting_arvs", + "column": "sdr.days_since_starting_arvs" + }, + { + "type": "simple_column", + "alias": "enrollment_date", + "column": "sdr.enrollment_date" + }, - { - "type": "simple_column", - "alias": "arv_start_date", - "column": "sdr.arv_start_date" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds_names", - "column": "sdr.cur_arv_meds_names" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds_strict", - "column": "sdr.cur_arv_meds_strict" - }, - { - "type": "simple_column", - "alias": "cur_arv_line", - "column": "sdr.cur_arv_line" - }, - { - "type": "simple_column", - "alias": "cur_arv_line_strict", - "column": "sdr.cur_arv_line_strict" - }, - { - "type": "simple_column", - "alias": "cur_arv_line_reported", - "column": "sdr.cur_arv_line_reported" - }, - { - "type": "simple_column", - "alias": "transfer_in_location_id", - "column": "sdr.transfer_in_location_id" - }, - { - "type": "simple_column", - "alias": "transfer_in_date", - "column": "sdr.transfer_in_date" - }, - { - "type": "simple_column", - "alias": "transfer_out_location_id", - "column": "sdr.transfer_out_location_id" - }, - { - "type": "simple_column", - "alias": "transfer_out_date", - "column": "sdr.transfer_out_date" - }, - { - "type": "simple_column", - "alias": "tb_tx_start_date", - "column": "sdr.tb_tx_start_date" - }, - { - "type": "simple_column", - "alias": "months_since_tb_tx_start_date", - "column": "sdr.months_since_tb_tx_start_date" - }, - { - "type": "simple_column", - "alias": "prev_status", - "column": "sdr.prev_status" - }, - { - "type": "simple_column", - "alias": "cur_status", - "column": "sdr.cur_status" - }, + { + "type": "simple_column", + "alias": "arv_start_date", + "column": "sdr.arv_start_date" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds_names", + "column": "sdr.cur_arv_meds_names" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds_strict", + "column": "sdr.cur_arv_meds_strict" + }, + { + "type": "simple_column", + "alias": "cur_arv_line", + "column": "sdr.cur_arv_line" + }, + { + "type": "simple_column", + "alias": "cur_arv_line_strict", + "column": "sdr.cur_arv_line_strict" + }, + { + "type": "simple_column", + "alias": "cur_arv_line_reported", + "column": "sdr.cur_arv_line_reported" + }, + { + "type": "simple_column", + "alias": "transfer_in_location_id", + "column": "sdr.transfer_in_location_id" + }, + { + "type": "simple_column", + "alias": "transfer_in_date", + "column": "sdr.transfer_in_date" + }, + { + "type": "simple_column", + "alias": "transfer_out_location_id", + "column": "sdr.transfer_out_location_id" + }, + { + "type": "simple_column", + "alias": "transfer_out_date", + "column": "sdr.transfer_out_date" + }, + { + "type": "simple_column", + "alias": "tb_tx_start_date", + "column": "sdr.tb_tx_start_date" + }, + { + "type": "simple_column", + "alias": "months_since_tb_tx_start_date", + "column": "sdr.months_since_tb_tx_start_date" + }, + { + "type": "simple_column", + "alias": "prev_status", + "column": "sdr.prev_status" + }, + { + "type": "simple_column", + "alias": "cur_status", + "column": "sdr.cur_status" + }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - }, - { - "type": "simple_column", - "alias": "eligible_and_on_dc", - "column": "sdr.eligible_and_on_dc" - }, - { - "type": "simple_column", - "alias": "eligible_not_on_dc", - "column": "sdr.eligible_not_on_dc" - }, - { - "type": "simple_column", - "alias": "eligible_not_on_dc_and_appointment_today", - "column": "sdr.eligible_not_on_dc_and_appointment_today" - }, - { - "type": "simple_column", - "alias": "eligible_not_on_dc_and_unscheduled_today", - "column": "sdr.eligible_not_on_dc_and_unscheduled_today" - }, - { - "type": "simple_column", - "alias": "eligible_and_on_dc_and_appointment_today", - "column": "sdr.eligible_and_on_dc_and_appointment_today" - }, - { - "type": "simple_column", - "alias": "eligible_and_on_dc_and_unscheduled_today", - "column": "sdr.eligible_and_on_dc_and_unscheduled_today" - }, - { - "type": "simple_column", - "alias": "elligible_total", - "column": "sdr.elligible_total" - }, - { - "type": "simple_column", - "alias": "has_vl_today", - "column": "sdr.has_vl_today" - }, - { - "type": "simple_column", - "alias": "tx2_unscheduled_today", - "column": "sdr.tx2_unscheduled_today" - }, - { - "type": "simple_column", - "alias": "started_dc_today", - "column": "sdr.started_dc_today" - }, - { - "type": "simple_column", - "alias": "ltfu_outcome_total_today", - "column": "sdr.ltfu_outcome_total_today" - }, - { - "type": "simple_column", - "alias": "ltfu_death_today", - "column": "sdr.ltfu_death_today" - } , - { - "type": "simple_column", - "alias": "ltfu_transfer_out_today", - "column": "sdr.ltfu_transfer_out_today" - }, - { - "type": "simple_column", - "alias": "ltfu_active_today", - "column": "sdr.ltfu_active_today" - }, - { - "type": "simple_column", - "alias": "defaulters_today", - "column": "sdr.defaulters_today" - }, - { - "type": "simple_column", - "alias": "newly_ltfu_today", - "column": "sdr.newly_ltfu_today" - }, - { - "type": "simple_column", - "alias": "dead_today", - "column": "sdr.dead_today" - }, - { - "type": "simple_column", - "alias": "on_dc_today", - "column": "sdr.on_dc_today" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "_date = ? ", - "parameterName": "_date" - }, - { - "filterType": "tableColumns", - "conditionExpression": "l.uuid in ?", - "parameterName": "locationUuids" - } - ] + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" + }, + { + "type": "simple_column", + "alias": "eligible_and_on_dc", + "column": "sdr.eligible_and_on_dc" + }, + { + "type": "simple_column", + "alias": "eligible_not_on_dc", + "column": "sdr.eligible_not_on_dc" + }, + { + "type": "simple_column", + "alias": "eligible_not_on_dc_and_appointment_today", + "column": "sdr.eligible_not_on_dc_and_appointment_today" + }, + { + "type": "simple_column", + "alias": "eligible_not_on_dc_and_unscheduled_today", + "column": "sdr.eligible_not_on_dc_and_unscheduled_today" + }, + { + "type": "simple_column", + "alias": "eligible_and_on_dc_and_appointment_today", + "column": "sdr.eligible_and_on_dc_and_appointment_today" + }, + { + "type": "simple_column", + "alias": "eligible_and_on_dc_and_unscheduled_today", + "column": "sdr.eligible_and_on_dc_and_unscheduled_today" + }, + { + "type": "simple_column", + "alias": "elligible_total", + "column": "sdr.elligible_total" + }, + { + "type": "simple_column", + "alias": "has_vl_today", + "column": "sdr.has_vl_today" + }, + { + "type": "simple_column", + "alias": "tx2_unscheduled_today", + "column": "sdr.tx2_unscheduled_today" + }, + { + "type": "simple_column", + "alias": "started_dc_today", + "column": "sdr.started_dc_today" + }, + { + "type": "simple_column", + "alias": "ltfu_outcome_total_today", + "column": "sdr.ltfu_outcome_total_today" + }, + { + "type": "simple_column", + "alias": "ltfu_death_today", + "column": "sdr.ltfu_death_today" + }, + { + "type": "simple_column", + "alias": "ltfu_transfer_out_today", + "column": "sdr.ltfu_transfer_out_today" + }, + { + "type": "simple_column", + "alias": "ltfu_active_today", + "column": "sdr.ltfu_active_today" + }, + { + "type": "simple_column", + "alias": "defaulters_today", + "column": "sdr.defaulters_today" + }, + { + "type": "simple_column", + "alias": "newly_ltfu_today", + "column": "sdr.newly_ltfu_today" + }, + { + "type": "simple_column", + "alias": "dead_today", + "column": "sdr.dead_today" + }, + { + "type": "simple_column", + "alias": "on_dc_today", + "column": "sdr.on_dc_today" } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "_date = ? ", + "parameterName": "_date" + }, + { + "filterType": "tableColumns", + "conditionExpression": "l.uuid in ?", + "parameterName": "locationUuids" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/surge-report-aggregate.json b/app/reporting-framework/json-reports/surge-report-aggregate.json index f0f6db7b1..b0824815e 100644 --- a/app/reporting-framework/json-reports/surge-report-aggregate.json +++ b/app/reporting-framework/json-reports/surge-report-aggregate.json @@ -1,766 +1,763 @@ { - "name": "SurgeReportAggregate", - "version": "1.0", - "tag": "", - "description": "", - "uses": [ { - "name": "surgeReport", - "version": "1.0", - "type": "dataset_def" - }], - "sources": [ - { - "dataSet": "surgeReport", - "alias": "srb" - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "location_uuid", - "column": "srb.location_uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "srb.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "srb.location" - }, - { - "type": "derived_column", - "alias": "scheduled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(scheduled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "visit_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(visit_this_week)" - } - }, - { - "type": "derived_column", - "alias": "on_schedule", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(on_schedule)" - } - }, - { - "type": "derived_column", - "alias": "unscheduled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(unscheduled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "early_appointment_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(early_appointment_this_week)" - } - }, - { - "type": "derived_column", - "alias": "late_appointment_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(late_appointment_this_week)" - } - }, - { - "type": "derived_column", - "alias": "missed_appointment_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(missed_appointment_this_week)" - } - }, - { - "type": "derived_column", - "alias": "ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu)" - } - }, - { - "type": "derived_column", - "alias": "defaulted", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(defaulted)" - } - }, - { - "type": "derived_column", - "alias": "missed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(missed)" - } - }, - { - "type": "derived_column", - "alias": "started_art_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(started_art_this_week)" - } - }, - { - "type": "derived_column", - "alias": "active_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(active_on_dc)" - } - }, - { - "type": "derived_column", - "alias": "started_dc_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(started_dc_this_week)" - } - }, - { - "type": "derived_column", - "alias": "dc_eligible_cumulative", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(dc_eligible_cumulative)" - } - }, - { - "type": "derived_column", - "alias": "dc_eligible_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(dc_eligible_this_week)" - } - }, - { - "type": "derived_column", - "alias": "dc_eligible_and_scheduled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(dc_eligible_and_scheduled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "new_prep_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(new_prep_this_week)" - } - }, - { - "type": "derived_column", - "alias": "cur_prep_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(cur_prep_this_week)" - } - }, - { - "type": "derived_column", - "alias": "enrolled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(enrolled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "has_vl_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(has_vl_this_week)" - } - }, - { - "type": "derived_column", - "alias": "is_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(is_suppressed)" - } - }, - { - "type": "derived_column", - "alias": "is_un_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(is_un_suppressed)" - } - }, - { - "type": "derived_column", - "alias": "tx2_scheduled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_scheduled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "tx2_scheduled_honored", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_scheduled_honored)" - } - }, - { - "type": "derived_column", - "alias": "active_in_care_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(active_in_care_this_week)" - } - }, - { - "type": "derived_column", - "alias": "is_pre_art_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(is_pre_art_this_week)" - } - }, - { - "type": "derived_column", - "alias": "art_revisit_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(art_revisit_this_week)" - } - }, - { - "type": "derived_column", - "alias": "on_art_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(on_art_this_week)" - } - }, - { - "type": "derived_column", - "alias": "transfer_in_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(transfer_in_this_week)" - } - }, - { - "type": "derived_column", - "alias": "transfer_out_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(transfer_out_this_week)" - } - }, - { - "type": "derived_column", - "alias": "scheduled_this_week_and_due_for_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(scheduled_this_week_and_due_for_vl)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_has_vl_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_has_vl_order)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_dont_have_order", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_dont_have_order)" - } - }, - { - "type": "derived_column", - "alias": "missed_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(missed_this_week)" - } - }, - { - "type": "derived_column", - "alias": "defaulted_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(defaulted_this_week)" - } - }, - { - "type": "derived_column", - "alias": "on_schedule_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(on_schedule_this_week)" - } - }, - { - "type": "derived_column", - "alias": "all_ltfus", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(all_ltfus)" - } - }, - { - "type": "derived_column", - "alias": "surge_ltfu_and_ltfu_after_may", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(surge_ltfu_and_ltfu_after_may)" - } - }, - { - "type": "derived_column", - "alias": "surge_ltfu_and_still_ltfu", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(surge_ltfu_and_still_ltfu)" - } - }, - { - "type": "derived_column", - "alias": "newly_ltfu_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(newly_ltfu_this_week)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_cumulative_outcomes_death", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_cumulative_outcomes_death)" - } - }, - { - "type": "derived_column", - "alias": "missed_tx2_visit_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(missed_tx2_visit_this_week)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_cumulative_outcomes_transfer_out", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_cumulative_outcomes_transfer_out)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_cumulative_outcomes_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_cumulative_outcomes_active)" - } - }, - { - "type": "derived_column", - "alias": "active_to_ltfu_count", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(active_to_ltfu_count)" - } - }, - { - "type": "derived_column", - "alias": "overdue_for_vl_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(overdue_for_vl_active)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_this_week_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_this_week_active)" - } - }, - { - "type": "derived_column", - "alias": "unscheduled_this_week_and_due_for_vl", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(unscheduled_this_week_and_due_for_vl)" - } - }, - { - "type": "derived_column", - "alias": "tx2_visit_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_visit_this_week)" - } - }, - { - "type": "derived_column", - "alias": "dead_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(dead_this_week)" - } - }, - { - "type": "derived_column", - "alias": "non_ltfu_dead_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(non_ltfu_dead_this_week)" - } - }, - { - "type": "derived_column", - "alias": "cumulative_dead", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(cumulative_dead)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_cumulative_outcomes_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_cumulative_outcomes_total)" - } - }, - { - "type": "derived_column", - "alias": "tx2_unscheduled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_unscheduled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "eligible_and_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_and_on_dc)" - } - }, - { - "type": "derived_column", - "alias": "eligible_not_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_not_on_dc)" - } - }, - { - "type": "derived_column", - "alias": "eligible_not_on_dc_and_scheduled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_not_on_dc_and_scheduled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "eligible_not_on_dc_and_unscheduled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_not_on_dc_and_unscheduled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "eligible_and_on_dc_and_scheduled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_and_on_dc_and_scheduled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "eligible_and_on_dc_and_unscheduled_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(eligible_and_on_dc_and_unscheduled_this_week)" - } - }, - { - "type": "derived_column", - "alias": "elligible_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(elligible_total)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_transfer_out_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_transfer_out_this_week)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_death_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_death_this_week)" - } - }, - { - "type": "derived_column", - "alias": "ltfu_active_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(ltfu_active_this_week)" - } - }, - { - "type": "derived_column", - "alias": "is_ltfu_after_may", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(is_ltfu_after_may)" - } - }, - { - "type": "derived_column", - "alias": "old_ltfus_to_active", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(old_ltfus_to_active)" - } - }, - { - "type": "derived_column", - "alias": "old_ltfus_to_active_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(old_ltfus_to_active_this_week)" - } - }, - { - "type": "derived_column", - "alias": "interventions", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(interventions)" - } - }, - { - "type": "derived_column", - "alias": "intervention_done_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(intervention_done_this_week)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_has_vl_order_scheduled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_has_vl_order_scheduled)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_has_vl_order_unscheduled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_has_vl_order_unscheduled)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_dont_have_order_scheduled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_dont_have_order_scheduled)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_dont_have_order_unscheduled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_dont_have_order_unscheduled)" - } - }, - { - "type": "derived_column", - "alias": "due_for_vl_has_vl_order_unscheduled", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(due_for_vl_has_vl_order_unscheduled)" - } - }, - { - "type": "derived_column", - "alias": "has_vl_this_week_and_suppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(has_vl_this_week_and_suppressed)" - } - }, - { - "type": "derived_column", - "alias": "has_vl_this_week_and_unsuppressed", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(has_vl_this_week_and_unsuppressed)" - } - }, - { - "type": "derived_column", - "alias": "is_ltfu_after_may_total", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(is_ltfu_after_may_total)" - } - }, - { - "type": "derived_column", - "alias": "missed_to_active_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(missed_to_active_this_week)" - } - }, - { - "type": "derived_column", - "alias": "defaulter_to_active_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(defaulter_to_active_this_week)" - } - }, - { - "type": "derived_column", - "alias": "not_elligible_and_on_dc", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(not_elligible_and_on_dc)" - } - }, - { - "type": "derived_column", - "alias": "tx2_scheduled_this_week_but_came_early", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(tx2_scheduled_this_week_but_came_early)" - } - }, - { - "type": "derived_column", - "alias": "elligible_total_revised", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(elligible_total_revised)" - } - }, - { - "type": "derived_column", - "alias": "med_surge_ltfus_cumulative", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(med_surge_ltfus_cumulative)" - } - }, - { - "type": "derived_column", - "alias": "med_surge_ltfu_and_med_ltfu_after_may", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(med_surge_ltfu_and_med_ltfu_after_may)" - } - }, - { - "type": "derived_column", - "alias": "med_defaulters", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(med_defaulters)" - } - }, - { - "type": "derived_column", - "alias": "newly_med_ltfu_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(newly_med_ltfu_this_week)" - } - }, - { - "type": "derived_column", - "alias": "med_surge_ltfus_outcomes", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(med_surge_ltfus_outcomes)" - } - }, - { - "type": "derived_column", - "alias": "med_surge_ltfus_outcomes_this_week", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "sum(med_surge_ltfus_outcomes_this_week)" - } - } - ], - "groupBy": { - "groupParam": "groupByParam", - "columns": [ - "location_uuid" - ], - "excludeParam": "excludeParam" - }, - "transFormDirectives": { - "joinColumn": "location_id", - "skipColumns": [ - "location_uuid", - "join_location" - ] - }, - "dynamicJsonQueryGenerationDirectives": { - "patientListGenerator": { - "useTemplate": "patient-list-frozen-template", - "useTemplateVersion": "1.0", - "generatingDirectives": { - "joinDirectives": { - "joinType": "INNER", - "joinCondition": "<> = <>", - "baseColumn": "person_id", - "templateColumn": "person_id" - } - } + "name": "SurgeReportAggregate", + "version": "1.0", + "tag": "", + "description": "", + "uses": [ + { + "name": "surgeReport", + "version": "1.0", + "type": "dataset_def" + } + ], + "sources": [ + { + "dataSet": "surgeReport", + "alias": "srb" + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "location_uuid", + "column": "srb.location_uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "srb.location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "srb.location" + }, + { + "type": "derived_column", + "alias": "scheduled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(scheduled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "visit_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(visit_this_week)" + } + }, + { + "type": "derived_column", + "alias": "on_schedule", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(on_schedule)" + } + }, + { + "type": "derived_column", + "alias": "unscheduled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(unscheduled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "early_appointment_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(early_appointment_this_week)" + } + }, + { + "type": "derived_column", + "alias": "late_appointment_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(late_appointment_this_week)" + } + }, + { + "type": "derived_column", + "alias": "missed_appointment_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(missed_appointment_this_week)" + } + }, + { + "type": "derived_column", + "alias": "ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu)" + } + }, + { + "type": "derived_column", + "alias": "defaulted", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(defaulted)" + } + }, + { + "type": "derived_column", + "alias": "missed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(missed)" + } + }, + { + "type": "derived_column", + "alias": "started_art_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(started_art_this_week)" + } + }, + { + "type": "derived_column", + "alias": "active_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(active_on_dc)" + } + }, + { + "type": "derived_column", + "alias": "started_dc_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(started_dc_this_week)" + } + }, + { + "type": "derived_column", + "alias": "dc_eligible_cumulative", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(dc_eligible_cumulative)" + } + }, + { + "type": "derived_column", + "alias": "dc_eligible_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(dc_eligible_this_week)" + } + }, + { + "type": "derived_column", + "alias": "dc_eligible_and_scheduled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(dc_eligible_and_scheduled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "new_prep_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(new_prep_this_week)" + } + }, + { + "type": "derived_column", + "alias": "cur_prep_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(cur_prep_this_week)" + } + }, + { + "type": "derived_column", + "alias": "enrolled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(enrolled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "has_vl_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(has_vl_this_week)" + } + }, + { + "type": "derived_column", + "alias": "is_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(is_suppressed)" + } + }, + { + "type": "derived_column", + "alias": "is_un_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(is_un_suppressed)" + } + }, + { + "type": "derived_column", + "alias": "tx2_scheduled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_scheduled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "tx2_scheduled_honored", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_scheduled_honored)" + } + }, + { + "type": "derived_column", + "alias": "active_in_care_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(active_in_care_this_week)" + } + }, + { + "type": "derived_column", + "alias": "is_pre_art_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(is_pre_art_this_week)" + } + }, + { + "type": "derived_column", + "alias": "art_revisit_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(art_revisit_this_week)" + } + }, + { + "type": "derived_column", + "alias": "on_art_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(on_art_this_week)" + } + }, + { + "type": "derived_column", + "alias": "transfer_in_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(transfer_in_this_week)" + } + }, + { + "type": "derived_column", + "alias": "transfer_out_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(transfer_out_this_week)" + } + }, + { + "type": "derived_column", + "alias": "scheduled_this_week_and_due_for_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(scheduled_this_week_and_due_for_vl)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_has_vl_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_has_vl_order)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_dont_have_order", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_dont_have_order)" + } + }, + { + "type": "derived_column", + "alias": "missed_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(missed_this_week)" + } + }, + { + "type": "derived_column", + "alias": "defaulted_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(defaulted_this_week)" + } + }, + { + "type": "derived_column", + "alias": "on_schedule_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(on_schedule_this_week)" + } + }, + { + "type": "derived_column", + "alias": "all_ltfus", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(all_ltfus)" + } + }, + { + "type": "derived_column", + "alias": "surge_ltfu_and_ltfu_after_may", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(surge_ltfu_and_ltfu_after_may)" + } + }, + { + "type": "derived_column", + "alias": "surge_ltfu_and_still_ltfu", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(surge_ltfu_and_still_ltfu)" + } + }, + { + "type": "derived_column", + "alias": "newly_ltfu_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(newly_ltfu_this_week)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_cumulative_outcomes_death", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_cumulative_outcomes_death)" + } + }, + { + "type": "derived_column", + "alias": "missed_tx2_visit_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(missed_tx2_visit_this_week)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_cumulative_outcomes_transfer_out", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_cumulative_outcomes_transfer_out)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_cumulative_outcomes_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_cumulative_outcomes_active)" + } + }, + { + "type": "derived_column", + "alias": "active_to_ltfu_count", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(active_to_ltfu_count)" + } + }, + { + "type": "derived_column", + "alias": "overdue_for_vl_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(overdue_for_vl_active)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_this_week_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_this_week_active)" + } + }, + { + "type": "derived_column", + "alias": "unscheduled_this_week_and_due_for_vl", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(unscheduled_this_week_and_due_for_vl)" + } + }, + { + "type": "derived_column", + "alias": "tx2_visit_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_visit_this_week)" + } + }, + { + "type": "derived_column", + "alias": "dead_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(dead_this_week)" + } + }, + { + "type": "derived_column", + "alias": "non_ltfu_dead_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(non_ltfu_dead_this_week)" + } + }, + { + "type": "derived_column", + "alias": "cumulative_dead", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(cumulative_dead)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_cumulative_outcomes_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_cumulative_outcomes_total)" + } + }, + { + "type": "derived_column", + "alias": "tx2_unscheduled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_unscheduled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "eligible_and_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_and_on_dc)" + } + }, + { + "type": "derived_column", + "alias": "eligible_not_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_not_on_dc)" + } + }, + { + "type": "derived_column", + "alias": "eligible_not_on_dc_and_scheduled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_not_on_dc_and_scheduled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "eligible_not_on_dc_and_unscheduled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_not_on_dc_and_unscheduled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "eligible_and_on_dc_and_scheduled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_and_on_dc_and_scheduled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "eligible_and_on_dc_and_unscheduled_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(eligible_and_on_dc_and_unscheduled_this_week)" + } + }, + { + "type": "derived_column", + "alias": "elligible_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(elligible_total)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_transfer_out_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_transfer_out_this_week)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_death_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_death_this_week)" + } + }, + { + "type": "derived_column", + "alias": "ltfu_active_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(ltfu_active_this_week)" + } + }, + { + "type": "derived_column", + "alias": "is_ltfu_after_may", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(is_ltfu_after_may)" + } + }, + { + "type": "derived_column", + "alias": "old_ltfus_to_active", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(old_ltfus_to_active)" + } + }, + { + "type": "derived_column", + "alias": "old_ltfus_to_active_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(old_ltfus_to_active_this_week)" + } + }, + { + "type": "derived_column", + "alias": "interventions", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(interventions)" + } + }, + { + "type": "derived_column", + "alias": "intervention_done_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(intervention_done_this_week)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_has_vl_order_scheduled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_has_vl_order_scheduled)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_has_vl_order_unscheduled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_has_vl_order_unscheduled)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_dont_have_order_scheduled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_dont_have_order_scheduled)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_dont_have_order_unscheduled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_dont_have_order_unscheduled)" + } + }, + { + "type": "derived_column", + "alias": "due_for_vl_has_vl_order_unscheduled", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(due_for_vl_has_vl_order_unscheduled)" + } + }, + { + "type": "derived_column", + "alias": "has_vl_this_week_and_suppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(has_vl_this_week_and_suppressed)" + } + }, + { + "type": "derived_column", + "alias": "has_vl_this_week_and_unsuppressed", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(has_vl_this_week_and_unsuppressed)" + } + }, + { + "type": "derived_column", + "alias": "is_ltfu_after_may_total", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(is_ltfu_after_may_total)" + } + }, + { + "type": "derived_column", + "alias": "missed_to_active_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(missed_to_active_this_week)" + } + }, + { + "type": "derived_column", + "alias": "defaulter_to_active_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(defaulter_to_active_this_week)" + } + }, + { + "type": "derived_column", + "alias": "not_elligible_and_on_dc", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(not_elligible_and_on_dc)" + } + }, + { + "type": "derived_column", + "alias": "tx2_scheduled_this_week_but_came_early", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(tx2_scheduled_this_week_but_came_early)" + } + }, + { + "type": "derived_column", + "alias": "elligible_total_revised", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(elligible_total_revised)" + } + }, + { + "type": "derived_column", + "alias": "med_surge_ltfus_cumulative", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(med_surge_ltfus_cumulative)" + } + }, + { + "type": "derived_column", + "alias": "med_surge_ltfu_and_med_ltfu_after_may", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(med_surge_ltfu_and_med_ltfu_after_may)" + } + }, + { + "type": "derived_column", + "alias": "med_defaulters", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(med_defaulters)" + } + }, + { + "type": "derived_column", + "alias": "newly_med_ltfu_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(newly_med_ltfu_this_week)" + } + }, + { + "type": "derived_column", + "alias": "med_surge_ltfus_outcomes", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(med_surge_ltfus_outcomes)" + } + }, + { + "type": "derived_column", + "alias": "med_surge_ltfus_outcomes_this_week", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "sum(med_surge_ltfus_outcomes_this_week)" + } + } + ], + "groupBy": { + "groupParam": "groupByParam", + "columns": ["location_uuid"], + "excludeParam": "excludeParam" + }, + "transFormDirectives": { + "joinColumn": "location_id", + "skipColumns": ["location_uuid", "join_location"] + }, + "dynamicJsonQueryGenerationDirectives": { + "patientListGenerator": { + "useTemplate": "patient-list-frozen-template", + "useTemplateVersion": "1.0", + "generatingDirectives": { + "joinDirectives": { + "joinType": "INNER", + "joinCondition": "<> = <>", + "baseColumn": "person_id", + "templateColumn": "person_id" } + } } -} \ No newline at end of file + } +} diff --git a/app/reporting-framework/json-reports/surge-report-base.json b/app/reporting-framework/json-reports/surge-report-base.json index 623070155..f07dad297 100644 --- a/app/reporting-framework/json-reports/surge-report-base.json +++ b/app/reporting-framework/json-reports/surge-report-base.json @@ -1,687 +1,687 @@ { - "name": "surgeReport", - "version": "1.0", - "tag": "", - "description": "", - "uses": [], - "sources": [ - { - "table": "<>", - "alias": "srb" - }, - { - "table": "amrs.location", - "alias": "l", - "join": { - "type": "INNER", - "joinCondition": "l.location_id = srb.location_id" - } - } - ], - "columns": [ - { - "type": "simple_column", - "alias": "year_week", - "column": "srb.year_week" - }, - { - "type": "simple_column", - "alias": "encounter_yw", - "column": "srb.encounter_yw" - }, - { - "type": "derived_column", - "alias": "encounter_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(srb.encounter_date, '%Y-%m-%d')" - } - }, - { - "type": "simple_olumn", - "alias": "end_date", - "column": "srb.end_date" - }, - { - "type": "simple_column", - "alias": "start_date", - "column": "srb.start_date" - }, - { - "type": "simple_column", - "alias": "age", - "column": "srb.age" - }, - { - "type": "simple_column", - "alias": "gender", - "column": "srb.gender" - }, - { - "type": "derived_column", - "alias": "prev_rtc_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(srb.prev_rtc_date, '%Y-%m-%d')" - } - }, - { - "type": "derived_column", - "alias": "rtc_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(srb.rtc_date, '%Y-%m-%d')" - } - }, - { - "type": "simple_column", - "alias": "visit_this_week", - "column": "srb.visit_this_week" - }, - { - "type": "simple_column", - "alias": "on_schedule", - "column": "srb.on_schedule" - }, - { - "type": "simple_column", - "alias": "early_appointment", - "column": "srb.early_appointment" - }, - { - "type": "simple_column", - "alias": "early_appointment_this_week", - "column": "srb.early_appointment_this_week" - }, - { - "type": "simple_column", - "alias": "late_appointment_this_week", - "column": "srb.late_appointment_this_week" - }, - { - "type": "simple_column", - "alias": "days_since_rtc_date", - "column": "srb.days_since_rtc_date" - }, - { - "type": "simple_column", - "alias": "scheduled_this_week", - "column": "srb.scheduled_this_week" - }, - { - "type": "simple_column", - "alias": "unscheduled_this_week", - "column": "srb.unscheduled_this_week" - }, - { - "type": "derived_column", - "alias": "death_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(srb.death_date, '%Y-%m-%d')" - } - }, - { - "type": "simple_column", - "alias": "missed_appointment_this_week", - "column": "srb.missed_appointment_this_week" - }, - { - "type": "simple_column", - "alias": "ltfu", - "column": "srb.ltfu" - }, - { - "type": "simple_column", - "alias": "defaulted", - "column": "srb.defaulted" - }, - { - "type": "simple_column", - "alias": "missed", - "column": "srb.missed" - }, - { - "type": "simple_column", - "alias": "active_in_care_this_week", - "column": "srb.active_in_care_this_week" - }, - { - "type": "simple_column", - "alias": "cur_arv_adherence", - "column": "srb.cur_arv_adherence" - }, - { - "type": "simple_column", - "alias": "cur_who_stage", - "column": "srb.cur_who_stage" - }, - { - "type": "simple_column", - "alias": "is_pre_art_this_week", - "column": "srb.is_pre_art_this_week" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_location_id", - "column": "srb.arv_first_regimen_location_id" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen", - "column": "srb.arv_first_regimen" - }, - { - "type": "simple_column", - "alias": "arv_first_regimen_names", - "column": "srb.arv_first_regimen_names" - }, - { - "type": "simple_column", - "alias": "started_art_this_week", - "column": "srb.started_art_this_week" - }, - { - "type": "derived_column", - "alias": "enrollment_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(srb.enrollment_date, '%Y-%m-%d')" - } - }, - { - "type": "simple_column", - "alias": "days_since_starting_arvs", - "column": "srb.days_since_starting_arvs" - }, - { - "type": "derived_column", - "alias": "arv_first_regimen_start_date", - "expressionType": "simple_expression", - "expressionOptions": { - "expression": "DATE_FORMAT(srb.arv_first_regimen_start_date, '%Y-%m-%d')" - } - }, - { - "type": "simple_column", - "alias": "enrolled_this_week", - "column": "srb.enrolled_this_week" - }, - { - "type": "simple_column", - "alias": "cur_arv_meds", - "column": "srb.cur_arv_meds" - }, - { - "type": "simple_column", - "alias": "art_revisit_this_week", - "column": "srb.art_revisit_this_week" - }, - { - "type": "simple_column", - "alias": "on_art_this_week", - "column": "srb.on_art_this_week" - }, - { - "type": "simple_column", - "alias": "has_vl_this_week", - "column": "srb.has_vl_this_week" - }, - { - "type": "simple_column", - "alias": "is_suppressed", - "column": "srb.is_suppressed" - }, - { - "type": "simple_column", - "alias": "is_un_suppressed", - "column": "srb.is_un_suppressed" - }, - { - "type": "simple_column", - "alias": "days_since_last_vl", - "column": "srb.days_since_last_vl" - }, - { - "type": "simple_column", - "alias": "cd4_1", - "column": "srb.cd4_1" - }, - { - "type": "simple_column", - "alias": "cd4_1_date", - "column": "srb.cd4_1_date" - }, - { - "type": "simple_column", - "alias": "child_hiv_status_disclosure_status", - "column": "srb.child_hiv_status_disclosure_status" - }, - { - "type": "simple_column", - "alias": "transfer_in_this_week", - "column": "srb.transfer_in_this_week" - }, - { - "type": "simple_column", - "alias": "transfer_in_location_id", - "column": "srb.transfer_in_location_id" - }, - { - "type": "simple_column", - "alias": "transfer_in_date", - "column": "DATE_FORMAT(srb.transfer_in_date, '%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "transfer_out_this_week", - "column": "srb.transfer_out_this_week" - }, - { - "type": "simple_column", - "alias": "transfer_out_location_id", - "column": "srb.transfer_out_location_id" - }, - { - "type": "simple_column", - "alias": "transfer_out_date", - "column": "date_format(srb.transfer_out_date,'%Y-%m-%d')" - }, - { - "type": "simple_column", - "alias": "week_patient_became_active", - "column": "srb.week_patient_became_active" - }, - { - "type": "simple_column", - "alias": "status", - "column": "srb.status" - }, - { - "type": "simple_column", - "alias": "prev_status", - "column": "srb.prev_status" - }, - { - "type": "simple_column", - "alias": "cur_status", - "column": "srb.cur_status" - }, - { - "type": "simple_column", - "alias": "dc_eligible_cumulative", - "column": "srb.dc_eligible_cumulative" - }, - { - "type": "simple_column", - "alias": "dc_eligible_this_week", - "column": "srb.dc_eligible_this_week" - }, - { - "type": "simple_column", - "alias": "dc_eligible_and_scheduled_this_week", - "column": "srb.dc_eligible_and_scheduled_this_week" - }, - { - "type": "simple_column", - "alias": "started_dc_this_week", - "column": "srb.started_dc_this_week" - }, - { - "type": "simple_column", - "alias": "active_on_dc", - "column": "srb.active_on_dc" - }, - { - "type": "simple_column", - "alias": "tx2_scheduled_this_week", - "column": "srb.tx2_scheduled_this_week" - }, - { - "type": "simple_column", - "alias": "tx2_scheduled_honored", - "column": "srb.tx2_scheduled_honored" - }, - { - "type": "simple_column", - "alias": "new_prep_this_week", - "column": "srb.new_prep_this_week" - }, - { - "type": "simple_column", - "alias": "cur_prep_this_week", - "column": "srb.cur_prep_this_week" - }, - { - "type": "simple_column", - "alias": "prev_enc_id", - "column": "srb.prev_enc_id" - }, - { - "type": "simple_column", - "alias": "cur_enc_id", - "column": "srb.cur_enc_id" - }, - { - "type": "simple_column", - "alias": "scheduled_this_week_and_due_for_vl", - "column": "srb.scheduled_this_week_and_due_for_vl" - }, - { - "type": "simple_column", - "alias": "due_for_vl_has_vl_order", - "column": "srb.due_for_vl_has_vl_order" - }, - { - "type": "simple_column", - "alias": "due_for_vl_dont_have_order", - "column": "srb.due_for_vl_dont_have_order" - }, - { - "type": "simple_column", - "alias": "missed_this_week", - "column": "srb.missed_this_week" - }, - { - "type": "simple_column", - "alias": "due_for_vl_this_week_active", - "column": "srb.due_for_vl_this_week_active" - }, - { - "type": "simple_column", - "alias": "on_schedule_this_week", - "column": "srb.on_schedule_this_week" - }, - { - "type": "simple_column", - "alias": "defaulted_this_week", - "column": "srb.defaulted_this_week" - }, + "name": "surgeReport", + "version": "1.0", + "tag": "", + "description": "", + "uses": [], + "sources": [ + { + "table": "<>", + "alias": "srb" + }, + { + "table": "amrs.location", + "alias": "l", + "join": { + "type": "INNER", + "joinCondition": "l.location_id = srb.location_id" + } + } + ], + "columns": [ + { + "type": "simple_column", + "alias": "year_week", + "column": "srb.year_week" + }, + { + "type": "simple_column", + "alias": "encounter_yw", + "column": "srb.encounter_yw" + }, + { + "type": "derived_column", + "alias": "encounter_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(srb.encounter_date, '%Y-%m-%d')" + } + }, + { + "type": "simple_olumn", + "alias": "end_date", + "column": "srb.end_date" + }, + { + "type": "simple_column", + "alias": "start_date", + "column": "srb.start_date" + }, + { + "type": "simple_column", + "alias": "age", + "column": "srb.age" + }, + { + "type": "simple_column", + "alias": "gender", + "column": "srb.gender" + }, + { + "type": "derived_column", + "alias": "prev_rtc_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(srb.prev_rtc_date, '%Y-%m-%d')" + } + }, + { + "type": "derived_column", + "alias": "rtc_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(srb.rtc_date, '%Y-%m-%d')" + } + }, + { + "type": "simple_column", + "alias": "visit_this_week", + "column": "srb.visit_this_week" + }, + { + "type": "simple_column", + "alias": "on_schedule", + "column": "srb.on_schedule" + }, + { + "type": "simple_column", + "alias": "early_appointment", + "column": "srb.early_appointment" + }, + { + "type": "simple_column", + "alias": "early_appointment_this_week", + "column": "srb.early_appointment_this_week" + }, + { + "type": "simple_column", + "alias": "late_appointment_this_week", + "column": "srb.late_appointment_this_week" + }, + { + "type": "simple_column", + "alias": "days_since_rtc_date", + "column": "srb.days_since_rtc_date" + }, + { + "type": "simple_column", + "alias": "scheduled_this_week", + "column": "srb.scheduled_this_week" + }, + { + "type": "simple_column", + "alias": "unscheduled_this_week", + "column": "srb.unscheduled_this_week" + }, + { + "type": "derived_column", + "alias": "death_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(srb.death_date, '%Y-%m-%d')" + } + }, + { + "type": "simple_column", + "alias": "missed_appointment_this_week", + "column": "srb.missed_appointment_this_week" + }, + { + "type": "simple_column", + "alias": "ltfu", + "column": "srb.ltfu" + }, + { + "type": "simple_column", + "alias": "defaulted", + "column": "srb.defaulted" + }, + { + "type": "simple_column", + "alias": "missed", + "column": "srb.missed" + }, + { + "type": "simple_column", + "alias": "active_in_care_this_week", + "column": "srb.active_in_care_this_week" + }, + { + "type": "simple_column", + "alias": "cur_arv_adherence", + "column": "srb.cur_arv_adherence" + }, + { + "type": "simple_column", + "alias": "cur_who_stage", + "column": "srb.cur_who_stage" + }, + { + "type": "simple_column", + "alias": "is_pre_art_this_week", + "column": "srb.is_pre_art_this_week" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_location_id", + "column": "srb.arv_first_regimen_location_id" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen", + "column": "srb.arv_first_regimen" + }, + { + "type": "simple_column", + "alias": "arv_first_regimen_names", + "column": "srb.arv_first_regimen_names" + }, + { + "type": "simple_column", + "alias": "started_art_this_week", + "column": "srb.started_art_this_week" + }, + { + "type": "derived_column", + "alias": "enrollment_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(srb.enrollment_date, '%Y-%m-%d')" + } + }, + { + "type": "simple_column", + "alias": "days_since_starting_arvs", + "column": "srb.days_since_starting_arvs" + }, + { + "type": "derived_column", + "alias": "arv_first_regimen_start_date", + "expressionType": "simple_expression", + "expressionOptions": { + "expression": "DATE_FORMAT(srb.arv_first_regimen_start_date, '%Y-%m-%d')" + } + }, + { + "type": "simple_column", + "alias": "enrolled_this_week", + "column": "srb.enrolled_this_week" + }, + { + "type": "simple_column", + "alias": "cur_arv_meds", + "column": "srb.cur_arv_meds" + }, + { + "type": "simple_column", + "alias": "art_revisit_this_week", + "column": "srb.art_revisit_this_week" + }, + { + "type": "simple_column", + "alias": "on_art_this_week", + "column": "srb.on_art_this_week" + }, + { + "type": "simple_column", + "alias": "has_vl_this_week", + "column": "srb.has_vl_this_week" + }, + { + "type": "simple_column", + "alias": "is_suppressed", + "column": "srb.is_suppressed" + }, + { + "type": "simple_column", + "alias": "is_un_suppressed", + "column": "srb.is_un_suppressed" + }, + { + "type": "simple_column", + "alias": "days_since_last_vl", + "column": "srb.days_since_last_vl" + }, + { + "type": "simple_column", + "alias": "cd4_1", + "column": "srb.cd4_1" + }, + { + "type": "simple_column", + "alias": "cd4_1_date", + "column": "srb.cd4_1_date" + }, + { + "type": "simple_column", + "alias": "child_hiv_status_disclosure_status", + "column": "srb.child_hiv_status_disclosure_status" + }, + { + "type": "simple_column", + "alias": "transfer_in_this_week", + "column": "srb.transfer_in_this_week" + }, + { + "type": "simple_column", + "alias": "transfer_in_location_id", + "column": "srb.transfer_in_location_id" + }, + { + "type": "simple_column", + "alias": "transfer_in_date", + "column": "DATE_FORMAT(srb.transfer_in_date, '%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "transfer_out_this_week", + "column": "srb.transfer_out_this_week" + }, + { + "type": "simple_column", + "alias": "transfer_out_location_id", + "column": "srb.transfer_out_location_id" + }, + { + "type": "simple_column", + "alias": "transfer_out_date", + "column": "date_format(srb.transfer_out_date,'%Y-%m-%d')" + }, + { + "type": "simple_column", + "alias": "week_patient_became_active", + "column": "srb.week_patient_became_active" + }, + { + "type": "simple_column", + "alias": "status", + "column": "srb.status" + }, + { + "type": "simple_column", + "alias": "prev_status", + "column": "srb.prev_status" + }, + { + "type": "simple_column", + "alias": "cur_status", + "column": "srb.cur_status" + }, + { + "type": "simple_column", + "alias": "dc_eligible_cumulative", + "column": "srb.dc_eligible_cumulative" + }, + { + "type": "simple_column", + "alias": "dc_eligible_this_week", + "column": "srb.dc_eligible_this_week" + }, + { + "type": "simple_column", + "alias": "dc_eligible_and_scheduled_this_week", + "column": "srb.dc_eligible_and_scheduled_this_week" + }, + { + "type": "simple_column", + "alias": "started_dc_this_week", + "column": "srb.started_dc_this_week" + }, + { + "type": "simple_column", + "alias": "active_on_dc", + "column": "srb.active_on_dc" + }, + { + "type": "simple_column", + "alias": "tx2_scheduled_this_week", + "column": "srb.tx2_scheduled_this_week" + }, + { + "type": "simple_column", + "alias": "tx2_scheduled_honored", + "column": "srb.tx2_scheduled_honored" + }, + { + "type": "simple_column", + "alias": "new_prep_this_week", + "column": "srb.new_prep_this_week" + }, + { + "type": "simple_column", + "alias": "cur_prep_this_week", + "column": "srb.cur_prep_this_week" + }, + { + "type": "simple_column", + "alias": "prev_enc_id", + "column": "srb.prev_enc_id" + }, + { + "type": "simple_column", + "alias": "cur_enc_id", + "column": "srb.cur_enc_id" + }, + { + "type": "simple_column", + "alias": "scheduled_this_week_and_due_for_vl", + "column": "srb.scheduled_this_week_and_due_for_vl" + }, + { + "type": "simple_column", + "alias": "due_for_vl_has_vl_order", + "column": "srb.due_for_vl_has_vl_order" + }, + { + "type": "simple_column", + "alias": "due_for_vl_dont_have_order", + "column": "srb.due_for_vl_dont_have_order" + }, + { + "type": "simple_column", + "alias": "missed_this_week", + "column": "srb.missed_this_week" + }, + { + "type": "simple_column", + "alias": "due_for_vl_this_week_active", + "column": "srb.due_for_vl_this_week_active" + }, + { + "type": "simple_column", + "alias": "on_schedule_this_week", + "column": "srb.on_schedule_this_week" + }, + { + "type": "simple_column", + "alias": "defaulted_this_week", + "column": "srb.defaulted_this_week" + }, - { - "type": "simple_column", - "alias": "all_ltfus", - "column": "srb.all_ltfus" - }, - { - "type": "simple_column", - "alias": "surge_ltfu_and_ltfu_after_may", - "column": "srb.surge_ltfu_and_ltfu_after_may" - }, - { - "type": "simple_column", - "alias": "surge_ltfu_and_still_ltfu", - "column": "srb.surge_ltfu_and_still_ltfu" - }, - { - "type": "simple_column", - "alias": "newly_ltfu_this_week", - "column": "srb.newly_ltfu_this_week" - }, - { - "type": "simple_column", - "alias": "missed_tx2_visit_this_week", - "column": "srb.missed_tx2_visit_this_week" - }, - { - "type": "simple_column", - "alias": "overdue_for_vl_active", - "column": "srb.overdue_for_vl_active" - }, - { - "type": "simple_column", - "alias": "unscheduled_this_week_and_due_for_vl", - "column": "srb.unscheduled_this_week_and_due_for_vl" - }, - { - "type": "simple_column", - "alias": "ltfu_cumulative_outcomes_death", - "column": "srb.ltfu_cumulative_outcomes_death" - }, - { - "type": "simple_column", - "alias": "ltfu_cumulative_outcomes_transfer_out", - "column": "srb.ltfu_cumulative_outcomes_transfer_out" - }, - { - "type": "simple_column", - "alias": "ltfu_cumulative_outcomes_active", - "column": "srb.ltfu_cumulative_outcomes_active" - }, - { - "type": "simple_column", - "alias": "active_to_ltfu_count", - "column": "srb.active_to_ltfu_count" - }, - { - "type": "simple_column", - "alias": "tx2_visit_this_week", - "column": "srb.tx2_visit_this_week" - }, - { - "type": "simple_column", - "alias": "clinical_visit_num", - "column": "srb.clinical_visit_num" - }, - { - "type": "simple_column", - "alias": "ltfu_cumulative_outcomes_total", - "column": "srb.ltfu_cumulative_outcomes_total" - }, - { - "type": "simple_column", - "alias": "tx2_unscheduled_this_week", - "column": "srb.tx2_unscheduled_this_week" - }, - { - "type": "simple_column", - "alias": "dead_this_week", - "column": "srb.dead_this_week" - }, - { - "type": "simple_column", - "alias": "non_ltfu_dead_this_week", - "column": "srb.non_ltfu_dead_this_week" - }, - { - "type": "simple_column", - "alias": "cumulative_dead", - "column": "srb.cumulative_dead" - }, - { - "type": "simple_column", - "alias": "eligible_and_on_dc", - "column": "srb.eligible_and_on_dc" - }, - { - "type": "simple_column", - "alias": "eligible_not_on_dc", - "column": "srb.eligible_not_on_dc" - }, - { - "type": "simple_column", - "alias": "eligible_not_on_dc_and_scheduled_this_week", - "column": "srb.eligible_not_on_dc_and_scheduled_this_week" - }, - { - "type": "simple_column", - "alias": "eligible_not_on_dc_and_unscheduled_this_week", - "column": "srb.eligible_not_on_dc_and_unscheduled_this_week" - }, - { - "type": "simple_column", - "alias": "eligible_and_on_dc_and_scheduled_this_week", - "column": "srb.eligible_and_on_dc_and_scheduled_this_week" - }, - { - "type": "simple_column", - "alias": "eligible_and_on_dc_and_unscheduled_this_week", - "column": "srb.eligible_and_on_dc_and_unscheduled_this_week" - }, - { - "type": "simple_column", - "alias": "elligible_total", - "column": "srb.elligible_total" - }, - { - "type": "simple_column", - "alias": "ltfu_transfer_out_this_week", - "column": "srb.ltfu_transfer_out_this_week" - }, - { - "type": "simple_column", - "alias": "ltfu_death_this_week", - "column": "srb.ltfu_death_this_week" - }, - { - "type": "simple_column", - "alias": "ltfu_active_this_week", - "column": "srb.ltfu_active_this_week" - }, - { - "type": "simple_column", - "alias": "is_ltfu_after_may", - "column": "srb.is_ltfu_after_may" - }, - { - "type": "simple_column", - "alias": "old_ltfus_to_active", - "column": "srb.old_ltfus_to_active" - }, - { - "type": "simple_column", - "alias": "old_ltfus_to_active_this_week", - "column": "srb.old_ltfus_to_active_this_week" - }, - { - "type": "simple_column", - "alias": "interventions", - "column": "srb.interventions" - }, - { - "type": "simple_column", - "alias": "intervention_done_this_week", - "column": "srb.intervention_done_this_week" - }, - { - "type": "simple_column", - "alias": "has_vl_this_week_and_suppressed", - "column": "srb.has_vl_this_week_and_suppressed" - }, - { - "type": "simple_column", - "alias": "due_for_vl_has_vl_order_scheduled", - "column": "srb.due_for_vl_has_vl_order_scheduled" - }, - { - "type": "simple_column", - "alias": "due_for_vl_has_vl_order_unscheduled", - "column": "srb.due_for_vl_has_vl_order_unscheduled" - }, - { - "type": "simple_column", - "alias": "due_for_vl_dont_have_order_scheduled", - "column": "srb.due_for_vl_dont_have_order_scheduled" - }, - { - "type": "simple_column", - "alias": "due_for_vl_dont_have_order_unscheduled", - "column": "srb.due_for_vl_dont_have_order_unscheduled" - }, - { - "type": "simple_column", - "alias": "has_vl_this_week_and_unsuppressed", - "column": "srb.has_vl_this_week_and_unsuppressed" - }, - { - "type": "simple_column", - "alias": "missed_to_active_this_week", - "column": "srb.missed_to_active_this_week" - }, - { - "type": "simple_column", - "alias": "defaulter_to_active_this_week", - "column": "srb.defaulter_to_active_this_week" - }, - { - "type": "simple_column", - "alias": "not_elligible_and_on_dc", - "column": "srb.not_elligible_and_on_dc" - }, - { - "type": "simple_column", - "alias": "is_ltfu_after_may_total", - "column": "srb.is_ltfu_after_may_total" - }, - { - "type": "simple_column", - "alias": "tx2_scheduled_this_week_but_came_early", - "column": "srb.tx2_scheduled_this_week_but_came_early" - }, - { - "type": "simple_column", - "alias": "elligible_total_revised", - "column": "srb.elligible_total_revised" - }, - { - "type": "simple_column", - "alias": "med_surge_ltfus_outcomes", - "column": "srb.med_surge_ltfus_outcomes" - }, - { - "type": "simple_column", - "alias": "med_surge_ltfus_outcomes_this_week", - "column": "srb.med_surge_ltfus_outcomes_this_week" - }, - { - "type": "simple_column", - "alias": "med_surge_ltfus_cumulative", - "column": "srb.med_surge_ltfus_cumulative" - }, - { - "type": "simple_column", - "alias": "med_surge_ltfu_and_med_ltfu_after_may", - "column": "srb.med_surge_ltfu_and_med_ltfu_after_may" - }, - { - "type": "simple_column", - "alias": "med_defaulters", - "column": "srb.med_defaulters" - }, - { - "type": "simple_column", - "alias": "newly_med_ltfu_this_week", - "column": "srb.newly_med_ltfu_this_week" - }, - { - "type": "simple_column", - "alias": "location_uuid", - "column": "l.uuid" - }, - { - "type": "simple_column", - "alias": "location_id", - "column": "l.location_id" - }, - { - "type": "simple_column", - "alias": "location", - "column": "l.name" - } - ], - "filters": { - "conditionJoinOperator": "and", - "conditions": [ - { - "filterType": "tableColumns", - "conditionExpression": "year_week = ? ", - "parameterName": "year_week" - }, - { - "filterType": "tableColumns", - "conditionExpression": "l.uuid in ?", - "parameterName": "locationUuids" - } - ] + { + "type": "simple_column", + "alias": "all_ltfus", + "column": "srb.all_ltfus" + }, + { + "type": "simple_column", + "alias": "surge_ltfu_and_ltfu_after_may", + "column": "srb.surge_ltfu_and_ltfu_after_may" + }, + { + "type": "simple_column", + "alias": "surge_ltfu_and_still_ltfu", + "column": "srb.surge_ltfu_and_still_ltfu" + }, + { + "type": "simple_column", + "alias": "newly_ltfu_this_week", + "column": "srb.newly_ltfu_this_week" + }, + { + "type": "simple_column", + "alias": "missed_tx2_visit_this_week", + "column": "srb.missed_tx2_visit_this_week" + }, + { + "type": "simple_column", + "alias": "overdue_for_vl_active", + "column": "srb.overdue_for_vl_active" + }, + { + "type": "simple_column", + "alias": "unscheduled_this_week_and_due_for_vl", + "column": "srb.unscheduled_this_week_and_due_for_vl" + }, + { + "type": "simple_column", + "alias": "ltfu_cumulative_outcomes_death", + "column": "srb.ltfu_cumulative_outcomes_death" + }, + { + "type": "simple_column", + "alias": "ltfu_cumulative_outcomes_transfer_out", + "column": "srb.ltfu_cumulative_outcomes_transfer_out" + }, + { + "type": "simple_column", + "alias": "ltfu_cumulative_outcomes_active", + "column": "srb.ltfu_cumulative_outcomes_active" + }, + { + "type": "simple_column", + "alias": "active_to_ltfu_count", + "column": "srb.active_to_ltfu_count" + }, + { + "type": "simple_column", + "alias": "tx2_visit_this_week", + "column": "srb.tx2_visit_this_week" + }, + { + "type": "simple_column", + "alias": "clinical_visit_num", + "column": "srb.clinical_visit_num" + }, + { + "type": "simple_column", + "alias": "ltfu_cumulative_outcomes_total", + "column": "srb.ltfu_cumulative_outcomes_total" + }, + { + "type": "simple_column", + "alias": "tx2_unscheduled_this_week", + "column": "srb.tx2_unscheduled_this_week" + }, + { + "type": "simple_column", + "alias": "dead_this_week", + "column": "srb.dead_this_week" + }, + { + "type": "simple_column", + "alias": "non_ltfu_dead_this_week", + "column": "srb.non_ltfu_dead_this_week" + }, + { + "type": "simple_column", + "alias": "cumulative_dead", + "column": "srb.cumulative_dead" + }, + { + "type": "simple_column", + "alias": "eligible_and_on_dc", + "column": "srb.eligible_and_on_dc" + }, + { + "type": "simple_column", + "alias": "eligible_not_on_dc", + "column": "srb.eligible_not_on_dc" + }, + { + "type": "simple_column", + "alias": "eligible_not_on_dc_and_scheduled_this_week", + "column": "srb.eligible_not_on_dc_and_scheduled_this_week" + }, + { + "type": "simple_column", + "alias": "eligible_not_on_dc_and_unscheduled_this_week", + "column": "srb.eligible_not_on_dc_and_unscheduled_this_week" + }, + { + "type": "simple_column", + "alias": "eligible_and_on_dc_and_scheduled_this_week", + "column": "srb.eligible_and_on_dc_and_scheduled_this_week" + }, + { + "type": "simple_column", + "alias": "eligible_and_on_dc_and_unscheduled_this_week", + "column": "srb.eligible_and_on_dc_and_unscheduled_this_week" + }, + { + "type": "simple_column", + "alias": "elligible_total", + "column": "srb.elligible_total" + }, + { + "type": "simple_column", + "alias": "ltfu_transfer_out_this_week", + "column": "srb.ltfu_transfer_out_this_week" + }, + { + "type": "simple_column", + "alias": "ltfu_death_this_week", + "column": "srb.ltfu_death_this_week" + }, + { + "type": "simple_column", + "alias": "ltfu_active_this_week", + "column": "srb.ltfu_active_this_week" + }, + { + "type": "simple_column", + "alias": "is_ltfu_after_may", + "column": "srb.is_ltfu_after_may" + }, + { + "type": "simple_column", + "alias": "old_ltfus_to_active", + "column": "srb.old_ltfus_to_active" + }, + { + "type": "simple_column", + "alias": "old_ltfus_to_active_this_week", + "column": "srb.old_ltfus_to_active_this_week" + }, + { + "type": "simple_column", + "alias": "interventions", + "column": "srb.interventions" + }, + { + "type": "simple_column", + "alias": "intervention_done_this_week", + "column": "srb.intervention_done_this_week" + }, + { + "type": "simple_column", + "alias": "has_vl_this_week_and_suppressed", + "column": "srb.has_vl_this_week_and_suppressed" + }, + { + "type": "simple_column", + "alias": "due_for_vl_has_vl_order_scheduled", + "column": "srb.due_for_vl_has_vl_order_scheduled" + }, + { + "type": "simple_column", + "alias": "due_for_vl_has_vl_order_unscheduled", + "column": "srb.due_for_vl_has_vl_order_unscheduled" + }, + { + "type": "simple_column", + "alias": "due_for_vl_dont_have_order_scheduled", + "column": "srb.due_for_vl_dont_have_order_scheduled" + }, + { + "type": "simple_column", + "alias": "due_for_vl_dont_have_order_unscheduled", + "column": "srb.due_for_vl_dont_have_order_unscheduled" + }, + { + "type": "simple_column", + "alias": "has_vl_this_week_and_unsuppressed", + "column": "srb.has_vl_this_week_and_unsuppressed" + }, + { + "type": "simple_column", + "alias": "missed_to_active_this_week", + "column": "srb.missed_to_active_this_week" + }, + { + "type": "simple_column", + "alias": "defaulter_to_active_this_week", + "column": "srb.defaulter_to_active_this_week" + }, + { + "type": "simple_column", + "alias": "not_elligible_and_on_dc", + "column": "srb.not_elligible_and_on_dc" + }, + { + "type": "simple_column", + "alias": "is_ltfu_after_may_total", + "column": "srb.is_ltfu_after_may_total" + }, + { + "type": "simple_column", + "alias": "tx2_scheduled_this_week_but_came_early", + "column": "srb.tx2_scheduled_this_week_but_came_early" + }, + { + "type": "simple_column", + "alias": "elligible_total_revised", + "column": "srb.elligible_total_revised" + }, + { + "type": "simple_column", + "alias": "med_surge_ltfus_outcomes", + "column": "srb.med_surge_ltfus_outcomes" + }, + { + "type": "simple_column", + "alias": "med_surge_ltfus_outcomes_this_week", + "column": "srb.med_surge_ltfus_outcomes_this_week" + }, + { + "type": "simple_column", + "alias": "med_surge_ltfus_cumulative", + "column": "srb.med_surge_ltfus_cumulative" + }, + { + "type": "simple_column", + "alias": "med_surge_ltfu_and_med_ltfu_after_may", + "column": "srb.med_surge_ltfu_and_med_ltfu_after_may" + }, + { + "type": "simple_column", + "alias": "med_defaulters", + "column": "srb.med_defaulters" + }, + { + "type": "simple_column", + "alias": "newly_med_ltfu_this_week", + "column": "srb.newly_med_ltfu_this_week" + }, + { + "type": "simple_column", + "alias": "location_uuid", + "column": "l.uuid" + }, + { + "type": "simple_column", + "alias": "location_id", + "column": "l.location_id" + }, + { + "type": "simple_column", + "alias": "location", + "column": "l.name" } -} \ No newline at end of file + ], + "filters": { + "conditionJoinOperator": "and", + "conditions": [ + { + "filterType": "tableColumns", + "conditionExpression": "year_week = ? ", + "parameterName": "year_week" + }, + { + "filterType": "tableColumns", + "conditionExpression": "l.uuid in ?", + "parameterName": "locationUuids" + } + ] + } +} diff --git a/app/reporting-framework/json-reports/surge-report.json b/app/reporting-framework/json-reports/surge-report.json index 0a43a293e..f576b5d39 100644 --- a/app/reporting-framework/json-reports/surge-report.json +++ b/app/reporting-framework/json-reports/surge-report.json @@ -1,7 +1,3 @@ { - "reports": [ - "surgeReport", - "prepReport", - "surgeBaselineReport" - ] -} \ No newline at end of file + "reports": ["surgeReport", "prepReport", "surgeBaselineReport"] +} diff --git a/app/reporting-framework/multi-dataset-patientlist.report.js b/app/reporting-framework/multi-dataset-patientlist.report.js index 1a12ba861..8f6344a4f 100755 --- a/app/reporting-framework/multi-dataset-patientlist.report.js +++ b/app/reporting-framework/multi-dataset-patientlist.report.js @@ -5,167 +5,180 @@ import { interfaces } from 'mocha'; var helpers = require('../../etl-helpers'); let mockPatientList = [ - { - gender: 'F', - birthdate: '1959-12-31T21:00:00.000Z', - age: 58, - person_id: 761391, - location_uuid: '0900abdc-1352-11df-a1f1-0026b9348838', - location: 'Moi University', - location_id: 72, - cur_arv_meds: '628 ## 633 ## 797', - enrollment_date: '22-12-2008', - arv_first_regimen_start_date: '01-01-1900', - cur_regimen_arv_start_date: '17-10-2017', - cur_arv_line: 1, - vl_1: 6730, - vl_1_date: '19-02-2018', - age_range: 'older_than_24', - enrolled_this_month: 0, - art_revisit_this_month: 1, - current_in_care: 1, - pre_art: 0, - started_art_pregnant: 0, - started_art_and_has_tb: 0, - active_on_art: 1, - on_ctx_prophylaxis: 1, - current_on_art: 1, - screened_for_tb: 1, - tb_screened_this_visit_this_month: 1, - tb_screened_positive: 0, - screened_for_cervical_ca: 0, - started_ipt: 0, - completed_ipt_past_12_months: 0, - condoms_provided: 0, - started_modern_contraception: 0, - on_modern_contraception: 0, - scheduled_visits: 0, - unscheduled_visits: 1, - total_visits: 1, - f_gte_18_visits: 1, - patient_uuid: '8d9f8be2-e772-49ef-94c1-2f3560739162', - uuid: '8d9f8be2-e772-49ef-94c1-2f3560739162', - person_name: 'LILY CHEBET MITEI', - identifiers: '256MU-8, 15205-00086' - } -] + { + gender: 'F', + birthdate: '1959-12-31T21:00:00.000Z', + age: 58, + person_id: 761391, + location_uuid: '0900abdc-1352-11df-a1f1-0026b9348838', + location: 'Moi University', + location_id: 72, + cur_arv_meds: '628 ## 633 ## 797', + enrollment_date: '22-12-2008', + arv_first_regimen_start_date: '01-01-1900', + cur_regimen_arv_start_date: '17-10-2017', + cur_arv_line: 1, + vl_1: 6730, + vl_1_date: '19-02-2018', + age_range: 'older_than_24', + enrolled_this_month: 0, + art_revisit_this_month: 1, + current_in_care: 1, + pre_art: 0, + started_art_pregnant: 0, + started_art_and_has_tb: 0, + active_on_art: 1, + on_ctx_prophylaxis: 1, + current_on_art: 1, + screened_for_tb: 1, + tb_screened_this_visit_this_month: 1, + tb_screened_positive: 0, + screened_for_cervical_ca: 0, + started_ipt: 0, + completed_ipt_past_12_months: 0, + condoms_provided: 0, + started_modern_contraception: 0, + on_modern_contraception: 0, + scheduled_visits: 0, + unscheduled_visits: 1, + total_visits: 1, + f_gte_18_visits: 1, + patient_uuid: '8d9f8be2-e772-49ef-94c1-2f3560739162', + uuid: '8d9f8be2-e772-49ef-94c1-2f3560739162', + person_name: 'LILY CHEBET MITEI', + identifiers: '256MU-8, 15205-00086' + } +]; export class MultiDatasetPatientlistReport extends MultiDatasetReport { - constructor(reportName, params) { - super(reportName, params); - } - // interprate - generatePatientListReport(indicators) { - let additionalParams = { - type: 'patient-list', - indicators: indicators - }; - - let that = this; - return new Promise((resolve, reject) => { - this.generateReport(additionalParams). - then((results) => { + constructor(reportName, params) { + super(reportName, params); + } + // interprate + generatePatientListReport(indicators) { + let additionalParams = { + type: 'patient-list', + indicators: indicators + }; - for (let i = 0; i < results.length; i++) { - if (results[i].results && results[i].results.results && results[i].results.results.results) { + let that = this; + return new Promise((resolve, reject) => { + this.generateReport(additionalParams) + .then((results) => { + for (let i = 0; i < results.length; i++) { + if ( + results[i].results && + results[i].results.results && + results[i].results.results.results + ) { + let datta = this.interprateCurrentArvMeds( + results[i].results.results.results + ); - let datta = this.interprateCurrentArvMeds(results[i].results.results.results); - - resolve({ - result: datta, - queriesAndSchemas: results[i], - indicators: indicators, - size: that.params.limit, - startIndex: that.params.startIndex, - allResults: results - }); - break; - } - } - reject('Patientlist error:', results); - }).catch((err) => { - console.error('Patientlist Error', err); - reject(err); - }); + resolve({ + result: datta, + queriesAndSchemas: results[i], + indicators: indicators, + size: that.params.limit, + startIndex: that.params.startIndex, + allResults: results + }); + break; + } + } + reject('Patientlist error:', results); + }) + .catch((err) => { + console.error('Patientlist Error', err); + reject(err); }); - } + }); + } - transformedPatientlistResults(results){ - return _.reduce(results, helpers.getARVNames(results.cur_arv_meds) ); + transformedPatientlistResults(results) { + return _.reduce(results, helpers.getARVNames(results.cur_arv_meds)); + } - } - - interprateCurrentArvMeds(result) { - let transformedResults = []; - - result.forEach((element) => { - let dataObject = {}; - dataObject['gender'] = element.gender, - dataObject['birthdate'] = element.birthdate, - dataObject['age'] = element.age, - dataObject['person_id'] = element.person_id, - dataObject['location_uuid'] = element.location_uuid, - dataObject['location'] = element.location, - dataObject['location_id'] = element.location_id, - dataObject['cur_arv_meds'] = helpers.getARVNames(element.cur_arv_meds), - dataObject['enrollment_date'] = element.enrollment_date, - dataObject['arv_first_regimen_start_date'] = element.arv_first_regimen_start_date, - dataObject['cur_regimen_arv_start_date'] = element.cur_regimen_arv_start_date, - dataObject['cur_arv_line'] = element.cur_arv_line, - dataObject['vl_1'] = element.vl_1, - dataObject['vl_1_date'] = element.vl_1_date, - dataObject['age_range'] = element.age_range, - dataObject['enrolled_this_month'] = element.enrolled_this_month, - dataObject['art_revisit_this_month'] = element.art_revisit_this_month, - dataObject['current_in_care'] = element.current_in_care, - dataObject['pre_art'] = element.pre_art, - dataObject['started_art_pregnant'] = element.started_art_pregnant, - dataObject['started_art_and_has_tb'] = element.started_art_and_has_tb, - dataObject['active_on_art'] = element.active_on_art, - dataObject['on_ctx_prophylaxis'] = element.on_ctx_prophylaxis, - dataObject['current_on_art'] = element.current_on_art, - dataObject['screened_for_tb'] = element.screened_for_tb, - dataObject['screened_for_tb_blue'] = element.screened_for_tb_blue, - dataObject['tb_screened_positive'] = element.tb_screened_positive, - dataObject['screened_for_cervical_ca'] = element.screened_for_cervical_ca, - dataObject['started_ipt'] = element.started_ipt, - dataObject['completed_ipt_past_12_months'] = element.completed_ipt_past_12_months, - dataObject['condoms_provided'] = element.condoms_provided, - dataObject['age_rstarted_modern_contraceptionange'] = element.started_modern_contraception, - dataObject['on_modern_contraception'] = element.on_modern_contraception, - dataObject['scheduled_visits'] = element.scheduled_visits, - dataObject['unscheduled_visits'] = element.unscheduled_visits, - dataObject['total_visits'] = element.total_visits, - dataObject['f_gte_18_visits'] = element.f_gte_18_visits, - dataObject['patient_uuid'] = element.patient_uuid, - dataObject['uuid'] = element.uuid, - dataObject['person_name'] = element.person_name, - dataObject['identifiers'] = element.identifiers, - dataObject['phone_number'] = element.phone_number, - dataObject['latest_rtc_date'] = element.latest_rtc_date, - dataObject['latest_vl'] = element.latest_vl, - dataObject['latest_vl_date'] = element.latest_vl_date, - dataObject['last_appointment'] = element.last_appointment, - dataObject['previous_vl'] = element.previous_vl, - dataObject['previous_vl_date'] = element.previous_vl_date, - dataObject['nearest_center'] = element.nearest_center + interprateCurrentArvMeds(result) { + let transformedResults = []; - const finalObj = Object.assign(element,dataObject); + result.forEach((element) => { + let dataObject = {}; + (dataObject['gender'] = element.gender), + (dataObject['birthdate'] = element.birthdate), + (dataObject['age'] = element.age), + (dataObject['person_id'] = element.person_id), + (dataObject['location_uuid'] = element.location_uuid), + (dataObject['location'] = element.location), + (dataObject['location_id'] = element.location_id), + (dataObject['cur_arv_meds'] = helpers.getARVNames( + element.cur_arv_meds + )), + (dataObject['enrollment_date'] = element.enrollment_date), + (dataObject['arv_first_regimen_start_date'] = + element.arv_first_regimen_start_date), + (dataObject['cur_regimen_arv_start_date'] = + element.cur_regimen_arv_start_date), + (dataObject['cur_arv_line'] = element.cur_arv_line), + (dataObject['vl_1'] = element.vl_1), + (dataObject['vl_1_date'] = element.vl_1_date), + (dataObject['age_range'] = element.age_range), + (dataObject['enrolled_this_month'] = element.enrolled_this_month), + (dataObject['art_revisit_this_month'] = element.art_revisit_this_month), + (dataObject['current_in_care'] = element.current_in_care), + (dataObject['pre_art'] = element.pre_art), + (dataObject['started_art_pregnant'] = element.started_art_pregnant), + (dataObject['started_art_and_has_tb'] = element.started_art_and_has_tb), + (dataObject['active_on_art'] = element.active_on_art), + (dataObject['on_ctx_prophylaxis'] = element.on_ctx_prophylaxis), + (dataObject['current_on_art'] = element.current_on_art), + (dataObject['screened_for_tb'] = element.screened_for_tb), + (dataObject['screened_for_tb_blue'] = element.screened_for_tb_blue), + (dataObject['tb_screened_positive'] = element.tb_screened_positive), + (dataObject['screened_for_cervical_ca'] = + element.screened_for_cervical_ca), + (dataObject['started_ipt'] = element.started_ipt), + (dataObject['completed_ipt_past_12_months'] = + element.completed_ipt_past_12_months), + (dataObject['condoms_provided'] = element.condoms_provided), + (dataObject['age_rstarted_modern_contraceptionange'] = + element.started_modern_contraception), + (dataObject['on_modern_contraception'] = + element.on_modern_contraception), + (dataObject['scheduled_visits'] = element.scheduled_visits), + (dataObject['unscheduled_visits'] = element.unscheduled_visits), + (dataObject['total_visits'] = element.total_visits), + (dataObject['f_gte_18_visits'] = element.f_gte_18_visits), + (dataObject['patient_uuid'] = element.patient_uuid), + (dataObject['uuid'] = element.uuid), + (dataObject['person_name'] = element.person_name), + (dataObject['identifiers'] = element.identifiers), + (dataObject['phone_number'] = element.phone_number), + (dataObject['latest_rtc_date'] = element.latest_rtc_date), + (dataObject['latest_vl'] = element.latest_vl), + (dataObject['latest_vl_date'] = element.latest_vl_date), + (dataObject['last_appointment'] = element.last_appointment), + (dataObject['previous_vl'] = element.previous_vl), + (dataObject['previous_vl_date'] = element.previous_vl_date), + (dataObject['nearest_center'] = element.nearest_center); - transformedResults.push(finalObj); - }) - return transformedResults; + const finalObj = Object.assign(element, dataObject); - } + transformedResults.push(finalObj); + }); + return transformedResults; + } - getReportHandler(reportName, params) { - return new PatientlistMysqlReport(reportName, params); - } + getReportHandler(reportName, params) { + return new PatientlistMysqlReport(reportName, params); + } - runSingleReport(reportObject, additionalParams) { - if (additionalParams && additionalParams.type === 'patient-list') { - return reportObject.generatePatientListReport(additionalParams.indicators); - } - return reportObject.generateReport(); + runSingleReport(reportObject, additionalParams) { + if (additionalParams && additionalParams.type === 'patient-list') { + return reportObject.generatePatientListReport( + additionalParams.indicators + ); } + return reportObject.generateReport(); + } } diff --git a/app/reporting-framework/multi-dataset.report.js b/app/reporting-framework/multi-dataset.report.js index abc1c8008..a61c9bbcc 100755 --- a/app/reporting-framework/multi-dataset.report.js +++ b/app/reporting-framework/multi-dataset.report.js @@ -1,102 +1,101 @@ -import { - Promise -} from 'bluebird'; -import { - BaseMysqlReport -} from './base-mysql.report'; +import { Promise } from 'bluebird'; +import { BaseMysqlReport } from './base-mysql.report'; export class MultiDatasetReport extends BaseMysqlReport { - constructor(reportName, params) { - super(reportName, params); - } + constructor(reportName, params) { + super(reportName, params); + } - generateReport(additionalParams) { - const that = this; - return new Promise((resolve, reject) => { - that._fetchAndInitReports() - .then((handlers) => { - that.executeReportHandlers(that.reportHandlers, additionalParams) - .then((results) => { - resolve(results); - }) - .catch((err) => { - reject(err); - }) - }) - .catch((err) => { - reject(err); - }) - }); - } - - _fetchAndInitReports() { - const that = this; - return new Promise((resolve, reject) => { - that.fetchReportSchema(that.reportName) - .then((reportSchemas) => { - that.reportSchemas = reportSchemas; - that._intializeReportHandlers(); - resolve(that.reportHandlers); - }) - .catch((err) => { - reject(err); - }); + generateReport(additionalParams) { + const that = this; + return new Promise((resolve, reject) => { + that + ._fetchAndInitReports() + .then((handlers) => { + that + .executeReportHandlers(that.reportHandlers, additionalParams) + .then((results) => { + resolve(results); + }) + .catch((err) => { + reject(err); + }); + }) + .catch((err) => { + reject(err); }); + }); + } - } - - _intializeReportHandlers() { - let that = this; - let handlers = []; - this.reportSchemas.main.reports.forEach(report => { - handlers.push(this.getReportHandler(report, that.params)); + _fetchAndInitReports() { + const that = this; + return new Promise((resolve, reject) => { + that + .fetchReportSchema(that.reportName) + .then((reportSchemas) => { + that.reportSchemas = reportSchemas; + that._intializeReportHandlers(); + resolve(that.reportHandlers); + }) + .catch((err) => { + reject(err); }); - that.reportHandlers = handlers; - } + }); + } + _intializeReportHandlers() { + let that = this; + let handlers = []; + this.reportSchemas.main.reports.forEach((report) => { + handlers.push(this.getReportHandler(report, that.params)); + }); + that.reportHandlers = handlers; + } + runSingleReport(reportObject, additionalParams) { + return reportObject.generateReport(); + } - runSingleReport(reportObject, additionalParams) { - return reportObject.generateReport(); - } + executeReportHandlers(reportHandlers, additionalParams) { + let that = this; - executeReportHandlers(reportHandlers, additionalParams) { - let that = this; + return new Promise((resolve, reject) => { + let results = []; - return new Promise((resolve, reject) => { - let results = []; - - Promise.reduce(reportHandlers, (previous, currentReport) => { - return new Promise((res, rej) => { - that.runSingleReport(currentReport, additionalParams) - .then((result) => { - let toAdd = results.push({ - report: currentReport, - results: result - }); - res(toAdd); - }). - catch((err) => { - console.error('Error occured while fetching report', err); - let toAdd = results.push({ - report: currentReport, - error: err - }); - res(toAdd); - }); - }) - }, 0) - .then((res) => { - resolve(results); - }) - .catch((err) => { - reject(err); + Promise.reduce( + reportHandlers, + (previous, currentReport) => { + return new Promise((res, rej) => { + that + .runSingleReport(currentReport, additionalParams) + .then((result) => { + let toAdd = results.push({ + report: currentReport, + results: result }); - + res(toAdd); + }) + .catch((err) => { + console.error('Error occured while fetching report', err); + let toAdd = results.push({ + report: currentReport, + error: err + }); + res(toAdd); + }); + }); + }, + 0 + ) + .then((res) => { + resolve(results); }) - } - - getReportHandler(reportName, params) { - return new BaseMysqlReport(reportName, params); - } + .catch((err) => { + reject(err); + }); + }); + } -} \ No newline at end of file + getReportHandler(reportName, params) { + return new BaseMysqlReport(reportName, params); + } +} diff --git a/app/reporting-framework/patient-flow.report.js b/app/reporting-framework/patient-flow.report.js index 858ddd849..b90f2f19b 100644 --- a/app/reporting-framework/patient-flow.report.js +++ b/app/reporting-framework/patient-flow.report.js @@ -1,27 +1,29 @@ -import { - BaseMysqlReport -} from './base-mysql.report'; -import * as etlProcessors from '../../etl-processors.js' +import { BaseMysqlReport } from './base-mysql.report'; +import * as etlProcessors from '../../etl-processors.js'; var _ = require('underscore'); export class PatientFlowReport extends BaseMysqlReport { - constructor(reportName, params) { - super('patientFlow', params); - } - generateReport() { - let that = this; - return super.generateReport().then(results => { - try { - let finalResult = etlProcessors.processPatientFlow(that.params.indicators, { - result: results.results.results - }, that.params.indicators); - finalResult.schemas = results.schemas; - finalResult.sqlQuery = results.sqlQuery; - results = finalResult; - } catch (error) { - console.log('Error', error); - return error; - } - return results; - }); - } -} \ No newline at end of file + constructor(reportName, params) { + super('patientFlow', params); + } + generateReport() { + let that = this; + return super.generateReport().then((results) => { + try { + let finalResult = etlProcessors.processPatientFlow( + that.params.indicators, + { + result: results.results.results + }, + that.params.indicators + ); + finalResult.schemas = results.schemas; + finalResult.sqlQuery = results.sqlQuery; + results = finalResult; + } catch (error) { + console.log('Error', error); + return error; + } + return results; + }); + } +} diff --git a/app/reporting-framework/patientlist-mysql.report.js b/app/reporting-framework/patientlist-mysql.report.js index 39d4ad753..867c65731 100755 --- a/app/reporting-framework/patientlist-mysql.report.js +++ b/app/reporting-framework/patientlist-mysql.report.js @@ -4,262 +4,318 @@ import { Promise } from 'bluebird'; import { BaseMysqlReport } from './base-mysql.report'; export class PatientlistMysqlReport extends BaseMysqlReport { - constructor(reportName, params) { - super(reportName, params); - } - - generatePatientListReport(indicators) { - // 1. Fetch report schema - // 2. Determine the aggregate, base - // 3. Fetch the template report - // 4. Generate patient list json query - // 5. Generate report sql using json2sql - // 6. Execute sql statement using sql generator - const that = this; - return new Promise((resolve, error) => { - // fetch reports - that.fetchReportSchema(that.reportName) - .then((reportSchemas) => { - that.reportSchemas = reportSchemas; - // consolidate params and indicators - indicators = that.consolidateParamsAndIndicators(that.params, indicators); - - // determine patient list seed schemas - let aggs = this.determineBaseAndAggrSchema(that.reportSchemas, indicators); - if (aggs.length > 0) { - // console.log('Potential schemas with supplied indicators', aggs.length); - that.plSchemasRaw = this.determineBaseAndAggrSchema(that.reportSchemas, indicators)[0]; - } - if (that.plSchemasRaw && that.plSchemasRaw.aggregate && that.plSchemasRaw.base) { - - that.fetchPatientListTemplate(that.plSchemasRaw.aggregate) - .then((template) => { - that.plTemplate = template.main; - - - let generated = - that.generatePatientListJsonQuery(that.plSchemasRaw.aggregate, that.plSchemasRaw.base, that.plTemplate, that.params); - // console.log('GENERATED', generated.generated.filters, that.params); - // if (this.hasEmptyDynamicExpressions(generated) && aggs.length > 1) { - // for (let i = 1; i < aggs.length; i++) { - // that.plSchemasRaw = this.determineBaseAndAggrSchema(that.reportSchemas, indicators)[i]; - // generated = - // that.generatePatientListJsonQuery(that.plSchemasRaw.aggregate, that.plSchemasRaw.base, - // that.plTemplate, that.params); - // if (!this.hasEmptyDynamicExpressions(generated)) { - // break; - // } - // } - - // } - // let aggregateDatasets = that.fetchReportSchema(that.reportSchemas); - - // assign all reports - that.generatedPL = { - main: generated.generated - }; - let combined = Object.assign(that.reportSchemas,that.generatedPL) - that.generatedPL = combined; - - // console.log('Potential schemas with supplied indicators', JSON.stringify(combined)); - that.modifiedParam = generated.params; - // generate query - that.generateReportQuery(that.generatedPL, that.modifiedParam) - .then((sqlQuery) => { - //allow 'null' as parameter value - sqlQuery=sqlQuery.replace(/\'null\'/g,"null"); - that.reportQuery = sqlQuery; - // run query - - that.executeReportQuery(that.reportQuery) - .then((results) => { - that.queryResults = results; - resolve({ - schemas: that.reportSchemas, - generatedSchemas: that.generatedPL, - sqlQuery: that.reportQuery, - results: that.queryResults - }); - }) - .catch((err) => { - console.error(that.reportQuery); - error(err); - }); - - }) - .catch((err) => { - error(err); - }); - }) - .catch((err) => { - console.error('Error fetching patientlist template', err); - error(err); - }); - } else { - error('Not a patientlist report'); - } - }) - .catch((err) => { + constructor(reportName, params) { + super(reportName, params); + } + + generatePatientListReport(indicators) { + // 1. Fetch report schema + // 2. Determine the aggregate, base + // 3. Fetch the template report + // 4. Generate patient list json query + // 5. Generate report sql using json2sql + // 6. Execute sql statement using sql generator + const that = this; + return new Promise((resolve, error) => { + // fetch reports + that + .fetchReportSchema(that.reportName) + .then((reportSchemas) => { + that.reportSchemas = reportSchemas; + // consolidate params and indicators + indicators = that.consolidateParamsAndIndicators( + that.params, + indicators + ); + + // determine patient list seed schemas + let aggs = this.determineBaseAndAggrSchema( + that.reportSchemas, + indicators + ); + if (aggs.length > 0) { + // console.log('Potential schemas with supplied indicators', aggs.length); + that.plSchemasRaw = this.determineBaseAndAggrSchema( + that.reportSchemas, + indicators + )[0]; + } + if ( + that.plSchemasRaw && + that.plSchemasRaw.aggregate && + that.plSchemasRaw.base + ) { + that + .fetchPatientListTemplate(that.plSchemasRaw.aggregate) + .then((template) => { + that.plTemplate = template.main; + + let generated = that.generatePatientListJsonQuery( + that.plSchemasRaw.aggregate, + that.plSchemasRaw.base, + that.plTemplate, + that.params + ); + // console.log('GENERATED', generated.generated.filters, that.params); + // if (this.hasEmptyDynamicExpressions(generated) && aggs.length > 1) { + // for (let i = 1; i < aggs.length; i++) { + // that.plSchemasRaw = this.determineBaseAndAggrSchema(that.reportSchemas, indicators)[i]; + // generated = + // that.generatePatientListJsonQuery(that.plSchemasRaw.aggregate, that.plSchemasRaw.base, + // that.plTemplate, that.params); + // if (!this.hasEmptyDynamicExpressions(generated)) { + // break; + // } + // } + + // } + // let aggregateDatasets = that.fetchReportSchema(that.reportSchemas); + + // assign all reports + that.generatedPL = { + main: generated.generated + }; + let combined = Object.assign( + that.reportSchemas, + that.generatedPL + ); + that.generatedPL = combined; + + // console.log('Potential schemas with supplied indicators', JSON.stringify(combined)); + that.modifiedParam = generated.params; + // generate query + that + .generateReportQuery(that.generatedPL, that.modifiedParam) + .then((sqlQuery) => { + //allow 'null' as parameter value + sqlQuery = sqlQuery.replace(/\'null\'/g, 'null'); + that.reportQuery = sqlQuery; + // run query + + that + .executeReportQuery(that.reportQuery) + .then((results) => { + that.queryResults = results; + resolve({ + schemas: that.reportSchemas, + generatedSchemas: that.generatedPL, + sqlQuery: that.reportQuery, + results: that.queryResults + }); + }) + .catch((err) => { + console.error(that.reportQuery); + error(err); + }); + }) + .catch((err) => { error(err); - }) + }); + }) + .catch((err) => { + console.error('Error fetching patientlist template', err); + error(err); + }); + } else { + error('Not a patientlist report'); + } + }) + .catch((err) => { + error(err); }); + }); + } + + fetchPatientListTemplate(aggregateReport) { + if ( + aggregateReport.dynamicJsonQueryGenerationDirectives && + aggregateReport.dynamicJsonQueryGenerationDirectives + .patientListGenerator && + aggregateReport.dynamicJsonQueryGenerationDirectives.patientListGenerator + .useTemplate + ) { + let name = + aggregateReport.dynamicJsonQueryGenerationDirectives + .patientListGenerator.useTemplate; + let version = + aggregateReport.dynamicJsonQueryGenerationDirectives + .patientListGenerator.useTemplateVersion; + return this.fetchReportSchema(name, version); } - - fetchPatientListTemplate(aggregateReport) { - if (aggregateReport.dynamicJsonQueryGenerationDirectives && - aggregateReport.dynamicJsonQueryGenerationDirectives.patientListGenerator && - aggregateReport.dynamicJsonQueryGenerationDirectives.patientListGenerator.useTemplate) { - let name = aggregateReport.dynamicJsonQueryGenerationDirectives.patientListGenerator.useTemplate; - let version = aggregateReport.dynamicJsonQueryGenerationDirectives.patientListGenerator.useTemplateVersion; - return this.fetchReportSchema(name, version); + // console.log('Invalid aggregate report. Missing template directives.') + return Promise.reject( + 'Invalid aggregate report. Missing template directives.' + ); + } + + determineBaseAndAggrSchema(schemas, indicators) { + // console.log('finding aggregate report with indicators', indicators); + let aggs = this.getAggregateWithIndicator(schemas, indicators); + + let found = []; + + aggs.forEach((agg) => { + let s = { + aggregate: agg, + base: schemas[agg.uses[0].name] + }; + // console.log('added base agg pair', agg); + found.push(s); + }); + return found; + } + + getAggregateWithIndicator(schemas, indicators) { + let found = []; + for (let s in schemas) { + // console.log('schema:',schemas[s]); + if (schemas[s].dynamicJsonQueryGenerationDirectives) { + if (this.schemaHasColumns(schemas[s], indicators)) { + found.push(schemas[s]); } - // console.log('Invalid aggregate report. Missing template directives.') - return Promise.reject('Invalid aggregate report. Missing template directives.'); + } } - - determineBaseAndAggrSchema(schemas, indicators) { - // console.log('finding aggregate report with indicators', indicators); - let aggs = this.getAggregateWithIndicator(schemas, indicators); - - let found = []; - - aggs.forEach(agg => { - let s = { - aggregate: agg, - base: schemas[agg.uses[0].name] - }; - // console.log('added base agg pair', agg); - found.push(s); - }); - return found; - } - - getAggregateWithIndicator(schemas, indicators) { - let found = []; - for (let s in schemas) { - // console.log('schema:',schemas[s]); - if (schemas[s].dynamicJsonQueryGenerationDirectives) { - if (this.schemaHasColumns(schemas[s], indicators)) { - found.push(schemas[s]); - } - } + // console.log('found with agg indicator', found); + return found; + } + + schemaHasColumns(schema, columns) { + // console.log('schema has columns', schema, columns); + let foundAll = true; + if (columns && columns.forEach) { + columns.forEach((column) => { + let found = false; + for (let i = 0; i < schema.columns.length; i++) { + let col = schema.columns[i]; + + if ( + col.alias === column || + col.column === column || + (typeof col.column === 'string' && + col.column.slice(col.column.indexOf('.') + 1)) === column + ) { + // console.log('found', column, col); + found = true; + break; + } } - // console.log('found with agg indicator', found); - return found; - } - - schemaHasColumns(schema, columns) { - // console.log('schema has columns', schema, columns); - let foundAll = true; - if (columns && columns.forEach) { - columns.forEach(column => { - let found = false; - for (let i = 0; i < schema.columns.length; i++) { - let col = schema.columns[i]; - if (col.alias === column || col.column === column || - (typeof col.column === 'string' && - col.column.slice(col.column.indexOf('.') + 1)) === column) { - // console.log('found', column, col); - found = true; - break; - } - } - - if (!found) { - foundAll = false; - } - }); - } else { - foundAll = false; + if (!found) { + foundAll = false; } - - return foundAll; + }); + } else { + foundAll = false; } - generatePatientListJsonQuery(aggregateSchema, baseSchema, tempateSchema, params) { - let gen = this.getPatientListGenerator(aggregateSchema, baseSchema, tempateSchema, params); - return gen.generatePatientListSchema(); - } - - getPatientListGenerator(aggregateSchema, baseSchema, tempateSchema, params) { - return new BasePatientListGen(baseSchema, aggregateSchema, tempateSchema, params); - } - - consolidateParamsAndIndicators(params, indicators) { - let consolidatedIndicators = []; - indicators.forEach(indicator => { - let generatedParams = []; - if (this.isDynamicallyCreatedIndicator(indicator)) { - let extracted = this.extractIndicators(indicator); - for (let o in extracted) { - generatedParams.push({ key: o, value: extracted[o] }) - consolidatedIndicators.push(o); - } - } else { - generatedParams.push({ key: indicator, value: 1 }); - consolidatedIndicators.push(indicator); - } - - generatedParams.forEach(paramValue => { - if (params[paramValue.key] === undefined || params[paramValue.key] === null) { - params[paramValue.key] = paramValue.value === null ? 1 : paramValue.value; - } - }); - }); - return consolidatedIndicators; - } - - addIndicatorsToParams(param, indicators) { - indicators.forEach(element => { - if (param[element] === undefined) { - param[element] = 1; - } - }); - } - - extractIndicators(indicator) { - let split = indicator.split('__'); - - let indicators = { - - }; - - for (let i = 1; i < split.length; i++) { - if (this.isEven(i)) { - indicators[split[i - 1]] = split[i]; - } else { - indicators[split[i]] = null; - } + return foundAll; + } + + generatePatientListJsonQuery( + aggregateSchema, + baseSchema, + tempateSchema, + params + ) { + let gen = this.getPatientListGenerator( + aggregateSchema, + baseSchema, + tempateSchema, + params + ); + return gen.generatePatientListSchema(); + } + + getPatientListGenerator(aggregateSchema, baseSchema, tempateSchema, params) { + return new BasePatientListGen( + baseSchema, + aggregateSchema, + tempateSchema, + params + ); + } + + consolidateParamsAndIndicators(params, indicators) { + let consolidatedIndicators = []; + indicators.forEach((indicator) => { + let generatedParams = []; + if (this.isDynamicallyCreatedIndicator(indicator)) { + let extracted = this.extractIndicators(indicator); + for (let o in extracted) { + generatedParams.push({ key: o, value: extracted[o] }); + consolidatedIndicators.push(o); } - - return indicators; + } else { + generatedParams.push({ key: indicator, value: 1 }); + consolidatedIndicators.push(indicator); + } + + generatedParams.forEach((paramValue) => { + if ( + params[paramValue.key] === undefined || + params[paramValue.key] === null + ) { + params[paramValue.key] = + paramValue.value === null ? 1 : paramValue.value; + } + }); + }); + return consolidatedIndicators; + } + + addIndicatorsToParams(param, indicators) { + indicators.forEach((element) => { + if (param[element] === undefined) { + param[element] = 1; + } + }); + } + + extractIndicators(indicator) { + let split = indicator.split('__'); + + let indicators = {}; + + for (let i = 1; i < split.length; i++) { + if (this.isEven(i)) { + indicators[split[i - 1]] = split[i]; + } else { + indicators[split[i]] = null; + } } - // hack to take care of mis-matched schemas for an indicator - hasEmptyDynamicExpressions(generated) { - let hasEmpty = false; - if (generated.generated.filters && generated.generated.filters.conditions.length > 0) { - generated.generated.filters.conditions.forEach(condition => { - if (condition.dynamicallyGenerated && - condition.filterType === 'tableColumns' && - condition.conditionExpression === '') { - hasEmpty = true; - } - }); + return indicators; + } + + // hack to take care of mis-matched schemas for an indicator + hasEmptyDynamicExpressions(generated) { + let hasEmpty = false; + if ( + generated.generated.filters && + generated.generated.filters.conditions.length > 0 + ) { + generated.generated.filters.conditions.forEach((condition) => { + if ( + condition.dynamicallyGenerated && + condition.filterType === 'tableColumns' && + condition.conditionExpression === '' + ) { + hasEmpty = true; } - return hasEmpty; + }); } + return hasEmpty; + } - isEven(n) { - return n % 2 == 0; - } + isEven(n) { + return n % 2 == 0; + } - isOdd(n) { - return Math.abs(n % 2) == 1; - } + isOdd(n) { + return Math.abs(n % 2) == 1; + } - isDynamicallyCreatedIndicator(indicator) { - return indicator.startsWith('dc__'); - } -} \ No newline at end of file + isDynamicallyCreatedIndicator(indicator) { + return indicator.startsWith('dc__'); + } +} diff --git a/app/reporting-framework/report-processor-helpers.service.js b/app/reporting-framework/report-processor-helpers.service.js index 2084fa3ca..4c569fe00 100755 --- a/app/reporting-framework/report-processor-helpers.service.js +++ b/app/reporting-framework/report-processor-helpers.service.js @@ -1,65 +1,87 @@ -import mergeByKey from "array-merge-by-key"; +import mergeByKey from 'array-merge-by-key'; const _ = require('lodash'); _.mixin({ - /* - * @groupByComposite - * - * Groups an array of objects by multiple properties. Uses _.groupBy under the covers, - * to group by a composite key, generated from the list of provided keys. - * - * @param {Object[]} collection - the array of objects. - * @param {string[]} keys - one or more property names to group by. - * @param {string} [delimiter=-] - a delimiter used in the creation of the composite key. - * - * @returns {Object} - the composed aggregate object. - */ - groupByComposite: (collection, keys, delimiter = '__') => - _.groupBy(collection, (item) => { - const compositeKey = []; - _.each(keys, key => compositeKey.push(`${key}__${item[key]}`)); - return compositeKey.join(delimiter); - }), + /* + * @groupByComposite + * + * Groups an array of objects by multiple properties. Uses _.groupBy under the covers, + * to group by a composite key, generated from the list of provided keys. + * + * @param {Object[]} collection - the array of objects. + * @param {string[]} keys - one or more property names to group by. + * @param {string} [delimiter=-] - a delimiter used in the creation of the composite key. + * + * @returns {Object} - the composed aggregate object. + */ + groupByComposite: (collection, keys, delimiter = '__') => + _.groupBy(collection, (item) => { + const compositeKey = []; + _.each(keys, (key) => compositeKey.push(`${key}__${item[key]}`)); + return compositeKey.join(delimiter); + }) }); export default class ReportProcessorHelpersService { - tranform(data, options) { - const initialGrouped = this.groupBy(data, options.joinColumn, options.joinColumn, 'children'); - let result = []; - for (let w of initialGrouped) { - let grouped = _.groupByComposite(w.children, options.use); - let final = {}; - for (let p in grouped) { - let group = grouped[p]; - for (let g of group) { - for (let i in g) { - if (!(options.use.includes(i) || options.joinColumn.includes(i) || options.skip.includes(i))) { - let dc = '' - if (p) { - dc = `dc__${p}__` - } - final[`${dc}${i}`] = g[i]; - } else if (options.joinColumn.includes(i) || options.skip.includes(i)) { - final[`${i}`] = g[i]; - } - } - } + tranform(data, options) { + const initialGrouped = this.groupBy( + data, + options.joinColumn, + options.joinColumn, + 'children' + ); + let result = []; + for (let w of initialGrouped) { + let grouped = _.groupByComposite(w.children, options.use); + let final = {}; + for (let p in grouped) { + let group = grouped[p]; + for (let g of group) { + for (let i in g) { + if ( + !( + options.use.includes(i) || + options.joinColumn.includes(i) || + options.skip.includes(i) + ) + ) { + let dc = ''; + if (p) { + dc = `dc__${p}__`; + } + final[`${dc}${i}`] = g[i]; + } else if ( + options.joinColumn.includes(i) || + options.skip.includes(i) + ) { + final[`${i}`] = g[i]; } - result.push(final); + } } - return result; + } + result.push(final); } + return result; + } - joinDataSets(joinColumn, dataset1, dataset2) { - return mergeByKey(joinColumn, dataset1, dataset2); - } + joinDataSets(joinColumn, dataset1, dataset2) { + return mergeByKey(joinColumn, dataset1, dataset2); + } - groupBy(dataToGroupOn, fieldNameToGroupOn, fieldNameForGroupName, fieldNameForChildren) { - let result = _.chain(dataToGroupOn) - .groupBy(fieldNameToGroupOn) - .toPairs() - .map(function (currentItem) { - return _.zipObject([fieldNameForGroupName, fieldNameForChildren], currentItem); - }) - .value(); - return result; - } -} \ No newline at end of file + groupBy( + dataToGroupOn, + fieldNameToGroupOn, + fieldNameForGroupName, + fieldNameForChildren + ) { + let result = _.chain(dataToGroupOn) + .groupBy(fieldNameToGroupOn) + .toPairs() + .map(function (currentItem) { + return _.zipObject( + [fieldNameForGroupName, fieldNameForChildren], + currentItem + ); + }) + .value(); + return result; + } +} diff --git a/app/routes/case-management.route.js b/app/routes/case-management.route.js index 916aad6a7..b02e0042b 100644 --- a/app/routes/case-management.route.js +++ b/app/routes/case-management.route.js @@ -1,200 +1,209 @@ var authorizer = require('../../authorization/etl-authorizer'); var privileges = authorizer.getAllPrivileges(); -var caseManagementData = require('../case-management/case-management') +var caseManagementData = require('../case-management/case-management'); var definitions = require('../case-management/case-management-indicator-service'); const routes = [ - { - method: 'GET', - path: '/etl/case-management', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let params = { - minDefaultPeriod: request.query.minDefaultPeriod, - maxDefaultPeriod: request.query.maxDefaultPeriod, - minFollowupPeriod: request.query.minFollowupPeriod, - maxFollowupPeriod: request.query.maxFollowupPeriod, - rtcStartDate: request.query.rtcStartDate, - rtcEndDate: request.query.rtcEndDate, - phoneFollowUpStartDate: request.query.phoneFollowUpStartDate, - locationUuid: request.query.locationUuid, - hasCaseManager: request.query.hasCaseManager, - hasPhoneRTC: request.query.hasPhoneRTC, - elevatedVL: request.query.elevatedVL, - dueForVl: request.query.dueForVl, - caseManagerUserId: request.query.caseManagerUserId, - isNewlyEnrolled: request.query.isNewlyEnrolled, - startIndex: request.query.startIndex, - limit: request.query.limit - } - caseManagementData.getCaseManagementData(params, - (result) => { - if (result.error) { - reply(result); - } else { - reply(result); - } - }) - }, - description: 'Case Management Data', - notes: 'Returns patient list', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + { + method: 'GET', + path: '/etl/case-management', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient } - }, - { - method: 'GET', - path: '/etl/case-managers', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let params = { - locationUuid: request.query.locationUuid - } - caseManagementData.getCaseManagers(params).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: 'List of case management providers filtered by locations', - notes: 'Returns providers list', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + }, + handler: function (request, reply) { + let params = { + minDefaultPeriod: request.query.minDefaultPeriod, + maxDefaultPeriod: request.query.maxDefaultPeriod, + minFollowupPeriod: request.query.minFollowupPeriod, + maxFollowupPeriod: request.query.maxFollowupPeriod, + rtcStartDate: request.query.rtcStartDate, + rtcEndDate: request.query.rtcEndDate, + phoneFollowUpStartDate: request.query.phoneFollowUpStartDate, + locationUuid: request.query.locationUuid, + hasCaseManager: request.query.hasCaseManager, + hasPhoneRTC: request.query.hasPhoneRTC, + elevatedVL: request.query.elevatedVL, + dueForVl: request.query.dueForVl, + caseManagerUserId: request.query.caseManagerUserId, + isNewlyEnrolled: request.query.isNewlyEnrolled, + startIndex: request.query.startIndex, + limit: request.query.limit + }; + caseManagementData.getCaseManagementData(params, (result) => { + if (result.error) { + reply(result); + } else { + reply(result); + } + }); + }, + description: 'Case Management Data', + notes: 'Returns patient list', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/case-managers', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient } - }, - { - method: 'POST', - path: '/etl/assign-patients', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let payload = { - patients: request.payload.patients, - caseManagers: request.payload.caseManagers - } - caseManagementData.assignPatientsToCaseManagers(payload).then((result) => { - let response = {} - if (result.length > 0) { - response = { - type: 'Error', - code: 500, - body: result - } - } else { - response = { - type: 'Success', - code: 200, - message: "All patients successfully assigned", - } - } - reply(response); - }).catch((error) => { - reply(error); - }); - }, - description: 'Used for massive asignments of patients to case managers', - notes: 'Returns assignment response', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + }, + handler: function (request, reply) { + let params = { + locationUuid: request.query.locationUuid + }; + caseManagementData + .getCaseManagers(params) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'List of case management providers filtered by locations', + notes: 'Returns providers list', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'POST', + path: '/etl/assign-patients', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient } - }, - { - method: 'POST', - path: '/etl/unassign-patients', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let payload = { - patients: request.payload.patients - } - caseManagementData.unAssignPatients(payload.patients).then((result) => { - let response = {} - if (result.length > 0) { - response = { - type: 'Error', - code: 500, - body: result - } - } else { - response = { - type: 'Success', - code: 200, - message: "All patients were successfully unassigned", - } - } - reply(response); - }).catch((error) => { - reply(error); - }); - }, - description: 'Used for massive asignments of patients to case managers', - notes: 'Returns assignment response', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} + }, + handler: function (request, reply) { + let payload = { + patients: request.payload.patients, + caseManagers: request.payload.caseManagers + }; + caseManagementData + .assignPatientsToCaseManagers(payload) + .then((result) => { + let response = {}; + if (result.length > 0) { + response = { + type: 'Error', + code: 500, + body: result + }; + } else { + response = { + type: 'Success', + code: 200, + message: 'All patients successfully assigned' + }; } + reply(response); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Used for massive asignments of patients to case managers', + notes: 'Returns assignment response', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'POST', + path: '/etl/unassign-patients', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient } - }, - { - method: 'GET', - path: '/etl/case-management/indicators', - config: { - plugins: { - }, - handler: function (request, reply) { - definitions.getIndicatorDefinitions().then((result)=> { - reply(result); - }).catch((error) => { - reply(error) - }); - - }, - description: 'List of case management indicators and their definitions', - notes: 'Returns Case Management indicators', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} + }, + handler: function (request, reply) { + let payload = { + patients: request.payload.patients + }; + caseManagementData + .unAssignPatients(payload.patients) + .then((result) => { + let response = {}; + if (result.length > 0) { + response = { + type: 'Error', + code: 500, + body: result + }; + } else { + response = { + type: 'Success', + code: 200, + message: 'All patients were successfully unassigned' + }; } - } + reply(response); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Used for massive asignments of patients to case managers', + notes: 'Returns assignment response', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/case-management/indicators', + config: { + plugins: {}, + handler: function (request, reply) { + definitions + .getIndicatorDefinitions() + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'List of case management indicators and their definitions', + notes: 'Returns Case Management indicators', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } } -] + } +]; -exports.routes = server => server.route(routes); \ No newline at end of file +exports.routes = (server) => server.route(routes); diff --git a/app/routes/dqa-reports.route.js b/app/routes/dqa-reports.route.js index a830c1d6a..6d6c80b58 100644 --- a/app/routes/dqa-reports.route.js +++ b/app/routes/dqa-reports.route.js @@ -3,48 +3,52 @@ var authorizer = require('../../authorization/etl-authorizer'); var resolveLocationUuidToId = require('../../location/resolve-location-uuid-to-id'); var privileges = authorizer.getAllPrivileges(); const routes = [ - { - method: 'GET', - path: '/etl/dqa-chart-abstraction', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - if (request.query.locationUuids) { - resolveLocationUuidToId.resolveLocationUuidsParamsToIds(request.query) - .then((result) => { - let locations = result; - let limit = 300; - if (request.query.limit != null) { - limit = request.query.limit; - } - let offset = 0; - if (request.query.startIndex != null) { - offset = request.query.startIndex; - } + { + method: 'GET', + path: '/etl/dqa-chart-abstraction', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + resolveLocationUuidToId + .resolveLocationUuidsParamsToIds(request.query) + .then((result) => { + let locations = result; + let limit = 300; + if (request.query.limit != null) { + limit = request.query.limit; + } + let offset = 0; + if (request.query.startIndex != null) { + offset = request.query.startIndex; + } - let service = new DQAChartAbstractionService(); - service.getDQAChartAbstractionReport(locations, limit, offset).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }) - } - }, - description: 'Get DQA reports ', - notes: 'Returns DQA reports', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + let service = new DQAChartAbstractionService(); + service + .getDQAChartAbstractionReport(locations, limit, offset) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); } + }, + description: 'Get DQA reports ', + notes: 'Returns DQA reports', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } } -] -exports.routes = server => server.route(routes); \ No newline at end of file + } +]; +exports.routes = (server) => server.route(routes); diff --git a/app/routes/enhanced-adherence-program.route.js b/app/routes/enhanced-adherence-program.route.js index 6783b5847..d8da1c945 100644 --- a/app/routes/enhanced-adherence-program.route.js +++ b/app/routes/enhanced-adherence-program.route.js @@ -3,57 +3,62 @@ var privileges = authorizer.getAllPrivileges(); var helpers = require('../../etl-helpers'); var _ = require('underscore'); var moment = require('moment'); -import { - PatientlistMysqlReport -} from '../reporting-framework/patientlist-mysql.report'; -const routes = [{ +import { PatientlistMysqlReport } from '../reporting-framework/patientlist-mysql.report'; +const routes = [ + { method: 'GET', path: '/etl/enhanced-adherence-program/patient-list', config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let requestParams = Object.assign({}, request.query, request.params); - let locationUuids = request.query.locationUuids.split(',') - let indicators = []; - if (requestParams.indicators) { - indicators = requestParams.indicators.split(','); - } + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + let requestParams = Object.assign({}, request.query, request.params); + let locationUuids = request.query.locationUuids.split(','); + let indicators = []; + if (requestParams.indicators) { + indicators = requestParams.indicators.split(','); + } - if(!requestParams.lower_vl){ - requestParams.lower_vl = 401; + if (!requestParams.lower_vl) { + requestParams.lower_vl = 401; + } + requestParams.locationUuids = locationUuids; + requestParams.startDate = requestParams.startDate.split('T')[0]; + requestParams.endDate = requestParams.endDate.split('T')[0]; + let report = new PatientlistMysqlReport( + 'enhancedAdherenceHIVProgramAggregate', + requestParams + ); + report + .generatePatientListReport(indicators) + .then((result) => { + if (result.results.results.length > 0) { + _.each(result.results.results, (item) => { + item.cur_arv_meds_max = helpers.getARVNames(item.cur_meds); + item.vl_1_date = moment(item.vl_1_date).format('DD-MM-YYYY'); + }); + reply(result); + } else { + reply(result); } - requestParams.locationUuids = locationUuids; - requestParams.startDate = requestParams.startDate.split('T')[0]; - requestParams.endDate = requestParams.endDate.split('T')[0]; - let report = new PatientlistMysqlReport('enhancedAdherenceHIVProgramAggregate', requestParams); - report.generatePatientListReport(indicators).then((result) => { - if (result.results.results.length > 0) { - _.each(result.results.results, (item) => { - item.cur_arv_meds_max = helpers.getARVNames(item.cur_meds); - item.vl_1_date = moment(item.vl_1_date).format('DD-MM-YYYY'); - }); - reply(result); - } else { - reply(result); - } - - }).catch((error) => { - reply(error); - }); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get the medical history report', + notes: 'Returns the the medical history of the selected patient', + tags: ['api'], + validate: { + options: { + allowUnknown: true }, - description: "Get the medical history report", - notes: "Returns the the medical history of the selected patient", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + params: {} + } } -}] -exports.routes = server => server.route(routes); \ No newline at end of file + } +]; +exports.routes = (server) => server.route(routes); diff --git a/app/routes/oncology-integrated-program-snapshot.route.js b/app/routes/oncology-integrated-program-snapshot.route.js index 0a6ca2c72..e11cef601 100644 --- a/app/routes/oncology-integrated-program-snapshot.route.js +++ b/app/routes/oncology-integrated-program-snapshot.route.js @@ -1,30 +1,30 @@ -const authorizer = require("../../authorization/etl-authorizer"); +const authorizer = require('../../authorization/etl-authorizer'); const privileges = authorizer.getAllPrivileges(); -import { getOncologyIntegratedProgramSnapshot } from "../../service/oncology/patient-oncology-summary-service"; +import { getOncologyIntegratedProgramSnapshot } from '../../service/oncology/patient-oncology-summary-service'; const routes = [ { - method: "GET", - path: "/etl/patient/{uuid}/oncology/integrated-program", + method: 'GET', + path: '/etl/patient/{uuid}/oncology/integrated-program', config: { plugins: { hapiAuthorization: { role: privileges.canViewPatient } }, - handler: function(request, reply) { + handler: function (request, reply) { let requestParams = Object.assign({}, request.query, request.params); getOncologyIntegratedProgramSnapshot(requestParams) - .then(data => { + .then((data) => { reply(data); }) - .catch(error => { + .catch((error) => { reply(error); }); }, - description: "Get the screening and diagnosis history report", - notes: "Returns the the screening programs a patient has been through", - tags: ["api"], + description: 'Get the screening and diagnosis history report', + notes: 'Returns the the screening programs a patient has been through', + tags: ['api'], validate: { options: { allowUnknown: true @@ -34,4 +34,4 @@ const routes = [ } } ]; -exports.routes = server => server.route(routes); +exports.routes = (server) => server.route(routes); diff --git a/app/routes/ovc-monthly-summary.route.js b/app/routes/ovc-monthly-summary.route.js index 1c1e1a23c..64a257996 100644 --- a/app/routes/ovc-monthly-summary.route.js +++ b/app/routes/ovc-monthly-summary.route.js @@ -1,82 +1,90 @@ var authorizer = require('../../authorization/etl-authorizer'); -import { - OvcMonthlySummary -} from '../ovc-report/ovc-monthly-summary.service'; +import { OvcMonthlySummary } from '../ovc-report/ovc-monthly-summary.service'; var etlHelpers = require('../../etl-helpers'); var privileges = authorizer.getAllPrivileges(); var preRequest = require('../../pre-request-processing'); const routes = [ - { - method: 'GET', - path: '/etl/ovc-monthly-summary', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - } - }, - handler: function (request, reply) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('ovc-monthly-summary', - ['endDate', 'locationUuids'], - requestParams); - - let service = new OvcMonthlySummary('ovcReport', reportParams.requestParams); - service.generateAggregateReport().then((result) => { - reply(result); - - }).catch((error) => { - reply(error); - }); - }); - - }, - description: 'ovc-monthly-summary dataset', - notes: 'ovc-monthly-summary dataset', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + { + method: 'GET', + path: '/etl/ovc-monthly-summary', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard } - }, - { - method: 'GET', - path: '/etl/ovc-monthly-summary-patient-list', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - } - }, - handler: function (request, reply) { - request.query.reportName = 'ovc-monthly-summarypatient-list'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - - let requestCopy = _.cloneDeep(requestParams); - let reportParams = etlHelpers.getReportParams(request.query.reportName, ['startDate', 'endDate', 'locationUuids', 'locations'], requestParams); - const service = new OvcMonthlySummary('ovcReport', requestCopy); + }, + handler: function (request, reply) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign({}, request.query, request.params); + let reportParams = etlHelpers.getReportParams( + 'ovc-monthly-summary', + ['endDate', 'locationUuids'], + requestParams + ); - service.generatePatientListReport(requestParams.indicators.split(',')).then((results) => { //.indicators.split(',') - reply(results); - }) - .catch((err) => { - reply(Boom.internal('An error occured', err)); - }); - }); - - }, - description: 'Get patient list for ovc monthly summary report of the location and month provided', - notes: 'Returns patient list of monthly summary indicators', - tags: ['api'] + let service = new OvcMonthlySummary( + 'ovcReport', + reportParams.requestParams + ); + service + .generateAggregateReport() + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'ovc-monthly-summary dataset', + notes: 'ovc-monthly-summary dataset', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/ovc-monthly-summary-patient-list', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard } + }, + handler: function (request, reply) { + request.query.reportName = 'ovc-monthly-summarypatient-list'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign({}, request.query, request.params); + + let requestCopy = _.cloneDeep(requestParams); + let reportParams = etlHelpers.getReportParams( + request.query.reportName, + ['startDate', 'endDate', 'locationUuids', 'locations'], + requestParams + ); + const service = new OvcMonthlySummary('ovcReport', requestCopy); + service + .generatePatientListReport(requestParams.indicators.split(',')) + .then((results) => { + //.indicators.split(',') + reply(results); + }) + .catch((err) => { + reply(Boom.internal('An error occured', err)); + }); + }); + }, + description: + 'Get patient list for ovc monthly summary report of the location and month provided', + notes: 'Returns patient list of monthly summary indicators', + tags: ['api'] } -] -exports.routes = server => server.route(routes); + } +]; +exports.routes = (server) => server.route(routes); diff --git a/app/routes/patient-diagnosis-history.route.js b/app/routes/patient-diagnosis-history.route.js index 9eb0cf0c1..e9922f193 100644 --- a/app/routes/patient-diagnosis-history.route.js +++ b/app/routes/patient-diagnosis-history.route.js @@ -1,37 +1,48 @@ -const authorizer = require("../../authorization/etl-authorizer"); +const authorizer = require('../../authorization/etl-authorizer'); const privileges = authorizer.getAllPrivileges(); -import { getPatientOncologyDiagnosis } from "../../service/oncology/patient-oncology-summary-service"; +import { getPatientOncologyDiagnosis } from '../../service/oncology/patient-oncology-summary-service'; -const helpers = require("../../etl-helpers"); +const helpers = require('../../etl-helpers'); const routes = [ { - method: "GET", - path: "/etl/patient/{uuid}/oncology/diagnosis-history", + method: 'GET', + path: '/etl/patient/{uuid}/oncology/diagnosis-history', config: { plugins: { hapiAuthorization: { role: privileges.canViewPatient } }, - handler: function(request, reply) { + handler: function (request, reply) { let requestParams = Object.assign({}, request.query, request.params); getPatientOncologyDiagnosis(requestParams) - .then(data => { + .then((data) => { let diagnosisData = data; _.each(diagnosisData.result, (summary) => { - summary.diagnosis = `${helpers.getConceptName(summary.cancer_type)}${summary.cancer_subtype ? ` - ${helpers.getConceptName(summary.cancer_subtype)}` : ''}`; - summary.diagnosis_date = helpers.filterDate(summary.diagnosis_date); + summary.diagnosis = `${helpers.getConceptName( + summary.cancer_type + )}${ + summary.cancer_subtype + ? ` - ${helpers.getConceptName(summary.cancer_subtype)}` + : '' + }`; + summary.diagnosis_date = helpers.filterDate( + summary.diagnosis_date + ); }); - diagnosisData.result = _.filter(diagnosisData.result, (summary) => !_.isNull(summary.cancer_type)); + diagnosisData.result = _.filter( + diagnosisData.result, + (summary) => !_.isNull(summary.cancer_type) + ); reply(diagnosisData); }) - .catch(error => { + .catch((error) => { reply(error); }); }, - description: "Get the diagnosis history report", - notes: "Returns the the diagnosis history of the selected patient", - tags: ["api"], + description: 'Get the diagnosis history report', + notes: 'Returns the the diagnosis history of the selected patient', + tags: ['api'], validate: { options: { allowUnknown: true @@ -41,4 +52,4 @@ const routes = [ } } ]; -exports.routes = server => server.route(routes); +exports.routes = (server) => server.route(routes); diff --git a/app/routes/patient-medication-history.route.js b/app/routes/patient-medication-history.route.js index 8de7b228c..fecc6bc78 100644 --- a/app/routes/patient-medication-history.route.js +++ b/app/routes/patient-medication-history.route.js @@ -1,67 +1,83 @@ var authorizer = require('../../authorization/etl-authorizer'); var privileges = authorizer.getAllPrivileges(); -import { generateMedsDataSet, getOncMeds } from '../../service/oncology/patient-oncology-summary-service' +import { + generateMedsDataSet, + getOncMeds +} from '../../service/oncology/patient-oncology-summary-service'; var helpers = require('../../etl-helpers'); -const routes = [{ +const routes = [ + { method: 'GET', path: '/etl/patient/{uuid}/oncology/medication-history', config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let oncMedsDetailed = []; - let oncMedHistory = {}; - let planAndDate = {}; - let requestParams = Object.assign({}, request.query, request.params); - getOncMeds(requestParams, '', '').then((data) => { - if (!!data) { - let groupedMedsData = generateMedsDataSet(data.result); - _.each(groupedMedsData, (summary) => { - if (summary.drugs) { - planAndDate = summary.treatment_plan; - _.each(summary.drugs, function (data) { - let oncMed = {}; - _.each(data, function (a) { - if (a.concept_id === 9918) { - oncMed.cur_onc_meds = helpers.getConceptName(a.value_coded); - } else if (a.concept_id === 1899) { - oncMed.cur_onc_meds_dose = a.value_numeric; - } else if (a.concept_id === 1896) { - oncMed.cur_onc_meds_frequency = helpers.getConceptName(a.value_coded); - } else if (a.concept_id === 7463) { - oncMed.cur_onc_meds_route = helpers.getConceptName(a.value_coded); - } - if (planAndDate.length > 0) { - oncMed.meds_start_date = helpers.filterDate(planAndDate[0].obs_datetime); - oncMed.chemotherapy_plan = helpers.getConceptName(planAndDate[0].value_coded); - } - }); - if (oncMed !== '') { - oncMedsDetailed.push(oncMed); - } - }); - } + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + let oncMedsDetailed = []; + let oncMedHistory = {}; + let planAndDate = {}; + let requestParams = Object.assign({}, request.query, request.params); + getOncMeds(requestParams, '', '') + .then((data) => { + if (!!data) { + let groupedMedsData = generateMedsDataSet(data.result); + _.each(groupedMedsData, (summary) => { + if (summary.drugs) { + planAndDate = summary.treatment_plan; + _.each(summary.drugs, function (data) { + let oncMed = {}; + _.each(data, function (a) { + if (a.concept_id === 9918) { + oncMed.cur_onc_meds = helpers.getConceptName( + a.value_coded + ); + } else if (a.concept_id === 1899) { + oncMed.cur_onc_meds_dose = a.value_numeric; + } else if (a.concept_id === 1896) { + oncMed.cur_onc_meds_frequency = helpers.getConceptName( + a.value_coded + ); + } else if (a.concept_id === 7463) { + oncMed.cur_onc_meds_route = helpers.getConceptName( + a.value_coded + ); + } + if (planAndDate.length > 0) { + oncMed.meds_start_date = helpers.filterDate( + planAndDate[0].obs_datetime + ); + oncMed.chemotherapy_plan = helpers.getConceptName( + planAndDate[0].value_coded + ); + } }); - oncMedHistory.result = oncMedsDetailed; - reply(oncMedHistory); + if (oncMed !== '') { + oncMedsDetailed.push(oncMed); + } + }); } - }).catch((error) => { - reply(error); - }); - + }); + oncMedHistory.result = oncMedsDetailed; + reply(oncMedHistory); + } + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get the medication history report', + notes: 'Returns the the medication history of the selected patient', + tags: ['api'], + validate: { + options: { + allowUnknown: true }, - description: "Get the medication history report", - notes: "Returns the the medication history of the selected patient", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + params: {} + } } -}]; -exports.routes = server => server.route(routes); \ No newline at end of file + } +]; +exports.routes = (server) => server.route(routes); diff --git a/app/routes/prep-monthly-summary.route.js b/app/routes/prep-monthly-summary.route.js index e7243968b..a0b6d6cd4 100644 --- a/app/routes/prep-monthly-summary.route.js +++ b/app/routes/prep-monthly-summary.route.js @@ -1,84 +1,94 @@ var authorizer = require('../../authorization/etl-authorizer'); -import { - PrepMonthlySummaryService -} from '../../service/prep-monthly-summary.service'; +import { PrepMonthlySummaryService } from '../../service/prep-monthly-summary.service'; var etlHelpers = require('../../etl-helpers'); var privileges = authorizer.getAllPrivileges(); var preRequest = require('../../pre-request-processing'); const routes = [ - { - method: 'GET', - path: '/etl/prep-monthly-summary', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - } - }, - handler: function (request, reply) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('prep-monthly-summary', - ['endDate', 'locationUuids'], - requestParams); - reportParams.requestParams.isAggregated = true - - let service = new PrepMonthlySummaryService('prepMonthlySummaryReport', reportParams.requestParams); - service.getAggregateReport().then((result) => { - reply(result); - - }).catch((error) => { - reply(error); - }); - }); - - }, - description: 'prep monthly summary dataset', - notes: 'prep monthly summary dataset', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + { + method: 'GET', + path: '/etl/prep-monthly-summary', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard } - }, - { - method: 'GET', - path: '/etl/prep-monthly-summary-patient-list', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - } - }, - handler: function (request, reply) { - request.query.reportName = 'prep-summary-patient-list'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - - let requestCopy = _.cloneDeep(requestParams); - let reportParams = etlHelpers.getReportParams(request.query.reportName, ['startDate', 'endDate', 'locationUuids', 'locations'], requestParams); - requestCopy.locationUuids = reportParams.requestParams.locationUuids; - const prepService = new PrepMonthlySummaryService('prepMonthlySummaryReport', requestCopy); + }, + handler: function (request, reply) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign({}, request.query, request.params); + let reportParams = etlHelpers.getReportParams( + 'prep-monthly-summary', + ['endDate', 'locationUuids'], + requestParams + ); + reportParams.requestParams.isAggregated = true; - prepService.generatePatientList(requestParams.indicators.split(',')).then((results) => { - reply(results); - }) - .catch((err) => { - reply(err); - }); - }); - - }, - description: 'Get patient list for prep monthly summary report of the location and month provided', - notes: 'Returns patient list of prep monthly summary indicators', - tags: ['api'] + let service = new PrepMonthlySummaryService( + 'prepMonthlySummaryReport', + reportParams.requestParams + ); + service + .getAggregateReport() + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'prep monthly summary dataset', + notes: 'prep monthly summary dataset', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/prep-monthly-summary-patient-list', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard } + }, + handler: function (request, reply) { + request.query.reportName = 'prep-summary-patient-list'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign({}, request.query, request.params); + + let requestCopy = _.cloneDeep(requestParams); + let reportParams = etlHelpers.getReportParams( + request.query.reportName, + ['startDate', 'endDate', 'locationUuids', 'locations'], + requestParams + ); + requestCopy.locationUuids = reportParams.requestParams.locationUuids; + const prepService = new PrepMonthlySummaryService( + 'prepMonthlySummaryReport', + requestCopy + ); + prepService + .generatePatientList(requestParams.indicators.split(',')) + .then((results) => { + reply(results); + }) + .catch((err) => { + reply(err); + }); + }); + }, + description: + 'Get patient list for prep monthly summary report of the location and month provided', + notes: 'Returns patient list of prep monthly summary indicators', + tags: ['api'] } -] -exports.routes = server => server.route(routes); \ No newline at end of file + } +]; +exports.routes = (server) => server.route(routes); diff --git a/app/routes/surge-daily-report.route.js b/app/routes/surge-daily-report.route.js index d3b6fc6ba..3cb39b782 100644 --- a/app/routes/surge-daily-report.route.js +++ b/app/routes/surge-daily-report.route.js @@ -1,65 +1,68 @@ var authorizer = require('../../authorization/etl-authorizer'); -import { - SurgeDailyReportService -} from '../../service/surge-reports/surge-daily-report-service'; +import { SurgeDailyReportService } from '../../service/surge-reports/surge-daily-report-service'; var privileges = authorizer.getAllPrivileges(); const routes = [ - { - method: 'GET', - path: '/etl/surge-daily-report', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - } - }, - handler: function (request, reply) { - let requestParams = Object.assign({}, request.query, request.params); - requestParams.reportName = 'surgeDailyReport'; - let service = new SurgeDailyReportService(); - service.getAggregateReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - - }, - description: 'Get aggregates of surge daily report of a given date and location ', - notes: 'Returns aggregates of surge indicators', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + { + method: 'GET', + path: '/etl/surge-daily-report', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard } - }, - { - method: 'GET', - path: '/etl/surge-daily-report-patient-list', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - } - }, - handler: function (request, reply) { - let requestParams = Object.assign({}, request.query, request.params); - requestParams.reportName = 'surgeDailyReport'; - let service = new SurgeDailyReportService(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - - }, - description: 'Get patient list for surge indicators report of the location and date provided', - notes: 'Returns patient list of surge indicators', - tags: ['api'] + }, + handler: function (request, reply) { + let requestParams = Object.assign({}, request.query, request.params); + requestParams.reportName = 'surgeDailyReport'; + let service = new SurgeDailyReportService(); + service + .getAggregateReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: + 'Get aggregates of surge daily report of a given date and location ', + notes: 'Returns aggregates of surge indicators', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/surge-daily-report-patient-list', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard } - + }, + handler: function (request, reply) { + let requestParams = Object.assign({}, request.query, request.params); + requestParams.reportName = 'surgeDailyReport'; + let service = new SurgeDailyReportService(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: + 'Get patient list for surge indicators report of the location and date provided', + notes: 'Returns patient list of surge indicators', + tags: ['api'] } -] -exports.routes = server => server.route(routes); \ No newline at end of file + } +]; +exports.routes = (server) => server.route(routes); diff --git a/app/routes/surge-reports.route.js b/app/routes/surge-reports.route.js index da6d4eefa..96fb35b6c 100644 --- a/app/routes/surge-reports.route.js +++ b/app/routes/surge-reports.route.js @@ -2,7 +2,5 @@ import { SurgeService } from '../../service/surge-reports/surge-report.service'; const authorizer = require('../../authorization/etl-authorizer'); const privileges = authorizer.getAllPrivileges(); -const routes = [ - -] -exports.routes = server => server.route(routes); \ No newline at end of file +const routes = []; +exports.routes = (server) => server.route(routes); diff --git a/app/utils/super-agent-cache.js b/app/utils/super-agent-cache.js index 69be6f0b3..0791d7545 100644 --- a/app/utils/super-agent-cache.js +++ b/app/utils/super-agent-cache.js @@ -2,36 +2,35 @@ // create a unique, global symbol name // ----------------------------------- -const MODULE_KEY = Symbol.for("App.Ampath.etl"); +const MODULE_KEY = Symbol.for('App.Ampath.etl'); // check if the global object has this symbol // add it if it does not have the symbol, yet // ------------------------------------------ var globalSymbols = Object.getOwnPropertySymbols(global); -var hasFoo = (globalSymbols.indexOf(MODULE_KEY) > -1); +var hasFoo = globalSymbols.indexOf(MODULE_KEY) > -1; if (!hasFoo) { - global[MODULE_KEY] = { - }; + global[MODULE_KEY] = {}; } // define the singleton API // ------------------------ var cachedAgents = {}; var singleton = { - saveAgent: function (key, agent) { - cachedAgents[key] = agent; - }, - getAgent: function (key) { - return cachedAgents[key]; - } + saveAgent: function (key, agent) { + cachedAgents[key] = agent; + }, + getAgent: function (key) { + return cachedAgents[key]; + } }; -Object.defineProperty(singleton, "instance", { - get: function () { - return global[MODULE_KEY]; - } +Object.defineProperty(singleton, 'instance', { + get: function () { + return global[MODULE_KEY]; + } }); // ensure the API is never changed @@ -42,4 +41,4 @@ Object.freeze(singleton); // export the singleton API only // ----------------------------- -module.exports = singleton; \ No newline at end of file +module.exports = singleton; diff --git a/authorization/etl-authorizer.js b/authorization/etl-authorizer.js index 984043644..c7b82ba1e 100755 --- a/authorization/etl-authorizer.js +++ b/authorization/etl-authorizer.js @@ -8,117 +8,140 @@ var analytics = require('../dao/analytics/etl-analytics-dao'); var _ = require('underscore'); var PRIVILEGES = { - canViewPatient: 'View Patients', - canViewDataAnalytics: 'View Data Analytics', - canViewDataEntryStats: 'View POC Data entry statitsisc', - canViewClinicDashBoard: 'View Clinic Dashboard' + canViewPatient: 'View Patients', + canViewDataAnalytics: 'View Data Analytics', + canViewDataEntryStats: 'View POC Data entry statitsisc', + canViewClinicDashBoard: 'View Clinic Dashboard' }; var reportPrivileges = { - 'daily-appointments': [PRIVILEGES.canViewClinicDashBoard, PRIVILEGES.canViewPatient], - 'daily-attendance': [PRIVILEGES.canViewClinicDashBoard, PRIVILEGES.canViewPatient], - 'daily-has-not-returned': [PRIVILEGES.canViewClinicDashBoard, PRIVILEGES.canViewPatient], - 'attended': [PRIVILEGES.canViewClinicDashBoard], - 'scheduled': [PRIVILEGES.canViewClinicDashBoard], - 'clinical-hiv-comparative-overview-report': [PRIVILEGES.canViewDataAnalytics], - 'clinical-art-overview-report': [PRIVILEGES.canViewDataAnalytics], - 'clinical-patient-care-status-overview-report': [PRIVILEGES.canViewDataAnalytics], - 'MOH-731-report': [PRIVILEGES.canViewDataAnalytics], - 'MOH-731-allsites-report': [PRIVILEGES.canViewDataAnalytics], - 'MOH-731-report-2017': [PRIVILEGES.canViewDataAnalytics], - 'patient-register-report': [PRIVILEGES.canViewPatient, PRIVILEGES.canViewDataAnalytics], - 'hiv-summary-report': [PRIVILEGES.canViewDataAnalytics], - 'clinic-comparator-report': [PRIVILEGES.canViewDataAnalytics], - 'hiv-summary-monthly-report': [PRIVILEGES.canViewDataAnalytics], - 'clinical-reminder-report': [PRIVILEGES.canViewPatient], - 'labs-report': [PRIVILEGES.canViewPatient, PRIVILEGES.canViewDataAnalytics], - 'viral-load-monitoring-report': [PRIVILEGES.canViewPatient, PRIVILEGES.canViewDataAnalytics], - 'medical-history-report': [PRIVILEGES.canViewPatient], - 'clinic-lab-orders-report': [PRIVILEGES.canViewClinicDashBoard, PRIVILEGES.canViewPatient], - 'patient-status-change-tracker-report': [PRIVILEGES.canViewDataAnalytics], - 'patient-care-cascade-report': [PRIVILEGES.canViewDataAnalytics], - 'cohort-report': [PRIVILEGES.canViewPatient], - 'patient-referral-report': [PRIVILEGES.canViewDataAnalytics] + 'daily-appointments': [ + PRIVILEGES.canViewClinicDashBoard, + PRIVILEGES.canViewPatient + ], + 'daily-attendance': [ + PRIVILEGES.canViewClinicDashBoard, + PRIVILEGES.canViewPatient + ], + 'daily-has-not-returned': [ + PRIVILEGES.canViewClinicDashBoard, + PRIVILEGES.canViewPatient + ], + attended: [PRIVILEGES.canViewClinicDashBoard], + scheduled: [PRIVILEGES.canViewClinicDashBoard], + 'clinical-hiv-comparative-overview-report': [PRIVILEGES.canViewDataAnalytics], + 'clinical-art-overview-report': [PRIVILEGES.canViewDataAnalytics], + 'clinical-patient-care-status-overview-report': [ + PRIVILEGES.canViewDataAnalytics + ], + 'MOH-731-report': [PRIVILEGES.canViewDataAnalytics], + 'MOH-731-allsites-report': [PRIVILEGES.canViewDataAnalytics], + 'MOH-731-report-2017': [PRIVILEGES.canViewDataAnalytics], + 'patient-register-report': [ + PRIVILEGES.canViewPatient, + PRIVILEGES.canViewDataAnalytics + ], + 'hiv-summary-report': [PRIVILEGES.canViewDataAnalytics], + 'clinic-comparator-report': [PRIVILEGES.canViewDataAnalytics], + 'hiv-summary-monthly-report': [PRIVILEGES.canViewDataAnalytics], + 'clinical-reminder-report': [PRIVILEGES.canViewPatient], + 'labs-report': [PRIVILEGES.canViewPatient, PRIVILEGES.canViewDataAnalytics], + 'viral-load-monitoring-report': [ + PRIVILEGES.canViewPatient, + PRIVILEGES.canViewDataAnalytics + ], + 'medical-history-report': [PRIVILEGES.canViewPatient], + 'clinic-lab-orders-report': [ + PRIVILEGES.canViewClinicDashBoard, + PRIVILEGES.canViewPatient + ], + 'patient-status-change-tracker-report': [PRIVILEGES.canViewDataAnalytics], + 'patient-care-cascade-report': [PRIVILEGES.canViewDataAnalytics], + 'cohort-report': [PRIVILEGES.canViewPatient], + 'patient-referral-report': [PRIVILEGES.canViewDataAnalytics] }; var SUPERUSER_ROLES = ['System Developer']; authorizer.setUser = function (openmrsUser) { - currentUser = openmrsUser; - if (openmrsUser === undefined) return; + currentUser = openmrsUser; + if (openmrsUser === undefined) return; - _setCurrentUserPrivileges(); - _setCurrentUserRoles(); + _setCurrentUserPrivileges(); + _setCurrentUserRoles(); }; authorizer.getUser = function () { - return currentUser; + return currentUser; }; authorizer.getCurrentUserPreviliges = function () { - //console.log('All privileges', currentUserPrivileges); - return currentUserPrivileges; + //console.log('All privileges', currentUserPrivileges); + return currentUserPrivileges; }; authorizer.getCurrentUserRoles = function () { - return currentUserRoles; + return currentUserRoles; }; authorizer.getAllPrivileges = function () { - return PRIVILEGES; + return PRIVILEGES; }; authorizer.getAllPrivilegesArray = function () { - var allPrivileges = []; + var allPrivileges = []; - for (var prop in PRIVILEGES) { - allPrivileges.push(PRIVILEGES[prop]); - } - //console.log('All privileges', allPrivileges); - return allPrivileges; + for (var prop in PRIVILEGES) { + allPrivileges.push(PRIVILEGES[prop]); + } + //console.log('All privileges', allPrivileges); + return allPrivileges; }; authorizer.hasPrivilege = function (privilege) { - if (authorizer.isSuperUser()) { - return true; - } - console.log('Current user privileges: ', JSON.stringify(currentUserPrivileges)); - console.log('Looking for privilege: ', privilege); - if (currentUserPrivileges.indexOf(privilege) > -1) { - return true; - } - return false; + if (authorizer.isSuperUser()) { + return true; + } + console.log( + 'Current user privileges: ', + JSON.stringify(currentUserPrivileges) + ); + console.log('Looking for privilege: ', privilege); + if (currentUserPrivileges.indexOf(privilege) > -1) { + return true; + } + return false; }; authorizer.hasPrivileges = function (arrayOfPrivileges) { - if (authorizer.isSuperUser()) { - return true; - } + if (authorizer.isSuperUser()) { + return true; + } - var hasPrivilege = true; + var hasPrivilege = true; - for (var i = 0; i < arrayOfPrivileges.length; i++) { - if (!authorizer.hasPrivilege(arrayOfPrivileges[i])) { - hasPrivilege = false; - break; - } + for (var i = 0; i < arrayOfPrivileges.length; i++) { + if (!authorizer.hasPrivilege(arrayOfPrivileges[i])) { + hasPrivilege = false; + break; } - return hasPrivilege; + } + return hasPrivilege; }; authorizer.hasReportAccess = function (reportName) { - var hasAccess = false; - var requiredPrivileges = reportPrivileges[reportName]; + var hasAccess = false; + var requiredPrivileges = reportPrivileges[reportName]; - if (requiredPrivileges) { - hasAccess = authorizer.hasPrivileges(requiredPrivileges); - } - return hasAccess; + if (requiredPrivileges) { + hasAccess = authorizer.hasPrivileges(requiredPrivileges); + } + return hasAccess; }; authorizer.isSuperUser = function () { - return true;//for now all users are super users - /** Disabled for now + return true; //for now all users are super users + /** Disabled for now for (var i = 0; i < SUPERUSER_ROLES.length; i++) { var role = SUPERUSER_ROLES[i]; if (currentUserRoles.indexOf(role) > -1) { @@ -130,90 +153,89 @@ authorizer.isSuperUser = function () { }; authorizer.getUserAuthorizedLocations = function (userProperties, callback) { - - var authorized = []; - resolveLocationName(userProperties, 'aggregate', function (r) { - authorized.push.apply(authorized, r); - resolveLocationName(userProperties, 'operational', function (s) { - authorized.push.apply(authorized, s); - callback(authorized) - }) + var authorized = []; + resolveLocationName(userProperties, 'aggregate', function (r) { + authorized.push.apply(authorized, r); + resolveLocationName(userProperties, 'operational', function (s) { + authorized.push.apply(authorized, s); + callback(authorized); }); + }); }; function resolveLocationName(userProperties, type, callback) { - var authorized = []; - for (var key in userProperties) { - if (type === 'operational') { - if (/^grantAccessToLocationOperationalData/.test(key)) { - if (userProperties[key] === '*') { - return callback([{ - uuid: userProperties[key], - name: 'All', - type: 'operational' - - }]) - - } else { - authorized.push(userProperties[key]) - } + var authorized = []; + for (var key in userProperties) { + if (type === 'operational') { + if (/^grantAccessToLocationOperationalData/.test(key)) { + if (userProperties[key] === '*') { + return callback([ + { + uuid: userProperties[key], + name: 'All', + type: 'operational' } - } else if (type === 'aggregate') { - if (/^grantAccessToLocationAggregateData/.test(key)) { - if (userProperties[key] === '*') { - return callback([{ - uuid: userProperties[key], - name: 'All', - type: 'aggregate' - }]) - } else { - authorized.push(userProperties[key]) - } + ]); + } else { + authorized.push(userProperties[key]); + } + } + } else if (type === 'aggregate') { + if (/^grantAccessToLocationAggregateData/.test(key)) { + if (userProperties[key] === '*') { + return callback([ + { + uuid: userProperties[key], + name: 'All', + type: 'aggregate' } + ]); + } else { + authorized.push(userProperties[key]); } + } } + } - if (authorized.length > 0) { - analytics.resolveLocationUuidsToName(authorized, function (results) { - var i = [] - _.each(results, function (result) { - if (type === 'operational') { - i.push({ - uuid: result.uuid, - name: result.name, - type: 'operational' - }) - } else if (type === 'aggregate') { - i.push({ - uuid: result.uuid, - name: result.name, - type: 'aggregate' - }) - } - }); - callback(i); - }) - - } else { - //for users whose privileges are not set - callback(authorized); - } - -}; + if (authorized.length > 0) { + analytics.resolveLocationUuidsToName(authorized, function (results) { + var i = []; + _.each(results, function (result) { + if (type === 'operational') { + i.push({ + uuid: result.uuid, + name: result.name, + type: 'operational' + }); + } else if (type === 'aggregate') { + i.push({ + uuid: result.uuid, + name: result.name, + type: 'aggregate' + }); + } + }); + callback(i); + }); + } else { + //for users whose privileges are not set + callback(authorized); + } +} module.exports = authorizer; function _setCurrentUserPrivileges() { - currentUserPrivileges = []; - for (var i = 0; i < currentUser.privileges.length; i++) { - //console.log('Adding privilege: ', currentUser.privileges[i].display); - currentUserPrivileges.push(currentUser.privileges[i].display); - } + currentUserPrivileges = []; + for (var i = 0; i < currentUser.privileges.length; i++) { + //console.log('Adding privilege: ', currentUser.privileges[i].display); + currentUserPrivileges.push(currentUser.privileges[i].display); + } } function _setCurrentUserRoles() { - currentUserRoles = []; - for (var i = 0; i < currentUser.roles.length; i++) { - currentUserRoles.push(currentUser.roles[i].display); - } + currentUserRoles = []; + for (var i = 0; i < currentUser.roles.length; i++) { + currentUserRoles.push(currentUser.roles[i].display); + } } diff --git a/authorization/location-authorizer.plugin.js b/authorization/location-authorizer.plugin.js index 77496eeb0..13ce90013 100755 --- a/authorization/location-authorizer.plugin.js +++ b/authorization/location-authorizer.plugin.js @@ -10,14 +10,14 @@ var _ = require('underscore'); var pluginName = 'openmrsLocationAuthorizer'; var internals = { - defaults: { - locationParameter: [ - { - type: 'params',//can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - } - ], - } + defaults: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } }; /** @@ -28,28 +28,26 @@ var internals = { * @param next */ exports.register = function (server, options, next) { + try { + var settings = Hoek.applyToDefaults(internals.defaults, options || {}); - try { - - - var settings = Hoek.applyToDefaults(internals.defaults, options || {}); - - server.bind({ - config: settings - }); - - // Validate the server options on the routes - if (server.after) { // Support for hapi < 11 - server.after(internals.validateRoutes); - } else { - server.ext('onPreStart', internals.validateRoutes); - } - server.ext('onPreHandler', internals.onPreHandler); + server.bind({ + config: settings + }); - next(); - } catch (e) { - next(e); + // Validate the server options on the routes + if (server.after) { + // Support for hapi < 11 + server.after(internals.validateRoutes); + } else { + server.ext('onPreStart', internals.validateRoutes); } + server.ext('onPreHandler', internals.onPreHandler); + + next(); + } catch (e) { + next(e); + } }; /** @@ -57,11 +55,10 @@ exports.register = function (server, options, next) { * TODO: Return contents of a valid package.json */ exports.register.attributes = { - name: pluginName, - version: '1.0.0' + name: pluginName, + version: '1.0.0' }; - /** * Runs on server start and validates that every route that has openmrsLocationAuthorizer params is valid * @@ -69,44 +66,49 @@ exports.register.attributes = { * @param next */ internals.validateRoutes = function (server, next) { - - try { - // Loop through each connection in the server - server.connections.forEach(function (connection) { - - var routes = (connection.routingTable) ? connection.routingTable() : connection.table(); - - // Loop through each route - routes.forEach(function (route) { - - var locationAuthorizerParams = route.settings.plugins[pluginName] ? route.settings.plugins[pluginName] : false; - - // If there are openmrsLocationAuthorizer params and are not disabled by using "false", validate em - if (locationAuthorizerParams !== false) { - - // If there is a default auth - if (connection.auth.settings.default) { - - // If there is also an auth on the route, make sure it's not false or null - if (route.settings.auth !== undefined) { - - // Make sure that there is either a default auth being set, or that there is an auth specified on every route with locationAuthorizer plugin params - Hoek.assert(route.settings.auth !== null && route.settings.auth !== false, 'openmrsLocationAuthorizer can be enabled only for secured route'); - } - } - // Else there is no default auth set, so validate each route's auth - else { - // Make sure that there is either a default auth being set, or that there is an auth specified on every route with locationAuthorizer plugin params - Hoek.assert(route.settings.auth && route.settings.auth !== null && route.settings.auth !== false, 'openmrsLocationAuthorizer can be enabled only for secured route'); - } - } - }); - }); - next(); - } - catch (err) { - next(err); - } + try { + // Loop through each connection in the server + server.connections.forEach(function (connection) { + var routes = connection.routingTable + ? connection.routingTable() + : connection.table(); + + // Loop through each route + routes.forEach(function (route) { + var locationAuthorizerParams = route.settings.plugins[pluginName] + ? route.settings.plugins[pluginName] + : false; + + // If there are openmrsLocationAuthorizer params and are not disabled by using "false", validate em + if (locationAuthorizerParams !== false) { + // If there is a default auth + if (connection.auth.settings.default) { + // If there is also an auth on the route, make sure it's not false or null + if (route.settings.auth !== undefined) { + // Make sure that there is either a default auth being set, or that there is an auth specified on every route with locationAuthorizer plugin params + Hoek.assert( + route.settings.auth !== null && route.settings.auth !== false, + 'openmrsLocationAuthorizer can be enabled only for secured route' + ); + } + } + // Else there is no default auth set, so validate each route's auth + else { + // Make sure that there is either a default auth being set, or that there is an auth specified on every route with locationAuthorizer plugin params + Hoek.assert( + route.settings.auth && + route.settings.auth !== null && + route.settings.auth !== false, + 'openmrsLocationAuthorizer can be enabled only for secured route' + ); + } + } + }); + }); + next(); + } catch (err) { + next(err); + } }; /** @@ -116,151 +118,183 @@ internals.validateRoutes = function (server, next) { * @param reply */ internals.onPreHandler = function (request, reply) { - // Ignore OPTIONS requests - if (request.route.method === 'options') { - return reply.continue(); - } - - var params; - try { - // Check if the current route is openmrsLocationAuthorizer enabled - params = internals.getRouteParams(request); - } - catch (err) { - return reply(Boom.badRequest(err.message)); - } - - // if openmrsLocationAuthorizer is enabled, get the user - if (params) { - var user = request.auth.credentials; - var routeSettings = request.route.settings.plugins[pluginName] || {locationParameter: [],exemptedParameter:[],aggregateReport:[]}; - if (user.authorizedLocations.length > 0) { - - var unAuthorisedOperationalLocations = []; - var unAuthorisedAggregateLocations = []; - var isExempted=false; - var isAggregate=false; - - //check for exemptions - isExempted= _.some(routeSettings.exemptedParameter||[], function (routeSetting) { - var passedExemptedValue = request[routeSetting.type][routeSetting.name] || ''; - return passedExemptedValue===routeSetting.value; - }); - - //check if passedParam is aggregate - isAggregate= _.some(routeSettings.aggregateReport||[], function (routeSetting) { - var passedParamValue = request[routeSetting.type][routeSetting.name] || ''; - return passedParamValue===routeSetting.value; - }); - - if(isExempted===false) { - if (isAggregate===true) { - //get all the selected locations that this user is not authorised to fetch data - _.each(routeSettings.locationParameter, function (routeSetting) { - var passedLocations = request[routeSetting.type][routeSetting.name] || 'All'; - if (passedLocations === 'All') { - //this means the user did not limit request parameters to any locations - //therefore check if user is allowed to access all location - var isAuthorised = _.some(user.authorizedLocations, function (authorizedLocation) { - if (authorizedLocation.type==='aggregate') return authorizedLocation.uuid === '*' - }); - if (!isAuthorised) unAuthorisedAggregateLocations.push('All'); - } else { - _.each(passedLocations.split(','), function (passedLocation) { - if (passedLocation.length >0) { //validate passedLocation is a uuid - //determine if user is authorised - var isAuthorised = _.some(user.authorizedLocations, function (authorizedLocation) { - if (authorizedLocation.type==='aggregate') { - if (authorizedLocation.uuid === '*') return true; - return authorizedLocation.uuid == passedLocation; - } - }); - //if not authorised then push the unauthorised locations - if (!isAuthorised) unAuthorisedAggregateLocations.push(passedLocation); - } - }) - } - }); - } else { - //get all the selected locations that this user is not authorised to fetch data - _.each(routeSettings.locationParameter, function (routeSetting) { - var passedLocations = request[routeSetting.type][routeSetting.name] || 'All'; - if (passedLocations === 'All') { - //this means the user did not limit request parameters to any locations - //therefore check if user is allowed to access all location - var isAuthorised = _.some(user.authorizedLocations, function (authorizedLocation) { - if(authorizedLocation.type==='operational')return authorizedLocation.uuid === '*' - }); - if (!isAuthorised) unAuthorisedOperationalLocations.push('All'); - } else { - _.each(passedLocations.split(','), function (passedLocation) { - if (passedLocation.length >0) { //validate passedLocation is a uuid - //determine if user is authorised - var isAuthorised = _.some(user.authorizedLocations, function (authorizedLocation) { - if(authorizedLocation.type==='operational') { - if (authorizedLocation.uuid === '*') return true; - return authorizedLocation.uuid == passedLocation; - } - }); - //if not authorised then push the unauthorised locations - if (!isAuthorised) unAuthorisedOperationalLocations.push(passedLocation); - } - }) - } - }); - } - } - //if any of the passed location is unauthorised then boom.forbidden() else reply.continue() - if (unAuthorisedOperationalLocations.length > 0) { - //construct message appropriately - var authorisedOperationLocations =[]; - _.each(user.authorizedLocations, function(location) { - if (location.type==='operational') { - authorisedOperationLocations.push(location['name']) ; + // Ignore OPTIONS requests + if (request.route.method === 'options') { + return reply.continue(); + } + + var params; + try { + // Check if the current route is openmrsLocationAuthorizer enabled + params = internals.getRouteParams(request); + } catch (err) { + return reply(Boom.badRequest(err.message)); + } + + // if openmrsLocationAuthorizer is enabled, get the user + if (params) { + var user = request.auth.credentials; + var routeSettings = request.route.settings.plugins[pluginName] || { + locationParameter: [], + exemptedParameter: [], + aggregateReport: [] + }; + if (user.authorizedLocations.length > 0) { + var unAuthorisedOperationalLocations = []; + var unAuthorisedAggregateLocations = []; + var isExempted = false; + var isAggregate = false; + + //check for exemptions + isExempted = _.some(routeSettings.exemptedParameter || [], function ( + routeSetting + ) { + var passedExemptedValue = + request[routeSetting.type][routeSetting.name] || ''; + return passedExemptedValue === routeSetting.value; + }); + + //check if passedParam is aggregate + isAggregate = _.some(routeSettings.aggregateReport || [], function ( + routeSetting + ) { + var passedParamValue = + request[routeSetting.type][routeSetting.name] || ''; + return passedParamValue === routeSetting.value; + }); + + if (isExempted === false) { + if (isAggregate === true) { + //get all the selected locations that this user is not authorised to fetch data + _.each(routeSettings.locationParameter, function (routeSetting) { + var passedLocations = + request[routeSetting.type][routeSetting.name] || 'All'; + if (passedLocations === 'All') { + //this means the user did not limit request parameters to any locations + //therefore check if user is allowed to access all location + var isAuthorised = _.some(user.authorizedLocations, function ( + authorizedLocation + ) { + if (authorizedLocation.type === 'aggregate') + return authorizedLocation.uuid === '*'; + }); + if (!isAuthorised) unAuthorisedAggregateLocations.push('All'); + } else { + _.each(passedLocations.split(','), function (passedLocation) { + if (passedLocation.length > 0) { + //validate passedLocation is a uuid + //determine if user is authorised + var isAuthorised = _.some(user.authorizedLocations, function ( + authorizedLocation + ) { + if (authorizedLocation.type === 'aggregate') { + if (authorizedLocation.uuid === '*') return true; + return authorizedLocation.uuid == passedLocation; } - - }); - if(authorisedOperationLocations.length > 0 ){ - return reply(Boom.forbidden('You are only allowed to view operational data in '+authorisedOperationLocations.toString()||'' - +' location(s)')); - - }else{ - - return reply(Boom.forbidden('You are not allowed to view operational data in any location ')); + }); + //if not authorised then push the unauthorised locations + if (!isAuthorised) + unAuthorisedAggregateLocations.push(passedLocation); } - - - } else if (unAuthorisedAggregateLocations.length > 0) { - - - var authorisedAggregateLocations =[]; - _.each(user.authorizedLocations, function(location) { - if (location.type==='aggregate') { - authorisedAggregateLocations.push(location['name']) ; + }); + } + }); + } else { + //get all the selected locations that this user is not authorised to fetch data + _.each(routeSettings.locationParameter, function (routeSetting) { + var passedLocations = + request[routeSetting.type][routeSetting.name] || 'All'; + if (passedLocations === 'All') { + //this means the user did not limit request parameters to any locations + //therefore check if user is allowed to access all location + var isAuthorised = _.some(user.authorizedLocations, function ( + authorizedLocation + ) { + if (authorizedLocation.type === 'operational') + return authorizedLocation.uuid === '*'; + }); + if (!isAuthorised) unAuthorisedOperationalLocations.push('All'); + } else { + _.each(passedLocations.split(','), function (passedLocation) { + if (passedLocation.length > 0) { + //validate passedLocation is a uuid + //determine if user is authorised + var isAuthorised = _.some(user.authorizedLocations, function ( + authorizedLocation + ) { + if (authorizedLocation.type === 'operational') { + if (authorizedLocation.uuid === '*') return true; + return authorizedLocation.uuid == passedLocation; } - - }); - if(authorisedAggregateLocations.length > 0 ){ - return reply(Boom.forbidden('You are only allowed to view aggregate data in '+authorisedAggregateLocations.toString()||'' - +' location(s)')); - - }else{ - - return reply(Boom.forbidden('You are not allowed to view aggregate data in any location ')); + }); + //if not authorised then push the unauthorised locations + if (!isAuthorised) + unAuthorisedOperationalLocations.push(passedLocation); } - - } else { - reply.continue(); + }); } + }); + } + } + //if any of the passed location is unauthorised then boom.forbidden() else reply.continue() + if (unAuthorisedOperationalLocations.length > 0) { + //construct message appropriately + var authorisedOperationLocations = []; + _.each(user.authorizedLocations, function (location) { + if (location.type === 'operational') { + authorisedOperationLocations.push(location['name']); + } + }); + if (authorisedOperationLocations.length > 0) { + return reply( + Boom.forbidden( + 'You are only allowed to view operational data in ' + + authorisedOperationLocations.toString() || '' + ' location(s)' + ) + ); } else { - //user is not authorised to any location - return reply(Boom.forbidden('You are not Authorised to view data in any location. Please contact your system ' + - 'administrator to grant you access to the selected location(s)')); + return reply( + Boom.forbidden( + 'You are not allowed to view operational data in any location ' + ) + ); } - - } else { + } else if (unAuthorisedAggregateLocations.length > 0) { + var authorisedAggregateLocations = []; + _.each(user.authorizedLocations, function (location) { + if (location.type === 'aggregate') { + authorisedAggregateLocations.push(location['name']); + } + }); + if (authorisedAggregateLocations.length > 0) { + return reply( + Boom.forbidden( + 'You are only allowed to view aggregate data in ' + + authorisedAggregateLocations.toString() || '' + ' location(s)' + ) + ); + } else { + return reply( + Boom.forbidden( + 'You are not allowed to view aggregate data in any location ' + ) + ); + } + } else { reply.continue(); + } + } else { + //user is not authorised to any location + return reply( + Boom.forbidden( + 'You are not Authorised to view data in any location. Please contact your system ' + + 'administrator to grant you access to the selected location(s)' + ) + ); } + } else { + reply.continue(); + } }; /** @@ -270,14 +304,14 @@ internals.onPreHandler = function (request, reply) { * @returns {*} */ internals.getRouteParams = function (request) { - try { - if (request.route.settings.plugins[pluginName]) { - var params = request.route.settings.plugins[pluginName]; - return params; - } else { - return null; - } - } catch (ex) { - return null; + try { + if (request.route.settings.plugins[pluginName]) { + var params = request.route.settings.plugins[pluginName]; + return params; + } else { + return null; } + } catch (ex) { + return null; + } }; diff --git a/conf/config.example.json b/conf/config.example.json index fbfa05d62..7d1387382 100755 --- a/conf/config.example.json +++ b/conf/config.example.json @@ -114,4 +114,4 @@ "generalPath": "", "cd4PanelPath": "" } -} \ No newline at end of file +} diff --git a/conf/eid-regimen-config.json b/conf/eid-regimen-config.json index f5ecb0166..3b8196b12 100644 --- a/conf/eid-regimen-config.json +++ b/conf/eid-regimen-config.json @@ -1,10 +1,9 @@ { - "eid_regimen_config":[ - { - "version": 2, - "column": "eidCode", - "tag": "eid config version two" - } - ] - -} \ No newline at end of file + "eid_regimen_config": [ + { + "version": 2, + "column": "eidCode", + "tag": "eid config version two" + } + ] +} diff --git a/conf/kibana-config-example.json b/conf/kibana-config-example.json index 3e4575f99..46cfefe09 100644 --- a/conf/kibana-config-example.json +++ b/conf/kibana-config-example.json @@ -1,7 +1,6 @@ { "dashboards": [ { - "id": 1, "title": "Dashboard Example", "department": "test", @@ -11,7 +10,6 @@ "description": "Test Sescription", "url": "https://www.test-dashboard.or.ke/test", "allowedDashboards": ["clinic", "data-analytics"] - } ] -} \ No newline at end of file +} diff --git a/dao/analytics/etl-analytics-dao.js b/dao/analytics/etl-analytics-dao.js index 07f26ff17..7321efd3b 100755 --- a/dao/analytics/etl-analytics-dao.js +++ b/dao/analytics/etl-analytics-dao.js @@ -7,452 +7,510 @@ var reportFactory = require('../../etl-factory'); var Boom = require('boom'); //extends Hapi Error Reporting. Returns HTTP-friendly error objects: github.com/hapijs/boom var helpers = require('../../etl-helpers'); var Promise = require('bluebird'); -module.exports = function () { - return { - getCustomData: function getCustomData(request, callback) { - - var passed_params = request.params.userParams.split('/'); - var table_ = "amrs." + passed_params[0]; - var column_name = passed_params[1]; - var column_value = passed_params[2]; - - - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - - var queryParts = { - columns: request.query.fields || "*", - table: table_, - where: [column_name + " = ?", column_value], - // order: order || [{column:'encounter_datetime',asc:false}], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); +module.exports = (function () { + return { + getCustomData: function getCustomData(request, callback) { + var passed_params = request.params.userParams.split('/'); + var table_ = 'amrs.' + passed_params[0]; + var column_name = passed_params[1]; + var column_value = passed_params[2]; + + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + + var queryParts = { + columns: request.query.fields || '*', + table: table_, + where: [column_name + ' = ?', column_value], + // order: order || [{column:'encounter_datetime',asc:false}], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + }, + resolveLocationUuidsToName: function resolveLocationUuidsToName( + uuids, + callback + ) { + var queryParts = { + columns: 'name,uuid', + table: 'amrs.location', + where: ['uuid in ?', uuids], + offset: 0, + limit: 300 + }; + + db.queryServer_test(queryParts, function (result) { + //stringify + result = JSON.stringify(result); + result = JSON.parse(result); + callback(result.result); + }); + }, + runReport: function runReport(reportParams) { + console.log('Report Params', reportParams); + //build report + var queryParts = reportFactory.singleReportToSql(reportParams); + console.log('Query Parts', queryParts); + return new Promise(function (resolve, reject) { + db.reportQueryServer(queryParts, function (results) { + if (results.error) { + results.queryParts = queryParts; + reject(results); + } else { + reportFactory.buildIndicatorsSchema(reportParams, function ( + indicators + ) { + results.indicatorDefinitions = indicators; + var resolved = reportFactory.resolveIndicators( + reportParams.reportName, + results, + reportParams.requestIndicators + ); + resolve(resolved); }); - }, - resolveLocationUuidsToName: function resolveLocationUuidsToName(uuids, callback) { - var queryParts = { - columns: 'name,uuid', - table: 'amrs.location', - where: ['uuid in ?', uuids], - offset: 0, - limit: 300 - }; - - db.queryServer_test(queryParts, function (result) { - //stringify - result = JSON.stringify(result); - result = JSON.parse(result); - callback(result.result); - }); - }, - runReport: function runReport(reportParams) { - console.log('Report Params', reportParams); - //build report - var queryParts = reportFactory.singleReportToSql(reportParams); - console.log('Query Parts', queryParts); - return new Promise(function (resolve, reject) { - db.reportQueryServer(queryParts, function (results) { - if (results.error) { - results.queryParts = queryParts; - reject(results); - } else { - reportFactory.buildIndicatorsSchema(reportParams, function (indicators) { - results.indicatorDefinitions = indicators; - var resolved = reportFactory.resolveIndicators(reportParams.reportName, results, reportParams.requestIndicators); - resolve(resolved); - }); - } - }); - }); - }, - getDataEntryIndicators: function getDataEntryIndicators(subType, request, callback) { - var reportName = subType; - var startDate = request.query.startDate || new Date().toISOString().substring(0, 10); - var endDate = request.query.endDate || new Date().toISOString().substring(0, 10); - var providerUuid; - // var creatorUuid; - // if (request.query.creatorUuid) creatorUuid = request.query.creatorUuid; - if (request.query.providerUuid) providerUuid = request.query.providerUuid; - - var queryParams = { - reportName: reportName, - countBy: 'encounter', //this gives the ability to count by either person_id or encounter_id, - locations: request.query.locationIds, - encounterTypeIds: request.query.encounterTypeIds, - visitTypeIds: request.query.visitTypeIds, - formIds: request.query.formIds, - creatoruuid: request.query.creatorUuid - }; - - var where = {}; - - helpers.buildWhereParamsDataEntryIndicators(queryParams, where); - - var requestIndicators = request.query.indicators; - - //build query params - if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; - if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; - console.log('Where', where); - var requestParams = { - reportName: reportName, - whereParams: [ - { - "name": "startDate", - "value": startDate - }, - { - "name": "endDate", - "value": endDate - }, - { - "name": "locations", - "value": where.locations - }, - { - "name": "providerUuid", - "value": providerUuid - }, - { - "name": "formIds", - "value": where.formIds - }, - { - "name": "creatorUuid", - "value": where.creator - }, - { - "name": "encounterTypeIds", - "value": where.encounterTypes - }, - { - "name": "visitTypeIds", - "value": where.visitTypes - } - ], - groupBy: request.query.groupBy || 'groupByEncounterTypeId', - offset: request.query.startIndex, - limit: request.query.limit || 1000000 - }; - //build report - var queryParts = reportFactory.singleReportToSql(requestParams); - // console.log('Query Parts', queryParts); - db.reportQueryServer(queryParts, function (results) { - var res = reportFactory.resolveIndicators(reportName, results); - _.each(res.result, (item) => { - item.cur_meds = helpers.getARVNames(item.cur_meds); - }); - callback(res); - - }); - - }, - getPatientFlowData: function getPatientFlowData(request, callback) { - var reportName = 'patient-flow-report'; - var dateStarted = request.query.dateStarted || new Date().toISOString().substring(0, 10); - if (!_.isUndefined(dateStarted)) dateStarted = dateStarted.split('T')[0]; - var locations; - if (request.query.locations) { - locations = []; - _.each(request.query.locations.split(','), function (loc) { - locations.push(Number(loc)); - }); + } + }); + }); + }, + getDataEntryIndicators: function getDataEntryIndicators( + subType, + request, + callback + ) { + var reportName = subType; + var startDate = + request.query.startDate || new Date().toISOString().substring(0, 10); + var endDate = + request.query.endDate || new Date().toISOString().substring(0, 10); + var providerUuid; + // var creatorUuid; + // if (request.query.creatorUuid) creatorUuid = request.query.creatorUuid; + if (request.query.providerUuid) providerUuid = request.query.providerUuid; + + var queryParams = { + reportName: reportName, + countBy: 'encounter', //this gives the ability to count by either person_id or encounter_id, + locations: request.query.locationIds, + encounterTypeIds: request.query.encounterTypeIds, + visitTypeIds: request.query.visitTypeIds, + formIds: request.query.formIds, + creatoruuid: request.query.creatorUuid + }; + + var where = {}; + + helpers.buildWhereParamsDataEntryIndicators(queryParams, where); + + var requestIndicators = request.query.indicators; + + //build query params + if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; + if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; + console.log('Where', where); + var requestParams = { + reportName: reportName, + whereParams: [ + { + name: 'startDate', + value: startDate + }, + { + name: 'endDate', + value: endDate + }, + { + name: 'locations', + value: where.locations + }, + { + name: 'providerUuid', + value: providerUuid + }, + { + name: 'formIds', + value: where.formIds + }, + { + name: 'creatorUuid', + value: where.creator + }, + { + name: 'encounterTypeIds', + value: where.encounterTypes + }, + { + name: 'visitTypeIds', + value: where.visitTypes + } + ], + groupBy: request.query.groupBy || 'groupByEncounterTypeId', + offset: request.query.startIndex, + limit: request.query.limit || 1000000 + }; + //build report + var queryParts = reportFactory.singleReportToSql(requestParams); + // console.log('Query Parts', queryParts); + db.reportQueryServer(queryParts, function (results) { + var res = reportFactory.resolveIndicators(reportName, results); + _.each(res.result, (item) => { + item.cur_meds = helpers.getARVNames(item.cur_meds); + }); + callback(res); + }); + }, + getPatientFlowData: function getPatientFlowData(request, callback) { + var reportName = 'patient-flow-report'; + var dateStarted = + request.query.dateStarted || new Date().toISOString().substring(0, 10); + if (!_.isUndefined(dateStarted)) dateStarted = dateStarted.split('T')[0]; + var locations; + if (request.query.locations) { + locations = []; + _.each(request.query.locations.split(','), function (loc) { + locations.push(Number(loc)); + }); + } + + var requestParams = { + reportName: reportName, + whereParams: [ + { + name: 'dateStarted', + value: dateStarted + }, + { + name: 'locations', + value: locations + } + ], + groupBy: 'groupByEncounter', + offset: request.query.startIndex || 0, + limit: request.query.limit || 1000000 + }; + + //build report + + var queryParts = reportFactory.singleReportToSql(requestParams); + db.reportQueryServer(queryParts, function (results) { + var finalResults = reportFactory.resolveIndicators(reportName, results); + if ( + request.query.excludePatientList && + (request.query.excludePatientList === 'true' || + request.query.excludePatientList === true) + ) { + var removePatientList = function (results) { + if (results.result) { + results.result = []; } - var requestParams = { - reportName: reportName, - whereParams: [ - { - "name": "dateStarted", - "value": dateStarted - }, - { - "name": "locations", - "value": locations - } - ], - groupBy: 'groupByEncounter', - offset: request.query.startIndex || 0, - limit: request.query.limit || 1000000 - }; - - //build report - - var queryParts = reportFactory.singleReportToSql(requestParams); - db.reportQueryServer(queryParts, function (results) { - var finalResults = reportFactory.resolveIndicators(reportName, results); - if (request.query.excludePatientList && - (request.query.excludePatientList === 'true' || - request.query.excludePatientList === true)) { - - var removePatientList = function (results) { - if (results.result) { - results.result = []; - } - - if (results.results) { - results.results = []; - } - - _.each(results.resultsByLocation, function (item) { - removePatientList(item); - }) - }; - - removePatientList(finalResults); - - } - callback(finalResults); - - }); - - }, - getClinicLabOrdersData: function getClinicLabOrdersData(request, callback) { - var reportName = 'clinic-lab-orders-report'; - var dateActivated = request.query.dateActivated || new Date().toISOString().substring(0, 10); - if (!_.isUndefined(dateActivated)) dateActivated = dateActivated.split('T')[0]; - var locations; - if (request.query.locations) { - locations = []; - _.each(request.query.locations.split(','), function (loc) { - locations.push(Number(loc)); - }); + if (results.results) { + results.results = []; } - var requestParams = { - reportName: reportName, - whereParams: [ - { - "name": "dateActivated", - "value": dateActivated - }, - { - "name": "locations", - "value": locations - } - ], - groupBy: 'groupByPerson', - offset: request.query.startIndex || 0, - limit: request.query.limit || 1000000 - }; - - //build report - - var queryParts = reportFactory.singleReportToSql(requestParams); - db.reportQueryServer(queryParts, function (results) { - callback(reportFactory.resolveIndicators(reportName, results)); - }); - - }, - getIndicatorsSchemaWithSections: function getIndicatorsSchemaWithSections(request, callback) { - var reportName = request.query.report; - //Check for undefined query field - if (reportName === undefined) - callback(Boom.badRequest('report (Report Name) is missing from your request query')); - //build query params - var queryParams = { - reportName: reportName - }; - //retrieve jsin - reportFactory.buildIndicatorsSchemaWithSections(queryParams, function (result) { - var schema = {}; - schema.result = result; - callback(schema); + _.each(results.resultsByLocation, function (item) { + removePatientList(item); }); - }, - getIndicatorsSchema: function getIndicatorsSchema(request, callback) { - var reportName = request.query.report; - //Check for undefined query field - if (reportName === undefined) - callback(Boom.badRequest('report (Report Name) is missing from your request query')); - //build query params - var queryParams = { - reportName: reportName - }; - //retrieve jsin - reportFactory.buildIndicatorsSchema(queryParams, function (result) { - var schema = {}; - schema.result = result; - callback(schema); - }); - }, - getIdsByUuidAsyc: function getIdsByUuidAsyc(fullTableName, idColumnName, uuidColumnName, arrayOfUuids, callback) { - var uuids = []; - _.each(arrayOfUuids.split(','), function (uuid) { - console.log('Uuid', uuid); - uuids.push(uuid); - }); - - var queryParts = { - columns: idColumnName, - table: fullTableName, - where: [uuidColumnName + " in ?", uuids] - }; - - var promise = { - onResolved: undefined, - results: undefined - }; - - db.queryServer_test(queryParts, function (result) { - var formattedResult = ''; - - _.each(result.result, function (rowPacket) { - if (formattedResult === '') { - formattedResult = formattedResult + rowPacket[idColumnName]; - } else { - formattedResult = formattedResult + ',' + rowPacket[idColumnName]; - } - }); - callback(formattedResult); - promise.results = formattedResult; - if (typeof promise.onResolved === 'function') { - promise.onResolved(promise); - } - }); - - return promise; - }, - getHivSummaryData: function getHivSummaryData(request, callback) { - var startDate = request.query.startDate || new Date().toISOString().substring(0, 10); - var endDate = request.query.endDate || new Date().toISOString().substring(0, 10); - var locationUuids = request.query.locationUuids || ''; - var locations = []; - _.each(locationUuids.split(','), function (loc) { - locations.push(loc); - }); - var columns = "name as location, t1.*, day(encounter_datetime) as day, t3.gender, " + - "week(encounter_datetime) as week, month(encounter_datetime) as month, year(encounter_datetime) as year," + - "DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(t3.birthdate, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < " + - "DATE_FORMAT(t3.birthdate,'00-%m-%d')) AS age, if(arv_start_date is not null, t1.person_id,null) as on_arvs, " + - "t2.location_id"; - - if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; - if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; - - var whereClause = ["date(encounter_datetime) >= ? and date(encounter_datetime) <= ? " + - "and t1.location_uuid in ?", startDate, endDate, locations]; - console.log('here is the no of locations selected', request.query.locationUuids); - if (request.query.locationUuids === undefined) - whereClause = ["date(encounter_datetime) >= ? and date(encounter_datetime) <= ?", startDate, endDate]; - var queryParts = { - columns: columns, - table: "etl.flat_hiv_summary_v15b", - where: whereClause, - joins: [ - ['amrs.location', 't2', 't1.location_uuid = t2.uuid'], - ['amrs.person', 't3', 't3.person_id=t1.person_id'] - ], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); - }); - - }, - getPatientListReport: function getPatientListReport(requestParams) { - var requestIndicators = requestParams.indicator; - var startDate = requestParams.startDate || new Date().toISOString().substring(0, 10); - var endDate = requestParams.endDate || new Date().toISOString().substring(0, 10); - var order = helpers.getSortOrder(requestParams.order); - var reportName = requestParams.reportName || 'hiv-summary-report'; - var locationIds = requestParams.locations || ''; - var locationUuids = []; - var stateUuids = []; - var locations = []; - var programUuids= []; - var startAge = requestParams.startAge || 0; - var endAge = requestParams.endAge || 150; - var gender = (requestParams.gender || 'M,F').split(','); - - _.each(locationIds.split(','), function (loc) { - locations.push(Number(loc)); - }); - - // format locationUuids - if (requestParams.locationUuids) { - _.each(requestParams.locationUuids.split(','), function (loc) { - locationUuids.push(String(loc)); - }); - } - //format StateUuids - if (requestParams.stateUuids) { - _.each(requestParams.stateUuids.split(','), function (s) { - stateUuids.push(String(s)); - }); - } - if (requestParams.programUuids) { - _.each(requestParams.programUuids.split(','), function (s) { - programUuids.push(String(s)); - }); + }; + + removePatientList(finalResults); + } + callback(finalResults); + }); + }, + getClinicLabOrdersData: function getClinicLabOrdersData(request, callback) { + var reportName = 'clinic-lab-orders-report'; + var dateActivated = + request.query.dateActivated || + new Date().toISOString().substring(0, 10); + if (!_.isUndefined(dateActivated)) + dateActivated = dateActivated.split('T')[0]; + var locations; + if (request.query.locations) { + locations = []; + _.each(request.query.locations.split(','), function (loc) { + locations.push(Number(loc)); + }); + } + + var requestParams = { + reportName: reportName, + whereParams: [ + { + name: 'dateActivated', + value: dateActivated + }, + { + name: 'locations', + value: locations + } + ], + groupBy: 'groupByPerson', + offset: request.query.startIndex || 0, + limit: request.query.limit || 1000000 + }; + + //build report + + var queryParts = reportFactory.singleReportToSql(requestParams); + db.reportQueryServer(queryParts, function (results) { + callback(reportFactory.resolveIndicators(reportName, results)); + }); + }, + getIndicatorsSchemaWithSections: function getIndicatorsSchemaWithSections( + request, + callback + ) { + var reportName = request.query.report; + //Check for undefined query field + if (reportName === undefined) + callback( + Boom.badRequest( + 'report (Report Name) is missing from your request query' + ) + ); + //build query params + var queryParams = { + reportName: reportName + }; + //retrieve jsin + reportFactory.buildIndicatorsSchemaWithSections(queryParams, function ( + result + ) { + var schema = {}; + schema.result = result; + callback(schema); + }); + }, + getIndicatorsSchema: function getIndicatorsSchema(request, callback) { + var reportName = request.query.report; + //Check for undefined query field + if (reportName === undefined) + callback( + Boom.badRequest( + 'report (Report Name) is missing from your request query' + ) + ); + //build query params + var queryParams = { + reportName: reportName + }; + //retrieve jsin + reportFactory.buildIndicatorsSchema(queryParams, function (result) { + var schema = {}; + schema.result = result; + callback(schema); + }); + }, + getIdsByUuidAsyc: function getIdsByUuidAsyc( + fullTableName, + idColumnName, + uuidColumnName, + arrayOfUuids, + callback + ) { + var uuids = []; + _.each(arrayOfUuids.split(','), function (uuid) { + console.log('Uuid', uuid); + uuids.push(uuid); + }); + + var queryParts = { + columns: idColumnName, + table: fullTableName, + where: [uuidColumnName + ' in ?', uuids] + }; + + var promise = { + onResolved: undefined, + results: undefined + }; + + db.queryServer_test(queryParts, function (result) { + var formattedResult = ''; + + _.each(result.result, function (rowPacket) { + if (formattedResult === '') { + formattedResult = formattedResult + rowPacket[idColumnName]; + } else { + formattedResult = formattedResult + ',' + rowPacket[idColumnName]; + } + }); + callback(formattedResult); + promise.results = formattedResult; + if (typeof promise.onResolved === 'function') { + promise.onResolved(promise); + } + }); + + return promise; + }, + getHivSummaryData: function getHivSummaryData(request, callback) { + var startDate = + request.query.startDate || new Date().toISOString().substring(0, 10); + var endDate = + request.query.endDate || new Date().toISOString().substring(0, 10); + var locationUuids = request.query.locationUuids || ''; + var locations = []; + _.each(locationUuids.split(','), function (loc) { + locations.push(loc); + }); + var columns = + 'name as location, t1.*, day(encounter_datetime) as day, t3.gender, ' + + 'week(encounter_datetime) as week, month(encounter_datetime) as month, year(encounter_datetime) as year,' + + "DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(t3.birthdate, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < " + + "DATE_FORMAT(t3.birthdate,'00-%m-%d')) AS age, if(arv_start_date is not null, t1.person_id,null) as on_arvs, " + + 't2.location_id'; + + if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; + if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; + + var whereClause = [ + 'date(encounter_datetime) >= ? and date(encounter_datetime) <= ? ' + + 'and t1.location_uuid in ?', + startDate, + endDate, + locations + ]; + console.log( + 'here is the no of locations selected', + request.query.locationUuids + ); + if (request.query.locationUuids === undefined) + whereClause = [ + 'date(encounter_datetime) >= ? and date(encounter_datetime) <= ?', + startDate, + endDate + ]; + var queryParts = { + columns: columns, + table: 'etl.flat_hiv_summary_v15b', + where: whereClause, + joins: [ + ['amrs.location', 't2', 't1.location_uuid = t2.uuid'], + ['amrs.person', 't3', 't3.person_id=t1.person_id'] + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + }, + getPatientListReport: function getPatientListReport(requestParams) { + var requestIndicators = requestParams.indicator; + var startDate = + requestParams.startDate || new Date().toISOString().substring(0, 10); + var endDate = + requestParams.endDate || new Date().toISOString().substring(0, 10); + var order = helpers.getSortOrder(requestParams.order); + var reportName = requestParams.reportName || 'hiv-summary-report'; + var locationIds = requestParams.locations || ''; + var locationUuids = []; + var stateUuids = []; + var locations = []; + var programUuids = []; + var startAge = requestParams.startAge || 0; + var endAge = requestParams.endAge || 150; + var gender = (requestParams.gender || 'M,F').split(','); + + _.each(locationIds.split(','), function (loc) { + locations.push(Number(loc)); + }); + + // format locationUuids + if (requestParams.locationUuids) { + _.each(requestParams.locationUuids.split(','), function (loc) { + locationUuids.push(String(loc)); + }); + } + //format StateUuids + if (requestParams.stateUuids) { + _.each(requestParams.stateUuids.split(','), function (s) { + stateUuids.push(String(s)); + }); + } + if (requestParams.programUuids) { + _.each(requestParams.programUuids.split(','), function (s) { + programUuids.push(String(s)); + }); + } + + if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; + if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; + + var queryParams = { + requestIndicators: requestIndicators, + reportName: reportName, + order: order, + groupBy: 'groupByPerson', + whereParams: [ + { + name: 'startDate', + value: startDate + }, + { + name: 'endDate', + value: endDate + }, + { + name: 'locationUuids', + value: locationUuids + }, + { + name: 'locations', + value: locations + }, + { + name: 'startAge', + value: startAge + }, + { + name: 'endAge', + value: endAge + }, + { + name: 'gender', + value: gender + }, + { + name: 'programUuids', + value: programUuids + }, + { + name: 'stateUuids', + value: stateUuids + } + ], + startIndex: requestParams.startIndex || 0, + limit: requestParams.limit || 300 + }; + + var queryParts = reportFactory.buildPatientListReportExpression( + queryParams + ); + return new Promise(function (resolve, reject) { + if (!_.isEmpty(queryParts)) { + db.reportQueryServer(queryParts, function (results) { + if (results.error) { + results.queryParts = queryParts; + reject(results); + } else { + resolve(reportFactory.resolveIndicators(reportName, results)); } - - if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; - if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; - - var queryParams = { - requestIndicators: requestIndicators, - reportName: reportName, - order: order, - groupBy: 'groupByPerson', - whereParams: [{ - "name": "startDate", - "value": startDate - }, { - "name": "endDate", - "value": endDate - }, { - "name": "locationUuids", - "value": locationUuids - }, { - "name": "locations", - "value": locations - }, { - "name": "startAge", - "value": startAge - }, { - "name": "endAge", - "value": endAge - }, { - "name": "gender", - "value": gender - }, - { - "name": "programUuids", - "value": programUuids - }, - { - "name": "stateUuids", - "value": stateUuids - } - - ], - startIndex: requestParams.startIndex || 0, - limit: requestParams.limit || 300 - }; - - var queryParts = reportFactory.buildPatientListReportExpression(queryParams); - return new Promise(function (resolve, reject) { - if (!_.isEmpty(queryParts)) { - db.reportQueryServer(queryParts, function (results) { - if (results.error) { - results.queryParts = queryParts; - reject(results); - } else { - resolve(reportFactory.resolveIndicators(reportName, results)); - } - }); - } else { - reject(Boom.badRequest('An error occurred while generating patient list, please check parameter and try again')); - } - }); - }, - - }; -}(); + }); + } else { + reject( + Boom.badRequest( + 'An error occurred while generating patient list, please check parameter and try again' + ) + ); + } + }); + } + }; +})(); diff --git a/dao/analytics/patient-care-status-analysis-dao.js b/dao/analytics/patient-care-status-analysis-dao.js index 72add3c7a..8a821ca17 100755 --- a/dao/analytics/patient-care-status-analysis-dao.js +++ b/dao/analytics/patient-care-status-analysis-dao.js @@ -7,333 +7,390 @@ var patientStatusReport = require('../../reports/patient-status-change-tracker-r var reportFactory = require('../../etl-factory'); var helpers = require('../../etl-helpers'); var Moment = require('moment'); -module.exports = function () { - return { - getPatientCareStatusAggregatesQuery: function (queryParams, callback) { - var queryParts = {}; - var indicators = []; - var whereClause = {}; - - // add patient level indicators from the report schema - _.each(patientStatusReport[0].indicators, function (reportIndicator) { - _.each(reportFactory.indicatorsSchema, function (indicator) { - if (indicator.name === reportIndicator.expression) { - indicators.push(indicator.expression + ' as ' + indicator.name); - //if (_.contains(requestIndicators, indicator.name)) - // whereClause += ' and (' + indicator.expression + ')'; - } - }); - }); - var column = ''; - if (queryParams.analysis === 'cohortAnalysis') { - column = "date_format(date('" + queryParams.endDate + "'), '%m/%Y') as reporting_month," + - "'" + queryParams.startDate + "' as from_month, " + - "'" + queryParams.endDate + "' as to_month, " - } else { - column = "date_format(if(to_month,to_month,last_day(date_add(from_month,interval 1 day))), '%m/%Y') as reporting_month," + - "if(from_month,from_month,date_sub(DATE_FORMAT(to_month, '%Y-%m-01'),interval 1 day)) as from_month, " + - "if(to_month,to_month,last_day(date_add(from_month,interval 1 day))) as to_month, " - } - var where1 = queryParams.analysis === 'cohortAnalysis' ? "t2.endDate = date('" + queryParams.startDate + "')" : - "t2.endDate >= date('" + queryParams.startDate + "') and t2.endDate <= date('" + queryParams.endDate + "')"; - var where2 = queryParams.analysis === 'cohortAnalysis' ? "t2.endDate = date('" + queryParams.endDate + "')" : - "t2.endDate >= date('" + queryParams.startDate + "') and t2.endDate <= date('" + queryParams.endDate + "')"; - var onClause = queryParams.analysis === 'cohortAnalysis' ? "on t1.person_id = t2.person_id ": - "on t1.person_id = t2.person_id and t1.endDate = date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day) "; - - var sql = - "select * from (" + - "select " + - "patient_uuid,next_state," + - column + - - "if(p1,p1,p2) as person_id, concat(initial_state,'_to_', next_state) as indicator, count(*) as counts " + - "from (" + - "select *, case when ar1 then 'active_return' when ne1 then 'new_enrollment' " + - "when ti1 then 'transfer_in' when ltfu1 then 'LTFU' when to1 then 'transfer_out' " + - "when d1 then 'dead' when neg1 then 'HIV_negative' when sd1 then 'self_disengaged' " + - "else 'self_transfer_out' end as initial_state, " + - "case when ar2 then 'active_return' when ne2 then 'new_enrollment' when ti2 then 'transfer_in' " + - "when ltfu2 then 'LTFU' when to2 then 'transfer_out' when d2 then 'dead' " + - "when neg2 then 'HIV_negative' when sd2 then 'self_disengaged' else 'self_transfer_out' " + - "end as next_state " + - - "from " + - - "(select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, " + - "if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, " + - "if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, " + - - "t1.active_return as ar1, t1.new_enrollments as ne1, t1.transfer_in as ti1, " + - "t1.LTFU as ltfu1, t1.transfer_out_patients as to1, t1.deaths as d1, " + - "t1.HIV_negative_patients as neg1, t1.self_disengaged_patients as sd1, " + - - "t2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, " + - "t2.LTFU as ltfu2, t2.transfer_out_patients as to2, t2.deaths as d2, " + - "t2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 " + - - - "from ( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where1) + " ) `t1` " + - - - "left outer join( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where2) + " ) t2 " + - - onClause + - - " union all " + - - "select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, " + - "if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, " + - "if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, " + - - " t1.active_return, t1.new_enrollments, t1.transfer_in, t1.LTFU, t1.transfer_out_patients, " + - " t1.deaths, t1.HIV_negative_patients, t1.self_disengaged_patients, " + - - "t2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, t2.LTFU as ltfu2, " + - "t2.transfer_out_patients as to2, t2.deaths as d2, t2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 " + - "from( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where1) + " ) `t1` " + - - - "right outer join( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where2) + " ) t2 " + - - onClause + - - "having t1.person_id is null ) tn ) tn2 group by from_month, to_month, indicator order by from_month, to_month " + - ") t1 "; - queryParts.sql = sql; - db.queryServer(queryParts, function (result) { - result.sql = sql; - callback(result); - }); - }, - getPatientCareStatusPatientListQuery: function (queryParams, callback) { - if( queryParams.analysis === 'cohortAnalysis') { - this.cohortPatientListQuery(queryParams, function (result) { - callback(result); - }); - } else { - this.monthlyPatientListQuery(queryParams, function (result) { - callback(result); - }); - } - }, - monthlyPatientListQuery: function (queryParams, callback) { - var queryParts = {}; - var indicators = []; - var whereClause = ''; - var requestIndicators = (queryParams.indicator || '').split('_to_'); - var columns = [ - 'patient_uuid', - 'p1p2', - 'next_state', - 'person.gender', 'person.birthdate', 'extract(year from (from_days(datediff(now(),person.birthdate)))) as age', - "concat(COALESCE(person_name.given_name,''),' ',COALESCE(person_name.middle_name,''),' ',COALESCE(person_name.family_name,'')) as person_name", - "group_concat(distinct id.identifier separator ', ') as identifiers" - ]; - - - // go back 1 month in time - var startDate = Moment(Moment(queryParams.startDate).format('YYYY-MM-DD')); - //var endDate = Moment(Moment(queryParams.endDate).format('YYYY-MM-DD')).endOf('month'); - queryParams.startDate = new Date(startDate.add(-1, 'months')).toISOString().substring(0, 10); - // queryParams.endDate = new Date(endDate.add(1, 'months')).toISOString().substring(0, 10); - - - // add patient level indicators from the report schema & whereClause from queryParams - _.each(patientStatusReport[0].indicators, function (reportIndicator) { - _.each(reportFactory.indicatorsSchema, function (indicator) { - if (indicator.name === reportIndicator.expression) { - indicators.push(indicator.expression + ' as ' + indicator.name); - //if (_.contains(requestIndicators, indicator.name)) - // whereClause += ' and (' + indicator.expression + ')'; - } - }); - }); - var where = " t2.endDate >= date('" + queryParams.startDate + "') and t2.endDate <= date('" + queryParams.endDate + "') "; - var onClause =" on t1.person_id = t2.person_id and t1.endDate = date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day) "; - var sql = - "select " + columns.toString() + " from (" + - "select *, if(p1, p1, p2) as p1p2, " + - " case when ar1 then 'active_return' when ne1 then 'new_enrollment' " + - "when ti1 then 'transfer_in' when ltfu1 then 'LTFU' when to1 then 'transfer_out' " + - "when d1 then 'dead' when neg1 then 'HIV_negative' when sd1 then 'self_disengaged' " + - "else 'self_transfer_out' end as initial_state, " + - "case when ar2 then 'active_return' when ne2 then 'new_enrollment' when ti2 then 'transfer_in' " + - "when ltfu2 then 'LTFU' when to2 then 'transfer_out' when d2 then 'dead' " + - "when neg2 then 'HIV_negative' when sd2 then 'self_disengaged' else 'self_transfer_out' " + - "end as next_state " + - - "from " + - - "(select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, " + - "if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, " + - "if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, " + - - "t1.active_return as ar1, t1.new_enrollments as ne1, t1.transfer_in as ti1, " + - "t1.LTFU as ltfu1, t1.transfer_out_patients as to1, t1.deaths as d1, " + - "t1.HIV_negative_patients as neg1, t1.self_disengaged_patients as sd1, " + - - "t2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, " + - "t2.LTFU as ltfu2, t2.transfer_out_patients as to2, t2.deaths as d2, " + - "t2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 " + - - - "from ( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where) + " ) `t1` " + - - - "left outer join( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where) + " ) t2 " + - - onClause + - - " union all " + - - "select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, " + - "if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, " + - "if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, " + - - " t1.active_return, t1.new_enrollments, t1.transfer_in, t1.LTFU, t1.transfer_out_patients, " + - " t1.deaths, t1.HIV_negative_patients, t1.self_disengaged_patients, " + - - "t2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, t2.LTFU as ltfu2, " + - "t2.transfer_out_patients as to2, t2.deaths as d2, t2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 " + - "from( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where) + " ) `t1` " + - - - "right outer join( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where) + " ) t2 " + - - onClause + - - "having t1.person_id is null ) tn " + - "having initial_state = '" + requestIndicators[0] + "' " + - "and next_state = '" + requestIndicators[1] + "' " + - " and date(to_month)=date('" + queryParams.endDate + "') " + - ") t1 " + - " INNER JOIN amrs.person_name `person_name` ON (t1.p1p2 = person_name.person_id and (person_name.voided is null || person_name.voided = 0)) " + - "LEFT OUTER JOIN amrs.patient_identifier `id` ON (t1.p1p2 = id.patient_id) " + - "INNER JOIN amrs.person `person` ON (t1.p1p2 = person.person_id) " - + ' group by t1.p1p2 ' - - ; - queryParts.sql = sql; - db.queryServer(queryParts, function (result) { - result.sql = sql; - callback(result); - }); - }, - cohortPatientListQuery: function (queryParams, callback) { - var queryParts = {}; - var indicators = []; - var whereClause = ''; - var requestIndicators = (queryParams.indicator || '').split('_to_'); - var columns = [ - 'patient_uuid', - 'p1p2', - 'next_state', - 'initial_state', - 'person.gender', 'person.birthdate', 'extract(year from (from_days(datediff(now(),person.birthdate)))) as age', - "concat(COALESCE(person_name.given_name,''),' ',COALESCE(person_name.middle_name,''),' ',COALESCE(person_name.family_name,'')) as person_name", - "group_concat(distinct id.identifier separator ', ') as identifiers" - ]; - - - // add patient level indicators from the report schema & whereClause from queryParams - _.each(patientStatusReport[0].indicators, function (reportIndicator) { - _.each(reportFactory.indicatorsSchema, function (indicator) { - if (indicator.name === reportIndicator.expression) { - indicators.push(indicator.expression + ' as ' + indicator.name); - //if (_.contains(requestIndicators, indicator.name)) - // whereClause += ' and (' + indicator.expression + ')'; - } - }); - }); - var where1 = " t2.endDate = date('" + queryParams.startDate + "') "; - var where2 = " t2.endDate = date('" + queryParams.endDate + "') "; - var onClause =" on t1.person_id = t2.person_id "; - var sql = - "select " + columns.toString() + " from (" + - " select patient_uuid, next_state, initial_state, if(p1, p1, p2) as p1p2 from (" + - "select *, " + - " case when ar1 then 'active_return' when ne1 then 'new_enrollment' " + - "when ti1 then 'transfer_in' when ltfu1 then 'LTFU' when to1 then 'transfer_out' " + - "when d1 then 'dead' when neg1 then 'HIV_negative' when sd1 then 'self_disengaged' " + - "else 'self_transfer_out' end as initial_state, " + - "case when ar2 then 'active_return' when ne2 then 'new_enrollment' when ti2 then 'transfer_in' " + - "when ltfu2 then 'LTFU' when to2 then 'transfer_out' when d2 then 'dead' " + - "when neg2 then 'HIV_negative' when sd2 then 'self_disengaged' else 'self_transfer_out' " + - "end as next_state " + - - "from " + - - "(select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, " + - "if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, " + - "if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, " + - - "t1.active_return as ar1, t1.new_enrollments as ne1, t1.transfer_in as ti1, " + - "t1.LTFU as ltfu1, t1.transfer_out_patients as to1, t1.deaths as d1, " + - "t1.HIV_negative_patients as neg1, t1.self_disengaged_patients as sd1, " + - - "t2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, " + - "t2.LTFU as ltfu2, t2.transfer_out_patients as to2, t2.deaths as d2, " + - "t2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 " + - - - "from ( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where1) + " ) `t1` " + - - - "left outer join( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where2) + " ) t2 " + - - onClause + - - " union all " + - - "select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, " + - "if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, " + - "if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, " + - - " t1.active_return, t1.new_enrollments, t1.transfer_in, t1.LTFU, t1.transfer_out_patients, " + - " t1.deaths, t1.HIV_negative_patients, t1.self_disengaged_patients, " + - - "t2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, t2.LTFU as ltfu2, " + - "t2.transfer_out_patients as to2, t2.deaths as d2, t2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 " + - "from( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where1) + " ) `t1` " + - - - "right outer join( " + this.getPatientCareStatusInternalQuery(queryParams, indicators, where2) + " ) t2 " + - - onClause + - "having t1.person_id is null ) tn ) tn2 " + - "group by p1p2 "+ - "having initial_state = '" + requestIndicators[0] + "' " + - "and next_state = '" + requestIndicators[1] + "' " + - ") t1 " + - " INNER JOIN amrs.person_name `person_name` ON (t1.p1p2 = person_name.person_id and (person_name.voided is null || person_name.voided = 0)) " + - "LEFT OUTER JOIN amrs.patient_identifier `id` ON (t1.p1p2 = id.patient_id) " + - "INNER JOIN amrs.person `person` ON (t1.p1p2 = person.person_id) " - + ' group by t1.p1p2 ' - - ; - queryParts.sql = sql; - db.queryServer(queryParts, function (result) { - result.sql = sql; - callback(result); - }); - }, - - getPatientCareStatusInternalQuery: function (queryParams, indicators, whereClause) { - - return " SELECT t2.endDate as reporting_date, " + - "date_format(t2.endDate, '%m/%Y') as reporting_month, " + - "t2.endDate,t1.uuid,t1.person_id, " + indicators.toString() + - " FROM etl.dates `t2` " + - "INNER JOIN etl.flat_hiv_summary_v15b `t1` force index (loc_id_enc_date_next_clinic) ON" + - " (date(t1.encounter_datetime) <= date(t2.endDate)) " + - "WHERE (" + - whereClause + - " and t1.location_id in(" + queryParams.locations.toString() + - ") and t1.is_clinical_encounter = 1 " + - "and (t1.next_clinical_datetime_hiv is null " + - "or date(t1.next_clinical_datetime_hiv) > t2.endDate)" + - ')'; - }, - }; -}(); \ No newline at end of file +module.exports = (function () { + return { + getPatientCareStatusAggregatesQuery: function (queryParams, callback) { + var queryParts = {}; + var indicators = []; + var whereClause = {}; + + // add patient level indicators from the report schema + _.each(patientStatusReport[0].indicators, function (reportIndicator) { + _.each(reportFactory.indicatorsSchema, function (indicator) { + if (indicator.name === reportIndicator.expression) { + indicators.push(indicator.expression + ' as ' + indicator.name); + //if (_.contains(requestIndicators, indicator.name)) + // whereClause += ' and (' + indicator.expression + ')'; + } + }); + }); + var column = ''; + if (queryParams.analysis === 'cohortAnalysis') { + column = + "date_format(date('" + + queryParams.endDate + + "'), '%m/%Y') as reporting_month," + + "'" + + queryParams.startDate + + "' as from_month, " + + "'" + + queryParams.endDate + + "' as to_month, "; + } else { + column = + "date_format(if(to_month,to_month,last_day(date_add(from_month,interval 1 day))), '%m/%Y') as reporting_month," + + "if(from_month,from_month,date_sub(DATE_FORMAT(to_month, '%Y-%m-01'),interval 1 day)) as from_month, " + + 'if(to_month,to_month,last_day(date_add(from_month,interval 1 day))) as to_month, '; + } + var where1 = + queryParams.analysis === 'cohortAnalysis' + ? "t2.endDate = date('" + queryParams.startDate + "')" + : "t2.endDate >= date('" + + queryParams.startDate + + "') and t2.endDate <= date('" + + queryParams.endDate + + "')"; + var where2 = + queryParams.analysis === 'cohortAnalysis' + ? "t2.endDate = date('" + queryParams.endDate + "')" + : "t2.endDate >= date('" + + queryParams.startDate + + "') and t2.endDate <= date('" + + queryParams.endDate + + "')"; + var onClause = + queryParams.analysis === 'cohortAnalysis' + ? 'on t1.person_id = t2.person_id ' + : "on t1.person_id = t2.person_id and t1.endDate = date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day) "; + + var sql = + 'select * from (' + + 'select ' + + 'patient_uuid,next_state,' + + column + + "if(p1,p1,p2) as person_id, concat(initial_state,'_to_', next_state) as indicator, count(*) as counts " + + 'from (' + + "select *, case when ar1 then 'active_return' when ne1 then 'new_enrollment' " + + "when ti1 then 'transfer_in' when ltfu1 then 'LTFU' when to1 then 'transfer_out' " + + "when d1 then 'dead' when neg1 then 'HIV_negative' when sd1 then 'self_disengaged' " + + "else 'self_transfer_out' end as initial_state, " + + "case when ar2 then 'active_return' when ne2 then 'new_enrollment' when ti2 then 'transfer_in' " + + "when ltfu2 then 'LTFU' when to2 then 'transfer_out' when d2 then 'dead' " + + "when neg2 then 'HIV_negative' when sd2 then 'self_disengaged' else 'self_transfer_out' " + + 'end as next_state ' + + 'from ' + + '(select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, ' + + 'if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, ' + + 'if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, ' + + 't1.active_return as ar1, t1.new_enrollments as ne1, t1.transfer_in as ti1, ' + + 't1.LTFU as ltfu1, t1.transfer_out_patients as to1, t1.deaths as d1, ' + + 't1.HIV_negative_patients as neg1, t1.self_disengaged_patients as sd1, ' + + 't2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, ' + + 't2.LTFU as ltfu2, t2.transfer_out_patients as to2, t2.deaths as d2, ' + + 't2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 ' + + 'from ( ' + + this.getPatientCareStatusInternalQuery( + queryParams, + indicators, + where1 + ) + + ' ) `t1` ' + + 'left outer join( ' + + this.getPatientCareStatusInternalQuery( + queryParams, + indicators, + where2 + ) + + ' ) t2 ' + + onClause + + ' union all ' + + 'select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, ' + + 'if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, ' + + 'if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, ' + + ' t1.active_return, t1.new_enrollments, t1.transfer_in, t1.LTFU, t1.transfer_out_patients, ' + + ' t1.deaths, t1.HIV_negative_patients, t1.self_disengaged_patients, ' + + 't2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, t2.LTFU as ltfu2, ' + + 't2.transfer_out_patients as to2, t2.deaths as d2, t2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 ' + + 'from( ' + + this.getPatientCareStatusInternalQuery( + queryParams, + indicators, + where1 + ) + + ' ) `t1` ' + + 'right outer join( ' + + this.getPatientCareStatusInternalQuery( + queryParams, + indicators, + where2 + ) + + ' ) t2 ' + + onClause + + 'having t1.person_id is null ) tn ) tn2 group by from_month, to_month, indicator order by from_month, to_month ' + + ') t1 '; + queryParts.sql = sql; + db.queryServer(queryParts, function (result) { + result.sql = sql; + callback(result); + }); + }, + getPatientCareStatusPatientListQuery: function (queryParams, callback) { + if (queryParams.analysis === 'cohortAnalysis') { + this.cohortPatientListQuery(queryParams, function (result) { + callback(result); + }); + } else { + this.monthlyPatientListQuery(queryParams, function (result) { + callback(result); + }); + } + }, + monthlyPatientListQuery: function (queryParams, callback) { + var queryParts = {}; + var indicators = []; + var whereClause = ''; + var requestIndicators = (queryParams.indicator || '').split('_to_'); + var columns = [ + 'patient_uuid', + 'p1p2', + 'next_state', + 'person.gender', + 'person.birthdate', + 'extract(year from (from_days(datediff(now(),person.birthdate)))) as age', + "concat(COALESCE(person_name.given_name,''),' ',COALESCE(person_name.middle_name,''),' ',COALESCE(person_name.family_name,'')) as person_name", + "group_concat(distinct id.identifier separator ', ') as identifiers" + ]; + + // go back 1 month in time + var startDate = Moment( + Moment(queryParams.startDate).format('YYYY-MM-DD') + ); + //var endDate = Moment(Moment(queryParams.endDate).format('YYYY-MM-DD')).endOf('month'); + queryParams.startDate = new Date(startDate.add(-1, 'months')) + .toISOString() + .substring(0, 10); + // queryParams.endDate = new Date(endDate.add(1, 'months')).toISOString().substring(0, 10); + + // add patient level indicators from the report schema & whereClause from queryParams + _.each(patientStatusReport[0].indicators, function (reportIndicator) { + _.each(reportFactory.indicatorsSchema, function (indicator) { + if (indicator.name === reportIndicator.expression) { + indicators.push(indicator.expression + ' as ' + indicator.name); + //if (_.contains(requestIndicators, indicator.name)) + // whereClause += ' and (' + indicator.expression + ')'; + } + }); + }); + var where = + " t2.endDate >= date('" + + queryParams.startDate + + "') and t2.endDate <= date('" + + queryParams.endDate + + "') "; + var onClause = + " on t1.person_id = t2.person_id and t1.endDate = date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day) "; + var sql = + 'select ' + + columns.toString() + + ' from (' + + 'select *, if(p1, p1, p2) as p1p2, ' + + " case when ar1 then 'active_return' when ne1 then 'new_enrollment' " + + "when ti1 then 'transfer_in' when ltfu1 then 'LTFU' when to1 then 'transfer_out' " + + "when d1 then 'dead' when neg1 then 'HIV_negative' when sd1 then 'self_disengaged' " + + "else 'self_transfer_out' end as initial_state, " + + "case when ar2 then 'active_return' when ne2 then 'new_enrollment' when ti2 then 'transfer_in' " + + "when ltfu2 then 'LTFU' when to2 then 'transfer_out' when d2 then 'dead' " + + "when neg2 then 'HIV_negative' when sd2 then 'self_disengaged' else 'self_transfer_out' " + + 'end as next_state ' + + 'from ' + + '(select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, ' + + 'if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, ' + + 'if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, ' + + 't1.active_return as ar1, t1.new_enrollments as ne1, t1.transfer_in as ti1, ' + + 't1.LTFU as ltfu1, t1.transfer_out_patients as to1, t1.deaths as d1, ' + + 't1.HIV_negative_patients as neg1, t1.self_disengaged_patients as sd1, ' + + 't2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, ' + + 't2.LTFU as ltfu2, t2.transfer_out_patients as to2, t2.deaths as d2, ' + + 't2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 ' + + 'from ( ' + + this.getPatientCareStatusInternalQuery(queryParams, indicators, where) + + ' ) `t1` ' + + 'left outer join( ' + + this.getPatientCareStatusInternalQuery(queryParams, indicators, where) + + ' ) t2 ' + + onClause + + ' union all ' + + 'select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, ' + + 'if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, ' + + 'if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, ' + + ' t1.active_return, t1.new_enrollments, t1.transfer_in, t1.LTFU, t1.transfer_out_patients, ' + + ' t1.deaths, t1.HIV_negative_patients, t1.self_disengaged_patients, ' + + 't2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, t2.LTFU as ltfu2, ' + + 't2.transfer_out_patients as to2, t2.deaths as d2, t2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 ' + + 'from( ' + + this.getPatientCareStatusInternalQuery(queryParams, indicators, where) + + ' ) `t1` ' + + 'right outer join( ' + + this.getPatientCareStatusInternalQuery(queryParams, indicators, where) + + ' ) t2 ' + + onClause + + 'having t1.person_id is null ) tn ' + + "having initial_state = '" + + requestIndicators[0] + + "' " + + "and next_state = '" + + requestIndicators[1] + + "' " + + " and date(to_month)=date('" + + queryParams.endDate + + "') " + + ') t1 ' + + ' INNER JOIN amrs.person_name `person_name` ON (t1.p1p2 = person_name.person_id and (person_name.voided is null || person_name.voided = 0)) ' + + 'LEFT OUTER JOIN amrs.patient_identifier `id` ON (t1.p1p2 = id.patient_id) ' + + 'INNER JOIN amrs.person `person` ON (t1.p1p2 = person.person_id) ' + + ' group by t1.p1p2 '; + + queryParts.sql = sql; + db.queryServer(queryParts, function (result) { + result.sql = sql; + callback(result); + }); + }, + cohortPatientListQuery: function (queryParams, callback) { + var queryParts = {}; + var indicators = []; + var whereClause = ''; + var requestIndicators = (queryParams.indicator || '').split('_to_'); + var columns = [ + 'patient_uuid', + 'p1p2', + 'next_state', + 'initial_state', + 'person.gender', + 'person.birthdate', + 'extract(year from (from_days(datediff(now(),person.birthdate)))) as age', + "concat(COALESCE(person_name.given_name,''),' ',COALESCE(person_name.middle_name,''),' ',COALESCE(person_name.family_name,'')) as person_name", + "group_concat(distinct id.identifier separator ', ') as identifiers" + ]; + + // add patient level indicators from the report schema & whereClause from queryParams + _.each(patientStatusReport[0].indicators, function (reportIndicator) { + _.each(reportFactory.indicatorsSchema, function (indicator) { + if (indicator.name === reportIndicator.expression) { + indicators.push(indicator.expression + ' as ' + indicator.name); + //if (_.contains(requestIndicators, indicator.name)) + // whereClause += ' and (' + indicator.expression + ')'; + } + }); + }); + var where1 = " t2.endDate = date('" + queryParams.startDate + "') "; + var where2 = " t2.endDate = date('" + queryParams.endDate + "') "; + var onClause = ' on t1.person_id = t2.person_id '; + var sql = + 'select ' + + columns.toString() + + ' from (' + + ' select patient_uuid, next_state, initial_state, if(p1, p1, p2) as p1p2 from (' + + 'select *, ' + + " case when ar1 then 'active_return' when ne1 then 'new_enrollment' " + + "when ti1 then 'transfer_in' when ltfu1 then 'LTFU' when to1 then 'transfer_out' " + + "when d1 then 'dead' when neg1 then 'HIV_negative' when sd1 then 'self_disengaged' " + + "else 'self_transfer_out' end as initial_state, " + + "case when ar2 then 'active_return' when ne2 then 'new_enrollment' when ti2 then 'transfer_in' " + + "when ltfu2 then 'LTFU' when to2 then 'transfer_out' when d2 then 'dead' " + + "when neg2 then 'HIV_negative' when sd2 then 'self_disengaged' else 'self_transfer_out' " + + 'end as next_state ' + + 'from ' + + '(select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, ' + + 'if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, ' + + 'if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, ' + + 't1.active_return as ar1, t1.new_enrollments as ne1, t1.transfer_in as ti1, ' + + 't1.LTFU as ltfu1, t1.transfer_out_patients as to1, t1.deaths as d1, ' + + 't1.HIV_negative_patients as neg1, t1.self_disengaged_patients as sd1, ' + + 't2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, ' + + 't2.LTFU as ltfu2, t2.transfer_out_patients as to2, t2.deaths as d2, ' + + 't2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 ' + + 'from ( ' + + this.getPatientCareStatusInternalQuery( + queryParams, + indicators, + where1 + ) + + ' ) `t1` ' + + 'left outer join( ' + + this.getPatientCareStatusInternalQuery( + queryParams, + indicators, + where2 + ) + + ' ) t2 ' + + onClause + + ' union all ' + + 'select t1.person_id as p1, t2.person_id as p2, t1.reporting_date as from_month, t2.reporting_date as to_month, ' + + 'if(t1.reporting_month, t1.reporting_month, t2.reporting_month) as reporting_month, ' + + 'if(t1.uuid, t1.uuid, t2.uuid) as patient_uuid, ' + + ' t1.active_return, t1.new_enrollments, t1.transfer_in, t1.LTFU, t1.transfer_out_patients, ' + + ' t1.deaths, t1.HIV_negative_patients, t1.self_disengaged_patients, ' + + 't2.active_return as ar2, t2.new_enrollments as ne2, t2.transfer_in as ti2, t2.LTFU as ltfu2, ' + + 't2.transfer_out_patients as to2, t2.deaths as d2, t2.HIV_negative_patients as neg2, t2.self_disengaged_patients as sd2 ' + + 'from( ' + + this.getPatientCareStatusInternalQuery( + queryParams, + indicators, + where1 + ) + + ' ) `t1` ' + + 'right outer join( ' + + this.getPatientCareStatusInternalQuery( + queryParams, + indicators, + where2 + ) + + ' ) t2 ' + + onClause + + 'having t1.person_id is null ) tn ) tn2 ' + + 'group by p1p2 ' + + "having initial_state = '" + + requestIndicators[0] + + "' " + + "and next_state = '" + + requestIndicators[1] + + "' " + + ') t1 ' + + ' INNER JOIN amrs.person_name `person_name` ON (t1.p1p2 = person_name.person_id and (person_name.voided is null || person_name.voided = 0)) ' + + 'LEFT OUTER JOIN amrs.patient_identifier `id` ON (t1.p1p2 = id.patient_id) ' + + 'INNER JOIN amrs.person `person` ON (t1.p1p2 = person.person_id) ' + + ' group by t1.p1p2 '; + + queryParts.sql = sql; + db.queryServer(queryParts, function (result) { + result.sql = sql; + callback(result); + }); + }, + + getPatientCareStatusInternalQuery: function ( + queryParams, + indicators, + whereClause + ) { + return ( + ' SELECT t2.endDate as reporting_date, ' + + "date_format(t2.endDate, '%m/%Y') as reporting_month, " + + 't2.endDate,t1.uuid,t1.person_id, ' + + indicators.toString() + + ' FROM etl.dates `t2` ' + + 'INNER JOIN etl.flat_hiv_summary_v15b `t1` force index (loc_id_enc_date_next_clinic) ON' + + ' (date(t1.encounter_datetime) <= date(t2.endDate)) ' + + 'WHERE (' + + whereClause + + ' and t1.location_id in(' + + queryParams.locations.toString() + + ') and t1.is_clinical_encounter = 1 ' + + 'and (t1.next_clinical_datetime_hiv is null ' + + 'or date(t1.next_clinical_datetime_hiv) > t2.endDate)' + + ')' + ); + } + }; +})(); diff --git a/dao/clinic/etl-clinic-dao.js b/dao/clinic/etl-clinic-dao.js index 0fcd2d5f8..98fa5c40d 100755 --- a/dao/clinic/etl-clinic-dao.js +++ b/dao/clinic/etl-clinic-dao.js @@ -6,320 +6,438 @@ var _ = require('underscore'); var reportFactory = require('../../etl-factory'); var Boom = require('boom'); //extends Hapi Error Reporting. Returns HTTP-friendly error objects: github.com/hapijs/boom var helpers = require('../../etl-helpers'); -module.exports = function () { - return { - getClinicEncounterData: function getClinicEncounterData(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - var filters = { - s: "" - }; - if (request.query.filters) - filters = helpers.getFilters(JSON.parse(request.query.filters)); - var where = ["t1.location_uuid = ?", uuid]; - if (filters.s !== "") { - where[0] += " AND " + filters.s; - where = where.concat(filters.vals); - } - - - var queryParts = { - columns: request.query.fields || "t1.*,t2.gender,round(datediff(t1.encounter_datetime,t2.birthdate)/365) as age,group_concat(identifier) as identifiers", - table: "etl.flat_hiv_summary", - joins: [ - ['amrs.person', 't2', 't1.person_id = t2.person_id'], - ['amrs.patient_identifier', 't3', 't1.person_id=t3.patient_id'] - ], - where: where, - group: ['person_id', 'encounter_id'], - order: order || [{ - column: 'encounter_datetime', - asc: false - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - _.each(result.result, function (row) { - row.cur_arv_meds = helpers.getARVNames(row.cur_arv_meds); - row.arv_first_regimen = helpers.getARVNames(row.arv_first_regimen); - }); - callback(result); - }); - }, - getClinicHivSummayIndicators: function getClinicHivSummayIndicators(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - - var query = ""; - - var queryParts = { - columns: request.query.fields || "*", - table: "etl.hiv_summary_indicators", - where: ["location = ?", uuid], - order: order || [{ - column: 'encounter_datetime', - asc: false - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); - }); - }, - getClinicAppointmentSchedule: function getClinicAppointmentSchedule(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - var startDate = request.query.startDate || new Date().toISOString().substring(0, 10); - var endDate = request.query.endDate || new Date().toISOString().substring(0, 10); - - if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; - if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; - - var queryParts = { - columns: request.query.fields || "t1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers", - table: "etl.flat_hiv_summary", - joins: [ - // ['etl.derived_encounter', 't2', 't1.encounter_id = t2.encounter_id'], - ['amrs.person_name', 't3', 't1.person_id = t3.person_id and (t3.voided is null || t3.voided = 0)'], - ['amrs.patient_identifier', 't4', 't1.person_id=t4.patient_id'] - ], - where: ["t1.location_uuid = ? and date(rtc_date) >= ? and date(rtc_date) <= ?", uuid, startDate, endDate], - group: ['person_id'], - order: order || [{ - column: 'family_name', - asc: true - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); - }); - - }, - getClinicDailyVisits: function getClinicDailyVisits(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - var startDate = request.query.startDate || new Date().toISOString().substring(0, 10); - var endDate = request.query.endDate || new Date().toISOString().substring(0, 10); - - if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; - if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; - - var queryParts = { - columns: request.query.fields || "t1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers", - table: "etl.flat_hiv_summary", - joins: [ - // ['etl.derived_encounter', 't2', 't1.encounter_id = t2.encounter_id'], - ['amrs.person_name', 't3', 't1.person_id = t3.person_id and (t3.voided is null || t3.voided = 0)'], - ['amrs.patient_identifier', 't4', 't1.person_id=t4.patient_id'] - ], - where: ["t1.location_uuid = ? and date(encounter_datetime) >= ? and date(encounter_datetime) <= ?", uuid, startDate, endDate], - group: ['person_id'], - order: order || [{ - column: 'family_name', - asc: true - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); - }); - - }, - getHasNotReturned: function getHasNotReturned(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - var startDate = request.query.startDate || new Date().toISOString().substring(0, 10); - var endDate = request.query.endDate || new Date().toISOString().substring(0, 10); - - if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; - if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; - - var queryParts = { - columns: request.query.fields || "t1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers", - table: "etl.flat_hiv_summary", - joins: [ - ['amrs.person_name', 't3', 't1.person_id = t3.person_id and (t3.voided is null || t3.voided = 0)'], - ['amrs.patient_identifier', 't4', 't1.person_id=t4.patient_id'] - ], - where: ["t1.location_uuid = ? and date(t1.rtc_date) between ? and ? and next_clinical_datetime_hiv is null", - - uuid, startDate, endDate - ], - group: ['person_id'], - order: order || [{ - column: 'family_name', - asc: true - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - db.queryServer_test(queryParts, function (result) { - callback(result); - }); - - }, - getClinicMonthlyAppointmentSchedule: function getClinicMonthlyAppointmentSchedule(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - var startDate = request.query.startDate || new Date().toISOString().substring(0, 10); - - var queryParts = { - columns: request.query.fields || ["date(rtc_date) as rtc_date", "date_format(rtc_date,'%W') as day_of_week", "count( distinct t1.person_id) as total"], - table: "etl.flat_hiv_summary", - where: ["t1.location_uuid = ? and date_format(rtc_date,'%Y-%m') = date_format(?,'%Y-%m')", uuid, startDate], - group: ['rtc_date'], - order: order || [{ - column: 'rtc_date', - asc: true - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); - }); - }, - getClinicMonthlySummary: function getClinicMonthlySummary(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - var startDate = request.query.startDate || new Date().toISOString().substring(0, 10); - var endDate = request.query.endDate || new Date().toISOString().substring(0, 10); - - if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; - if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; - - var queryParts = {}; - queryParts.values = [uuid, startDate, endDate, uuid, startDate, endDate]; - queryParts.startDate = startDate; - var sql = "SELECT d AS rtc_date," + - " date_format(d,'%W') AS day_of_week," + - " SUM(CASE WHEN description = 'schedule' THEN total_scheduled ELSE 0 END) AS total_visited," + - " SUM(CASE WHEN description = 'encounter' THEN total_scheduled ELSE 0 END) AS total," + - " (CASE WHEN CURDATE() > d THEN scheduled_and_attended ELSE 0 END) as scheduled_and_attended," + - " (CASE WHEN CURDATE() > d THEN has_not_returned ELSE 0 END) as has_not_returned from" + - " (SELECT date(rtc_date) AS d, 'schedule' AS description, date_format(rtc_date,'%W') AS day_of_week, count(DISTINCT t1.person_id) AS total_scheduled,location_id, count(DISTINCT if(next_clinical_datetime_hiv IS NOT NULL,t1.person_id,NULL)) AS scheduled_and_attended, count(DISTINCT if(next_clinical_datetime_hiv IS NULL,t1.person_id,NULL)) AS has_not_returned" + - " FROM etl.flat_hiv_summary t1" + - " WHERE t1.location_uuid = ?" + - " AND rtc_date BETWEEN ? AND ? GROUP BY d" + - " UNION SELECT date(encounter_datetime) AS d, 'encounter' AS description, date_format(encounter_datetime,'%W') AS day_of_week, count(DISTINCT t1.person_id) AS total_visits,location_id, count(DISTINCT if(next_clinical_datetime_hiv IS NOT NULL,t1.person_id,NULL)) AS scheduled_and_attended, count(DISTINCT if(next_clinical_datetime_hiv IS NULL,t1.person_id,NULL)) AS has_not_returned" + - " FROM etl.flat_hiv_summary t1" + - " WHERE t1.location_uuid = ? " + - " AND date(encounter_datetime) BETWEEN ? AND ?" + - " GROUP BY d) AS a GROUP BY d;"; - queryParts.sql = sql; - db.queryServer(queryParts, function (result) { - callback(result); - }); - }, - getClinicMonthlyVisits: function getClinicMonthlyVisits(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - var startDate = request.query.startDate || new Date().toISOString().substring(0, 10); - - var queryParts = { - columns: request.query.fields || ["date(encounter_datetime) as visit_date", "date_format(encounter_datetime,'%W') as day_of_week", "count( distinct t1.person_id) as total"], - table: "etl.flat_hiv_summary", - where: ["t1.location_uuid = ? and date_format(encounter_datetime,'%Y-%m') = date_format(?,'%Y-%m')", uuid, startDate], - group: ['encounter_datetime'], - order: order || [{ - column: 'encounter_datetime', - asc: true - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); - }); - }, - getDefaulterList: function getDefaulterList(request, callback) { - var uuids = request.query.locationUuids; - var order = helpers.getSortOrder(request.query.order); - - var defaulterPeriod = request.query.defaulterPeriod || 30; - var maxPeriod = request.query.maxDefaultPeriod || ''; - var maxDefaultPeriodFilter = ''; - var programUuid = request.query.programUuid; - - // Define optional max default period - if (maxPeriod) { - maxDefaultPeriodFilter = 'and days_since_rtc <= ?'; - } - - var queryParts = { - columns: request.query.fields || ["*", "extract(year from (from_days(datediff(now(),t3.birthdate)))) as age", - "date_format(fhs.rtc_date, '%Y-%m-%d') as latest_rtc_date", - "fhs.vl_1 as latest_vl", - "date_format(fhs.vl_1_date, '%Y-%m-%d') as latest_vl_date", - "CONCAT(COALESCE(DATE_FORMAT(fhs.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, '')) as last_appointment", - "fhs.cur_arv_meds as cur_meds", - "fhs.vl_2 as previous_vl", - "date_format(fhs.vl_2_date, '%Y-%m-%d') as previous_vl_date", - "pa.address3 as nearest_center" - ], - table: "etl.flat_defaulters", - joins: [ - ['amrs.person', 't3', 't1.person_id = t3.person_id and t3.death_date is null'] - ], - leftOuterJoins: [ - ['amrs.patient_program', 't4', 't1.person_id = t4.patient_id AND t4.date_completed IS NULL'], - ['(SELECT program_id, uuid as `programuuid` FROM amrs.program ) `t5` ON (t4.program_id = t5.program_id)'], - ['etl.flat_hiv_summary_v15b', 'fhs', 't1.person_id = fhs.person_id AND fhs.next_clinical_location_id IS NULL AND fhs.encounter_type NOT IN (99999)'], - ['amrs.encounter_type', 'et', 'fhs.encounter_type = et.encounter_type_id'], - ['amrs.person_address', 'pa', 't1.person_id = pa.person_id'] - ], - where: ["t1.location_uuid in (?) and programuuid in (?) and days_since_rtc >= ? " + maxDefaultPeriodFilter, uuids, programUuid, defaulterPeriod, maxPeriod], - order: order || [{ - column: 'days_since_rtc', - asc: true - }], - group: ['t1.person_id'], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - _.each(result.result, (item) => { - item.cur_meds = helpers.getARVNames(item.cur_meds); - }); - callback(result); - }); - }, - getClinicDefaulterList: function getClinicDefaulterList(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - - var defaulterPeriod = request.query.defaulterPeriod || 30; - - var queryParts = { - columns: request.query.fields || ["*", "extract(year from (from_days(datediff(now(),t3.birthdate)))) as age"], - table: "etl.flat_defaulters", - joins: [ - ['amrs.person', 't3', 't1.person_id = t3.person_id '] - ], - where: ["location_uuid = ? and days_since_rtc >= ?", uuid, defaulterPeriod], - order: order || [{ - column: 'days_since_rtc', - asc: true - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); - }); - } - }; -} (); \ No newline at end of file +module.exports = (function () { + return { + getClinicEncounterData: function getClinicEncounterData(request, callback) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + var filters = { + s: '' + }; + if (request.query.filters) + filters = helpers.getFilters(JSON.parse(request.query.filters)); + var where = ['t1.location_uuid = ?', uuid]; + if (filters.s !== '') { + where[0] += ' AND ' + filters.s; + where = where.concat(filters.vals); + } + + var queryParts = { + columns: + request.query.fields || + 't1.*,t2.gender,round(datediff(t1.encounter_datetime,t2.birthdate)/365) as age,group_concat(identifier) as identifiers', + table: 'etl.flat_hiv_summary', + joins: [ + ['amrs.person', 't2', 't1.person_id = t2.person_id'], + ['amrs.patient_identifier', 't3', 't1.person_id=t3.patient_id'] + ], + where: where, + group: ['person_id', 'encounter_id'], + order: order || [ + { + column: 'encounter_datetime', + asc: false + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + _.each(result.result, function (row) { + row.cur_arv_meds = helpers.getARVNames(row.cur_arv_meds); + row.arv_first_regimen = helpers.getARVNames(row.arv_first_regimen); + }); + callback(result); + }); + }, + getClinicHivSummayIndicators: function getClinicHivSummayIndicators( + request, + callback + ) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + + var query = ''; + + var queryParts = { + columns: request.query.fields || '*', + table: 'etl.hiv_summary_indicators', + where: ['location = ?', uuid], + order: order || [ + { + column: 'encounter_datetime', + asc: false + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + }, + getClinicAppointmentSchedule: function getClinicAppointmentSchedule( + request, + callback + ) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + var startDate = + request.query.startDate || new Date().toISOString().substring(0, 10); + var endDate = + request.query.endDate || new Date().toISOString().substring(0, 10); + + if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; + if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; + + var queryParts = { + columns: + request.query.fields || + 't1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers', + table: 'etl.flat_hiv_summary', + joins: [ + // ['etl.derived_encounter', 't2', 't1.encounter_id = t2.encounter_id'], + [ + 'amrs.person_name', + 't3', + 't1.person_id = t3.person_id and (t3.voided is null || t3.voided = 0)' + ], + ['amrs.patient_identifier', 't4', 't1.person_id=t4.patient_id'] + ], + where: [ + 't1.location_uuid = ? and date(rtc_date) >= ? and date(rtc_date) <= ?', + uuid, + startDate, + endDate + ], + group: ['person_id'], + order: order || [ + { + column: 'family_name', + asc: true + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + }, + getClinicDailyVisits: function getClinicDailyVisits(request, callback) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + var startDate = + request.query.startDate || new Date().toISOString().substring(0, 10); + var endDate = + request.query.endDate || new Date().toISOString().substring(0, 10); + + if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; + if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; + + var queryParts = { + columns: + request.query.fields || + 't1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers', + table: 'etl.flat_hiv_summary', + joins: [ + // ['etl.derived_encounter', 't2', 't1.encounter_id = t2.encounter_id'], + [ + 'amrs.person_name', + 't3', + 't1.person_id = t3.person_id and (t3.voided is null || t3.voided = 0)' + ], + ['amrs.patient_identifier', 't4', 't1.person_id=t4.patient_id'] + ], + where: [ + 't1.location_uuid = ? and date(encounter_datetime) >= ? and date(encounter_datetime) <= ?', + uuid, + startDate, + endDate + ], + group: ['person_id'], + order: order || [ + { + column: 'family_name', + asc: true + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + }, + getHasNotReturned: function getHasNotReturned(request, callback) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + var startDate = + request.query.startDate || new Date().toISOString().substring(0, 10); + var endDate = + request.query.endDate || new Date().toISOString().substring(0, 10); + + if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; + if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; + + var queryParts = { + columns: + request.query.fields || + 't1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers', + table: 'etl.flat_hiv_summary', + joins: [ + [ + 'amrs.person_name', + 't3', + 't1.person_id = t3.person_id and (t3.voided is null || t3.voided = 0)' + ], + ['amrs.patient_identifier', 't4', 't1.person_id=t4.patient_id'] + ], + where: [ + 't1.location_uuid = ? and date(t1.rtc_date) between ? and ? and next_clinical_datetime_hiv is null', + + uuid, + startDate, + endDate + ], + group: ['person_id'], + order: order || [ + { + column: 'family_name', + asc: true + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + }, + getClinicMonthlyAppointmentSchedule: function getClinicMonthlyAppointmentSchedule( + request, + callback + ) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + var startDate = + request.query.startDate || new Date().toISOString().substring(0, 10); + + var queryParts = { + columns: request.query.fields || [ + 'date(rtc_date) as rtc_date', + "date_format(rtc_date,'%W') as day_of_week", + 'count( distinct t1.person_id) as total' + ], + table: 'etl.flat_hiv_summary', + where: [ + "t1.location_uuid = ? and date_format(rtc_date,'%Y-%m') = date_format(?,'%Y-%m')", + uuid, + startDate + ], + group: ['rtc_date'], + order: order || [ + { + column: 'rtc_date', + asc: true + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + }, + getClinicMonthlySummary: function getClinicMonthlySummary( + request, + callback + ) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + var startDate = + request.query.startDate || new Date().toISOString().substring(0, 10); + var endDate = + request.query.endDate || new Date().toISOString().substring(0, 10); + + if (!_.isUndefined(startDate)) startDate = startDate.split('T')[0]; + if (!_.isUndefined(endDate)) endDate = endDate.split('T')[0]; + + var queryParts = {}; + queryParts.values = [uuid, startDate, endDate, uuid, startDate, endDate]; + queryParts.startDate = startDate; + var sql = + 'SELECT d AS rtc_date,' + + " date_format(d,'%W') AS day_of_week," + + " SUM(CASE WHEN description = 'schedule' THEN total_scheduled ELSE 0 END) AS total_visited," + + " SUM(CASE WHEN description = 'encounter' THEN total_scheduled ELSE 0 END) AS total," + + ' (CASE WHEN CURDATE() > d THEN scheduled_and_attended ELSE 0 END) as scheduled_and_attended,' + + ' (CASE WHEN CURDATE() > d THEN has_not_returned ELSE 0 END) as has_not_returned from' + + " (SELECT date(rtc_date) AS d, 'schedule' AS description, date_format(rtc_date,'%W') AS day_of_week, count(DISTINCT t1.person_id) AS total_scheduled,location_id, count(DISTINCT if(next_clinical_datetime_hiv IS NOT NULL,t1.person_id,NULL)) AS scheduled_and_attended, count(DISTINCT if(next_clinical_datetime_hiv IS NULL,t1.person_id,NULL)) AS has_not_returned" + + ' FROM etl.flat_hiv_summary t1' + + ' WHERE t1.location_uuid = ?' + + ' AND rtc_date BETWEEN ? AND ? GROUP BY d' + + " UNION SELECT date(encounter_datetime) AS d, 'encounter' AS description, date_format(encounter_datetime,'%W') AS day_of_week, count(DISTINCT t1.person_id) AS total_visits,location_id, count(DISTINCT if(next_clinical_datetime_hiv IS NOT NULL,t1.person_id,NULL)) AS scheduled_and_attended, count(DISTINCT if(next_clinical_datetime_hiv IS NULL,t1.person_id,NULL)) AS has_not_returned" + + ' FROM etl.flat_hiv_summary t1' + + ' WHERE t1.location_uuid = ? ' + + ' AND date(encounter_datetime) BETWEEN ? AND ?' + + ' GROUP BY d) AS a GROUP BY d;'; + queryParts.sql = sql; + db.queryServer(queryParts, function (result) { + callback(result); + }); + }, + getClinicMonthlyVisits: function getClinicMonthlyVisits(request, callback) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + var startDate = + request.query.startDate || new Date().toISOString().substring(0, 10); + + var queryParts = { + columns: request.query.fields || [ + 'date(encounter_datetime) as visit_date', + "date_format(encounter_datetime,'%W') as day_of_week", + 'count( distinct t1.person_id) as total' + ], + table: 'etl.flat_hiv_summary', + where: [ + "t1.location_uuid = ? and date_format(encounter_datetime,'%Y-%m') = date_format(?,'%Y-%m')", + uuid, + startDate + ], + group: ['encounter_datetime'], + order: order || [ + { + column: 'encounter_datetime', + asc: true + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + }, + getDefaulterList: function getDefaulterList(request, callback) { + var uuids = request.query.locationUuids; + var order = helpers.getSortOrder(request.query.order); + + var defaulterPeriod = request.query.defaulterPeriod || 30; + var maxPeriod = request.query.maxDefaultPeriod || ''; + var maxDefaultPeriodFilter = ''; + var programUuid = request.query.programUuid; + + // Define optional max default period + if (maxPeriod) { + maxDefaultPeriodFilter = 'and days_since_rtc <= ?'; + } + + var queryParts = { + columns: request.query.fields || [ + '*', + 'extract(year from (from_days(datediff(now(),t3.birthdate)))) as age', + "date_format(fhs.rtc_date, '%Y-%m-%d') as latest_rtc_date", + 'fhs.vl_1 as latest_vl', + "date_format(fhs.vl_1_date, '%Y-%m-%d') as latest_vl_date", + "CONCAT(COALESCE(DATE_FORMAT(fhs.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, '')) as last_appointment", + 'fhs.cur_arv_meds as cur_meds', + 'fhs.vl_2 as previous_vl', + "date_format(fhs.vl_2_date, '%Y-%m-%d') as previous_vl_date", + 'pa.address3 as nearest_center' + ], + table: 'etl.flat_defaulters', + joins: [ + [ + 'amrs.person', + 't3', + 't1.person_id = t3.person_id and t3.death_date is null' + ] + ], + leftOuterJoins: [ + [ + 'amrs.patient_program', + 't4', + 't1.person_id = t4.patient_id AND t4.date_completed IS NULL' + ], + [ + '(SELECT program_id, uuid as `programuuid` FROM amrs.program ) `t5` ON (t4.program_id = t5.program_id)' + ], + [ + 'etl.flat_hiv_summary_v15b', + 'fhs', + 't1.person_id = fhs.person_id AND fhs.next_clinical_location_id IS NULL AND fhs.encounter_type NOT IN (99999)' + ], + [ + 'amrs.encounter_type', + 'et', + 'fhs.encounter_type = et.encounter_type_id' + ], + ['amrs.person_address', 'pa', 't1.person_id = pa.person_id'] + ], + where: [ + 't1.location_uuid in (?) and programuuid in (?) and days_since_rtc >= ? ' + + maxDefaultPeriodFilter, + uuids, + programUuid, + defaulterPeriod, + maxPeriod + ], + order: order || [ + { + column: 'days_since_rtc', + asc: true + } + ], + group: ['t1.person_id'], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + _.each(result.result, (item) => { + item.cur_meds = helpers.getARVNames(item.cur_meds); + }); + callback(result); + }); + }, + getClinicDefaulterList: function getClinicDefaulterList(request, callback) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + + var defaulterPeriod = request.query.defaulterPeriod || 30; + + var queryParts = { + columns: request.query.fields || [ + '*', + 'extract(year from (from_days(datediff(now(),t3.birthdate)))) as age' + ], + table: 'etl.flat_defaulters', + joins: [['amrs.person', 't3', 't1.person_id = t3.person_id ']], + where: [ + 'location_uuid = ? and days_since_rtc >= ?', + uuid, + defaulterPeriod + ], + order: order || [ + { + column: 'days_since_rtc', + asc: true + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + } + }; +})(); diff --git a/dao/concepts/concept-name-dao.js b/dao/concepts/concept-name-dao.js index bcad45da4..21ab7766c 100644 --- a/dao/concepts/concept-name-dao.js +++ b/dao/concepts/concept-name-dao.js @@ -2,9 +2,9 @@ 'use strict'; const NodeCache = require('node-cache'); const concept_cache = new NodeCache(); -var Promise = require('bluebird'); -var squel = require('squel'); -var _ = require('lodash'); +var Promise = require('bluebird'); +var squel = require('squel'); +var _ = require('lodash'); var connection = require('../../dao/connection/mysql-connection-service.js'); var getConceptName = { @@ -13,52 +13,56 @@ var getConceptName = { module.exports = getConceptName; -function getConceptNames () { - +function getConceptNames() { return new Promise(function (resolve, reject) { - connection.getServerConnection() + connection + .getServerConnection() .then(function (conn) { - var query = squel.select() + var query = squel + .select() .field('cn.concept_id') .field('cn.name') .field('cn.uuid') .from('amrs.concept_name', 'cn') .toString(); - conn.query(query + ' where concept_name_type is not null', {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); + conn.query( + query + ' where concept_name_type is not null', + {}, + function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + resolve(JSON.parse(JSON.stringify(rows))); + } + conn.release(); } - else { - resolve(JSON.parse(JSON.stringify(rows))); - } - conn.release(); - }); + ); }) .catch(function (err) { reject('Error establishing connection to MySql Server'); }); }); - } -function getConceptNamesFromCacheSync () { +function getConceptNamesFromCacheSync() { return new Promise(function (resolve, reject) { concept_cache.get('concept_names', function (err, reply) { if (err) { reject(err); } else { - if (reply == undefined) { - getConceptNames().then(function (rows) { - var tests = {}; - _.each(rows, function(concept) { - tests[concept.concept_id] = concept.name + getConceptNames() + .then(function (rows) { + var tests = {}; + _.each(rows, function (concept) { + tests[concept.concept_id] = concept.name; + }); + concept_cache.set('concept_names', tests, 86400000); + resolve(tests); + }) + .catch(function (_err) { + reject(_err); }); - concept_cache.set('concept_names', tests, 86400000); - resolve(tests); - }).catch(function(_err) { - reject(_err); - }); } else { resolve(reply); } @@ -66,7 +70,3 @@ function getConceptNamesFromCacheSync () { }); }); } - - - - diff --git a/dao/connection/mysql-connection-service.js b/dao/connection/mysql-connection-service.js index 9ddc894ce..3c95605d3 100755 --- a/dao/connection/mysql-connection-service.js +++ b/dao/connection/mysql-connection-service.js @@ -5,22 +5,22 @@ var mysql = require('mysql'); var Promise = require('bluebird'); var config = require('../../conf/config'); - var pool = mysql.createPool(config.mysql); +var pool = mysql.createPool(config.mysql); var def = { - getServerConnection: getServerConnection + getServerConnection: getServerConnection }; module.exports = def; function getServerConnection() { - return new Promise(function (resolve, reject) { - pool.getConnection(function (err, connection) { - if (err) { - reject(err); - } else { - resolve(connection); - } - }); + return new Promise(function (resolve, reject) { + pool.getConnection(function (err, connection) { + if (err) { + reject(err); + } else { + resolve(connection); + } }); + }); } diff --git a/dao/eid/eid-sync-log.js b/dao/eid/eid-sync-log.js index cbadaf59b..5cc71bf32 100755 --- a/dao/eid/eid-sync-log.js +++ b/dao/eid/eid-sync-log.js @@ -1,14 +1,17 @@ 'use strict'; var db = require('../../etl-db'); -var eidResultsSchema=require('../../eid-lab-results'); +var eidResultsSchema = require('../../eid-lab-results'); module.exports = { getEidSyncLog: getEidSyncLog -} +}; -function getEidSyncLog(request,callback) { +function getEidSyncLog(request, callback) { var queryParts = { columns: eidResultsSchema.patientLabResultsSchema.columns, - table: eidResultsSchema.patientLabResultsSchema.table.schema + '.' + eidResultsSchema.patientLabResultsSchema.table.tableName, + table: + eidResultsSchema.patientLabResultsSchema.table.schema + + '.' + + eidResultsSchema.patientLabResultsSchema.table.tableName, where: [ eidResultsSchema.patientLabResultsSchema.filters[0].expression, request.query.patientUuId @@ -22,14 +25,11 @@ function getEidSyncLog(request,callback) { limit: 3 }; - return new Promise(function(resolve, reject) { - db.queryServer_test(queryParts, function(result) { - - if(callback) - callback(result); + return new Promise(function (resolve, reject) { + db.queryServer_test(queryParts, function (result) { + if (callback) callback(result); resolve(result); }); }); - } diff --git a/dao/eid/etl-eid-dao.js b/dao/eid/etl-eid-dao.js index c4db0f6f9..50d072bf9 100755 --- a/dao/eid/etl-eid-dao.js +++ b/dao/eid/etl-eid-dao.js @@ -1,82 +1,84 @@ /*jshint -W003, -W097, -W117, -W026 */ 'use strict'; -const - db = require('../../etl-db') - , _ = require('underscore') - , Boom = require('boom') //extends Hapi Error Reporting. Returns HTTP-friendly error objects: github.com/hapijs/boom - , helpers = require('../../etl-helpers') - , http = require('http') - , https = require('https') - , Promise = require('bluebird') - , rp = require('../../request-config') - , config = require('../../conf/config') - , eidService = require('../../service/eid/eid.service'); - -module.exports = function () { - - function postLabOrderToEid(request, callback) { - - const rawPayload = JSON.parse(JSON.stringify(request.payload)); - const labName = request.params.lab; - const orderNumber = rawPayload.orderNumber; - - getEidOrder(rawPayload, labName, orderNumber) - .then(function(orders) { - - if(orders.length == 0) { - - eidService.generatePayload(rawPayload, - function (payload) { - var eidServer = eidService.getEidServerUrl(labName, rawPayload.type,'post'); - return new Promise(function (resolve, reject) { - rp.postRequestPromise(payload, eidServer.url) - .then(function (response) { - if(response === 'Could not select database'){ - reject(response); - callback(Boom.internal(response)); - return; - } - resolve(response); - callback(payload); - }) - .catch(function (error) { - reject(error); - callback(Boom.badData(error.message)); - }) - }); - }, - function (err) { - callback(Boom.badData(err.message)); +const db = require('../../etl-db'), + _ = require('underscore'), + Boom = require('boom'), //extends Hapi Error Reporting. Returns HTTP-friendly error objects: github.com/hapijs/boom + helpers = require('../../etl-helpers'), + http = require('http'), + https = require('https'), + Promise = require('bluebird'), + rp = require('../../request-config'), + config = require('../../conf/config'), + eidService = require('../../service/eid/eid.service'); + +module.exports = (function () { + function postLabOrderToEid(request, callback) { + const rawPayload = JSON.parse(JSON.stringify(request.payload)); + const labName = request.params.lab; + const orderNumber = rawPayload.orderNumber; + + getEidOrder(rawPayload, labName, orderNumber) + .then(function (orders) { + if (orders.length == 0) { + eidService.generatePayload( + rawPayload, + function (payload) { + var eidServer = eidService.getEidServerUrl( + labName, + rawPayload.type, + 'post' + ); + return new Promise(function (resolve, reject) { + rp.postRequestPromise(payload, eidServer.url) + .then(function (response) { + if (response === 'Could not select database') { + reject(response); + callback(Boom.internal(response)); + return; + } + resolve(response); + callback(payload); + }) + .catch(function (error) { + reject(error); + callback(Boom.badData(error.message)); }); - } else { - - callback(Boom.badData('Forbidden: An order with the same order number exists in the eid system')); + }); + }, + function (err) { + callback(Boom.badData(err.message)); } + ); + } else { + callback( + Boom.badData( + 'Forbidden: An order with the same order number exists in the eid system' + ) + ); + } + }) + .catch(function (err) { + callback(Boom.badData(err.message)); + }); + } - }).catch(function(err) { - callback(Boom.badData(err.message)); - }); - }; - - function getPocToLabOrderPayload(request) { - - const rawPayload = JSON.parse(JSON.stringify(request.payload)); - const labName = request.params.lab; - const orderNumber = rawPayload.orderNumber; - - return new Promise(function(resolve, reject) { + function getPocToLabOrderPayload(request) { + const rawPayload = JSON.parse(JSON.stringify(request.payload)); + const labName = request.params.lab; + const orderNumber = rawPayload.orderNumber; - // getEidOrder(rawPayload, labName, orderNumber) - // .then(function(orders) { + return new Promise(function (resolve, reject) { + // getEidOrder(rawPayload, labName, orderNumber) + // .then(function(orders) { - // if(orders.length == 0) { + // if(orders.length == 0) { - var eidPayLoad = eidService.generatePocToEidPayLoad(rawPayload); - if(!_.isEmpty(eidPayLoad)){ - resolve(eidPayLoad); - }else{ - reject('Error Generating Payload'); - } + var eidPayLoad = eidService.generatePocToEidPayLoad(rawPayload); + if (!_.isEmpty(eidPayLoad)) { + resolve(eidPayLoad); + } else { + reject('Error Generating Payload'); + } // } else { @@ -85,110 +87,99 @@ module.exports = function () { // }).catch(function(err) { // reject(err.message); - // }); - - }); - }; - - function getEidOrder(rawPayload, labName, orderNumber) { - - var payload = { - "patientID[]" : '', - "location" : '', - "orderno[]" : orderNumber, - "DateDispatched" : '' - }; - - let eidServer = eidService.getEidServerUrl(labName, '', 'post'); - - switch (rawPayload.type) { - case 'VL': - payload.test = 2; - break; - case 'DNAPCR': - payload.test = 1; - break; - case 'CD4': + // }); + }); + } + + function getEidOrder(rawPayload, labName, orderNumber) { + var payload = { + 'patientID[]': '', + location: '', + 'orderno[]': orderNumber, + DateDispatched: '' + }; - var serverConfig = config.eidServer[labName]; + let eidServer = eidService.getEidServerUrl(labName, '', 'post'); - var apikey = ""; - var locations = config.eid.locations; + switch (rawPayload.type) { + case 'VL': + payload.test = 2; + break; + case 'DNAPCR': + payload.test = 1; + break; + case 'CD4': + var serverConfig = config.eidServer[labName]; - for(var i = 0; i < locations.length; i++) { + var apikey = ''; + var locations = config.eid.locations; - if(locations[i].name === labName) { - apikey = locations[i].cd4ApiKey; - break; - } - } - - eidServer = { - url: serverConfig.host + ':' + serverConfig.port + '/cd4/orders/api.php', - apiKey: apikey - }; + for (var i = 0; i < locations.length; i++) { + if (locations[i].name === labName) { + apikey = locations[i].cd4ApiKey; break; - } - - payload.apikey = eidServer.apiKey; - - return rp.getRequestPromise(payload, eidServer.url) - .then(function(response) { - - return new Promise(function(resolve, reject) { - if(response && response.posts) - resolve(response.posts); - else - resolve([]); - }); - }); - }; - - function loadOrderJustifications(request, reply) { - - var uuid = request.query.uuid; - const eidOrderMap = require('../../app/lab-integration/utils/regimen-config-loader'); - - var testOrderJustification = eidOrderMap.testOrderJustification; + } + } - if(uuid && testOrderJustification[uuid]) { + eidServer = { + url: + serverConfig.host + ':' + serverConfig.port + '/cd4/orders/api.php', + apiKey: apikey + }; + break; + } - var row = testOrderJustification[uuid]; - row.uuid = uuid; - var data = [row]; + payload.apikey = eidServer.apiKey; - reply({ - "statusCode": 0, - "data": data + return rp + .getRequestPromise(payload, eidServer.url) + .then(function (response) { + return new Promise(function (resolve, reject) { + if (response && response.posts) resolve(response.posts); + else resolve([]); }); + }); + } - } else if(uuid) { - - reply(Boom.notFound('justification not found')); - - } else { - - var data = []; + function loadOrderJustifications(request, reply) { + var uuid = request.query.uuid; + const eidOrderMap = require('../../app/lab-integration/utils/regimen-config-loader'); - for(var key in testOrderJustification) { - var obj = testOrderJustification[key]; - obj.uuid = key; - data.push(obj); - } + var testOrderJustification = eidOrderMap.testOrderJustification; - reply({ - "statusCode": 0, - "data": data - }) + if (uuid && testOrderJustification[uuid]) { + var row = testOrderJustification[uuid]; + row.uuid = uuid; + var data = [row]; - //load everything + reply({ + statusCode: 0, + data: data + }); + } else if (uuid) { + reply(Boom.notFound('justification not found')); + } else { + var data = []; + + for (var key in testOrderJustification) { + var obj = testOrderJustification[key]; + obj.uuid = key; + data.push(obj); } - }; - return { - postLabOrderToEid: postLabOrderToEid, - getPocToLabOrderPayload: getPocToLabOrderPayload, - loadOrderJustifications: loadOrderJustifications, - getEidOrder: getEidOrder + reply({ + statusCode: 0, + data: data + }); + + //load everything } -}(); + } + + return { + postLabOrderToEid: postLabOrderToEid, + getPocToLabOrderPayload: getPocToLabOrderPayload, + loadOrderJustifications: loadOrderJustifications, + getEidOrder: getEidOrder + }; +})(); diff --git a/dao/encounter-type/encounter-type-dao.js b/dao/encounter-type/encounter-type-dao.js index b99aec3d2..e298d279c 100755 --- a/dao/encounter-type/encounter-type-dao.js +++ b/dao/encounter-type/encounter-type-dao.js @@ -9,42 +9,34 @@ var connection = require('../../dao/connection/mysql-connection-service.js'); var authorizer = require('../../authorization/etl-authorizer'); var encounterType = { - getEncounterTypes : getEncounterTypes + getEncounterTypes: getEncounterTypes }; module.exports = encounterType; function getEncounterTypes() { - - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('et.encounter_type_id') - .field('et.name') - .field('et.uuid') - .from('amrs.encounter_type', 'et') - .toString(); - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - - - - }); - + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('et.encounter_type_id') + .field('et.name') + .field('et.uuid') + .from('amrs.encounter_type', 'et') + .toString(); + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } - - - - diff --git a/dao/enrollment/double-enrollment-check.js b/dao/enrollment/double-enrollment-check.js index 7de33b2a1..dde5d05e7 100644 --- a/dao/enrollment/double-enrollment-check.js +++ b/dao/enrollment/double-enrollment-check.js @@ -9,43 +9,40 @@ var connection = require('../../dao/connection/mysql-connection-service.js'); var authorizer = require('../../authorization/etl-authorizer'); var double_enrollment_check = { - getDoubleEnrollment : getDoubleEnrollment + getDoubleEnrollment: getDoubleEnrollment }; module.exports = double_enrollment_check; //check if patient is enrolled to a program before autoenrolling to prevent double enrollment -function getDoubleEnrollment(patientUuid,programUuid) { - - return new Promise(function (resolve, reject) { - - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('count(*) as count') - .from('amrs.patient_program', 'pp') - .join('amrs.person','p','pp.patient_id = p.person_id') - .join('amrs.program','pr','pp.program_id = pr.program_id') - .where('p.uuid = ?',patientUuid) - .where('pr.uuid = ?', programUuid) - .where('pp.date_completed IS NULL') - .toString(); - conn.query(query, {}, function (err, rows, fields) { - if (err) { - console.log(err); - reject('Error querying server'); - } - else { - - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); -//amrs patient - }); - -}; +function getDoubleEnrollment(patientUuid, programUuid) { + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('count(*) as count') + .from('amrs.patient_program', 'pp') + .join('amrs.person', 'p', 'pp.patient_id = p.person_id') + .join('amrs.program', 'pr', 'pp.program_id = pr.program_id') + .where('p.uuid = ?', patientUuid) + .where('pr.uuid = ?', programUuid) + .where('pp.date_completed IS NULL') + .toString(); + conn.query(query, {}, function (err, rows, fields) { + if (err) { + console.log(err); + reject('Error querying server'); + } else { + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + //amrs patient + }); +} diff --git a/dao/enrollment/enrollment-patient-program-dao.js b/dao/enrollment/enrollment-patient-program-dao.js index f7ef6b497..f28d71efc 100644 --- a/dao/enrollment/enrollment-patient-program-dao.js +++ b/dao/enrollment/enrollment-patient-program-dao.js @@ -9,40 +9,39 @@ var connection = require('../../dao/connection/mysql-connection-service.js'); var authorizer = require('../../authorization/etl-authorizer'); var enrollments = { - getPatientProgramEnrollment : getPatientProgramEnrollment + getPatientProgramEnrollment: getPatientProgramEnrollment }; module.exports = enrollments; -function getPatientProgramEnrollment(patientUuid,incompatibleprograms) { - - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('pp.uuid') - .from('amrs.patient_program', 'pp') - .join('amrs.person','p','pp.patient_id = p.person_id') - .join('amrs.program','pr','pp.program_id = pr.program_id') - .where('pr.uuid in ?',incompatibleprograms) - .where('p.uuid = ?',patientUuid) - .where('pp.date_completed IS NULL') - .toString(); - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - // console.log('patient programs Rows', rows); - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); -//amrs patient - }); - -}; +function getPatientProgramEnrollment(patientUuid, incompatibleprograms) { + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('pp.uuid') + .from('amrs.patient_program', 'pp') + .join('amrs.person', 'p', 'pp.patient_id = p.person_id') + .join('amrs.program', 'pr', 'pp.program_id = pr.program_id') + .where('pr.uuid in ?', incompatibleprograms) + .where('p.uuid = ?', patientUuid) + .where('pp.date_completed IS NULL') + .toString(); + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + // console.log('patient programs Rows', rows); + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + //amrs patient + }); +} diff --git a/dao/form-entry/errors-dao.js b/dao/form-entry/errors-dao.js index 5625459ce..18e207da5 100755 --- a/dao/form-entry/errors-dao.js +++ b/dao/form-entry/errors-dao.js @@ -4,27 +4,32 @@ var _ = require('underscore'); var cache = require('../../session-cache'); var etlLogger = require('../../etl-file-logger'); -module.exports = function () { +module.exports = (function () { + function logError(request, reply) { + var data = request.payload || request.body; - function logError(request, reply) { + var username = + request.auth && request.auth.credentials + ? request.auth.credentials.username + : ''; - var data = request.payload || request.body; + var file = '/tmp/form-submit-errors_' + username + '.log'; - var username = (request.auth && request.auth.credentials) ? request.auth.credentials.username : ''; + var logger = etlLogger.logger(file); + logger.error( + '-----------------------------------------------------------------------------------------------------------------------' + ); + logger.error(data); + logger.error( + '-----------------------------------------------------------------------------------------------------------------------' + ); + logger.close(); + reply({ + message: 'ok' + }); + } - var file = '/tmp/form-submit-errors_' + username + '.log'; - - var logger = etlLogger.logger(file); - logger.error('-----------------------------------------------------------------------------------------------------------------------') - logger.error(data); - logger.error('-----------------------------------------------------------------------------------------------------------------------') - logger.close(); - reply({ - message: 'ok' - }); - } - - return { - logError: logError - } -}(); + return { + logError: logError + }; +})(); diff --git a/dao/lab-cohorts/lab-cohorts-dao.js b/dao/lab-cohorts/lab-cohorts-dao.js index 8d10511d1..47e10b7a3 100755 --- a/dao/lab-cohorts/lab-cohorts-dao.js +++ b/dao/lab-cohorts/lab-cohorts-dao.js @@ -9,28 +9,27 @@ var eidPatientCohortService = require('../../service/eid/eid-patient-cohort.serv var config = require('../../conf/config'); var etlLogger = require('../../etl-file-logger'); - - module.exports = { - loadLabCohorts: loadLabCohorts, syncLabCohorts: syncLabCohorts -} +}; var max_limit = 1000000; function loadLabCohorts(request, reply) { - var startDate = request.query.startDate; var endDate = request.query.endDate; var limit = request.query.limit; var offset = request.query.offset; load(startDate, endDate, limit, offset) - .then(function(data) { + .then(function (data) { reply(data); - }).catch(function(err) { - var logger = etlLogger.logger(config.logging.eidPath + '/' + config.logging.eidFile); + }) + .catch(function (err) { + var logger = etlLogger.logger( + config.logging.eidPath + '/' + config.logging.eidFile + ); logger.error('Error Loading lab cohorts: ' + err.stack.split('/n')); logger.close(); @@ -42,7 +41,6 @@ function loadLabCohorts(request, reply) { } function syncLabCohorts(request, reply) { - var startDate = request.query.startDate; var endDate = request.query.endDate; var locations = request.query.locations; @@ -52,22 +50,19 @@ function syncLabCohorts(request, reply) { var eid_locations = config.eid.locations; - if(locations && locations.length > 0) { + if (locations && locations.length > 0) { var l = locations.trim().split(','); - for(var i = 0; i < l.length; i++) { - + for (var i = 0; i < l.length; i++) { var has_location = false; - for(var x = 0; x < eid_locations.length; x++) { - - if(eid_locations[x].name === l[i]) { - + for (var x = 0; x < eid_locations.length; x++) { + if (eid_locations[x].name === l[i]) { has_location = true; break; } } - if(has_location) locations_list.push(l[i]); + if (has_location) locations_list.push(l[i]); } } @@ -81,9 +76,11 @@ function syncLabCohorts(request, reply) { var responses = { success: [], - fail: [] + fail: [] }; - var logger = etlLogger.logger(config.logging.eidPath + '/' + config.logging.eidFile); + var logger = etlLogger.logger( + config.logging.eidPath + '/' + config.logging.eidFile + ); logger.info('starting patient sync..'); logger.close(); //load uuids and loop through them @@ -95,29 +92,27 @@ function syncLabCohorts(request, reply) { * @params startDate, endDate */ function load(startDate, endDate, limit, offset) { - var qParts = getQueryParts(startDate, endDate, limit, offset); return db.queryDb(qParts); -}; +} function getQueryParts(startDate, endDate, limit, offset) { - offset = isNaN(offset) ? 0 : offset; limit = isNaN(limit) ? max_limit : limit; - if(!isNaN(limit) && parseInt(limit) > max_limit) limit = max_limit; + if (!isNaN(limit) && parseInt(limit) > max_limit) limit = max_limit; - var columns = ["distinct pe.uuid"]; + var columns = ['distinct pe.uuid']; var qParts = { columns: columns, - table: "amrs.patient", + table: 'amrs.patient', alias: 'p', - where: ["e.date_created between ? and ?", startDate, endDate], + where: ['e.date_created between ? and ?', startDate, endDate], leftOuterJoins: [ - ["amrs.person", "pe", "pe.person_id = p.patient_id"], - ["amrs.encounter", "e", "e.patient_id = p.patient_id"] + ['amrs.person', 'pe', 'pe.person_id = p.patient_id'], + ['amrs.encounter', 'e', 'e.patient_id = p.patient_id'] ], offset: offset, limit: limit @@ -127,7 +122,6 @@ function getQueryParts(startDate, endDate, limit, offset) { } function queuePatientUuids(startDate, endDate, limit, offset) { - var qParts = getQueryParts(startDate, endDate, limit, offset); var selectSql = db.transformQueryPartsToSql(qParts); @@ -145,10 +139,11 @@ function queuePatientUuids(startDate, endDate, limit, offset) { * Calls itself until all db records are syncd */ function sync(params, responses, reply) { - var limit = params.limit; - var logger = etlLogger.logger(config.logging.eidPath + '/' + config.logging.eidFile); + var logger = etlLogger.logger( + config.logging.eidPath + '/' + config.logging.eidFile + ); logger.info('Loading db data: params: ' + JSON.stringify(params)); logger.close(); @@ -159,18 +154,21 @@ function sync(params, responses, reply) { * Posts an array of uuids to the sync function */ function post(locations, data) { - var arr = []; - _.each(data.result, function(row) { + _.each(data.result, function (row) { arr.push(row.uuid); }); - var logger = etlLogger.logger(config.logging.eidPath + '/' + config.logging.eidFile); + var logger = etlLogger.logger( + config.logging.eidPath + '/' + config.logging.eidFile + ); logger.info('syncronizing ' + arr.length + ' records'); - return new Promise(function(resolve, reject) { - eidPatientCohortService.synchronizePatientCohort(arr, locations, function(res) { + return new Promise(function (resolve, reject) { + eidPatientCohortService.synchronizePatientCohort(arr, locations, function ( + res + ) { logger.info('sync result: %s', JSON.stringify(res)); logger.close(); resolve(res); diff --git a/dao/location/location-dao.js b/dao/location/location-dao.js index d3aa13324..b2ca8aa61 100755 --- a/dao/location/location-dao.js +++ b/dao/location/location-dao.js @@ -9,43 +9,35 @@ var connection = require('../../dao/connection/mysql-connection-service.js'); var authorizer = require('../../authorization/etl-authorizer'); var locations = { - getLocations : getLocations + getLocations: getLocations }; module.exports = locations; function getLocations() { - - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('l.location_id') - .field('l.name') - .field('l.uuid') - .from('amrs.location', 'l') - .toString(); - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - // console.log('Location Rows', rows); - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - - - - }); - + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('l.location_id') + .field('l.name') + .field('l.uuid') + .from('amrs.location', 'l') + .toString(); + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + // console.log('Location Rows', rows); + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } - - - - diff --git a/dao/motd_notification/motd_notification-dao.js b/dao/motd_notification/motd_notification-dao.js index e61267946..f51c25f9f 100755 --- a/dao/motd_notification/motd_notification-dao.js +++ b/dao/motd_notification/motd_notification-dao.js @@ -9,47 +9,39 @@ var connection = require('../../dao/connection/mysql-connection-service.js'); var authorizer = require('../../authorization/etl-authorizer'); var motd = { - getMotdNotifications : getMotdNotifications + getMotdNotifications: getMotdNotifications }; module.exports = motd; function getMotdNotifications() { - - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('mo.message_id') - .field('mo.message') - .field('mo.title') - .field('mo.startDate') - .field('mo.expireTime') - .field('mo.dateCreated') - .field('mo.alert_type') - .field('mo.alert_interval') - .from('etl.motd_messages', 'mo') - .toString(); - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - - - - }); - + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('mo.message_id') + .field('mo.message') + .field('mo.title') + .field('mo.startDate') + .field('mo.expireTime') + .field('mo.dateCreated') + .field('mo.alert_type') + .field('mo.alert_interval') + .from('etl.motd_messages', 'mo') + .toString(); + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } - - - - diff --git a/dao/patient-list/patient-list-dao.js b/dao/patient-list/patient-list-dao.js index c8051b528..1eb5833a6 100755 --- a/dao/patient-list/patient-list-dao.js +++ b/dao/patient-list/patient-list-dao.js @@ -9,448 +9,479 @@ var connection = require('../../dao/connection/mysql-connection-service.js'); var authorizer = require('../../authorization/etl-authorizer'); var def = { - getCohortUsersByCohortUuid: getCohortUsersByCohortUuid, - getCohortUser: getCohortUser, - voidCohortUser: voidCohortUser, - updateCohortUser: updateCohortUser, - createCohortUser: createCohortUser + getCohortUsersByCohortUuid: getCohortUsersByCohortUuid, + getCohortUser: getCohortUser, + voidCohortUser: voidCohortUser, + updateCohortUser: updateCohortUser, + createCohortUser: createCohortUser }; module.exports = def; function getCohortUsersByCohortUuid(cohortUuid) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('u.user_id') - .field('cu.cohort_user_id') - .field('cu.voided') - .field('cu.role') - .field('u.username') - .field('case when cu.role is null or cu.user_id != u.user_id then "admin" else cu.role end as role') - .field('case when cu.role is null or cu.user_id != u.user_id then "null" else cu.cohort_user_id end as cohort_user_id') - .field('case when cu.role is null or cu.user_id != u.user_id then 0 else cu.voided end as voided') - .from('amrs.cohort', 'c') - .left_join('etl.cohort_user', 'cu', 'c.cohort_id = cu.cohort_id and cu.voided = 0 ') - .join('amrs.users', 'u', squel.expr().or('cu.user_id = u.user_id').or('c.creator = u.user_id')) - .where('c.uuid = ?', cohortUuid) - .where('c.voided = 0') - .group('u.username') - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - }); + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('u.user_id') + .field('cu.cohort_user_id') + .field('cu.voided') + .field('cu.role') + .field('u.username') + .field( + 'case when cu.role is null or cu.user_id != u.user_id then "admin" else cu.role end as role' + ) + .field( + 'case when cu.role is null or cu.user_id != u.user_id then "null" else cu.cohort_user_id end as cohort_user_id' + ) + .field( + 'case when cu.role is null or cu.user_id != u.user_id then 0 else cu.voided end as voided' + ) + .from('amrs.cohort', 'c') + .left_join( + 'etl.cohort_user', + 'cu', + 'c.cohort_id = cu.cohort_id and cu.voided = 0 ' + ) + .join( + 'amrs.users', + 'u', + squel + .expr() + .or('cu.user_id = u.user_id') + .or('c.creator = u.user_id') + ) + .where('c.uuid = ?', cohortUuid) + .where('c.voided = 0') + .group('u.username') + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } function getCohortUser(cohortUserId) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('cu.cohort_user_id') - .field('cu.role') - .field('u.username') - .field('cu.voided') - .from('etl.cohort_user', 'cu') - .join('amrs.users', 'u', 'cu.user_id = u.user_id') - .join('amrs.cohort', 'c', 'c.cohort_id = cu.cohort_id') - .where('cu.cohort_user_id = ?', cohortUserId) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - if (rows.length > 0) { - resolve(rows[0]); - } else { - resolve(null); - } - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - }); + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('cu.cohort_user_id') + .field('cu.role') + .field('u.username') + .field('cu.voided') + .from('etl.cohort_user', 'cu') + .join('amrs.users', 'u', 'cu.user_id = u.user_id') + .join('amrs.cohort', 'c', 'c.cohort_id = cu.cohort_id') + .where('cu.cohort_user_id = ?', cohortUserId) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + if (rows.length > 0) { + resolve(rows[0]); + } else { + resolve(null); + } + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } function voidCohortUser(cohortUserId) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.update() - .table('etl.cohort_user') - .set('voided', 1) - .set('date_voided', squel.fval('NOW()')) - .set('voided_by', getCurrentUserIdSquel()) - .where('cohort_user_id = ?', cohortUserId) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - console.error(err); - reject('Error deleting resource'); - } - else { - resolve('Resource deleted'); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - }); + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .update() + .table('etl.cohort_user') + .set('voided', 1) + .set('date_voided', squel.fval('NOW()')) + .set('voided_by', getCurrentUserIdSquel()) + .where('cohort_user_id = ?', cohortUserId) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + console.error(err); + reject('Error deleting resource'); + } else { + resolve('Resource deleted'); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } function updateCohortUser(cohortUserId, newCohortUser) { - return new Promise(function (resolve, reject) { - validateUpdatePayload(newCohortUser) - .then(function (validationStatus) { - if (validationStatus.isValid === false) { - reject(validationStatus); - } else { - connection.getServerConnection() - .then(function (conn) { - var query = squel.update() - .table('etl.cohort_user') - .set('role', newCohortUser.role) - .set('date_changed', squel.fval('NOW()')) - .set('changed_by', getCurrentUserIdSquel()) - .where('cohort_user_id = ?', cohortUserId) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - console.error(err); - reject('Error updating resource'); - } - else { - getCohortUser(cohortUserId) - .then(function (updatedCohort) { - resolve(updatedCohort); - }) - .catch(function (error) { - resolve('An unknown error occured when trying to fetch the updated resource'); - }) - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - } - + return new Promise(function (resolve, reject) { + validateUpdatePayload(newCohortUser).then(function (validationStatus) { + if (validationStatus.isValid === false) { + reject(validationStatus); + } else { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .update() + .table('etl.cohort_user') + .set('role', newCohortUser.role) + .set('date_changed', squel.fval('NOW()')) + .set('changed_by', getCurrentUserIdSquel()) + .where('cohort_user_id = ?', cohortUserId) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + console.error(err); + reject('Error updating resource'); + } else { + getCohortUser(cohortUserId) + .then(function (updatedCohort) { + resolve(updatedCohort); + }) + .catch(function (error) { + resolve( + 'An unknown error occured when trying to fetch the updated resource' + ); + }); + } + conn.release(); }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + } }); + }); } function createCohortUser(newCohortUser) { - return new Promise(function (resolve, reject) { - var requiredFieldsCheck = hasRequireFields(newCohortUser) + return new Promise(function (resolve, reject) { + var requiredFieldsCheck = hasRequireFields(newCohortUser); - if (!requiredFieldsCheck.isValid) { - return reject(requiredFieldsCheck); - } + if (!requiredFieldsCheck.isValid) { + return reject(requiredFieldsCheck); + } - resolveUuidsToIds(newCohortUser). - then(function (newCohortUser) { - validateCreatePayload(newCohortUser) - .then(function (validationStatus) { - if (validationStatus.isValid === false) { - reject(validationStatus); - } else { - connection.getServerConnection() - .then(function (conn) { - var query = squel.insert() - .into('etl.cohort_user') - .set('role', newCohortUser.role) - .set('cohort_id', newCohortUser.cohortId) - .set('user_id', newCohortUser.userId) - .set('date_created', squel.fval('NOW()')) - .set('creator', getCurrentUserIdSquel()) - .set('voided', 0) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - console.error(err); - reject('Error updating resource'); - } - else { - findCohortUser(newCohortUser.userId, newCohortUser.cohortId, 0) - .then(function (updatedCohort) { - resolve(updatedCohort[0]); - }) - .catch(function (error) { - resolve('An unknown error occured when trying to fetch the updated resource'); - }); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - } - - }); - }) - .catch(function (error) { - reject('could not resolve user or cohort uuid to id'); - }); - }); -} - -function findCohortUser(userId, cohortId, voided) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('cu.cohort_user_id') - .field('cu.role') - .field('u.username') - .field('cu.voided') - .from('etl.cohort_user', 'cu') - .join('amrs.users', 'u', 'cu.user_id = u.user_id') - .join('amrs.cohort', 'c', 'c.cohort_id = cu.cohort_id') - .where('cu.cohort_id = ?', cohortId) - .where('cu.user_id = ?', userId) - .where('cu.voided = ?', voided) - .toString(); + resolveUuidsToIds(newCohortUser) + .then(function (newCohortUser) { + validateCreatePayload(newCohortUser).then(function (validationStatus) { + if (validationStatus.isValid === false) { + reject(validationStatus); + } else { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .insert() + .into('etl.cohort_user') + .set('role', newCohortUser.role) + .set('cohort_id', newCohortUser.cohortId) + .set('user_id', newCohortUser.userId) + .set('date_created', squel.fval('NOW()')) + .set('creator', getCurrentUserIdSquel()) + .set('voided', 0) + .toString(); conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - resolve(rows); - } - conn.release(); + if (err) { + console.error(err); + reject('Error updating resource'); + } else { + findCohortUser( + newCohortUser.userId, + newCohortUser.cohortId, + 0 + ) + .then(function (updatedCohort) { + resolve(updatedCohort[0]); + }) + .catch(function (error) { + resolve( + 'An unknown error occured when trying to fetch the updated resource' + ); + }); + } + conn.release(); }); - }) - .catch(function (err) { + }) + .catch(function (err) { reject('Error establishing connection to MySql Server'); - }); - }); + }); + } + }); + }) + .catch(function (error) { + reject('could not resolve user or cohort uuid to id'); + }); + }); +} + +function findCohortUser(userId, cohortId, voided) { + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('cu.cohort_user_id') + .field('cu.role') + .field('u.username') + .field('cu.voided') + .from('etl.cohort_user', 'cu') + .join('amrs.users', 'u', 'cu.user_id = u.user_id') + .join('amrs.cohort', 'c', 'c.cohort_id = cu.cohort_id') + .where('cu.cohort_id = ?', cohortId) + .where('cu.user_id = ?', userId) + .where('cu.voided = ?', voided) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } function resolveUuidsToIds(cohortUserPayload) { - return new Promise(function (resolve, reject) { - getCohortId(cohortUserPayload.cohort) - .then(function (cohortId) { - cohortUserPayload.cohortId = cohortId; - getUserId(cohortUserPayload.user) - .then(function (userId) { - cohortUserPayload.userId = userId; - resolve(cohortUserPayload); - }) - .catch(function (err) { - console.error(err); - reject(err); - }) - }) - .catch(function (error) { - console.error(err); - reject(error); - }) - }); + return new Promise(function (resolve, reject) { + getCohortId(cohortUserPayload.cohort) + .then(function (cohortId) { + cohortUserPayload.cohortId = cohortId; + getUserId(cohortUserPayload.user) + .then(function (userId) { + cohortUserPayload.userId = userId; + resolve(cohortUserPayload); + }) + .catch(function (err) { + console.error(err); + reject(err); + }); + }) + .catch(function (error) { + console.error(err); + reject(error); + }); + }); } function getUserId(userUuid) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('u.user_id') - .from('amrs.users', 'u') - .where('u.uuid = ?', userUuid) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - if (rows.length > 0) { - resolve(rows[0]['user_id']); - } else { - resolve(undefined); - } - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - }); + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('u.user_id') + .from('amrs.users', 'u') + .where('u.uuid = ?', userUuid) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + if (rows.length > 0) { + resolve(rows[0]['user_id']); + } else { + resolve(undefined); + } + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } function getCohortId(cohortUuid) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('u.cohort_id') - .from('amrs.cohort', 'u') - .where('u.uuid = ?', cohortUuid) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - if (rows.length > 0) { - resolve(rows[0]['cohort_id']); - } else { - resolve(undefined); - } - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - }); + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('u.cohort_id') + .from('amrs.cohort', 'u') + .where('u.uuid = ?', cohortUuid) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + if (rows.length > 0) { + resolve(rows[0]['cohort_id']); + } else { + resolve(undefined); + } + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } function validateUpdatePayload(cohortUserPayload) { - return new Promise(function (resolve, reject) { - var validationErrors = { - isValid: true, - errors: [] - }; - - if (!hasValidRole(cohortUserPayload)) { - validationErrors.isValid = false; - validationErrors.errors.push({ - field: 'role', - error: 'Invalid value for role.' - }); - } + return new Promise(function (resolve, reject) { + var validationErrors = { + isValid: true, + errors: [] + }; - resolve(validationErrors); - }); + if (!hasValidRole(cohortUserPayload)) { + validationErrors.isValid = false; + validationErrors.errors.push({ + field: 'role', + error: 'Invalid value for role.' + }); + } + + resolve(validationErrors); + }); } function validateCreatePayload(cohortUserPayload) { - return new Promise(function (resolve, reject) { - var validationErrors = { - isValid: true, - errors: [] - }; - - if (!hasValidRole(cohortUserPayload)) { - validationErrors.isValid = false; - validationErrors.errors.push({ - field: 'role', - error: 'Invalid value for role.' - }); - } + return new Promise(function (resolve, reject) { + var validationErrors = { + isValid: true, + errors: [] + }; - if (!cohortUserPayload.cohortId) { - validationErrors.isValid = false; - validationErrors.errors.push({ - field: 'cohort', - error: 'cohort does not exist.' - }); - } + if (!hasValidRole(cohortUserPayload)) { + validationErrors.isValid = false; + validationErrors.errors.push({ + field: 'role', + error: 'Invalid value for role.' + }); + } - if (!cohortUserPayload.userId) { - validationErrors.isValid = false; - validationErrors.errors.push({ - field: 'user', - error: 'user does not exist.' - }); - } + if (!cohortUserPayload.cohortId) { + validationErrors.isValid = false; + validationErrors.errors.push({ + field: 'cohort', + error: 'cohort does not exist.' + }); + } - if (validationErrors.errors.length > 1) { - return resolve(validationErrors); - } + if (!cohortUserPayload.userId) { + validationErrors.isValid = false; + validationErrors.errors.push({ + field: 'user', + error: 'user does not exist.' + }); + } - findCohortUser(cohortUserPayload.userId, cohortUserPayload.cohortId, 0) - .then(function (results) { - if (results.length > 0) { - validationErrors.isValid = false; - validationErrors.errors.push({ - field: 'cohort and user combination', - error: 'Duplicate record exists.' - }); - } - resolve(validationErrors); - }) - .catch(function (error) { - reject('An error occured while trying to validate cohort payload'); - }) - }); + if (validationErrors.errors.length > 1) { + return resolve(validationErrors); + } + + findCohortUser(cohortUserPayload.userId, cohortUserPayload.cohortId, 0) + .then(function (results) { + if (results.length > 0) { + validationErrors.isValid = false; + validationErrors.errors.push({ + field: 'cohort and user combination', + error: 'Duplicate record exists.' + }); + } + resolve(validationErrors); + }) + .catch(function (error) { + reject('An error occured while trying to validate cohort payload'); + }); + }); } function hasValidRole(cohortUserPayload) { - if (cohortUserPayload.role) { - if (cohortUserPayload.role !== 'view' && - cohortUserPayload.role !== 'edit') { - return false; - } + if (cohortUserPayload.role) { + if ( + cohortUserPayload.role !== 'view' && + cohortUserPayload.role !== 'edit' + ) { + return false; } - return true; + } + return true; } function hasRequireFields(newCohortUserPayload) { - var validationResult = { - isValid: true, - errors: [] - }; - if (_.isEmpty(newCohortUserPayload.user)) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'user', - message: 'user is required' - }); - } + var validationResult = { + isValid: true, + errors: [] + }; + if (_.isEmpty(newCohortUserPayload.user)) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'user', + message: 'user is required' + }); + } - if (_.isEmpty(newCohortUserPayload.cohort)) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'cohort', - message: 'cohort is required' - }); - } + if (_.isEmpty(newCohortUserPayload.cohort)) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'cohort', + message: 'cohort is required' + }); + } - if (_.isEmpty(newCohortUserPayload.role)) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'role', - message: 'role is required' - }); - } + if (_.isEmpty(newCohortUserPayload.role)) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'role', + message: 'role is required' + }); + } - return validationResult; + return validationResult; } function getCurrentUserIdSquel() { - return squel.select().field('MAX(user_id)') - .from('amrs.users').where('uuid = ?', authorizer.getUser().uuid); + return squel + .select() + .field('MAX(user_id)') + .from('amrs.users') + .where('uuid = ?', authorizer.getUser().uuid); } - - - diff --git a/dao/patient-referral/patient-referral-dao.js b/dao/patient-referral/patient-referral-dao.js index 90ffab52b..b0ef4ca40 100755 --- a/dao/patient-referral/patient-referral-dao.js +++ b/dao/patient-referral/patient-referral-dao.js @@ -9,669 +9,780 @@ var connection = require('../../dao/connection/mysql-connection-service.js'); var authorizer = require('../../authorization/etl-authorizer'); var def = { - createPatientReferral: createPatientReferral, - updatePatientReferralNotification:updatePatientReferralNotification, - getPatientReferralByEnrollmentUuid:getPatientReferralByEnrollmentUuid + createPatientReferral: createPatientReferral, + updatePatientReferralNotification: updatePatientReferralNotification, + getPatientReferralByEnrollmentUuid: getPatientReferralByEnrollmentUuid }; module.exports = def; - - - function createPatientReferral(newPatientReferral) { - return new Promise(function (resolve, reject) { - var requiredFieldsCheck = hasRequiredReferralFields(newPatientReferral) - - if (!requiredFieldsCheck.isValid) { - return reject(requiredFieldsCheck); - } - - try{ - resolveEnrollmentUuidsToIds(newPatientReferral). - then(function (newPateintReferral) { - - validateCreateReferralPayload(newPateintReferral) - .then(function (validationStatus) { - - if (validationStatus && validationStatus.isValid === false) { - reject(validationStatus); - } else { - connection.getServerConnection() - .then(function (conn) { - var query = squel.insert() - .into('etl.patient_referral') - .set('encounter_id', newPateintReferral.encounterId) - .set('patient_program_id', newPateintReferral.patientProgramId) - .set('provider_id', newPateintReferral.providerId) - .set('referred_from_location_id', newPateintReferral.referredFromLocationId) - .set('referred_to_location_id', newPateintReferral.referredToLocationId) - .set('notification_status', newPateintReferral.notificationStatus) - .set('referral_reason', newPateintReferral.referralReason) - .set('creator', getCurrentUserIdSquel()) - .set('voided', 0) - .toString(); - console.log('-------->', query); - conn.query(query, {}, function (err, rows, fields) { - console.log(err) - if (err) { - reject('Error updating resource'); - } - else { - - var resolvedFieldsCheck = checkResolvedReferralFields(newPateintReferral) - if (!resolvedFieldsCheck.isValid) { - return reject(resolvedFieldsCheck); - } - - findPatientReferral( - newPateintReferral.encounterId, - newPateintReferral.providerId, - newPateintReferral.referredToLocationId, - newPateintReferral.referredFromLocationId, 0) - .then(function (updatedCohort) { - resolve(updatedCohort); - }) - .catch(function (error) { - reject('An unknown error occured when trying to fetch the updated resource'); - }); - } - conn.release(); - }); - }) - .catch(function (err) { - console.log(err) - reject('Error establishing connection to MySql Server for updated resource'); - }); - } - - }); - }) - .catch(function (error) { - reject('could not resolve all payload property uuids to their respective ids ',error); - }); + return new Promise(function (resolve, reject) { + var requiredFieldsCheck = hasRequiredReferralFields(newPatientReferral); - } catch(error){ + if (!requiredFieldsCheck.isValid) { + return reject(requiredFieldsCheck); } - }); - -} - -function updatePatientReferralNotification(patientReferralId, newPatientReferral) { - return new Promise(function (resolve, reject) { - validateUpdateNotificationPayload(newPatientReferral) - .then(function (validationStatus) { - if (validationStatus.isValid === false) { - reject(validationStatus); - } else { - connection.getServerConnection() - .then(function (conn) { - var query = squel.update() - .table('etl.patient_referral') - .set('notification_status', newPatientReferral.notificationStatus) - .set('date_changed', moment().format()) - .set('changed_by', getCurrentUserIdSquel()) - .where('patient_referral_id = ?', patientReferralId) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - console.error(err); - reject('Error updating resource'); - } - else { - getPatientReferral(patientReferralId) - .then(function (updatedPatientReferral) { - resolve(updatedPatientReferral); - }) - .catch(function (error) { - resolve('An unknown error occured when trying to fetch the updated resource',error); - }) - } - conn.release(); - }); - }) - .catch(function (err) { - - reject('Error establishing connection to MySql Server to update the resource'); - }); - } - - }); - }); -} -function getPatientReferral(patientReferralId) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('pr.patient_referral_id') - .field('pr.voided') - .field('pr.encounter_id') - .field('pr.provider_id') - .field('pr.referred_to_location_id') - .field('pr.referred_from_location_id') - .field('pr.patient_program_id') - .field('pr.notification_status') - .field('pr.referral_reason') - .from('etl.patient_referral', 'pr') - // .join('amrs.encounter', 'u', 'pr.encounter_id = u.encounter_id') - .join('amrs.provider', 'ap', 'ap.provider_id = pr.provider_id') - .join('amrs.location', 'lr', 'pr.referred_to_location_id = lr.location_id') - .join('amrs.location', 'lt', 'pr.referred_from_location_id = lt.location_id') - .join('amrs.patient_program', 'p', 'pr.patient_program_id = p.patient_program_id') - .where('pr.patient_referral_id = ?', patientReferralId) + try { + resolveEnrollmentUuidsToIds(newPatientReferral) + .then(function (newPateintReferral) { + validateCreateReferralPayload(newPateintReferral).then(function ( + validationStatus + ) { + if (validationStatus && validationStatus.isValid === false) { + reject(validationStatus); + } else { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .insert() + .into('etl.patient_referral') + .set('encounter_id', newPateintReferral.encounterId) + .set( + 'patient_program_id', + newPateintReferral.patientProgramId + ) + .set('provider_id', newPateintReferral.providerId) + .set( + 'referred_from_location_id', + newPateintReferral.referredFromLocationId + ) + .set( + 'referred_to_location_id', + newPateintReferral.referredToLocationId + ) + .set( + 'notification_status', + newPateintReferral.notificationStatus + ) + .set('referral_reason', newPateintReferral.referralReason) + .set('creator', getCurrentUserIdSquel()) + .set('voided', 0) .toString(); - - conn.query(query, {}, function (err, rows, fields) { + console.log('-------->', query); + conn.query(query, {}, function (err, rows, fields) { + console.log(err); if (err) { - console.log(err) - reject('Error querying to get patient referral by Id server'); - } - else { - if (rows.length > 0) { - resolve(rows[0]); - } else { - resolve(null); - } + reject('Error updating resource'); + } else { + var resolvedFieldsCheck = checkResolvedReferralFields( + newPateintReferral + ); + if (!resolvedFieldsCheck.isValid) { + return reject(resolvedFieldsCheck); + } + + findPatientReferral( + newPateintReferral.encounterId, + newPateintReferral.providerId, + newPateintReferral.referredToLocationId, + newPateintReferral.referredFromLocationId, + 0 + ) + .then(function (updatedCohort) { + resolve(updatedCohort); + }) + .catch(function (error) { + reject( + 'An unknown error occured when trying to fetch the updated resource' + ); + }); } conn.release(); + }); + }) + .catch(function (err) { + console.log(err); + reject( + 'Error establishing connection to MySql Server for updated resource' + ); }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - }); + } + }); + }) + .catch(function (error) { + reject( + 'could not resolve all payload property uuids to their respective ids ', + error + ); + }); + } catch (error) {} + }); } -function getPatientReferralByEnrollmentUuid(locationUuid, enrollmentUuid) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('pr.patient_referral_id') - .field('pr.voided') - .field('e.uuid as encounter_uuid') - .field('pr.provider_id') - .field('pr.referred_to_location_id') - .field('pr.referred_from_location_id') - .field('pr.patient_program_id') - .field('pr.notification_status') - .field('lt.name as referred_to_location') - .field('lt.uuid as referred_to_location_uuid') - .field('lf.name as referred_from_location') - .field('lf.uuid as referred_from_location_uuid') - .field('p.uuid as patient_program_uuid') - .from('etl.patient_referral', 'pr') - .join('amrs.provider', 'ap', 'ap.provider_id = pr.provider_id') - .join('amrs.location', 'lt', 'pr.referred_to_location_id = lt.location_id') - .join('amrs.encounter', 'e', 'e.encounter_id = pr.encounter_id') - .join('amrs.location', 'lf', 'pr.referred_from_location_id = lf.location_id') - .join('amrs.patient_program', 'p', 'pr.patient_program_id = p.patient_program_id') - .where('lt.uuid = ?', locationUuid) - .where('p.uuid = ?', enrollmentUuid) - .toString(); - conn.query(query, {}, function (err, rows, fields) { - if (err) { - console.log(err); - reject('Error querying to get patient referral details by enrollment server'); - } else { - if (rows.length > 0) { - resolve(rows[0]); - } else { - resolve({}); - } - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); +function updatePatientReferralNotification( + patientReferralId, + newPatientReferral +) { + return new Promise(function (resolve, reject) { + validateUpdateNotificationPayload(newPatientReferral).then(function ( + validationStatus + ) { + if (validationStatus.isValid === false) { + reject(validationStatus); + } else { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .update() + .table('etl.patient_referral') + .set('notification_status', newPatientReferral.notificationStatus) + .set('date_changed', moment().format()) + .set('changed_by', getCurrentUserIdSquel()) + .where('patient_referral_id = ?', patientReferralId) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + console.error(err); + reject('Error updating resource'); + } else { + getPatientReferral(patientReferralId) + .then(function (updatedPatientReferral) { + resolve(updatedPatientReferral); + }) + .catch(function (error) { + resolve( + 'An unknown error occured when trying to fetch the updated resource', + error + ); + }); + } + conn.release(); }); + }) + .catch(function (err) { + reject( + 'Error establishing connection to MySql Server to update the resource' + ); + }); + } }); + }); } -function validateUpdateNotificationPayload(newPatientReferralPayload) { - return new Promise(function (resolve, reject) { - var validationResult = { - isValid: true, - errors: [] - }; - if (_.isNil(newPatientReferralPayload.notificationStatus)) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'Notification status', - message: 'Notification status is required' - }); - } - - resolve(validationResult); - }); +function getPatientReferral(patientReferralId) { + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('pr.patient_referral_id') + .field('pr.voided') + .field('pr.encounter_id') + .field('pr.provider_id') + .field('pr.referred_to_location_id') + .field('pr.referred_from_location_id') + .field('pr.patient_program_id') + .field('pr.notification_status') + .field('pr.referral_reason') + .from('etl.patient_referral', 'pr') + // .join('amrs.encounter', 'u', 'pr.encounter_id = u.encounter_id') + .join('amrs.provider', 'ap', 'ap.provider_id = pr.provider_id') + .join( + 'amrs.location', + 'lr', + 'pr.referred_to_location_id = lr.location_id' + ) + .join( + 'amrs.location', + 'lt', + 'pr.referred_from_location_id = lt.location_id' + ) + .join( + 'amrs.patient_program', + 'p', + 'pr.patient_program_id = p.patient_program_id' + ) + .where('pr.patient_referral_id = ?', patientReferralId) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + console.log(err); + reject('Error querying to get patient referral by Id server'); + } else { + if (rows.length > 0) { + resolve(rows[0]); + } else { + resolve(null); + } + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } -function validateCreateReferralPayload(patientReferralPayload) { - return new Promise(function (resolve, reject) { - var validationErrors = { - isValid: true, - errors: [] - }; - - var resolvedFieldsCheck = checkResolvedReferralFields(patientReferralPayload) - if (!resolvedFieldsCheck.isValid) { - return reject(resolvedFieldsCheck); +function getPatientReferralByEnrollmentUuid(locationUuid, enrollmentUuid) { + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('pr.patient_referral_id') + .field('pr.voided') + .field('e.uuid as encounter_uuid') + .field('pr.provider_id') + .field('pr.referred_to_location_id') + .field('pr.referred_from_location_id') + .field('pr.patient_program_id') + .field('pr.notification_status') + .field('lt.name as referred_to_location') + .field('lt.uuid as referred_to_location_uuid') + .field('lf.name as referred_from_location') + .field('lf.uuid as referred_from_location_uuid') + .field('p.uuid as patient_program_uuid') + .from('etl.patient_referral', 'pr') + .join('amrs.provider', 'ap', 'ap.provider_id = pr.provider_id') + .join( + 'amrs.location', + 'lt', + 'pr.referred_to_location_id = lt.location_id' + ) + .join('amrs.encounter', 'e', 'e.encounter_id = pr.encounter_id') + .join( + 'amrs.location', + 'lf', + 'pr.referred_from_location_id = lf.location_id' + ) + .join( + 'amrs.patient_program', + 'p', + 'pr.patient_program_id = p.patient_program_id' + ) + .where('lt.uuid = ?', locationUuid) + .where('p.uuid = ?', enrollmentUuid) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + console.log(err); + reject( + 'Error querying to get patient referral details by enrollment server' + ); + } else { + if (rows.length > 0) { + resolve(rows[0]); + } else { + resolve({}); } - - findPatientReferral( - patientReferralPayload.encounterId, - patientReferralPayload.providerId, - patientReferralPayload.referredToLocationId, - patientReferralPayload.referredFromLocationId, 0) - .then(function (results) { - if (results.length > 0) { - validationErrors.isValid = false; - validationErrors.errors.push({ - field: 'Patient Referral details', - error: 'Duplicate record exists.' - }); - } - resolve(validationErrors); - }) - .catch(function (error) { - validationErrors.isValid = false; - resolve(validationErrors); - console.log('An error occured while trying to validate patient referral payload',error); - }) - - - }).catch(function (error) { - console.log('An error occured while trying to validate patient referral payload',error); - }); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } - - -function hasRequiredReferralFields(newPatientReferralPayload) { +function validateUpdateNotificationPayload(newPatientReferralPayload) { + return new Promise(function (resolve, reject) { var validationResult = { - isValid: true, - errors: [] + isValid: true, + errors: [] }; - if (_.isEmpty(newPatientReferralPayload.provider)) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'provider', - message: 'Provider is required' - }); - } - - if (_.isEmpty(newPatientReferralPayload.referredToLocation)) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'referredToLocation', - message: 'Referred To Location is required' - }); + if (_.isNil(newPatientReferralPayload.notificationStatus)) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'Notification status', + message: 'Notification status is required' + }); } - if (_.isEmpty(newPatientReferralPayload.patientProgram)) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'patientProgram', - message: 'Patient Program is required' - }); - } + resolve(validationResult); + }); +} +function validateCreateReferralPayload(patientReferralPayload) { + return new Promise(function (resolve, reject) { + var validationErrors = { + isValid: true, + errors: [] + }; - if (_.isEmpty(newPatientReferralPayload.referredFromLocation)) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'referredFromLocation', - message: 'Referred From Location is required' - }); + var resolvedFieldsCheck = checkResolvedReferralFields( + patientReferralPayload + ); + if (!resolvedFieldsCheck.isValid) { + return reject(resolvedFieldsCheck); } - return validationResult; + findPatientReferral( + patientReferralPayload.encounterId, + patientReferralPayload.providerId, + patientReferralPayload.referredToLocationId, + patientReferralPayload.referredFromLocationId, + 0 + ) + .then(function (results) { + if (results.length > 0) { + validationErrors.isValid = false; + validationErrors.errors.push({ + field: 'Patient Referral details', + error: 'Duplicate record exists.' + }); + } + resolve(validationErrors); + }) + .catch(function (error) { + validationErrors.isValid = false; + resolve(validationErrors); + console.log( + 'An error occured while trying to validate patient referral payload', + error + ); + }); + }).catch(function (error) { + console.log( + 'An error occured while trying to validate patient referral payload', + error + ); + }); } -function resolveEnrollmentUuidsToIds(referralPayload) { - return new Promise(function (resolve, reject) { - getEncounterId(referralPayload.encounter) - .then(function (encounterId) { - referralPayload.encounterId = encounterId; - getPatientProgramId(referralPayload.patientProgram) - .then(function (patientProgramId) { - referralPayload.patientProgramId = patientProgramId; - getProviderId(referralPayload.provider) - .then(function (providerId) { - referralPayload.providerId = providerId; - getLocation(referralPayload.referredToLocation) - .then(function (referredToLocationId) { - referralPayload.referredToLocationId = referredToLocationId; - getLocation(referralPayload.referredFromLocation) - .then(function (referredFromLocationId) { - referralPayload.referredFromLocationId = referredFromLocationId; - resolve(referralPayload); - }) - .catch(function (err) { - console.error(err); - reject(err); - }) - }) - .catch(function (err) { - console.error(err); - reject(err); - }) - }) - .catch(function (err) { - console.error(err); - reject(err); - }) - }) - .catch(function (err) { - console.error(err); - reject(err); - }) - }) - .catch(function (error) { - console.error(error); - resolve(error); - }) +function hasRequiredReferralFields(newPatientReferralPayload) { + var validationResult = { + isValid: true, + errors: [] + }; + if (_.isEmpty(newPatientReferralPayload.provider)) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'provider', + message: 'Provider is required' }); -} - + } -function findPatientReferral(encounterId, providerId,referredToLocationId,referredFromLocationId, voided) { - - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('pr.patient_referral_id') - .field('pr.encounter_id') - .field('pr.provider_id') - .field('pr.referred_to_location_id') - .field('pr.referred_from_location_id') - .field('pr.patient_program_id') - .field('pr.notification_status') - .field('pr.referral_reason') - .from('etl.patient_referral', 'pr') - .join('amrs.encounter', 'u', 'pr.encounter_id = u.encounter_id') - .join('amrs.provider', 'apr', 'apr.provider_id = pr.provider_id') - .join('amrs.location', 'lr', 'pr.referred_to_location_id = lr.location_id') - .join('amrs.location', 'lt', 'pr.referred_from_location_id = lt.location_id') - .join('amrs.patient_program', 'p', 'pr.patient_program_id = p.patient_program_id') - .where('pr.provider_id = ?', providerId) - .where('pr.encounter_id = ?', encounterId) - .where('pr.referred_to_location_id = ?', referredToLocationId) - .where('pr.referred_from_location_id = ?', referredFromLocationId) - .where('pr.voided = ?', voided) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - console.log(err) - if (err) { - reject('Error querying to find if duplicate record exists server'); - } - else { - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - console.log(err) - reject('Error establishing connection to MySql Server find duplicate'); - }); - }); - - -} -function getPatientReferralStats(providerId,startDate,endDate) { - - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('pr.patient_referral_id') - .field('pr.encounter_id') - .field('pr.provider_id') - .field('pr.referred_to_location_id') - .field('pr.referred_from_location_id') - .field('pr.patient_program_id') - .field('pr.notification_status') - .field('pr.referral_reason') - .from('etl.patient_referral', 'pr') - .join('amrs.encounter', 'u', 'pr.encounter_id = u.encounter_id') - .join('amrs.provider', 'apr', 'apr.provider_id = pr.provider_id') - .join('amrs.location', 'lr', 'pr.referred_to_location_id = lr.location_id') - .join('amrs.location', 'lt', 'pr.referred_from_location_id = lt.location_id') - .join('amrs.patient_program', 'p', 'pr.patient_program_id = p.patient_program_id') - .join('amrs.program_workflow_state', 'ps', 'pr.program_workflow_state_id = ps.program_workflow_state_id') - .where('pr.provider_id = ?', providerId) - .where('pr.encounter_id = ?', encounterId) - .where('pr.referred_to_location_id = ?', referredToLocationId) - .where('pr.referred_from_location_id = ?', referredFromLocationId) - .where('pr.program_workflow_state_id = ?', programWorkflowStateId) - .where('pr.voided = ?', voided) - .toString(); + if (_.isEmpty(newPatientReferralPayload.referredToLocation)) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'referredToLocation', + message: 'Referred To Location is required' + }); + } - conn.query(query, {}, function (err, rows, fields) { - console.log(err) - if (err) { - reject('Error querying to find if duplicate record exists server'); - } - else { - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - console.log(err) - reject('Error establishing connection to MySql Server find duplicate'); + if (_.isEmpty(newPatientReferralPayload.patientProgram)) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'patientProgram', + message: 'Patient Program is required' + }); + } - }); + if (_.isEmpty(newPatientReferralPayload.referredFromLocation)) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'referredFromLocation', + message: 'Referred From Location is required' }); + } + return validationResult; +} +function resolveEnrollmentUuidsToIds(referralPayload) { + return new Promise(function (resolve, reject) { + getEncounterId(referralPayload.encounter) + .then(function (encounterId) { + referralPayload.encounterId = encounterId; + getPatientProgramId(referralPayload.patientProgram) + .then(function (patientProgramId) { + referralPayload.patientProgramId = patientProgramId; + getProviderId(referralPayload.provider) + .then(function (providerId) { + referralPayload.providerId = providerId; + getLocation(referralPayload.referredToLocation) + .then(function (referredToLocationId) { + referralPayload.referredToLocationId = referredToLocationId; + getLocation(referralPayload.referredFromLocation) + .then(function (referredFromLocationId) { + referralPayload.referredFromLocationId = referredFromLocationId; + resolve(referralPayload); + }) + .catch(function (err) { + console.error(err); + reject(err); + }); + }) + .catch(function (err) { + console.error(err); + reject(err); + }); + }) + .catch(function (err) { + console.error(err); + reject(err); + }); + }) + .catch(function (err) { + console.error(err); + reject(err); + }); + }) + .catch(function (error) { + console.error(error); + resolve(error); + }); + }); } - - - function getEncounterId(encounterUuid) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('u.encounter_id') - .from('amrs.encounter', 'u') - .where('u.uuid = ?', encounterUuid) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - console.log(err) - resolve('Error querying server Encounter'); - } - else { - if (rows.length > 0) { - resolve(rows[0]['encounter_id']); - } else { - resolve(undefined); - } - } - conn.release(); - }); - }) - .catch(function (err) { - resolve('Error establishing connection to MySql Server to resolve encounter id'); - }); + +function findPatientReferral( + encounterId, + providerId, + referredToLocationId, + referredFromLocationId, + voided +) { + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('pr.patient_referral_id') + .field('pr.encounter_id') + .field('pr.provider_id') + .field('pr.referred_to_location_id') + .field('pr.referred_from_location_id') + .field('pr.patient_program_id') + .field('pr.notification_status') + .field('pr.referral_reason') + .from('etl.patient_referral', 'pr') + .join('amrs.encounter', 'u', 'pr.encounter_id = u.encounter_id') + .join('amrs.provider', 'apr', 'apr.provider_id = pr.provider_id') + .join( + 'amrs.location', + 'lr', + 'pr.referred_to_location_id = lr.location_id' + ) + .join( + 'amrs.location', + 'lt', + 'pr.referred_from_location_id = lt.location_id' + ) + .join( + 'amrs.patient_program', + 'p', + 'pr.patient_program_id = p.patient_program_id' + ) + .where('pr.provider_id = ?', providerId) + .where('pr.encounter_id = ?', encounterId) + .where('pr.referred_to_location_id = ?', referredToLocationId) + .where('pr.referred_from_location_id = ?', referredFromLocationId) + .where('pr.voided = ?', voided) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + console.log(err); + if (err) { + reject('Error querying to find if duplicate record exists server'); + } else { + resolve(rows); + } + conn.release(); }); - } - function getPatientProgramId(patientProgramUuid) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('u.patient_program_id') - .from('amrs.patient_program', 'u') - .where('u.uuid = ?', patientProgramUuid) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying patient program server'); - } - else { - if (rows.length > 0) { - resolve(rows[0]['patient_program_id']); - } else { - resolve(undefined); - } - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server to resolve patient program'); - }); + }) + .catch(function (err) { + console.log(err); + reject('Error establishing connection to MySql Server find duplicate'); + }); + }); +} +function getPatientReferralStats(providerId, startDate, endDate) { + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('pr.patient_referral_id') + .field('pr.encounter_id') + .field('pr.provider_id') + .field('pr.referred_to_location_id') + .field('pr.referred_from_location_id') + .field('pr.patient_program_id') + .field('pr.notification_status') + .field('pr.referral_reason') + .from('etl.patient_referral', 'pr') + .join('amrs.encounter', 'u', 'pr.encounter_id = u.encounter_id') + .join('amrs.provider', 'apr', 'apr.provider_id = pr.provider_id') + .join( + 'amrs.location', + 'lr', + 'pr.referred_to_location_id = lr.location_id' + ) + .join( + 'amrs.location', + 'lt', + 'pr.referred_from_location_id = lt.location_id' + ) + .join( + 'amrs.patient_program', + 'p', + 'pr.patient_program_id = p.patient_program_id' + ) + .join( + 'amrs.program_workflow_state', + 'ps', + 'pr.program_workflow_state_id = ps.program_workflow_state_id' + ) + .where('pr.provider_id = ?', providerId) + .where('pr.encounter_id = ?', encounterId) + .where('pr.referred_to_location_id = ?', referredToLocationId) + .where('pr.referred_from_location_id = ?', referredFromLocationId) + .where('pr.program_workflow_state_id = ?', programWorkflowStateId) + .where('pr.voided = ?', voided) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + console.log(err); + if (err) { + reject('Error querying to find if duplicate record exists server'); + } else { + resolve(rows); + } + conn.release(); }); - } - - + }) + .catch(function (err) { + console.log(err); + reject('Error establishing connection to MySql Server find duplicate'); + }); + }); +} +function getEncounterId(encounterUuid) { + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('u.encounter_id') + .from('amrs.encounter', 'u') + .where('u.uuid = ?', encounterUuid) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + console.log(err); + resolve('Error querying server Encounter'); + } else { + if (rows.length > 0) { + resolve(rows[0]['encounter_id']); + } else { + resolve(undefined); + } + } + conn.release(); + }); + }) + .catch(function (err) { + resolve( + 'Error establishing connection to MySql Server to resolve encounter id' + ); + }); + }); +} +function getPatientProgramId(patientProgramUuid) { + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('u.patient_program_id') + .from('amrs.patient_program', 'u') + .where('u.uuid = ?', patientProgramUuid) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying patient program server'); + } else { + if (rows.length > 0) { + resolve(rows[0]['patient_program_id']); + } else { + resolve(undefined); + } + } + conn.release(); + }); + }) + .catch(function (err) { + reject( + 'Error establishing connection to MySql Server to resolve patient program' + ); + }); + }); +} function getProviderId(providerUuid) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('u.provider_id') - .from('amrs.provider', 'u') - .where('u.uuid = ?', providerUuid) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying for provider server'); - } - else { - if (rows.length > 0) { - resolve(rows[0]['provider_id']); - } else { - resolve(undefined); - } - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server to get provider'); - }); - }); + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('u.provider_id') + .from('amrs.provider', 'u') + .where('u.uuid = ?', providerUuid) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying for provider server'); + } else { + if (rows.length > 0) { + resolve(rows[0]['provider_id']); + } else { + resolve(undefined); + } + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server to get provider'); + }); + }); } function getWorkFlowState(workFlowStateUuid) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('u.program_workflow_state_id') - .from('amrs.program_workflow_state', 'u') - .where('u.uuid = ?', workFlowStateUuid) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying for workflow state server'); - } - else { - if (rows.length > 0) { - resolve(rows[0]['program_workflow_state_id']); - } else { - resolve(undefined); - } - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server to get workflow state'); - }); - }); + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('u.program_workflow_state_id') + .from('amrs.program_workflow_state', 'u') + .where('u.uuid = ?', workFlowStateUuid) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying for workflow state server'); + } else { + if (rows.length > 0) { + resolve(rows[0]['program_workflow_state_id']); + } else { + resolve(undefined); + } + } + conn.release(); + }); + }) + .catch(function (err) { + reject( + 'Error establishing connection to MySql Server to get workflow state' + ); + }); + }); } function getLocation(locationUuid) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('u.location_id') - .from('amrs.location', 'u') - .where('u.uuid = ?', locationUuid) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying location server'); - } - else { - if (rows.length > 0) { - resolve(rows[0]['location_id']); - } else { - resolve(undefined); - } - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server for location'); - }); - }); + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('u.location_id') + .from('amrs.location', 'u') + .where('u.uuid = ?', locationUuid) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying location server'); + } else { + if (rows.length > 0) { + resolve(rows[0]['location_id']); + } else { + resolve(undefined); + } + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server for location'); + }); + }); } function getCurrentUserIdSquel() { - return squel.select().field('MAX(user_id)') - .from('amrs.users').where('uuid = ?', authorizer.getUser().uuid); + return squel + .select() + .field('MAX(user_id)') + .from('amrs.users') + .where('uuid = ?', authorizer.getUser().uuid); } function checkResolvedReferralFields(newPatientReferralPayload) { - var validationResult = { - isValid: true, - errors: [] - }; - if (_.isEmpty(newPatientReferralPayload.providerId) && newPatientReferralPayload.providerId===undefined) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'provider', - message: 'Provider is Not Found' - }); - } - - if (_.isEmpty(newPatientReferralPayload.encounterId) && newPatientReferralPayload.encounterId===undefined) { - validationResult.isValid = true; - } - - if (_.isEmpty(newPatientReferralPayload.referredToLocationId) && newPatientReferralPayload.referredToLocationId===undefined) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'referredToLocation', - message: 'Referred To Location is Not Found' - }); - } - - if (_.isEmpty(newPatientReferralPayload.patientProgramId) && newPatientReferralPayload.patientProgramId===undefined) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'patientProgram', - message: 'Patient Program is Not Found' - }); - } + var validationResult = { + isValid: true, + errors: [] + }; + if ( + _.isEmpty(newPatientReferralPayload.providerId) && + newPatientReferralPayload.providerId === undefined + ) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'provider', + message: 'Provider is Not Found' + }); + } + + if ( + _.isEmpty(newPatientReferralPayload.encounterId) && + newPatientReferralPayload.encounterId === undefined + ) { + validationResult.isValid = true; + } + + if ( + _.isEmpty(newPatientReferralPayload.referredToLocationId) && + newPatientReferralPayload.referredToLocationId === undefined + ) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'referredToLocation', + message: 'Referred To Location is Not Found' + }); + } + + if ( + _.isEmpty(newPatientReferralPayload.patientProgramId) && + newPatientReferralPayload.patientProgramId === undefined + ) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'patientProgram', + message: 'Patient Program is Not Found' + }); + } + + if ( + _.isEmpty(newPatientReferralPayload.referredFromLocationId) && + newPatientReferralPayload.referredFromLocationId === undefined + ) { + validationResult.isValid = false; + validationResult.errors.push({ + field: 'referredFromLocation', + message: 'Referred From Location is Not Found' + }); + } - if (_.isEmpty(newPatientReferralPayload.referredFromLocationId) && newPatientReferralPayload.referredFromLocationId===undefined) { - validationResult.isValid = false; - validationResult.errors.push({ - field: 'referredFromLocation', - message: 'Referred From Location is Not Found' - }); - } - - return validationResult; -} \ No newline at end of file + return validationResult; +} diff --git a/dao/patient/etl-patient-dao.js b/dao/patient/etl-patient-dao.js index 8cd5380b9..bc1ce988b 100755 --- a/dao/patient/etl-patient-dao.js +++ b/dao/patient/etl-patient-dao.js @@ -1,6 +1,6 @@ /*jshint -W003, -W097, -W117, -W026 */ 'use strict'; -import {BaseMysqlReport} from '../../app/reporting-framework/base-mysql.report'; +import { BaseMysqlReport } from '../../app/reporting-framework/base-mysql.report'; var Promise = require('bluebird'); var noteService = require('../../service/notes.service'); @@ -11,463 +11,597 @@ var Boom = require('boom'); //extends Hapi Error Reporting. Returns HTTP-friendl var helpers = require('../../etl-helpers'); var patientReminderService = require('../../service/patient-reminder.service.js'); -module.exports = function () { - function getPatientHivSummary(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - var includeNonClinicalEncounter = Boolean(true || false); - var whereClause = includeNonClinicalEncounter === true ? ["uuid = ?", +module.exports = (function () { + function getPatientHivSummary(request, callback) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + var includeNonClinicalEncounter = Boolean(true || false); + var whereClause = + includeNonClinicalEncounter === true + ? ['uuid = ?', uuid] + : [ + 'uuid = ? and t1.encounter_type in (1,2,3,4,17,21,110,117,99999)', uuid - ] : ["uuid = ? and t1.encounter_type in (1,2,3,4,17,21,110,117,99999)", uuid]; - var queryParts = { - columns: request.query.fields || "*", - table: "etl.flat_hiv_summary_v15b", - where: whereClause, - order: order || [{ - column: 'encounter_datetime', - asc: false - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - var qParts = { - columns: "*", - table: "amrs.encounter_type", - where: ["retired = ?", 0], - offset: request.query.startIndex, - limit: 1000 - }; - - var encounterTypeNames = {}; - //get encounter type Name - var encounterNamesPromise = db.queryDb(qParts); - var summaryDataPromise = db.queryDb(queryParts); - - var promise = Promise.all([encounterNamesPromise, summaryDataPromise]) - .then(function (data) { - var encTypeNames = data[0]; - var summaryData = data[1]; - - // Map encounter type ids to names. - _.each(encTypeNames.result, function (row) { - encounterTypeNames[row.encounter_type_id] = row.name; - }); - - // Format & Clean up raw summaries - _.each(summaryData.result, function (summary) { - summary.cur_arv_meds_id = summary.cur_arv_meds; - summary.arv_first_regimen_id = summary.arv_first_regimen; - summary.cur_arv_meds = helpers.getARVNames(summary.cur_arv_meds); - summary.arv_first_regimen = helpers.getARVNames(summary.arv_first_regimen); - summary.contraceptive_method= helpers.getContraceptiveMethod(summary.contraceptive_method); - summary['encounter_type_name'] = encounterTypeNames[summary.encounter_type]; - summary['prev_encounter_type_name'] = encounterTypeNames[summary.prev_encounter_type_hiv]; - // console.log("menstruaction status", summary.menstruation_status, summary.encounter_datetime); - }); - - // Return when done. - return summaryData; - }).catch((error) => { - console.error('EROR : GetPatientHivSummary', error); - }); - - if (_.isFunction(callback)) { - promise.then(function (result) { - callback(result); - }).catch(function (err) { - callback(err); - }); + ]; + var queryParts = { + columns: request.query.fields || '*', + table: 'etl.flat_hiv_summary_v15b', + where: whereClause, + order: order || [ + { + column: 'encounter_datetime', + asc: false } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + var qParts = { + columns: '*', + table: 'amrs.encounter_type', + where: ['retired = ?', 0], + offset: request.query.startIndex, + limit: 1000 + }; + + var encounterTypeNames = {}; + //get encounter type Name + var encounterNamesPromise = db.queryDb(qParts); + var summaryDataPromise = db.queryDb(queryParts); + + var promise = Promise.all([encounterNamesPromise, summaryDataPromise]) + .then(function (data) { + var encTypeNames = data[0]; + var summaryData = data[1]; + + // Map encounter type ids to names. + _.each(encTypeNames.result, function (row) { + encounterTypeNames[row.encounter_type_id] = row.name; + }); + + // Format & Clean up raw summaries + _.each(summaryData.result, function (summary) { + summary.cur_arv_meds_id = summary.cur_arv_meds; + summary.arv_first_regimen_id = summary.arv_first_regimen; + summary.cur_arv_meds = helpers.getARVNames(summary.cur_arv_meds); + summary.arv_first_regimen = helpers.getARVNames( + summary.arv_first_regimen + ); + summary.contraceptive_method = helpers.getContraceptiveMethod( + summary.contraceptive_method + ); + summary['encounter_type_name'] = + encounterTypeNames[summary.encounter_type]; + summary['prev_encounter_type_name'] = + encounterTypeNames[summary.prev_encounter_type_hiv]; + // console.log("menstruaction status", summary.menstruation_status, summary.encounter_datetime); + }); - return promise; + // Return when done. + return summaryData; + }) + .catch((error) => { + console.error('EROR : GetPatientHivSummary', error); + }); + + if (_.isFunction(callback)) { + promise + .then(function (result) { + callback(result); + }) + .catch(function (err) { + callback(err); + }); } - function getPatientOncologySummary(request, callback) { - let queryParts = { - columns: request.query.fields || "*", - order: [{ + return promise; + } + + function getPatientOncologySummary(request, callback) { + let queryParts = { + columns: request.query.fields || '*', + order: [ + { column: 'encounter_datetime', asc: false - }] - }; + } + ] + }; - getOncologyPatientReport(request, queryParts) - .then(data => { + getOncologyPatientReport(request, queryParts) + .then((data) => { let oncSummary = data; - _.each(oncSummary.result, summary => { + _.each(oncSummary.result, (summary) => { summary.diagnosis = summary.cancer_type && summary.cancer_subtype - ? helpers.titleCase(helpers.getConceptName(summary.cancer_type)) - + " - " + helpers.titleCase(helpers.getConceptName(summary.cancer_subtype)) + ? helpers.titleCase(helpers.getConceptName(summary.cancer_type)) + + ' - ' + + helpers.titleCase( + helpers.getConceptName(summary.cancer_subtype) + ) : helpers.titleCase(helpers.getConceptName(summary.cancer_type)); - summary.diagnosis_method = helpers.getConceptName(summary.diagnosis_method); + summary.diagnosis_method = helpers.getConceptName( + summary.diagnosis_method + ); summary.cancer_stage = helpers.getConceptName(summary.cancer_stage); - summary.overall_cancer_stage_group = helpers.getConceptName(summary.overall_cancer_stage_group); - summary.oncology_treatment_plan = helpers.getConceptName(summary.oncology_treatment_plan); - summary.chemotherapy_plan = helpers.getConceptName(summary.chemotherapy_plan); - summary.cancer_type = helpers.titleCase(helpers.getConceptName(summary.cancer_type)); - summary.cancer_subtype = helpers.titleCase(helpers.getConceptName(summary.cancer_subtype)); - summary.cancer_diagnosis_status = helpers.titleCase(helpers.getConceptName(summary.cancer_diagnosis_status)); - summary.chemotherapy = helpers.titleCase(helpers.getConceptName(summary.chemotherapy)); - summary.total_chemo_cycles_planned = summary.total_chemo_cycles_planned; + summary.overall_cancer_stage_group = helpers.getConceptName( + summary.overall_cancer_stage_group + ); + summary.oncology_treatment_plan = helpers.getConceptName( + summary.oncology_treatment_plan + ); + summary.chemotherapy_plan = helpers.getConceptName( + summary.chemotherapy_plan + ); + summary.cancer_type = helpers.titleCase( + helpers.getConceptName(summary.cancer_type) + ); + summary.cancer_subtype = helpers.titleCase( + helpers.getConceptName(summary.cancer_subtype) + ); + summary.cancer_diagnosis_status = helpers.titleCase( + helpers.getConceptName(summary.cancer_diagnosis_status) + ); + summary.chemotherapy = helpers.titleCase( + helpers.getConceptName(summary.chemotherapy) + ); + summary.total_chemo_cycles_planned = + summary.total_chemo_cycles_planned; summary.current_chemo_cycle = summary.current_chemo_cycle; summary.chemotherapy_regimen = summary.chemotherapy_regimen; - summary.chemotherapy_intent = helpers.getConceptName(summary.chemotherapy_intent); + summary.chemotherapy_intent = helpers.getConceptName( + summary.chemotherapy_intent + ); summary.drug_route = helpers.getConceptName(summary.drug_route); - summary.medication_history = helpers.getConceptName(summary.medication_history); - summary.other_meds_added = helpers.getConceptName(summary.other_meds_addeds); - summary.breast_exam_findings = helpers.getConceptName(summary.breast_exam_findings); - summary.via_test_result = helpers.getConceptName(summary.via_test_result); - summary.encounter_datetime = helpers.filterDate(summary.encounter_datetime); - summary.visit_start_datetime = helpers.filterDate(summary.visit_start_datetime); + summary.medication_history = helpers.getConceptName( + summary.medication_history + ); + summary.other_meds_added = helpers.getConceptName( + summary.other_meds_addeds + ); + summary.breast_exam_findings = helpers.getConceptName( + summary.breast_exam_findings + ); + summary.via_test_result = helpers.getConceptName( + summary.via_test_result + ); + summary.encounter_datetime = helpers.filterDate( + summary.encounter_datetime + ); + summary.visit_start_datetime = helpers.filterDate( + summary.visit_start_datetime + ); summary.enrollment_date = helpers.filterDate(summary.enrollment_date); summary.rtc_date = helpers.filterDate(summary.rtc_date); summary.prev_rtc_date = helpers.filterDate(summary.prev_rtc_date); summary.diagnosis_date = helpers.filterDate(summary.diagnosis_date); - summary.cur_onc_meds_start_date = helpers.filterDate(summary.cur_onc_meds_start_date); + summary.cur_onc_meds_start_date = helpers.filterDate( + summary.cur_onc_meds_start_date + ); }); callback(oncSummary); }) - .catch(error => { - console.error("Error fetching oncSummary: ", error); + .catch((error) => { + console.error('Error fetching oncSummary: ', error); callback(error); }); - } - - function getOncologyPatientReport(request, query) { - let patientUuid = request.params.uuid; - let programUuid = request.query.programUuid; - let whereClause = ["uuid = ? AND programuuid = ? ", patientUuid, programUuid]; - - _.merge(query, { - table: "etl.flat_onc_patient_history", - where: whereClause, - leftOuterJoins: [ - ['(SELECT program_id, uuid as `programuuid` FROM amrs.program ) `t5` ON (t1.program_id = t5.program_id)'], - ['(SELECT uuid as `location_uuid`, location_id FROM amrs.location) `loc` ON (loc.location_id = t1.location_id)'] - ], - offset: request.query.startIndex, - limit: request.query.limit - }); - return db.queryDb(query); - } - - function getPatientVitals(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - // request.query.page; - // request.query.pageSize; - - var queryParts = { - columns: request.query.fields || "*", - table: "etl.flat_vitals", - where: ["uuid = ?", uuid], - order: order || [{ - column: 'encounter_datetime', - asc: false - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - // Use promisified function instead - var promise = db.queryDb(queryParts); - - if (_.isFunction(callback)) { - promise.then(function (result) { - callback(result); - }).catch(function (err) { - callback(err); - }); + } + + function getOncologyPatientReport(request, query) { + let patientUuid = request.params.uuid; + let programUuid = request.query.programUuid; + let whereClause = [ + 'uuid = ? AND programuuid = ? ', + patientUuid, + programUuid + ]; + + _.merge(query, { + table: 'etl.flat_onc_patient_history', + where: whereClause, + leftOuterJoins: [ + [ + '(SELECT program_id, uuid as `programuuid` FROM amrs.program ) `t5` ON (t1.program_id = t5.program_id)' + ], + [ + '(SELECT uuid as `location_uuid`, location_id FROM amrs.location) `loc` ON (loc.location_id = t1.location_id)' + ] + ], + offset: request.query.startIndex, + limit: request.query.limit + }); + return db.queryDb(query); + } + + function getPatientVitals(request, callback) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + // request.query.page; + // request.query.pageSize; + + var queryParts = { + columns: request.query.fields || '*', + table: 'etl.flat_vitals', + where: ['uuid = ?', uuid], + order: order || [ + { + column: 'encounter_datetime', + asc: false } - - // return the promise - return promise; - } - - function getHivPatientClinicalSummary(request, callback) { - var patientUuid = request.params.uuid; - var patientEncounters = encounterService.getPatientEncounters(patientUuid); - var patientHivSummary = getPatientHivSummary(request); - var patientVitals = getPatientVitals(request); - var patientLabData = new Promise(function (resolve) { - var extendedRequest = request; - extendedRequest.query.limit = 300; - getPatientLabData(extendedRequest, function (result) { - resolve(result); - }); - }); - var patientReminders = new Promise(function (resolve, reject) { - var extendedRequest = request; - extendedRequest.query.limit = 1; - extendedRequest.params['referenceDate'] = new Date().toISOString().substring(0, 10); - extendedRequest.params.patientUuid = patientUuid; - - getPatientReminders(extendedRequest, - function (result) { - resolve(result); - }, function (error) { - reject(error); - }); - }); - - Promise.all([patientEncounters, patientHivSummary, patientVitals, patientLabData, patientReminders]) - .then(function (data) { - var encounters = data[0]; - var hivSummaries = data[1].result; - var vitals = data[2].result; - var labDataSummary = data[3].result; - var reminders = data[4].result; - var notes = noteService.generateNotes(encounters, hivSummaries, vitals); - callback({ - patientUuid: patientUuid, - notes: notes, - vitals: vitals, - hivSummaries: hivSummaries, - reminders: reminders.reminders || [], - labDataSummary: labDataSummary - }); - }) - .catch(function (e) { - // Return error - console.error('An error occured', e); - callback(Boom.badData(JSON.stringify(e))); - }); - } - - function getPatientReminders(request, onSuccess, onError) { - var combineRequestParams = Object.assign({}, request.query, request.params); - combineRequestParams.limitParam = 1; - var reportParams = helpers.getReportParams('clinical-reminder-report', ['referenceDate', 'patientUuid', 'offSetParam', 'limitParam'], combineRequestParams); - - var report = new BaseMysqlReport('clinicalReminderReport', reportParams.requestParams); - report.generateReport().then(function (results) { - try { - if (results.results.results.length > 0) { - var processedResults = patientReminderService.generateReminders(results.results.results, []); - results.result = processedResults; - } else { - results.result = { - person_uuid: combineRequestParams.person_uuid, - reminders: [] - }; - } - onSuccess(results); - } catch (error) { - console.error('Error generating reminders', error); - onError(new Error('Error generating reminders')); - } - }).catch(function (error) { - console.error('Error generating reminders', error); - onError(new Error('Error generating reminders')); - }); - } - - function getClinicalNotes(request, callback) { - var patientEncounters = encounterService.getPatientEncounters(request.params.uuid); - var patientHivSummary = getPatientHivSummary(request); - var patientVitals = getPatientVitals(request); - - Promise.all([patientEncounters, patientHivSummary, patientVitals]).then(function (data) { - var encounters = data[0]; - var hivSummaries = data[1].result; - var vitals = data[2].result; - var notes = noteService.generateNotes(encounters, hivSummaries, vitals); - callback({ - notes: notes, - status: 'notes generated' - }); + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + // Use promisified function instead + var promise = db.queryDb(queryParts); + + if (_.isFunction(callback)) { + promise + .then(function (result) { + callback(result); }) - .catch(function (e) { - // Return empty json on error - callback({ - notes: [], - status: 'error generating notes', - error: e - }); - }); - } - - function getPatientLabData(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - - var queryParts = { - columns: request.query.fields || "t1.*, t2.cur_arv_meds", - table: "etl.flat_labs_and_imaging", - leftOuterJoins: [ - ['(select * from etl.flat_hiv_summary_v15b where is_clinical_encounter and uuid="' + uuid + '" group by date(encounter_datetime))', - 't2', 'date(t1.test_datetime) = date(t2.encounter_datetime)' - ] - ], - where: ["t1.uuid = ?", uuid], - order: order || [{ - column: 'test_datetime', - asc: false - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - _.each(result.result, function (row) { - row.tests_ordered = helpers.getTestsOrderedNames(row.tests_ordered); - row.hiv_rapid_test = helpers.getConceptName(row.hiv_rapid_test); - row.cur_arv_meds = helpers.getARVNames(row.cur_arv_meds); - row.lab_errors = helpers.resolvedLabOrderErrors(row.vl_error, row.cd4_error, row.hiv_dna_pcr_error); - row.hiv_dna_pcr = helpers.getConceptName(row.hiv_dna_pcr); - row.antibody_screen = helpers.getConceptName(row.antibody_screen); - row.pus_c_urine = helpers.getConceptName(row.pus_c_urine); - row.protein_urine = helpers.getConceptName(row.protein_urine); - row.leuc = helpers.getConceptName(row.leuc); - row.ketone = helpers.getConceptName(row.ketone); - row.sugar_urine = helpers.getConceptName(row.sugar_urine); - row.nitrites = helpers.getConceptName(row.nitrites); - row.chest_xray = helpers.getConceptName(row.chest_xray); - row.ecg = helpers.getConceptName(row.ecg); - row.test_datetime = row.test_datetime.toString(); - }); - var arr = result.result; - - var resultsByDay = getUniqueResultsByDay(arr); - var cleanResult = getUnique(resultsByDay, 'test_datetime'); - result.result = cleanResult; - callback(result); + .catch(function (err) { + callback(err); }); } - function getUnique(arr, comp) { - const unique = arr.map(e => e[comp]) - .map((e, i, final) => final.indexOf(e) === i && i) - .filter(e => arr[e]).map(e => arr[e]); - - return unique; - - } - - function getUniqueResultsByDay(results){ - let resultTracker = {}; - const sortedArray = results.map((result,index) => { - const test_date = result.test_datetime; - const curResult = result; - if(resultTracker.hasOwnProperty(test_date)){ - const prevResult = resultTracker[test_date]; - const mergedResult = mergeResults(curResult,prevResult); - resultTracker[test_date] = mergedResult; - return mergedResult; - }else{ - resultTracker[test_date] = result; - return result; - } - }).filter((result) => { - const test_date = result.test_datetime; - return _.isEqual(result, resultTracker[test_date]); - }); - return sortedArray; - - } - - function mergeResults(curResult,prevResult){ - let mergedResult = {}; - Object.keys(curResult).forEach((key) => { - if((curResult[key] === null || curResult[key] === '') && (prevResult[key] !== null || prevResult[key] !== '')){ - mergedResult[key] = prevResult[key]; - }else{ - mergedResult[key] = curResult[key]; - } - }); - - return mergedResult; - - } - - function getPatient(request, callback) { - var uuid = request.params.uuid; - var order = helpers.getSortOrder(request.query.order); - - var queryParts = { - columns: request.query.fields || "*", - table: "etl.flat_hiv_summary_v15b", - where: ["uuid = ?", uuid], - order: order || [{ - column: 'encounter_datetime', - asc: false - }], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); + // return the promise + return promise; + } + + function getHivPatientClinicalSummary(request, callback) { + var patientUuid = request.params.uuid; + var patientEncounters = encounterService.getPatientEncounters(patientUuid); + var patientHivSummary = getPatientHivSummary(request); + var patientVitals = getPatientVitals(request); + var patientLabData = new Promise(function (resolve) { + var extendedRequest = request; + extendedRequest.query.limit = 300; + getPatientLabData(extendedRequest, function (result) { + resolve(result); + }); + }); + var patientReminders = new Promise(function (resolve, reject) { + var extendedRequest = request; + extendedRequest.query.limit = 1; + extendedRequest.params[ + 'referenceDate' + ] = new Date().toISOString().substring(0, 10); + extendedRequest.params.patientUuid = patientUuid; + + getPatientReminders( + extendedRequest, + function (result) { + resolve(result); + }, + function (error) { + reject(error); + } + ); + }); + + Promise.all([ + patientEncounters, + patientHivSummary, + patientVitals, + patientLabData, + patientReminders + ]) + .then(function (data) { + var encounters = data[0]; + var hivSummaries = data[1].result; + var vitals = data[2].result; + var labDataSummary = data[3].result; + var reminders = data[4].result; + var notes = noteService.generateNotes(encounters, hivSummaries, vitals); + callback({ + patientUuid: patientUuid, + notes: notes, + vitals: vitals, + hivSummaries: hivSummaries, + reminders: reminders.reminders || [], + labDataSummary: labDataSummary }); - } - - function getPatientCountGroupedByLocation(request, callback) { - var periodFrom = request.query.startDate || new Date().toISOString().substring(0, 10); - var periodTo = request.query.endDate || new Date().toISOString().substring(0, 10); - var order = helpers.getSortOrder(request.query.order); - - var queryParts = { - columns: "t3.location_id,t3.name,count( distinct t1.patient_id) as total", - table: "amrs.patient", - where: ["date_format(t1.date_created,'%Y-%m-%d') between date_format(?,'%Y-%m-%d') AND date_format(?,'%Y-%m-%d')", periodFrom, periodTo], - group: ['t3.uuid,t3.name'], - order: order || [{ - column: 't2.location_id', - asc: false - }], - joins: [ - ['amrs.encounter', 't2', 't1.patient_id = t2.patient_id'], - ['amrs.location', 't3', 't2.location_id=t3.location_id'], - ['amrs.person_name', 't4', 't4.person_id=t1.patient_id and (t4.voided is null || t4.voided = 0)'] - ], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); + }) + .catch(function (e) { + // Return error + console.error('An error occured', e); + callback(Boom.badData(JSON.stringify(e))); + }); + } + + function getPatientReminders(request, onSuccess, onError) { + var combineRequestParams = Object.assign({}, request.query, request.params); + combineRequestParams.limitParam = 1; + var reportParams = helpers.getReportParams( + 'clinical-reminder-report', + ['referenceDate', 'patientUuid', 'offSetParam', 'limitParam'], + combineRequestParams + ); + + var report = new BaseMysqlReport( + 'clinicalReminderReport', + reportParams.requestParams + ); + report + .generateReport() + .then(function (results) { + try { + if (results.results.results.length > 0) { + var processedResults = patientReminderService.generateReminders( + results.results.results, + [] + ); + results.result = processedResults; + } else { + results.result = { + person_uuid: combineRequestParams.person_uuid, + reminders: [] + }; + } + onSuccess(results); + } catch (error) { + console.error('Error generating reminders', error); + onError(new Error('Error generating reminders')); + } + }) + .catch(function (error) { + console.error('Error generating reminders', error); + onError(new Error('Error generating reminders')); + }); + } + + function getClinicalNotes(request, callback) { + var patientEncounters = encounterService.getPatientEncounters( + request.params.uuid + ); + var patientHivSummary = getPatientHivSummary(request); + var patientVitals = getPatientVitals(request); + + Promise.all([patientEncounters, patientHivSummary, patientVitals]) + .then(function (data) { + var encounters = data[0]; + var hivSummaries = data[1].result; + var vitals = data[2].result; + var notes = noteService.generateNotes(encounters, hivSummaries, vitals); + callback({ + notes: notes, + status: 'notes generated' }); - } - - function getPatientDetailsGroupedByLocation(request, callback) { - var location = request.params.location; - var periodFrom = request.query.startDate || new Date().toISOString().substring(0, 10); - var periodTo = request.query.endDate || new Date().toISOString().substring(0, 10); - var order = helpers.getSortOrder(request.query.order); - var queryParts = { - columns: "distinct t4.uuid as patientUuid, t1.patient_id, t3.given_name, t3.middle_name, t3.family_name, t4.gender, extract(year from (from_days(datediff(now(),t4.birthdate)))) as age", - table: "amrs.patient", - where: ["t2.location_id = ? AND date_format(t1.date_created,'%Y-%m-%d') between date_format(?,'%Y-%m-%d') AND date_format(?,'%Y-%m-%d')", location, periodFrom, periodTo], - order: order || [{ - column: 't2.location_id', - asc: false - }], - joins: [ - ['amrs.encounter', 't2', 't1.patient_id = t2.patient_id'], q - ['amrs.person_name', 't3', 't3.person_id=t1.patient_id and (t3.voided is null || t3.voided = 0)'], - ['amrs.person', 't4', 't4.person_id=t1.patient_id'] - ], - offset: request.query.startIndex, - limit: request.query.limit - }; - - db.queryServer_test(queryParts, function (result) { - callback(result); + }) + .catch(function (e) { + // Return empty json on error + callback({ + notes: [], + status: 'error generating notes', + error: e }); - } - - return { - getPatientHivSummary: getPatientHivSummary, - getPatientOncologySummary: getPatientOncologySummary, - getPatientVitals: getPatientVitals, - getClinicalNotes: getClinicalNotes, - getPatientData: getPatientLabData, - getPatient: getPatient, - getHivPatientClinicalSummary: getHivPatientClinicalSummary, - getPatientCountGroupedByLocation: getPatientCountGroupedByLocation, - getPatientDetailsGroupedByLocation: getPatientDetailsGroupedByLocation - } -}(); + }); + } + + function getPatientLabData(request, callback) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + + var queryParts = { + columns: request.query.fields || 't1.*, t2.cur_arv_meds', + table: 'etl.flat_labs_and_imaging', + leftOuterJoins: [ + [ + '(select * from etl.flat_hiv_summary_v15b where is_clinical_encounter and uuid="' + + uuid + + '" group by date(encounter_datetime))', + 't2', + 'date(t1.test_datetime) = date(t2.encounter_datetime)' + ] + ], + where: ['t1.uuid = ?', uuid], + order: order || [ + { + column: 'test_datetime', + asc: false + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + _.each(result.result, function (row) { + row.tests_ordered = helpers.getTestsOrderedNames(row.tests_ordered); + row.hiv_rapid_test = helpers.getConceptName(row.hiv_rapid_test); + row.cur_arv_meds = helpers.getARVNames(row.cur_arv_meds); + row.lab_errors = helpers.resolvedLabOrderErrors( + row.vl_error, + row.cd4_error, + row.hiv_dna_pcr_error + ); + row.hiv_dna_pcr = helpers.getConceptName(row.hiv_dna_pcr); + row.antibody_screen = helpers.getConceptName(row.antibody_screen); + row.pus_c_urine = helpers.getConceptName(row.pus_c_urine); + row.protein_urine = helpers.getConceptName(row.protein_urine); + row.leuc = helpers.getConceptName(row.leuc); + row.ketone = helpers.getConceptName(row.ketone); + row.sugar_urine = helpers.getConceptName(row.sugar_urine); + row.nitrites = helpers.getConceptName(row.nitrites); + row.chest_xray = helpers.getConceptName(row.chest_xray); + row.ecg = helpers.getConceptName(row.ecg); + row.test_datetime = row.test_datetime.toString(); + }); + var arr = result.result; + + var resultsByDay = getUniqueResultsByDay(arr); + var cleanResult = getUnique(resultsByDay, 'test_datetime'); + result.result = cleanResult; + callback(result); + }); + } + + function getUnique(arr, comp) { + const unique = arr + .map((e) => e[comp]) + .map((e, i, final) => final.indexOf(e) === i && i) + .filter((e) => arr[e]) + .map((e) => arr[e]); + + return unique; + } + + function getUniqueResultsByDay(results) { + let resultTracker = {}; + const sortedArray = results + .map((result, index) => { + const test_date = result.test_datetime; + const curResult = result; + if (resultTracker.hasOwnProperty(test_date)) { + const prevResult = resultTracker[test_date]; + const mergedResult = mergeResults(curResult, prevResult); + resultTracker[test_date] = mergedResult; + return mergedResult; + } else { + resultTracker[test_date] = result; + return result; + } + }) + .filter((result) => { + const test_date = result.test_datetime; + return _.isEqual(result, resultTracker[test_date]); + }); + return sortedArray; + } + + function mergeResults(curResult, prevResult) { + let mergedResult = {}; + Object.keys(curResult).forEach((key) => { + if ( + (curResult[key] === null || curResult[key] === '') && + (prevResult[key] !== null || prevResult[key] !== '') + ) { + mergedResult[key] = prevResult[key]; + } else { + mergedResult[key] = curResult[key]; + } + }); + + return mergedResult; + } + + function getPatient(request, callback) { + var uuid = request.params.uuid; + var order = helpers.getSortOrder(request.query.order); + + var queryParts = { + columns: request.query.fields || '*', + table: 'etl.flat_hiv_summary_v15b', + where: ['uuid = ?', uuid], + order: order || [ + { + column: 'encounter_datetime', + asc: false + } + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + } + + function getPatientCountGroupedByLocation(request, callback) { + var periodFrom = + request.query.startDate || new Date().toISOString().substring(0, 10); + var periodTo = + request.query.endDate || new Date().toISOString().substring(0, 10); + var order = helpers.getSortOrder(request.query.order); + + var queryParts = { + columns: 't3.location_id,t3.name,count( distinct t1.patient_id) as total', + table: 'amrs.patient', + where: [ + "date_format(t1.date_created,'%Y-%m-%d') between date_format(?,'%Y-%m-%d') AND date_format(?,'%Y-%m-%d')", + periodFrom, + periodTo + ], + group: ['t3.uuid,t3.name'], + order: order || [ + { + column: 't2.location_id', + asc: false + } + ], + joins: [ + ['amrs.encounter', 't2', 't1.patient_id = t2.patient_id'], + ['amrs.location', 't3', 't2.location_id=t3.location_id'], + [ + 'amrs.person_name', + 't4', + 't4.person_id=t1.patient_id and (t4.voided is null || t4.voided = 0)' + ] + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + } + + function getPatientDetailsGroupedByLocation(request, callback) { + var location = request.params.location; + var periodFrom = + request.query.startDate || new Date().toISOString().substring(0, 10); + var periodTo = + request.query.endDate || new Date().toISOString().substring(0, 10); + var order = helpers.getSortOrder(request.query.order); + var queryParts = { + columns: + 'distinct t4.uuid as patientUuid, t1.patient_id, t3.given_name, t3.middle_name, t3.family_name, t4.gender, extract(year from (from_days(datediff(now(),t4.birthdate)))) as age', + table: 'amrs.patient', + where: [ + "t2.location_id = ? AND date_format(t1.date_created,'%Y-%m-%d') between date_format(?,'%Y-%m-%d') AND date_format(?,'%Y-%m-%d')", + location, + periodFrom, + periodTo + ], + order: order || [ + { + column: 't2.location_id', + asc: false + } + ], + joins: [ + ['amrs.encounter', 't2', 't1.patient_id = t2.patient_id'], + q[ + ('amrs.person_name', + 't3', + 't3.person_id=t1.patient_id and (t3.voided is null || t3.voided = 0)') + ], + ['amrs.person', 't4', 't4.person_id=t1.patient_id'] + ], + offset: request.query.startIndex, + limit: request.query.limit + }; + + db.queryServer_test(queryParts, function (result) { + callback(result); + }); + } + + return { + getPatientHivSummary: getPatientHivSummary, + getPatientOncologySummary: getPatientOncologySummary, + getPatientVitals: getPatientVitals, + getClinicalNotes: getClinicalNotes, + getPatientData: getPatientLabData, + getPatient: getPatient, + getHivPatientClinicalSummary: getHivPatientClinicalSummary, + getPatientCountGroupedByLocation: getPatientCountGroupedByLocation, + getPatientDetailsGroupedByLocation: getPatientDetailsGroupedByLocation + }; +})(); diff --git a/dao/patient/etl-patient-hiv-summary-dao.js b/dao/patient/etl-patient-hiv-summary-dao.js index 2d98d88ea..039262a08 100755 --- a/dao/patient/etl-patient-hiv-summary-dao.js +++ b/dao/patient/etl-patient-hiv-summary-dao.js @@ -3,48 +3,61 @@ var Promise = require('bluebird'); var db = require('../../etl-db'); var def = { - getPatientHivSummary: getPatientHivSummary, - getPatientLastEncounter: getPatientLastEncounter + getPatientHivSummary: getPatientHivSummary, + getPatientLastEncounter: getPatientLastEncounter }; module.exports = def; -function getPatientHivSummary(patientUuid, clinicalOnly, - params, startIndex, limit) { - - var whereClause = clinicalOnly ? ['uuid = ? AND is_clinical_encounter = true', patientUuid] : ['uuid = ?', patientUuid]; - var queryObject = { - columns: '*', - table: 'etl.flat_hiv_summary_v15b', - where: whereClause, - order: [{ - column: 'encounter_datetime', - asc: false - }], - offset: startIndex, - limit: limit - }; - - return db.queryDb(queryObject); +function getPatientHivSummary( + patientUuid, + clinicalOnly, + params, + startIndex, + limit +) { + var whereClause = clinicalOnly + ? ['uuid = ? AND is_clinical_encounter = true', patientUuid] + : ['uuid = ?', patientUuid]; + var queryObject = { + columns: '*', + table: 'etl.flat_hiv_summary_v15b', + where: whereClause, + order: [ + { + column: 'encounter_datetime', + asc: false + } + ], + offset: startIndex, + limit: limit + }; + + return db.queryDb(queryObject); } function getPatientLastEncounter(patientUuid) { - - var whereClause = ["encounter_type IN (2,106) AND visit_type_id = 59 AND (e.voided in (0) OR e.voided IS NULL) AND p.uuid = ?", patientUuid]; - var queryObject = { - columns: 'TIMESTAMPDIFF(MONTH, MAX(encounter_datetime), DATE(NOW())) as `months_from_last_visit`', - table: 'amrs.encounter', - alias: 'e', - where: whereClause, - leftOuterJoins: [ - ["amrs.person", "p", "p.person_id = e.patient_id"], - ["amrs.visit", "v", "e.visit_id = v.visit_id"] - ], - order: [{ - column: 'encounter_datetime', - asc: false - }] - }; - - return db.queryDb(queryObject); -} \ No newline at end of file + var whereClause = [ + 'encounter_type IN (2,106) AND visit_type_id = 59 AND (e.voided in (0) OR e.voided IS NULL) AND p.uuid = ?', + patientUuid + ]; + var queryObject = { + columns: + 'TIMESTAMPDIFF(MONTH, MAX(encounter_datetime), DATE(NOW())) as `months_from_last_visit`', + table: 'amrs.encounter', + alias: 'e', + where: whereClause, + leftOuterJoins: [ + ['amrs.person', 'p', 'p.person_id = e.patient_id'], + ['amrs.visit', 'v', 'e.visit_id = v.visit_id'] + ], + order: [ + { + column: 'encounter_datetime', + asc: false + } + ] + }; + + return db.queryDb(queryObject); +} diff --git a/dao/program-type/program-type-dao.js b/dao/program-type/program-type-dao.js index 22c01dfc9..a1e149534 100755 --- a/dao/program-type/program-type-dao.js +++ b/dao/program-type/program-type-dao.js @@ -9,42 +9,34 @@ var connection = require('../../dao/connection/mysql-connection-service.js'); var authorizer = require('../../authorization/etl-authorizer'); var programType = { - getProgramTypes : getProgramTypes + getProgramTypes: getProgramTypes }; module.exports = programType; function getProgramTypes() { - - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('p.program_id') - .field('p.name') - .field('p.uuid') - .from('amrs.program', 'p') - .toString(); - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - - - - }); - + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('p.program_id') + .field('p.name') + .field('p.uuid') + .from('amrs.program', 'p') + .toString(); + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } - - - - diff --git a/dao/session/session.js b/dao/session/session.js index 41242fc84..52eb97bee 100755 --- a/dao/session/session.js +++ b/dao/session/session.js @@ -4,26 +4,27 @@ var db = require('../../etl-db'); var _ = require('underscore'); var cache = require('../../session-cache'); - -module.exports = function () { - - function invalidateUserSession(request, callback) { - if(request.headers.authorization) { - var header =request.headers.authorization; - var authBuffer=header.replace('Basic ',''); - cache.encriptKey(authBuffer, function (hash) { - cache.removeFromCache(hash); - callback('user session was invalidated successfully in etl server'); - }, function (err) { - callback(Boom.badData(err)); - }); - } else{ - callback(Boom.badData(err)); +module.exports = (function () { + function invalidateUserSession(request, callback) { + if (request.headers.authorization) { + var header = request.headers.authorization; + var authBuffer = header.replace('Basic ', ''); + cache.encriptKey( + authBuffer, + function (hash) { + cache.removeFromCache(hash); + callback('user session was invalidated successfully in etl server'); + }, + function (err) { + callback(Boom.badData(err)); } + ); + } else { + callback(Boom.badData(err)); } + } - - return { - invalidateUserSession: invalidateUserSession - } -}(); + return { + invalidateUserSession: invalidateUserSession + }; +})(); diff --git a/dao/visit-type/visit-type-dao.js b/dao/visit-type/visit-type-dao.js index e3145cd93..ab760bb07 100755 --- a/dao/visit-type/visit-type-dao.js +++ b/dao/visit-type/visit-type-dao.js @@ -9,43 +9,35 @@ var connection = require('../../dao/connection/mysql-connection-service.js'); var authorizer = require('../../authorization/etl-authorizer'); var visitType = { - getVisitTypes : getVisitTypes + getVisitTypes: getVisitTypes }; module.exports = visitType; function getVisitTypes() { - - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - var query = squel.select() - .field('vt.visit_type_id') - .field('vt.name') - .field('vt.uuid') - .from('amrs.visit_type', 'vt') - .toString(); - conn.query(query, {}, function (err, rows, fields) { - if (err) { - reject('Error querying server'); - } - else { - // console.log('Visit Type Rows', rows); - resolve(rows); - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - - - - }); - + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .select() + .field('vt.visit_type_id') + .field('vt.name') + .field('vt.uuid') + .from('amrs.visit_type', 'vt') + .toString(); + conn.query(query, {}, function (err, rows, fields) { + if (err) { + reject('Error querying server'); + } else { + // console.log('Visit Type Rows', rows); + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } - - - - diff --git a/departments/department-programs-config.json b/departments/department-programs-config.json index 30c12211f..5c36100c0 100755 --- a/departments/department-programs-config.json +++ b/departments/department-programs-config.json @@ -1,191 +1,179 @@ { - "uud1":{ - "name":"HIV", - "programs":[ - { - "uuid":"781d85b0-1359-11df-a1f1-0026b9348838", - "name": "STANDARD HIV TREATMENT" - }, - { - "uuid":"f7793d42-11ac-4cfd-9b35-e0a21a7a7c31", - "name": "RESISTANCE CLINIC PROGRAM" - }, - { - "uuid":"781d897a-1359-11df-a1f1-0026b9348838", - "name": "PREVENTION OF MOTHER-TO-CHILD TRANSMISSION OF HIV" - - }, - { - "uuid":"96047aaf-7ab3-45e9-be6a-b61810fe617d", - "name": "PEP PROGRAM" - - }, - { - "uuid":"c19aec66-1a40-4588-9b03-b6be55a8dd1d", - "name": "PrEP PROGRAM" - - }, - { - "uuid":"334c9e98-173f-4454-a8ce-f80b20b7fdf0", - "name": "HIV DIFFERENTIATED CARE PROGRAM" - - }, - { - "uuid":"96ba279b-b23b-4e78-aba9-dcbd46a96b7b", - "name": "HIV TRANSIT PROGRAM" - - }, - { - "uuid":"781d8880-1359-11df-a1f1-0026b9348838", - "name": "EXPRESS CARE PROGRAM" - - }, - { - "uuid":"c6bf3625-de80-4a88-a913-38273e300a55", - "name": "HIV RETENTION PROGRAM" - - }, - { - "uuid":"4480c782-ef05-4d88-b2f8-c892c99438f6", - "name": "ACTG PROGRAM" - - }, - { - "uuid":"c4246ff0-b081-460c-bcc5-b0678012659e", - "name": "VIREMIA PROGRAM" - - }, - { - "uuid":"781d8768-1359-11df-a1f1-0026b9348838", - "name": "OVC PROGRAM" - }, - { - "uuid":"6ff0a6dc-ef8f-467a-86fc-9d9b263d8761", - "name": "DTG PHARMACO-VIGILANCE" - }, - { - "uuid": "a8e7c30d-6d2f-401c-bb52-d4433689a36b", - "name": "HEI PROGRAM" - }, - { - "uuid": "a685c057-d475-42ef-bb33-8b0c1d73b122", - "name": "HIV SOCIAL WORK PROGRAM" - }, - { - "uuid": "03552f68-8233-4793-8353-3db1847bb617", - "name": "NUTRITION PROGRAM" - } - ] - }, - "uud2":{ - "name":"HEMATO-ONCOLOGY", - "programs":[ - { - "uuid":"43b42170-b3ce-4e03-9390-6bd78384ac06", - "name": "GYN-ONCOLOGY TREATMENT PROGRAM" - }, - { - "uuid":"88566621-828f-4569-9af5-c54f8237750a", - "name": "BREAST CANCER TREATMENT PROGRAM" - }, - { - "uuid":"e48b266e-4d80-41f8-a56a-a8ce5449ebc6", - "name": "SICKLE CELL PROGRAM" - }, - { - "uuid":"698b7153-bff3-4931-9638-d279ca47b32e", - "name": "MULTIPLE MYELOMA PROGRAM" - }, - { - "uuid":"a3610ba4-9811-46b3-9628-83ec9310be13", - "name": "HEMOPHILIA PROGRAM" - }, - { - "uuid":"725b5193-3452-43fc-aca3-6a80432d9bfa", - "name": "GENERAL ONCOLOGY PROGRAM" - }, - { - "uuid":"e8bc5036-1462-44fa-bcfe-ced21eae2790", - "name": "LUNG CANCER TREATMENT PROGRAM" - }, - { - "uuid": "418fe011-a903-4862-93d4-5e7c84d9c253", - "name": "ANTICOAGULATION TREATMENT PROGRAM" - }, - { - "uuid": "40677054-c402-4c56-a0e4-5dd7d799b52f", - "name": "LYMPHOMA TREATMENT PROGRAM" - }, - { - "uuid": "37ff4124-91fd-49e6-8261-057ccfb4fcd0", - "name": "ONCOLOGY SCREENING AND DIAGNOSIS PROGRAM" - } - ] - }, - "uud3":{ - "name":"CDM", - "programs":[ - - { - "uuid":"b731ba72-cf99-4176-9fcd-37cd186400c7", - "name": "HTN AND DM CARE AT THE SECONDARY CARE LEVEL" - }, - { - "uuid":"bd9a8b06-73c7-44a8-928c-5e72247f4c1d", - "name": "HTN AND DM CARE AT THE TERTIARY CARE LEVEL PROGRAM" - }, - { - "uuid":"876a154d-310d-4caf-8b58-be9dbcc7e753", - "name": "HTN AND DM CARE AT THE PRIMARY CARE LEVEL" - }, - { - "uuid": "da0c184e-751c-4b7e-a761-a60dc2d3f798", - "name": "INTEGRATED SCREENING PROGRAM" - }, - { - "uuid": "f5cbf61f-eadc-4fe6-999c-2dfe9556df95", - "name": "BIGPIC PROGRAM" - }, - { - "uuid": "62741bb8-949e-4acc-9e38-50d9d874c1fb", - "name": "BI KUZA AFYA PROGRAM " - }, - { - "uuid": "a15a58a4-0daa-4195-bf29-b4bccd5df01e", - "name": "REFERRAL PEER NAVIGATOR PROGRAM" - }, - { - "uuid": "ff446cb9-0cf4-4b39-8288-16a43ffcca25", - "name": "CDM DEFAULTER TRACING PROGRAM" - }, - { - "uuid": "d2090d0b-990a-4b82-98a8-32f987329f63", - "name": "HOME GLUCOSE MONITORING PROGRAM" - }, - { - "uuid": "6976b7eb-6d66-4aba-bcc0-cd8be80041cd", - "name": "MENTAL HEALTH PROGRAM" - } - ] - }, - "uud4":{ - "name":"BSG", - "programs":[ - { - "uuid":"781d8a88-1359-11df-a1f1-0026b9348838", - "name": "BSG PROGRAM" - } - - ] - }, - "uud5":{ - "name":"DERMATOLOGY", - "programs":[ - { - "uuid":"b3575274-1850-429b-bb8f-2ff83faedbaf", - "name": "DERMATOLOGY" - } - - ] - } + "uud1": { + "name": "HIV", + "programs": [ + { + "uuid": "781d85b0-1359-11df-a1f1-0026b9348838", + "name": "STANDARD HIV TREATMENT" + }, + { + "uuid": "f7793d42-11ac-4cfd-9b35-e0a21a7a7c31", + "name": "RESISTANCE CLINIC PROGRAM" + }, + { + "uuid": "781d897a-1359-11df-a1f1-0026b9348838", + "name": "PREVENTION OF MOTHER-TO-CHILD TRANSMISSION OF HIV" + }, + { + "uuid": "96047aaf-7ab3-45e9-be6a-b61810fe617d", + "name": "PEP PROGRAM" + }, + { + "uuid": "c19aec66-1a40-4588-9b03-b6be55a8dd1d", + "name": "PrEP PROGRAM" + }, + { + "uuid": "334c9e98-173f-4454-a8ce-f80b20b7fdf0", + "name": "HIV DIFFERENTIATED CARE PROGRAM" + }, + { + "uuid": "96ba279b-b23b-4e78-aba9-dcbd46a96b7b", + "name": "HIV TRANSIT PROGRAM" + }, + { + "uuid": "781d8880-1359-11df-a1f1-0026b9348838", + "name": "EXPRESS CARE PROGRAM" + }, + { + "uuid": "c6bf3625-de80-4a88-a913-38273e300a55", + "name": "HIV RETENTION PROGRAM" + }, + { + "uuid": "4480c782-ef05-4d88-b2f8-c892c99438f6", + "name": "ACTG PROGRAM" + }, + { + "uuid": "c4246ff0-b081-460c-bcc5-b0678012659e", + "name": "VIREMIA PROGRAM" + }, + { + "uuid": "781d8768-1359-11df-a1f1-0026b9348838", + "name": "OVC PROGRAM" + }, + { + "uuid": "6ff0a6dc-ef8f-467a-86fc-9d9b263d8761", + "name": "DTG PHARMACO-VIGILANCE" + }, + { + "uuid": "a8e7c30d-6d2f-401c-bb52-d4433689a36b", + "name": "HEI PROGRAM" + }, + { + "uuid": "a685c057-d475-42ef-bb33-8b0c1d73b122", + "name": "HIV SOCIAL WORK PROGRAM" + }, + { + "uuid": "03552f68-8233-4793-8353-3db1847bb617", + "name": "NUTRITION PROGRAM" + } + ] + }, + "uud2": { + "name": "HEMATO-ONCOLOGY", + "programs": [ + { + "uuid": "43b42170-b3ce-4e03-9390-6bd78384ac06", + "name": "GYN-ONCOLOGY TREATMENT PROGRAM" + }, + { + "uuid": "88566621-828f-4569-9af5-c54f8237750a", + "name": "BREAST CANCER TREATMENT PROGRAM" + }, + { + "uuid": "e48b266e-4d80-41f8-a56a-a8ce5449ebc6", + "name": "SICKLE CELL PROGRAM" + }, + { + "uuid": "698b7153-bff3-4931-9638-d279ca47b32e", + "name": "MULTIPLE MYELOMA PROGRAM" + }, + { + "uuid": "a3610ba4-9811-46b3-9628-83ec9310be13", + "name": "HEMOPHILIA PROGRAM" + }, + { + "uuid": "725b5193-3452-43fc-aca3-6a80432d9bfa", + "name": "GENERAL ONCOLOGY PROGRAM" + }, + { + "uuid": "e8bc5036-1462-44fa-bcfe-ced21eae2790", + "name": "LUNG CANCER TREATMENT PROGRAM" + }, + { + "uuid": "418fe011-a903-4862-93d4-5e7c84d9c253", + "name": "ANTICOAGULATION TREATMENT PROGRAM" + }, + { + "uuid": "40677054-c402-4c56-a0e4-5dd7d799b52f", + "name": "LYMPHOMA TREATMENT PROGRAM" + }, + { + "uuid": "37ff4124-91fd-49e6-8261-057ccfb4fcd0", + "name": "ONCOLOGY SCREENING AND DIAGNOSIS PROGRAM" + } + ] + }, + "uud3": { + "name": "CDM", + "programs": [ + { + "uuid": "b731ba72-cf99-4176-9fcd-37cd186400c7", + "name": "HTN AND DM CARE AT THE SECONDARY CARE LEVEL" + }, + { + "uuid": "bd9a8b06-73c7-44a8-928c-5e72247f4c1d", + "name": "HTN AND DM CARE AT THE TERTIARY CARE LEVEL PROGRAM" + }, + { + "uuid": "876a154d-310d-4caf-8b58-be9dbcc7e753", + "name": "HTN AND DM CARE AT THE PRIMARY CARE LEVEL" + }, + { + "uuid": "da0c184e-751c-4b7e-a761-a60dc2d3f798", + "name": "INTEGRATED SCREENING PROGRAM" + }, + { + "uuid": "f5cbf61f-eadc-4fe6-999c-2dfe9556df95", + "name": "BIGPIC PROGRAM" + }, + { + "uuid": "62741bb8-949e-4acc-9e38-50d9d874c1fb", + "name": "BI KUZA AFYA PROGRAM " + }, + { + "uuid": "a15a58a4-0daa-4195-bf29-b4bccd5df01e", + "name": "REFERRAL PEER NAVIGATOR PROGRAM" + }, + { + "uuid": "ff446cb9-0cf4-4b39-8288-16a43ffcca25", + "name": "CDM DEFAULTER TRACING PROGRAM" + }, + { + "uuid": "d2090d0b-990a-4b82-98a8-32f987329f63", + "name": "HOME GLUCOSE MONITORING PROGRAM" + }, + { + "uuid": "6976b7eb-6d66-4aba-bcc0-cd8be80041cd", + "name": "MENTAL HEALTH PROGRAM" + } + ] + }, + "uud4": { + "name": "BSG", + "programs": [ + { + "uuid": "781d8a88-1359-11df-a1f1-0026b9348838", + "name": "BSG PROGRAM" + } + ] + }, + "uud5": { + "name": "DERMATOLOGY", + "programs": [ + { + "uuid": "b3575274-1850-429b-bb8f-2ff83faedbaf", + "name": "DERMATOLOGY" + } + ] + } } diff --git a/departments/departments-programs.service.js b/departments/departments-programs.service.js index ecf6175f3..878ed9f8f 100755 --- a/departments/departments-programs.service.js +++ b/departments/departments-programs.service.js @@ -4,47 +4,45 @@ const departmentsConfig = require('./department-programs-config.json'); const _ = require('lodash'); var serviceDefinition = { - getAllDepartmentsConfig: getAllDepartmentsConfig, - getDepartmentPrograms: getDepartmentPrograms, - getDepartmentProgramUuids: getDepartmentProgramUuids + getAllDepartmentsConfig: getAllDepartmentsConfig, + getDepartmentPrograms: getDepartmentPrograms, + getDepartmentProgramUuids: getDepartmentProgramUuids }; module.exports = serviceDefinition; function getAllDepartmentsConfig() { - return JSON.parse(JSON.stringify(departmentsConfig)); + return JSON.parse(JSON.stringify(departmentsConfig)); } -function getDepartmentPrograms(department){ - return new Promise(function (resolve, reject) { - let departmentProgramConfig = departmentsConfig; - let departmentPrograms = []; - _.each(departmentProgramConfig, (departmentConf) => { - let departmentName = departmentConf.name; - let programs = departmentConf.programs; - if(departmentName === department || department === ''){ - _.each(programs,(program) => { - departmentPrograms.push(program); - }); - } - }); - - resolve(JSON.stringify(departmentPrograms)); - +function getDepartmentPrograms(department) { + return new Promise(function (resolve, reject) { + let departmentProgramConfig = departmentsConfig; + let departmentPrograms = []; + _.each(departmentProgramConfig, (departmentConf) => { + let departmentName = departmentConf.name; + let programs = departmentConf.programs; + if (departmentName === department || department === '') { + _.each(programs, (program) => { + departmentPrograms.push(program); + }); + } }); + + resolve(JSON.stringify(departmentPrograms)); + }); } -function getDepartmentProgramUuids(department){ +function getDepartmentProgramUuids(department) { let departmentProgramConfig = departmentsConfig; let departmentPrograms = []; _.each(departmentProgramConfig, (departmentConf) => { - let departmentName = departmentConf.name; - let programs = departmentConf.programs; - if(departmentName === department || department === ''){ - _.each(programs,(program) => { - departmentPrograms.push(program.uuid); - }); - } + let departmentName = departmentConf.name; + let programs = departmentConf.programs; + if (departmentName === department || department === '') { + _.each(programs, (program) => { + departmentPrograms.push(program.uuid); + }); + } }); return departmentPrograms; - } diff --git a/docker-compose.yml b/docker-compose.yml index 29e187f6e..e0fe44587 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,22 +1,22 @@ version: '2' services: - eid-services: - container_name: eid-services - image: 10.50.80.56:5005/eid-services - environment: - - NODE_TLS_REJECT_UNAUTHORIZED=0 - - TZ=Africa/Nairobi - dns: - - 10.50.80.150 - - 8.8.8.8 + eid-services: + container_name: eid-services + image: 10.50.80.56:5005/eid-services + environment: + - NODE_TLS_REJECT_UNAUTHORIZED=0 + - TZ=Africa/Nairobi + dns: + - 10.50.80.150 + - 8.8.8.8 - volumes: - - /Users/achachiez/Code/AmpathWorkSpace/etl-rest-server/conf:/opt/etl/conf - # deploy: - # mode: replicated - # replicas: 1 - # placement: - # constraints: - # - node.hostname == upgrade1 - ports: - - 8004:8004 \ No newline at end of file + volumes: + - /Users/achachiez/Code/AmpathWorkSpace/etl-rest-server/conf:/opt/etl/conf + # deploy: + # mode: replicated + # replicas: 1 + # placement: + # constraints: + # - node.hostname == upgrade1 + ports: + - 8004:8004 diff --git a/docker-settings.js b/docker-settings.js index 04c8ea3ff..1361f94b5 100755 --- a/docker-settings.js +++ b/docker-settings.js @@ -8,8 +8,8 @@ module.exports = { host: '0.0.0.0', port: 8002, tls: true, - key: '/keys/server.key', // Server Key - cert: '/keys/server.crt' // Certificate to allow TLS access to the server + key: '/keys/server.key', // Server Key + cert: '/keys/server.crt' // Certificate to allow TLS access to the server }, mysql: { connectionLimit: 10, diff --git a/eid-data-synchronization/eid-lab-results.js b/eid-data-synchronization/eid-lab-results.js index 2b4915097..fe063b031 100755 --- a/eid-data-synchronization/eid-lab-results.js +++ b/eid-data-synchronization/eid-lab-results.js @@ -5,35 +5,33 @@ var obs = require('../service/openmrs-rest/obs.service'); module.exports = { getPatientLabResults: getPatientLabResults -} +}; function getPatientLabResults(request, reply) { - eidSyncLog.getEidSyncLog(request, function (result) { - var patientHasEverBeenSynced = false; - if (result.result.length > 0) - patientHasEverBeenSynced = true; + if (result.result.length > 0) patientHasEverBeenSynced = true; if (patientHasEverBeenSynced) { - if (result.result[0]['status'] === 0 && (result.result.length ===1 || result.result[1]['status'] === 0) && - result.result[0]['TIMESTAMPDIFF(HOUR,date_updated,now())'] < 6) { + if ( + result.result[0]['status'] === 0 && + (result.result.length === 1 || result.result[1]['status'] === 0) && + result.result[0]['TIMESTAMPDIFF(HOUR,date_updated,now())'] < 6 + ) { console.log('Patient synced..'); - obs.getPatientTodaysTestObsByPatientUuId(request.query.patientUuId) + obs + .getPatientTodaysTestObsByPatientUuId(request.query.patientUuId) .then(function (response) { - reply({ updatedObs: response, last_sync_date: result.result[0]['date_updated'] }); }); - } - else { + } else { console.log('Syncing patient...'); syncAndGetPatientLabResults(request, reply); } - } - else { + } else { console.log('Syncing patient...'); syncAndGetPatientLabResults(request, reply); } @@ -41,44 +39,42 @@ function getPatientLabResults(request, reply) { } function syncAndGetPatientLabResults(request, reply) { - var patientUuId = request.query.patientUuId; - eidService.getSynchronizedPatientLabResults(patientUuId) + eidService + .getSynchronizedPatientLabResults(patientUuId) .then(function (syncRespose) { - eidSyncLog.getEidSyncLog(request, function (result) { - var patientHasEverBeenSynced = false; - if (result.result.length > 0) - patientHasEverBeenSynced = true; + if (result.result.length > 0) patientHasEverBeenSynced = true; if (patientHasEverBeenSynced) if (result.result[0]['TIMESTAMPDIFF(HOUR,date_updated,now())'] < 6) - obs.getPatientTodaysTestObsByPatientUuId(patientUuId) + obs + .getPatientTodaysTestObsByPatientUuId(patientUuId) .then(function (response) { reply({ updatedObs: response, last_sync_date: result.result[0]['date_updated'], errors: syncRespose.errors - }).catch((error)=>{ - console.log('ERROR',error); + }).catch((error) => { + console.log('ERROR', error); }); }); else reply({ updatedObs: [], errors: syncRespose.errors - }) + }); else reply({ updatedObs: [], errors: syncRespose.errors - }) + }); }); }) .catch(function (err) { reply({ updatedObs: [] - }) + }); }); } diff --git a/eid-lab-results.json b/eid-lab-results.json index 93848f938..885519896 100755 --- a/eid-lab-results.json +++ b/eid-lab-results.json @@ -1,47 +1,55 @@ { - "patientLabResultsSchema":{ - "name": "etl_sync_log", - "table": { - "schema": "etl", - "tableName": "eid_sync_log", - "alias": "t1" - }, - "joins": [], - "columns": ["TIMESTAMPDIFF(HOUR,date_updated,now())", "person_uuid", "date_updated", "date_created", "status", "message", "site"], - "parameters": [ - { - "name": "TIMESTAMPDIFF(HOUR,date_updated,now())", - "defaultValue":["defaultValue"] - }, - { - "name": "person_uuid=?", - "defaultValue": ["defaultValue"] - }, - { - "name": "date_updated", - "defaultValue": ["defaultValue"] - }, - { - "name": "date_created=?", - "defaultValue": ["defaultValue"] - }, - { - "name": "status=?", - "defaultValue": ["defaultValue"] - }, - { - "name": "message=?", - "defaultValue": ["defaultValue"] - } - ], - "filters": [ - { - "expression": "person_uuid=?", - "parameter": "person_uuid" - } - ], - "groupClause": [], - "indicators": [], - "supplementColumns": [] - } + "patientLabResultsSchema": { + "name": "etl_sync_log", + "table": { + "schema": "etl", + "tableName": "eid_sync_log", + "alias": "t1" + }, + "joins": [], + "columns": [ + "TIMESTAMPDIFF(HOUR,date_updated,now())", + "person_uuid", + "date_updated", + "date_created", + "status", + "message", + "site" + ], + "parameters": [ + { + "name": "TIMESTAMPDIFF(HOUR,date_updated,now())", + "defaultValue": ["defaultValue"] + }, + { + "name": "person_uuid=?", + "defaultValue": ["defaultValue"] + }, + { + "name": "date_updated", + "defaultValue": ["defaultValue"] + }, + { + "name": "date_created=?", + "defaultValue": ["defaultValue"] + }, + { + "name": "status=?", + "defaultValue": ["defaultValue"] + }, + { + "name": "message=?", + "defaultValue": ["defaultValue"] + } + ], + "filters": [ + { + "expression": "person_uuid=?", + "parameter": "person_uuid" + } + ], + "groupClause": [], + "indicators": [], + "supplementColumns": [] + } } diff --git a/eid-obs-compare.js b/eid-obs-compare.js index c0abd5a9c..ac2f36a2b 100755 --- a/eid-obs-compare.js +++ b/eid-obs-compare.js @@ -1,348 +1,399 @@ -'use strict' +'use strict'; var moment = require('moment'); var _ = require('underscore'); var moduleDefinition = { - isViralLoadEquivalent: isViralLoadEquivalent, - isDnaPcrEquivalent: isDnaPcrEquivalent, - isCd4PanelEquivalent: isCd4PanelEquivalent, - findAllMissingEidResults: findAllMissingEidResults, - findConflictingEidAmrsViralLoadResults: findConflictingEidAmrsViralLoadResults, - - //helpers - findEquivalentObject: findEquivalentObject, - conceptDateComparer: conceptDateComparer, - findMissingEidResults: findMissingEidResults, - mergeEidResults: mergeEidResults, - isEidViralLoadError: isEidViralLoadError, - isEidCD4PanelError: isEidCD4PanelError, - isObsViralLoadError: isObsViralLoadError, - isObsCd4PanelError: isObsCd4PanelError - + isViralLoadEquivalent: isViralLoadEquivalent, + isDnaPcrEquivalent: isDnaPcrEquivalent, + isCd4PanelEquivalent: isCd4PanelEquivalent, + findAllMissingEidResults: findAllMissingEidResults, + findConflictingEidAmrsViralLoadResults: findConflictingEidAmrsViralLoadResults, + + //helpers + findEquivalentObject: findEquivalentObject, + conceptDateComparer: conceptDateComparer, + findMissingEidResults: findMissingEidResults, + mergeEidResults: mergeEidResults, + isEidViralLoadError: isEidViralLoadError, + isEidCD4PanelError: isEidCD4PanelError, + isObsViralLoadError: isObsViralLoadError, + isObsCd4PanelError: isObsCd4PanelError }; module.exports = moduleDefinition; function findAllMissingEidResults(allEidResults, arrayOfObs) { - var results = { - viralLoad: [], - pcr: [], - cd4Panel: [] - }; - - if (allEidResults.viralLoad.length > 0) { - // console.log('EID Viral load results', results.viralLoad); - results.viralLoad = - moduleDefinition.findMissingEidResults(filterOutResultsWithoutDateCollected(allEidResults.viralLoad), - arrayOfObs, isViralLoadEquivalent); - } - - if (allEidResults.pcr.length > 0) { - results.pcr = - moduleDefinition.findMissingEidResults(filterOutResultsWithoutDateCollected(allEidResults.pcr), - arrayOfObs, isDnaPcrEquivalent); - } - - if (allEidResults.cd4Panel.length > 0) { - results.cd4Panel = - moduleDefinition.findMissingEidResults(filterOutResultsWithoutDateCollected(allEidResults.cd4Panel), - arrayOfObs, isCd4PanelEquivalent); - } - - // console.log('MISSING LABS', results); - return results; + var results = { + viralLoad: [], + pcr: [], + cd4Panel: [] + }; + + if (allEidResults.viralLoad.length > 0) { + // console.log('EID Viral load results', results.viralLoad); + results.viralLoad = moduleDefinition.findMissingEidResults( + filterOutResultsWithoutDateCollected(allEidResults.viralLoad), + arrayOfObs, + isViralLoadEquivalent + ); + } + + if (allEidResults.pcr.length > 0) { + results.pcr = moduleDefinition.findMissingEidResults( + filterOutResultsWithoutDateCollected(allEidResults.pcr), + arrayOfObs, + isDnaPcrEquivalent + ); + } + + if (allEidResults.cd4Panel.length > 0) { + results.cd4Panel = moduleDefinition.findMissingEidResults( + filterOutResultsWithoutDateCollected(allEidResults.cd4Panel), + arrayOfObs, + isCd4PanelEquivalent + ); + } + + // console.log('MISSING LABS', results); + return results; } function filterOutResultsWithoutDateCollected(resultsArray) { - var results = []; - _.each(resultsArray, function (result) { - if (moment(result.DateCollected).isValid()) { - results.push(result); - } - }); - return results; + var results = []; + _.each(resultsArray, function (result) { + if (moment(result.DateCollected).isValid()) { + results.push(result); + } + }); + return results; } function findConflictingEidAmrsViralLoadResults(arrayOfEidResult, arrayOfObs) { - var conflicting = []; - - _.each(arrayOfEidResult, function (eid) { - var cnflts = findConflictsForEidViralLoad(eid, arrayOfObs); - if (cnflts.length > 0) { - conflicting.push({ - eid: eid, - obs: cnflts - }); - } - }); - - return conflicting; + var conflicting = []; + + _.each(arrayOfEidResult, function (eid) { + var cnflts = findConflictsForEidViralLoad(eid, arrayOfObs); + if (cnflts.length > 0) { + conflicting.push({ + eid: eid, + obs: cnflts + }); + } + }); + + return conflicting; } function findConflictsForEidViralLoad(eidViralload, arrayOfObs) { - var conflicting = []; + var conflicting = []; - var eid = eidViralload; - var filteredObs = findViralLoadObsResultsByDate(eidViralload.DateCollected, arrayOfObs); + var eid = eidViralload; + var filteredObs = findViralLoadObsResultsByDate( + eidViralload.DateCollected, + arrayOfObs + ); - _.each(filteredObs, function (obs) { - if (!isViralLoadEquivalent(eid, obs)) { - conflicting.push(obs); - } - }); - return conflicting; + _.each(filteredObs, function (obs) { + if (!isViralLoadEquivalent(eid, obs)) { + conflicting.push(obs); + } + }); + return conflicting; } function findViralLoadObsResultsByDate(obsDate, arrayOfObs) { - var results = []; - _.each(arrayOfObs, function (obs) { - if ((obs.concept.uuid === 'a8982474-1350-11df-a1f1-0026b9348838' || isObsViralLoadError(obs)) && - _areDatesEqual(obsDate, obs.obsDatetime)) { - results.push(obs); - } - }); - return results; + var results = []; + _.each(arrayOfObs, function (obs) { + if ( + (obs.concept.uuid === 'a8982474-1350-11df-a1f1-0026b9348838' || + isObsViralLoadError(obs)) && + _areDatesEqual(obsDate, obs.obsDatetime) + ) { + results.push(obs); + } + }); + return results; } -function findMissingEidResults(arrayOfEidResult, arrayOfObs, comparisonFunction) { - var missingEid = []; - - for (var i = 0; i < arrayOfEidResult.length; i++) { - if (findEquivalentObject(arrayOfEidResult[i], arrayOfObs, comparisonFunction) === null) { - missingEid.push(arrayOfEidResult[i]); - } +function findMissingEidResults( + arrayOfEidResult, + arrayOfObs, + comparisonFunction +) { + var missingEid = []; + + for (var i = 0; i < arrayOfEidResult.length; i++) { + if ( + findEquivalentObject( + arrayOfEidResult[i], + arrayOfObs, + comparisonFunction + ) === null + ) { + missingEid.push(arrayOfEidResult[i]); } - return missingEid; + } + return missingEid; } function findEquivalentObject(obj, searchSpaceArray, comparisonFunction) { - for (var i = 0; i < searchSpaceArray.length; i++) { - if (comparisonFunction(obj, searchSpaceArray[i])) { - return searchSpaceArray[i]; - } + for (var i = 0; i < searchSpaceArray.length; i++) { + if (comparisonFunction(obj, searchSpaceArray[i])) { + return searchSpaceArray[i]; } - return null; + } + return null; } function mergeEidResults(arrayOfEidResults) { - var results = { - viralLoad: [], - pcr: [], - cd4Panel: [] - }; - if (_.isEmpty(arrayOfEidResults)) return results; - _.each(arrayOfEidResults, function (result) { - results.viralLoad = results.viralLoad.concat(result.viralLoad); - results.pcr = results.pcr.concat(result.pcr); - results.cd4Panel = results.cd4Panel.concat(result.cd4Panel); - }); - - return results; + var results = { + viralLoad: [], + pcr: [], + cd4Panel: [] + }; + if (_.isEmpty(arrayOfEidResults)) return results; + _.each(arrayOfEidResults, function (result) { + results.viralLoad = results.viralLoad.concat(result.viralLoad); + results.pcr = results.pcr.concat(result.pcr); + results.cd4Panel = results.cd4Panel.concat(result.cd4Panel); + }); + + return results; } - function isViralLoadEquivalent(eidViralLoad, amrsViralLoadObs) { - if (!isEidViralLoadError(eidViralLoad)) { - if (conceptDateComparer(eidViralLoad, amrsViralLoadObs, - 'a8982474-1350-11df-a1f1-0026b9348838')) { - return areViralLoadValuesEquivalent(eidViralLoad, amrsViralLoadObs); - } else { - return false; - } + if (!isEidViralLoadError(eidViralLoad)) { + if ( + conceptDateComparer( + eidViralLoad, + amrsViralLoadObs, + 'a8982474-1350-11df-a1f1-0026b9348838' + ) + ) { + return areViralLoadValuesEquivalent(eidViralLoad, amrsViralLoadObs); + } else { + return false; } + } - //the eid result is an error at this point - if (!isObsViralLoadError(amrsViralLoadObs)) - return false; + //the eid result is an error at this point + if (!isObsViralLoadError(amrsViralLoadObs)) return false; - //at this point the amrs obs is a viral load error - return _areDatesEqual(eidViralLoad.DateCollected, amrsViralLoadObs.obsDatetime); + //at this point the amrs obs is a viral load error + return _areDatesEqual( + eidViralLoad.DateCollected, + amrsViralLoadObs.obsDatetime + ); } function areViralLoadValuesEquivalent(eidViralLoad, amrsViralLoadObs) { - - if (_hasNumbersOnly(eidViralLoad.FinalResult) && - _hasNumbersOnly(amrsViralLoadObs.value + '')) { - return parseInt(eidViralLoad.FinalResult) === amrsViralLoadObs.value; - } - - if ((_hasLessThanSymbol(eidViralLoad.FinalResult) || - eidViralLoad.FinalResult === 'Target Not Detected') && - _hasNumbersOnly(amrsViralLoadObs.value + '')) { - return amrsViralLoadObs.value === 0; - } - - return false; + if ( + _hasNumbersOnly(eidViralLoad.FinalResult) && + _hasNumbersOnly(amrsViralLoadObs.value + '') + ) { + return parseInt(eidViralLoad.FinalResult) === amrsViralLoadObs.value; + } + + if ( + (_hasLessThanSymbol(eidViralLoad.FinalResult) || + eidViralLoad.FinalResult === 'Target Not Detected') && + _hasNumbersOnly(amrsViralLoadObs.value + '') + ) { + return amrsViralLoadObs.value === 0; + } + + return false; } function isDnaPcrEquivalent(eidDnaPcr, amrsEidPcrObs) { - return conceptDateComparer(eidDnaPcr, amrsEidPcrObs, - 'a898fe80-1350-11df-a1f1-0026b9348838'); + return conceptDateComparer( + eidDnaPcr, + amrsEidPcrObs, + 'a898fe80-1350-11df-a1f1-0026b9348838' + ); } - function isCd4PanelEquivalent(eidCd4Panel, amrsCd4PanelObs) { - if (!isEidCD4PanelError(eidCd4Panel)) - return conceptDateComparer(eidCd4Panel, amrsCd4PanelObs, - 'a896cce6-1350-11df-a1f1-0026b9348838'); - - //the eid result is an error at this point - if (!isObsCd4PanelError(amrsCd4PanelObs)) - return false; - - //at this point the amrs obs is a cd4 load error - return _areDatesEqual(eidCd4Panel.DateCollected, amrsCd4PanelObs.obsDatetime); + if (!isEidCD4PanelError(eidCd4Panel)) + return conceptDateComparer( + eidCd4Panel, + amrsCd4PanelObs, + 'a896cce6-1350-11df-a1f1-0026b9348838' + ); + + //the eid result is an error at this point + if (!isObsCd4PanelError(amrsCd4PanelObs)) return false; + + //at this point the amrs obs is a cd4 load error + return _areDatesEqual(eidCd4Panel.DateCollected, amrsCd4PanelObs.obsDatetime); } function conceptDateComparer(eidResult, amrsObs, conceptUuid) { + if (!(eidResult && amrsObs)) { + return false; + } - if (!(eidResult && amrsObs)) { - return false; - } - - //check Obs for result concept - if (!(amrsObs.concept && - amrsObs.concept.uuid === conceptUuid)) { - return false; - } - + //check Obs for result concept + if (!(amrsObs.concept && amrsObs.concept.uuid === conceptUuid)) { + return false; + } - //check for dates equality - if (!_areDatesEqual(eidResult.DateCollected, amrsObs.obsDatetime)) { - return false; - } + //check for dates equality + if (!_areDatesEqual(eidResult.DateCollected, amrsObs.obsDatetime)) { + return false; + } - return true; + return true; } function _areDatesEqual(date1, date2) { + var d1 = null; + var d2 = null; - var d1 = null; - var d2 = null; + try { + d1 = new Date(date1); + d2 = new Date(date2); + d1 = new moment(d1); + d2 = new moment(d2); + } catch (e) {} - try { - d1 = new Date(date1); - d2 = new Date(date2); - d1 = new moment(d1); - d2 = new moment(d2); - } catch (e) { } - - return d1.isSame(d2, 'day'); + return d1.isSame(d2, 'day'); } function isEidViralLoadError(eidViralLoadResult) { - var isError = false; - if (_.isEmpty(eidViralLoadResult)) return false; - var viralLoadResult = eidViralLoadResult.FinalResult; - if (!_hasNumbersOnly(viralLoadResult) && + var isError = false; + if (_.isEmpty(eidViralLoadResult)) return false; + var viralLoadResult = eidViralLoadResult.FinalResult; + if ( + !_hasNumbersOnly(viralLoadResult) && !_hasLessThanSymbol(viralLoadResult) && - (viralLoadResult.trim() === 'Target Not Detected') === false) { - isError = true; - } - // console.log('Checking Values:::::::', eidViralLoadResult.FinalResult, isError); - return isError; + (viralLoadResult.trim() === 'Target Not Detected') === false + ) { + isError = true; + } + // console.log('Checking Values:::::::', eidViralLoadResult.FinalResult, isError); + return isError; } function _hasNumbersOnly(stringValue) { - var trimmedValue = _removeWhiteSpace(stringValue); - var hasNumbersOnly = /^[0-9]*(?:\.\d{1,2})?$/; - return hasNumbersOnly.test(trimmedValue) + var trimmedValue = _removeWhiteSpace(stringValue); + var hasNumbersOnly = /^[0-9]*(?:\.\d{1,2})?$/; + return hasNumbersOnly.test(trimmedValue); } function _hasLessThanSymbol(stringValue) { - var trimmedValue = _removeWhiteSpace(stringValue); - var hasLessThanSymbol = / 0) { - hasErrors = true; - } - - return hasErrors; + var hasErrors = false; + var exceptions = []; + var hasNumbersOnly = /^[0-9]*(?:\.\d{1,2})?$/; + var hasLessThanSymbol = / 0) { + hasErrors = true; + } + + return hasErrors; } function isObsViralLoadError(obs) { - if (_.isEmpty(obs) || _.isEmpty(obs.concept)) return false; + if (_.isEmpty(obs) || _.isEmpty(obs.concept)) return false; - if (obs.concept.uuid !== '457c741d-8f71-4829-b59d-594e0a618892') return false; + if (obs.concept.uuid !== '457c741d-8f71-4829-b59d-594e0a618892') return false; - if (obs.groupMembers.length <= 0) return false; + if (obs.groupMembers.length <= 0) return false; - var foundObs = _getObsObjectWithValue(obs.groupMembers, 'a8982474-1350-11df-a1f1-0026b9348838'); - if (foundObs === undefined) - return false; + var foundObs = _getObsObjectWithValue( + obs.groupMembers, + 'a8982474-1350-11df-a1f1-0026b9348838' + ); + if (foundObs === undefined) return false; - return true; + return true; } function isObsCd4PanelError(obs) { - if (_.isEmpty(obs) || _.isEmpty(obs.concept)) return false; - - if (obs.concept.uuid !== '457c741d-8f71-4829-b59d-594e0a618892') return false; - - if (obs.groupMembers.length <= 0) return false; - - var cd4PanelTestConcepts = [ - 'a89c4220-1350-11df-a1f1-0026b9348838', - 'a898fcd2-1350-11df-a1f1-0026b9348838', - 'a8970a26-1350-11df-a1f1-0026b9348838', - 'a8a8bb18-1350-11df-a1f1-0026b9348838', - 'a89c4914-1350-11df-a1f1-0026b9348838' - ]; - var foundObs = - _getObsObjectWithAnyOfValueArray(obs.groupMembers, cd4PanelTestConcepts); - if (foundObs === undefined) - return false; - - return true + if (_.isEmpty(obs) || _.isEmpty(obs.concept)) return false; + + if (obs.concept.uuid !== '457c741d-8f71-4829-b59d-594e0a618892') return false; + + if (obs.groupMembers.length <= 0) return false; + + var cd4PanelTestConcepts = [ + 'a89c4220-1350-11df-a1f1-0026b9348838', + 'a898fcd2-1350-11df-a1f1-0026b9348838', + 'a8970a26-1350-11df-a1f1-0026b9348838', + 'a8a8bb18-1350-11df-a1f1-0026b9348838', + 'a89c4914-1350-11df-a1f1-0026b9348838' + ]; + var foundObs = _getObsObjectWithAnyOfValueArray( + obs.groupMembers, + cd4PanelTestConcepts + ); + if (foundObs === undefined) return false; + + return true; } function _getObsObjectWithValue(obsArray, value) { - if (!Array.isArray(obsArray)) return; - - for (var i = 0; i < obsArray.length; i++) { - if (obsArray[i].value && obsArray[i].value.uuid && obsArray[i].value.uuid === value) return obsArray[i]; - } + if (!Array.isArray(obsArray)) return; + + for (var i = 0; i < obsArray.length; i++) { + if ( + obsArray[i].value && + obsArray[i].value.uuid && + obsArray[i].value.uuid === value + ) + return obsArray[i]; + } } function _getObsObjectWithAnyOfValueArray(obsArray, valuesArray) { - if (!Array.isArray(obsArray)) return; - - for (var i = 0; i < obsArray.length; i++) { - if (obsArray[i].value && obsArray[i].value.uuid && valuesArray.indexOf(obsArray[i].value.uuid) >= 0) return obsArray[i]; - - if (valuesArray.indexOf(obsArray[i].value) >= 0) return obsArray[i]; - } + if (!Array.isArray(obsArray)) return; + + for (var i = 0; i < obsArray.length; i++) { + if ( + obsArray[i].value && + obsArray[i].value.uuid && + valuesArray.indexOf(obsArray[i].value.uuid) >= 0 + ) + return obsArray[i]; + + if (valuesArray.indexOf(obsArray[i].value) >= 0) return obsArray[i]; + } } function _removeWhiteSpace(string) { - return string === null || string === undefined || typeof string !== 'string' ? '' : string.replace(/\s+/g, ''); + return string === null || string === undefined || typeof string !== 'string' + ? '' + : string.replace(/\s+/g, ''); } diff --git a/eid-rest-formatter.js b/eid-rest-formatter.js index 43a154169..3966abc81 100755 --- a/eid-rest-formatter.js +++ b/eid-rest-formatter.js @@ -4,7 +4,7 @@ var Promise = require('bluebird'); var config = require('./conf/config'); var rp = require('./request-config'); var _ = require('underscore'); -module.exports = function () { +module.exports = (function () { function getRestResource(path) { var link = config.openmrs.host + ':' + config.openmrs.port + path; if (config.openmrs.https === true) { @@ -16,13 +16,12 @@ module.exports = function () { } function removeWhiteSpace(string) { var whitePaceVar; - if(string === '' || string === null){ - whitePaceVar = ''; - }else{ - whitePaceVar = string.replace(/\s+/g, ''); + if (string === '' || string === null) { + whitePaceVar = ''; + } else { + whitePaceVar = string.replace(/\s+/g, ''); } return whitePaceVar; - } function checkStatusOfViralLoad(viralLoadPayload) { var status = 0; @@ -31,18 +30,18 @@ module.exports = function () { if (_.isEmpty(viralLoadPayload)) return -1; var viralLoadResult = removeWhiteSpace(viralLoadPayload.FinalResult); - if (_.isEmpty(viralLoadResult)) { return -1; } if (hasNumbersOnly.test(viralLoadResult)) { status = 1; - } - else if (hasLessThanSymbol.test(viralLoadResult) || viralLoadPayload.FinalResult.trim()==='Target Not Detected') { + } else if ( + hasLessThanSymbol.test(viralLoadResult) || + viralLoadPayload.FinalResult.trim() === 'Target Not Detected' + ) { status = 0; - } - else { + } else { status = 2; } // console.log('ASSESSING EID RESULT ',status, viralLoadResult); @@ -53,7 +52,10 @@ module.exports = function () { var hasNumbersOnly = /^[0-9]*(?:\.\d{1,2})?$/; var hasLessThanSymbol = / 0) { _.each(AVGCD3percentLymph, function (groupMember) { body.groupMembers.push(groupMember); }); } - var AVGCD3AbsCnt = cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, "AVGCD3AbsCnt", "a898fcd2-1350-11df-a1f1-0026b9348838", date); + var AVGCD3AbsCnt = cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + 'AVGCD3AbsCnt', + 'a898fcd2-1350-11df-a1f1-0026b9348838', + date + ); if (AVGCD3AbsCnt.length > 0) { _.each(AVGCD3AbsCnt, function (groupMember) { body.groupMembers.push(groupMember); }); } - var AVGCD3CD4percentLymph = cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, "AVGCD3CD4percentLymph", "a8970a26-1350-11df-a1f1-0026b9348838", date); + var AVGCD3CD4percentLymph = cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + 'AVGCD3CD4percentLymph', + 'a8970a26-1350-11df-a1f1-0026b9348838', + date + ); if (AVGCD3CD4percentLymph.length > 0) { _.each(AVGCD3CD4percentLymph, function (groupMember) { body.groupMembers.push(groupMember); }); } - var AVGCD3CD4AbsCnt = cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, "AVGCD3CD4AbsCnt", "a8a8bb18-1350-11df-a1f1-0026b9348838", date); + var AVGCD3CD4AbsCnt = cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + 'AVGCD3CD4AbsCnt', + 'a8a8bb18-1350-11df-a1f1-0026b9348838', + date + ); if (AVGCD3CD4AbsCnt.length > 0) { _.each(AVGCD3CD4AbsCnt, function (groupMember) { body.groupMembers.push(groupMember); }); } - var CD45AbsCnt = cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, "CD45AbsCnt", "a89c4914-1350-11df-a1f1-0026b9348838", date); + var CD45AbsCnt = cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + 'CD45AbsCnt', + 'a89c4914-1350-11df-a1f1-0026b9348838', + date + ); if (CD45AbsCnt.length > 0) { _.each(CD45AbsCnt, function (groupMember) { body.groupMembers.push(groupMember); @@ -381,23 +450,38 @@ module.exports = function () { return new Promise(function (resolve, reject) { resolve(body); }); - } - function cd4ExceptionGroupMemberGenerator(patientUuId, CD4payload, typeOfTest, labTestConcept, date) { + function cd4ExceptionGroupMemberGenerator( + patientUuId, + CD4payload, + typeOfTest, + labTestConcept, + date + ) { var groupMembers = []; var labExceptions = getLabExceptions(); if (typeOfTest in CD4payload) { if (CD4payload[typeOfTest].toUpperCase() in labExceptions) { - var codedConceptValue = labExceptions[CD4payload[typeOfTest].toUpperCase()]; - var codedPayload = generateCodedPayload(patientUuId, labTestConcept, codedConceptValue, date); + var codedConceptValue = + labExceptions[CD4payload[typeOfTest].toUpperCase()]; + var codedPayload = generateCodedPayload( + patientUuId, + labTestConcept, + codedConceptValue, + date + ); _.each(codedPayload.groupMembers, function (groupMember) { groupMembers.push(groupMember); }); - } - else { + } else { var value = CD4payload[typeOfTest]; - var nonCodedPayload = generateNonCodedPayload(patientUuId, labTestConcept, value, date); + var nonCodedPayload = generateNonCodedPayload( + patientUuId, + labTestConcept, + value, + date + ); _.each(nonCodedPayload.groupMembers, function (groupMember) { groupMembers.push(groupMember); }); @@ -408,19 +492,22 @@ module.exports = function () { function convertDNAPCRPayloadTORestConsumableObs(DNAPCRPayload, patientUuId) { var body = { - concept: "a898fe80-1350-11df-a1f1-0026b9348838", + concept: 'a898fe80-1350-11df-a1f1-0026b9348838', person: patientUuId }; var date = moment(DNAPCRPayload.DateCollected).format(); body.obsDatetime = date; console.error('DNA PCR DNAPCRPayload.FinalResult is null'); - if (DNAPCRPayload.FinalResult !== null && - DNAPCRPayload.FinalResult.toUpperCase() == "NEGATIVE") { - body.value = "a896d2cc-1350-11df-a1f1-0026b9348838"; - } - else if (DNAPCRPayload.FinalResult !== null && - DNAPCRPayload.FinalResult.toUpperCase() == "POSITIVE") { - body.value = "a896f3a6-1350-11df-a1f1-0026b9348838"; + if ( + DNAPCRPayload.FinalResult !== null && + DNAPCRPayload.FinalResult.toUpperCase() == 'NEGATIVE' + ) { + body.value = 'a896d2cc-1350-11df-a1f1-0026b9348838'; + } else if ( + DNAPCRPayload.FinalResult !== null && + DNAPCRPayload.FinalResult.toUpperCase() == 'POSITIVE' + ) { + body.value = 'a896f3a6-1350-11df-a1f1-0026b9348838'; } if (DNAPCRPayload['OrderNo'] && stringNotEmpty(DNAPCRPayload['OrderNo'])) { @@ -430,7 +517,6 @@ module.exports = function () { return new Promise(function (resolve, reject) { resolve(body); }); - } function attachOrderUuid(obsPayload, orderNo) { @@ -456,54 +542,58 @@ module.exports = function () { function getLabExceptions() { return { - "POOR SAMPLE QUALITY": "a89c3f1e-1350-11df-a1f1-0026b9348838", - "NOT DONE": "a899ea48-1350-11df-a1f1-0026b9348838", - "INDETERMINATE": "a89a7ae4-1350-11df-a1f1-0026b9348838", - "BELOW DETECTABLE LIMIT": "a89c3f1e-1350-11df-a1f1-0026b9348838", - "UNABLE TO COLLECT SAMPLE": "a8afcec6-1350-11df-a1f1-0026b9348838", - "SPECIMEN NOT RECEIVED": "0271c15e-4f7f-4a18-9b45-2d7e5b6f7057", - "ORDERED FOR WRONG PATIENT": "3366412a-e279-4428-a671-37221804c6e6" - } + 'POOR SAMPLE QUALITY': 'a89c3f1e-1350-11df-a1f1-0026b9348838', + 'NOT DONE': 'a899ea48-1350-11df-a1f1-0026b9348838', + INDETERMINATE: 'a89a7ae4-1350-11df-a1f1-0026b9348838', + 'BELOW DETECTABLE LIMIT': 'a89c3f1e-1350-11df-a1f1-0026b9348838', + 'UNABLE TO COLLECT SAMPLE': 'a8afcec6-1350-11df-a1f1-0026b9348838', + 'SPECIMEN NOT RECEIVED': '0271c15e-4f7f-4a18-9b45-2d7e5b6f7057', + 'ORDERED FOR WRONG PATIENT': '3366412a-e279-4428-a671-37221804c6e6' + }; } - function generateCodedPayload(patientUuId, labTestConcept, codedConceptValue, date) { + function generateCodedPayload( + patientUuId, + labTestConcept, + codedConceptValue, + date + ) { var payload = { - concept: "457c741d-8f71-4829-b59d-594e0a618892", + concept: '457c741d-8f71-4829-b59d-594e0a618892', groupMembers: [ { - concept: "f67ff075-f91e-4b71-897a-9ded87b34984", + concept: 'f67ff075-f91e-4b71-897a-9ded87b34984', person: patientUuId, value: labTestConcept, obsDatetime: date }, { - concept: "5026a3ee-0612-48bf-b9a3-a2944ddc3e04", + concept: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04', person: patientUuId, value: codedConceptValue, obsDatetime: date } ] - } + }; return payload; } function generateNonCodedPayload(patientUuId, labTestConcept, value, date) { var payload = { - concept: "457c741d-8f71-4829-b59d-594e0a618892", + concept: '457c741d-8f71-4829-b59d-594e0a618892', groupMembers: [ { - concept: "f67ff075-f91e-4b71-897a-9ded87b34984", + concept: 'f67ff075-f91e-4b71-897a-9ded87b34984', person: patientUuId, value: labTestConcept, obsDatetime: date }, { - concept: "a8a06fc6-1350-11df-a1f1-0026b9348838", + concept: 'a8a06fc6-1350-11df-a1f1-0026b9348838', person: patientUuId, value: value, obsDatetime: date } - ] - } + }; return payload; } function generateCD4PanelSingleObject(patientUuId, conceptUuId, value, date) { @@ -512,14 +602,16 @@ module.exports = function () { person: patientUuId, value: value, obsDatetime: date - } + }; return payload; } function getOrderByOrderNumber(orderNo) { - var uri = getRestResource('/'+ config.openmrs.applicationName + '/ws/rest/v1/order/' + orderNo); + var uri = getRestResource( + '/' + config.openmrs.applicationName + '/ws/rest/v1/order/' + orderNo + ); var queryString = { v: 'full' - } + }; return new Promise(function (resolve, reject) { rp.getRequestPromise(queryString, uri) .then(function (response) { @@ -527,7 +619,7 @@ module.exports = function () { }) .catch(function (error) { reject(error); - }) + }); }); } return { @@ -550,5 +642,5 @@ module.exports = function () { cd4PanelHasErrors: cd4PanelHasErrors, generateCd4Exceptions: generateCd4Exceptions, generateCd4ValidData: generateCd4ValidData - } -}(); + }; +})(); diff --git a/elastic/elastic.access.js b/elastic/elastic.access.js index 3489b483e..d168e2c61 100755 --- a/elastic/elastic.access.js +++ b/elastic/elastic.access.js @@ -1,257 +1,320 @@ -module.exports = (function(){ - 'use strict'; - var careQueries = require('./queries/care.treatment.query.js'); - var _ = require('lodash'); - var elastic = require('elasticsearch'); - - var eClient = new elastic.Client({ - host: 'https://etl.ampath.or.ke/elastic', - log: 'debug' - }); - - function getEnrolledInCare(params, callback, eCallback) { - var query = careQueries.enrolledInCareQuery(params); - console.log(JSON.stringify(query)); - eClient.search(query).then(function(data) { - var count = data.aggregations.enrolled.buckets.length; - if(typeof callback === 'function') { - callback(count); - } - }, function(err) { - console.trace(err.message) - if(typeof eCallback === 'function') { - eCallback(err); - } - }); - } - - function getEnrolledInCareMOh(params, callback) { - // Below 1 year - var params = params || {}; - params.upperAgeLimit = 1; - - var query = careQueries.enrolledInCareQuery(params); - console.log('getEnrolledInCareMOh: below 1 query: ', JSON.stringify(query)); - var below1; - eClient.search(query).then(function(data) { - below1 = data.aggregations.enrolled.buckets.length; - //Below 15 years Male - params.upperAgeLimit = 14; - params.gender = 'M'; +module.exports = (function () { + 'use strict'; + var careQueries = require('./queries/care.treatment.query.js'); + var _ = require('lodash'); + var elastic = require('elasticsearch'); + + var eClient = new elastic.Client({ + host: 'https://etl.ampath.or.ke/elastic', + log: 'debug' + }); + + function getEnrolledInCare(params, callback, eCallback) { + var query = careQueries.enrolledInCareQuery(params); + console.log(JSON.stringify(query)); + eClient.search(query).then( + function (data) { + var count = data.aggregations.enrolled.buckets.length; + if (typeof callback === 'function') { + callback(count); + } + }, + function (err) { + console.trace(err.message); + if (typeof eCallback === 'function') { + eCallback(err); + } + } + ); + } + + function getEnrolledInCareMOh(params, callback) { + // Below 1 year + var params = params || {}; + params.upperAgeLimit = 1; + + var query = careQueries.enrolledInCareQuery(params); + console.log('getEnrolledInCareMOh: below 1 query: ', JSON.stringify(query)); + var below1; + eClient.search(query).then(function (data) { + below1 = data.aggregations.enrolled.buckets.length; + //Below 15 years Male + params.upperAgeLimit = 14; + params.gender = 'M'; + query = careQueries.enrolledInCareQuery(params); + console.log( + 'getEnrolledInCareMOh: below 15 (female) query: ', + JSON.stringify(query) + ); + var below15Male; + eClient.search(query).then(function (data) { + below15Male = data.aggregations.enrolled.buckets.length; + + //Below 15 years Female + params = params || {}; + params.upperAgeLimit = 14; + params.gender = 'F'; + query = careQueries.enrolledInCareQuery(params); + console.log( + 'getEnrolledInCareMOh: below 15 (female) query: ', + JSON.stringify(query) + ); + eClient.search(query).then(function (data) { + var below15Female = data.aggregations.enrolled.buckets.length; + delete params.upperAgeLimit; + // 15 years and above Male + params = params || {}; + params.lowerAgeLimit = 14; + params.gender = 'M'; + console.log('params: ', params, 'params object', params); + query = careQueries.enrolledInCareQuery(params); + console.log( + 'getEnrolledInCareMOh: 15 and above (Male) query: ', + JSON.stringify(query) + ); + eClient.search(query).then(function (data) { + var above15Male = data.aggregations.enrolled.buckets.length; + + // 15 years and above Female + params = params || {}; + params.lowerAgeLimit = 14; + params.gender = 'F'; query = careQueries.enrolledInCareQuery(params); - console.log('getEnrolledInCareMOh: below 15 (female) query: ', - JSON.stringify(query)); - var below15Male; - eClient.search(query).then(function(data) { - below15Male = data.aggregations.enrolled.buckets.length; - - //Below 15 years Female - params = params || {}; - params.upperAgeLimit = 14; - params.gender = 'F'; - query = careQueries.enrolledInCareQuery(params); - console.log('getEnrolledInCareMOh: below 15 (female) query: ', - JSON.stringify(query)); - eClient.search(query).then(function(data) { - var below15Female = data.aggregations.enrolled.buckets.length; - delete params.upperAgeLimit; - // 15 years and above Male - params = params || {}; - params.lowerAgeLimit = 14; - params.gender = 'M'; - console.log('params: ',params, 'params object', params); - query = careQueries.enrolledInCareQuery(params); - console.log('getEnrolledInCareMOh: 15 and above (Male) query: ', JSON.stringify(query)); - eClient.search(query).then(function(data) { - var above15Male = data.aggregations.enrolled.buckets.length; - - // 15 years and above Female - params = params || {}; - params.lowerAgeLimit = 14; - params.gender = 'F'; - query = careQueries.enrolledInCareQuery(params); - console.log('getEnrolledInCareMOh: 15 and above (Female) query: ', JSON.stringify(query)); - eClient.search(query).then(function(data) { - var above15Female = data.aggregations.enrolled.buckets.length; - var total = below15Male + below15Female + above15Female + above15Male; - var response = { - indicator: 'enrolled in care', - total: total, - 'below1': below1, - 'below15': { - male: below15Male, - female: below15Female - }, - 'above15': { - male: above15Male, - female: above15Female - } - }; - - if(params.location) { - response.location = params.location; - } - - if(typeof callback === 'function'){ - callback(response); - } - }); - }); - }); + console.log( + 'getEnrolledInCareMOh: 15 and above (Female) query: ', + JSON.stringify(query) + ); + eClient.search(query).then(function (data) { + var above15Female = data.aggregations.enrolled.buckets.length; + var total = + below15Male + below15Female + above15Female + above15Male; + var response = { + indicator: 'enrolled in care', + total: total, + below1: below1, + below15: { + male: below15Male, + female: below15Female + }, + above15: { + male: above15Male, + female: above15Female + } + }; + + if (params.location) { + response.location = params.location; + } + + if (typeof callback === 'function') { + callback(response); + } }); + }); }); - } - - function getActiveInCareMoh(params, callback, eCallback) { - // Below 1 year - var params = params || {}; - params.upperAgeLimit = 1; - - var query = careQueries.activeInCareQuery(params); - console.log('getActiveInCareMoh: below 1 query: ', JSON.stringify(query)); - eClient.search(query).then(function(data) { + }); + }); + } + + function getActiveInCareMoh(params, callback, eCallback) { + // Below 1 year + var params = params || {}; + params.upperAgeLimit = 1; + + var query = careQueries.activeInCareQuery(params); + console.log('getActiveInCareMoh: below 1 query: ', JSON.stringify(query)); + eClient.search(query).then(function (data) { + var buckets = data.aggregations.active.patients.buckets; + var below1Patients = _getPatients(buckets); + //Get transfer outs. + if (params.endDate) { + var d = new Date(params.endDate); + d.setMonth(d.getMonth() - 3); + params.startDate = d; + } + + var below1; + _getActiveInCarePatientsCount( + params, + below1Patients, + function (data) { + below1 = data; + }, + 'getActiveInCareMoh: below1 tranferout query: ' + ); + // var q = careQueries.transferOutQuery(params); + // console.log('getActiveInCareMoh: below1 tranferout query: ', JSON.stringify(query)); + // eClient.search(q).then(function(data) { + // var outBuckets = data.aggregations.transferOut.patients.buckets; + // var below1transferOuts = _getPatients(outBuckets); + // + // //eliminate transfer out. + // var below1Count = _.difference(below1Patients, below1transferOuts).length; + // }) + //Below 15 years Male + params.upperAgeLimit = 14; + params.gender = 'M'; + query = careQueries.activeInCareQuery(params); + console.log( + 'getActiveInCareMoh: below 15 (female) query: ', + JSON.stringify(query) + ); + eClient.search(query).then(function (data) { + var buckets = data.aggregations.active.patients.buckets; + var below15Patients = _getPatients(buckets); + + //Get the transferOut + var below15Male; + _getActiveInCarePatientsCount( + params, + below15Patients, + function (data) { + below15Male = data; + }, + 'getActiveInCareMoh: below15 Male tranferout query: ' + ); + + //Below 15 years Female + params = params || {}; + params.upperAgeLimit = 14; + params.gender = 'F'; + query = careQueries.activeInCareQuery(params); + console.log( + 'getActiveInCareMoh: below 15 (female) query: ', + JSON.stringify(query) + ); + eClient.search(query).then(function (data) { + var buckets = data.aggregations.active.patients.buckets; + var below15FemalePatients = _getPatients(buckets); + delete params.upperAgeLimit; + + //eliminate transfer out + var below15Female; + _getActiveInCarePatientsCount( + params, + below15FemalePatients, + function (data) { + below15Female = data; + }, + 'getActiveInCareMoh: below15 feMale tranferout query: ' + ); + // 15 years and above Male + params = params || {}; + params.lowerAgeLimit = 14; + params.gender = 'M'; + console.log('params: ', params, 'params object', params); + query = careQueries.activeInCareQuery(params); + console.log( + 'getActiveInCareMoh: 15 and above (Male) query: ', + JSON.stringify(query) + ); + eClient.search(query).then(function (data) { var buckets = data.aggregations.active.patients.buckets; - var below1Patients = _getPatients(buckets); - //Get transfer outs. - if(params.endDate) { - var d = new Date(params.endDate); - d.setMonth(d.getMonth() - 3); - params.startDate = d; - } - - var below1; - _getActiveInCarePatientsCount(params, below1Patients, function(data) { - below1 = data; - }, 'getActiveInCareMoh: below1 tranferout query: '); - // var q = careQueries.transferOutQuery(params); - // console.log('getActiveInCareMoh: below1 tranferout query: ', JSON.stringify(query)); - // eClient.search(q).then(function(data) { - // var outBuckets = data.aggregations.transferOut.patients.buckets; - // var below1transferOuts = _getPatients(outBuckets); - // - // //eliminate transfer out. - // var below1Count = _.difference(below1Patients, below1transferOuts).length; - // }) - //Below 15 years Male - params.upperAgeLimit = 14; - params.gender = 'M'; + var above15MalePatients = _getPatients(buckets); + + // Eliminate transfer outs + var above15Male; + _getActiveInCarePatientsCount( + params, + above15MalePatients, + function (data) { + above15Male = data; + }, + 'getActiveInCareMoh: Above 15 Male tranferout query: ' + ); + + // 15 years and above Female + params = params || {}; + params.lowerAgeLimit = 14; + params.gender = 'F'; query = careQueries.activeInCareQuery(params); - console.log('getActiveInCareMoh: below 15 (female) query: ', - JSON.stringify(query)); - eClient.search(query).then(function(data) { - var buckets = data.aggregations.active.patients.buckets; - var below15Patients = _getPatients(buckets); - - //Get the transferOut - var below15Male; - _getActiveInCarePatientsCount(params, below15Patients, function(data) { - below15Male = data; - }, 'getActiveInCareMoh: below15 Male tranferout query: '); - - //Below 15 years Female - params = params || {}; - params.upperAgeLimit = 14; - params.gender = 'F'; - query = careQueries.activeInCareQuery(params); - console.log('getActiveInCareMoh: below 15 (female) query: ', - JSON.stringify(query)); - eClient.search(query).then(function(data) { - var buckets = data.aggregations.active.patients.buckets; - var below15FemalePatients = _getPatients(buckets); - delete params.upperAgeLimit; - - //eliminate transfer out - var below15Female; - _getActiveInCarePatientsCount(params, below15FemalePatients, function(data) { - below15Female = data; - }, 'getActiveInCareMoh: below15 feMale tranferout query: '); - // 15 years and above Male - params = params || {}; - params.lowerAgeLimit = 14; - params.gender = 'M'; - console.log('params: ',params, 'params object', params); - query = careQueries.activeInCareQuery(params); - console.log('getActiveInCareMoh: 15 and above (Male) query: ', JSON.stringify(query)); - eClient.search(query).then(function(data) { - var buckets = data.aggregations.active.patients.buckets; - var above15MalePatients = _getPatients(buckets); - - // Eliminate transfer outs - var above15Male; - _getActiveInCarePatientsCount(params, above15MalePatients, function(data) { - above15Male = data; - }, 'getActiveInCareMoh: Above 15 Male tranferout query: '); - - // 15 years and above Female - params = params || {}; - params.lowerAgeLimit = 14; - params.gender = 'F'; - query = careQueries.activeInCareQuery(params); - console.log('getActiveInCareMoh: 15 and above (Female) query: ', JSON.stringify(query)); - eClient.search(query).then(function(data) { - var buckets = data.aggregations.active.patients.buckets; - var above15FemalePatients = _getPatients(buckets); - - // Eliminate transfer outs - var above15Female; - _getActiveInCarePatientsCount(params, above15FemalePatients, function(data) { - above15Female = data; - - console.log('below15Male: ',below15Male, ', below15Female: ', below15Female, - ', above15Female: ', above15Female, 'above15Male:', above15Male); - var total = below15Male + below15Female + above15Female + above15Male; - var response = { - indicator: 'active in care', - total: total, - 'below1': below1, - 'below15': { - male: below15Male, - female: below15Female - }, - 'above15': { - male: above15Male, - female: above15Female - } - }; - - if(params.location) { - response.location = params.location; - } - - if(typeof callback === 'function'){ - callback(response); - } - }, 'getActiveInCareMoh: Above 15 feMale tranferout query: '); - }); - }); - }); + console.log( + 'getActiveInCareMoh: 15 and above (Female) query: ', + JSON.stringify(query) + ); + eClient.search(query).then(function (data) { + var buckets = data.aggregations.active.patients.buckets; + var above15FemalePatients = _getPatients(buckets); + + // Eliminate transfer outs + var above15Female; + _getActiveInCarePatientsCount( + params, + above15FemalePatients, + function (data) { + above15Female = data; + + console.log( + 'below15Male: ', + below15Male, + ', below15Female: ', + below15Female, + ', above15Female: ', + above15Female, + 'above15Male:', + above15Male + ); + var total = + below15Male + below15Female + above15Female + above15Male; + var response = { + indicator: 'active in care', + total: total, + below1: below1, + below15: { + male: below15Male, + female: below15Female + }, + above15: { + male: above15Male, + female: above15Female + } + }; + + if (params.location) { + response.location = params.location; + } + + if (typeof callback === 'function') { + callback(response); + } + }, + 'getActiveInCareMoh: Above 15 feMale tranferout query: ' + ); }); + }); }); - } - - function _getPatients(buckets) { - var array = []; - _.each(buckets, function(b) { - array.push(b.key); - }); - return array; - } - - function _getActiveInCarePatientsCount(params, patientsCount, callback, message) { - var q = careQueries.transferOutQuery(params); - console.log(message, JSON.stringify(q)); - eClient.search(q).then(function(data) { - var outBuckets = data.aggregations.transferOut.patients.buckets; - var transferOuts = _getPatients(outBuckets); - - //eliminate transfer out. - var count = _.difference(patientsCount, transferOuts).length; - callback(count); - }) - } - return { - getEnrolledInCare: getEnrolledInCare, - getEnrolledInCareMOh: getEnrolledInCareMOh, - getActiveInCareMoh: getActiveInCareMoh - } + }); + }); + } + + function _getPatients(buckets) { + var array = []; + _.each(buckets, function (b) { + array.push(b.key); + }); + return array; + } + + function _getActiveInCarePatientsCount( + params, + patientsCount, + callback, + message + ) { + var q = careQueries.transferOutQuery(params); + console.log(message, JSON.stringify(q)); + eClient.search(q).then(function (data) { + var outBuckets = data.aggregations.transferOut.patients.buckets; + var transferOuts = _getPatients(outBuckets); + + //eliminate transfer out. + var count = _.difference(patientsCount, transferOuts).length; + callback(count); + }); + } + return { + getEnrolledInCare: getEnrolledInCare, + getEnrolledInCareMOh: getEnrolledInCareMOh, + getActiveInCareMoh: getActiveInCareMoh + }; })(); diff --git a/elastic/queries/care.treatment.query.js b/elastic/queries/care.treatment.query.js index dee51c0aa..c1085b9f0 100755 --- a/elastic/queries/care.treatment.query.js +++ b/elastic/queries/care.treatment.query.js @@ -1,307 +1,320 @@ -module.exports = (function(){ - 'use strict'; - - // Create a query to fetch all documents with patients enrolled in care. - var ADULTINIT = 1; - var ADULTRET = 2; - var PEADINIT = 3; - var PEADRET = 4; - var index = 'amrs'; - var type = 'obs'; - - var _ = require('lodash'); - var ejs = require('elastic.js'); - var concepts = require('./concept.ids'); - - function _queryBuilder(params, encounterTypeArray) { - var conditions = []; - if(!_.isEmpty(params)) { - _handleVoidedCondition(params, conditions); - _handleAgeCondition(params, conditions); - _handleLocationCondition(params, conditions); - _handlePeriodCondition(params, conditions); - _handleGenderCondition(params, conditions); - } - - // console.log('Params +++', params); - var queryObj = { - index: params['index'] || index, - type: params['type'] || type - }; - - // basic mult-select query conditions - var encounterType = ejs.TermsQuery('encounter_type', encounterTypeArray); - - //create query - var _body = ejs.Request() - .size(0) - .query( - ejs.BoolQuery() - .must(encounterType) - .must(conditions) - ) - .agg( - ejs.TermsAggregation(params.aggsName) - .field('person_id') - .size(0) - ) - - queryObj.body = _body; - return queryObj; +module.exports = (function () { + 'use strict'; + + // Create a query to fetch all documents with patients enrolled in care. + var ADULTINIT = 1; + var ADULTRET = 2; + var PEADINIT = 3; + var PEADRET = 4; + var index = 'amrs'; + var type = 'obs'; + + var _ = require('lodash'); + var ejs = require('elastic.js'); + var concepts = require('./concept.ids'); + + function _queryBuilder(params, encounterTypeArray) { + var conditions = []; + if (!_.isEmpty(params)) { + _handleVoidedCondition(params, conditions); + _handleAgeCondition(params, conditions); + _handleLocationCondition(params, conditions); + _handlePeriodCondition(params, conditions); + _handleGenderCondition(params, conditions); } - - /** - * Function enrolledInCareQuery - * Possible params properties are - * 1. location (can be an array), - * 2. startDate, - * 3. endDate - * 4. lowerAgeLimit - * 5. upperAgeLimit - * 6. gender - * 7. index - * 8. type - * 9. voided (boolean) - * startDate & endDate define reporting period. - * lowerAgeLimit & upperAgeLimit define age group inclusively - * location currently expects ids. - */ - function enrolledInCareQuery(params){ - var params = params || {}; - params.aggsName = params.aggsName || 'enrolled'; - var queryObj = _queryBuilder(params, [ADULTINIT, PEADINIT]); - console.log('enrolledIncareQuery :', JSON.stringify(queryObj)); - - return queryObj; - } - - /** - * Function activeInCareQuery - * Possible params properties are - * 1. location (can be an array), - * 2. startDate, - * 3. endDate - * 4. lowerAgeLimit - * 5. upperAgeLimit - * 6. gender - * 7. index - * 8. type - * 9. voided - * startDate & endDate define reporting period. - * lowerAgeLimit & upperAgeLimit define age group inclusively - * location currently expects ids. - */ - function activeInCareQuery(params) { - var params = params || {}; - - //Prepare startDate and endDate - params.startDate = 'now-3m'; - if(params.endDate) { - params.startDate = params.endDate + '||-3M'; - } else { - params.endDate = 'now'; - } - - var queryObj = _queryBuilder(params, [ADULTINIT, ADULTRET, PEADINIT, PEADRET]); - console.log('activeIncareQuery :', JSON.stringify(queryObj)); - - return queryObj; + + // console.log('Params +++', params); + var queryObj = { + index: params['index'] || index, + type: params['type'] || type + }; + + // basic mult-select query conditions + var encounterType = ejs.TermsQuery('encounter_type', encounterTypeArray); + + //create query + var _body = ejs + .Request() + .size(0) + .query(ejs.BoolQuery().must(encounterType).must(conditions)) + .agg(ejs.TermsAggregation(params.aggsName).field('person_id').size(0)); + + queryObj.body = _body; + return queryObj; + } + + /** + * Function enrolledInCareQuery + * Possible params properties are + * 1. location (can be an array), + * 2. startDate, + * 3. endDate + * 4. lowerAgeLimit + * 5. upperAgeLimit + * 6. gender + * 7. index + * 8. type + * 9. voided (boolean) + * startDate & endDate define reporting period. + * lowerAgeLimit & upperAgeLimit define age group inclusively + * location currently expects ids. + */ + function enrolledInCareQuery(params) { + var params = params || {}; + params.aggsName = params.aggsName || 'enrolled'; + var queryObj = _queryBuilder(params, [ADULTINIT, PEADINIT]); + console.log('enrolledIncareQuery :', JSON.stringify(queryObj)); + + return queryObj; + } + + /** + * Function activeInCareQuery + * Possible params properties are + * 1. location (can be an array), + * 2. startDate, + * 3. endDate + * 4. lowerAgeLimit + * 5. upperAgeLimit + * 6. gender + * 7. index + * 8. type + * 9. voided + * startDate & endDate define reporting period. + * lowerAgeLimit & upperAgeLimit define age group inclusively + * location currently expects ids. + */ + function activeInCareQuery(params) { + var params = params || {}; + + //Prepare startDate and endDate + params.startDate = 'now-3m'; + if (params.endDate) { + params.startDate = params.endDate + '||-3M'; + } else { + params.endDate = 'now'; } - - // function transferOutQuery(params) { - // var params = params || {}; - // - // var query = { - // index: params['index'] || index, - // type: params['type'] || type, - // body: { - // 'aggs': { - // 'transferOut': { - // 'filter': { - // 'bool': { - // 'must': [ - // {'bool': { - // 'should': [ - // { - // 'bool': { - // 'must': [{ - // 'term': { - // 'concept_id': 1946 - // } - // },{ - // 'terms': { - // 'value_coded': [1065] - // } - // } - // ] - // } - // }, - // { - // 'terms': { - // 'concept_id': [1596,1285] - // } - // } - // ] - // }} - // ]} - // }, - // 'aggs': { - // 'patients': { - // 'terms':{ - // 'field':'person_id', - // 'size': 0 - // } - // } - // } - // } - // }, - // 'size': 0 - // } - // }; - - // if(!_.isEmpty(params)) { - // var conditions = query.body.aggs.transferOut.filter.bool.must; - // - // _handleAgeCondition(params, conditions); - // _handleLocationCondition(params, conditions); - // _handlePeriodCondition(params, conditions); - // - // //Deal with gender. - // if(params.gender) { - // var gender = { - // 'term':{ - // 'gender':params.gender - // } - // }; - // conditions.push(gender); - // } - // } - // return query; - // } - - function transferOutQuery(params) { - var params = params || {}; - // basic mult-select query conditions - var conditions = []; - if(!_.isEmpty(params)) { - _handleAgeCondition(params, conditions); - _handleLocationCondition(params, conditions); - _handlePeriodCondition(params, conditions); - _handleGenderCondition(params, conditions); - _handleVoidedCondition(params, conditions); - } - var _body = ejs.Request() - .size(0) - .query( - ejs.BoolQuery() - .must(conditions) - .must( - ejs.BoolQuery() - .should( - ejs.BoolQuery() - .must(ejs.TermQuery('concept_id', concepts.HIV_NEGATIVE)) - .must(ejs.TermQuery('value_coded', concepts.YES)) - ) - .should(ejs.TermsQuery('concept_id', [concepts.REASON_EXITED, - concepts.TRANSFERED])) - ) - ) - .agg( - ejs.TermsAggregation(params.aggsName) - .field('person_id') - .size(0) - ); - - var queryObj = { - index: params['index'] || index, - type: params['type'] || type, - body:_body - - } - - return queryObj; + + var queryObj = _queryBuilder(params, [ + ADULTINIT, + ADULTRET, + PEADINIT, + PEADRET + ]); + console.log('activeIncareQuery :', JSON.stringify(queryObj)); + + return queryObj; + } + + // function transferOutQuery(params) { + // var params = params || {}; + + // var query = { + // index: params['index'] || index, + // type: params['type'] || type, + // body: { + // aggs: { + // transferOut: { + // filter: { + // bool: { + // must: [ + // { + // bool: { + // should: [ + // { + // bool: { + // must: [ + // { + // term: { + // concept_id: 1946 + // } + // }, + // { + // terms: { + // value_coded: [1065] + // } + // } + // ] + // } + // }, + // { + // terms: { + // concept_id: [1596, 1285] + // } + // } + // ] + // } + // } + // ] + // } + // }, + // aggs: { + // patients: { + // terms: { + // field: 'person_id', + // size: 0 + // } + // } + // } + // } + // }, + // size: 0 + // } + // }; + + // if (!_.isEmpty(params)) { + // var conditions = query.body.aggs.transferOut.filter.bool.must; + + // _handleAgeCondition(params, conditions); + // _handleLocationCondition(params, conditions); + // _handlePeriodCondition(params, conditions); + + // //Deal with gender. + // if (params.gender) { + // var gender = { + // term: { + // gender: params.gender + // } + // }; + // conditions.push(gender); + // } + // } + // return query; + // } + + function transferOutQuery(params) { + var params = params || {}; + // basic mult-select query conditions + var conditions = []; + if (!_.isEmpty(params)) { + _handleAgeCondition(params, conditions); + _handleLocationCondition(params, conditions); + _handlePeriodCondition(params, conditions); + _handleGenderCondition(params, conditions); + _handleVoidedCondition(params, conditions); } - - function _handlePeriodCondition(params, conditionsArray) { - var includeCondition = false; - var period = ejs.RangeQuery('obs_datetime'); - - if(params.startDate) { - period = ejs.RangeQuery('obs_datetime').gte(params.startDate); - includeCondition = true; - } - - if(params.endDate) { - period = ejs.RangeQuery('obs_datetime').lte(params.endDate); - includeCondition = true; - } - - if(includeCondition) { - conditionsArray.push(period); - } + var _body = ejs + .Request() + .size(0) + .query( + ejs + .BoolQuery() + .must(conditions) + .must( + ejs + .BoolQuery() + .should( + ejs + .BoolQuery() + .must(ejs.TermQuery('concept_id', concepts.HIV_NEGATIVE)) + .must(ejs.TermQuery('value_coded', concepts.YES)) + ) + .should( + ejs.TermsQuery('concept_id', [ + concepts.REASON_EXITED, + concepts.TRANSFERED + ]) + ) + ) + ) + .agg(ejs.TermsAggregation(params.aggsName).field('person_id').size(0)); + + var queryObj = { + index: params['index'] || index, + type: params['type'] || type, + body: _body + }; + + return queryObj; + } + + function _handlePeriodCondition(params, conditionsArray) { + var includeCondition = false; + var period = ejs.RangeQuery('obs_datetime'); + + if (params.startDate) { + period = ejs.RangeQuery('obs_datetime').gte(params.startDate); + includeCondition = true; } - - function _handleAgeCondition(params, conditionsArray) { - var age = ejs.RangeQuery('birthdate'); - - var includeCondition = false; - - if(params.lowerAgeLimit) { - if(params.endDate) { - age = ejs.RangeQuery('birthdate').lte(params.endDate + '||-' + params.lowerAgeLimit + 'y'); - } else { - age = ejs.RangeQuery('birthdate').lte('now-' + params.lowerAgeLimit + 'y'); - } - includeCondition = true; - } - - if(params.upperAgeLimit) { - if(params.endDate) { - age = ejs.RangeQuery('birthdate').gte(params.endDate + '||-' + params.upperAgeLimit + 'y'); - } else { - age = ejs.RangeQuery('birthdate').gte('now-' + params.upperAgeLimit + 'y'); - } - includeCondition = true; - } - - if(includeCondition) { - conditionsArray.push(age); - } + + if (params.endDate) { + period = ejs.RangeQuery('obs_datetime').lte(params.endDate); + includeCondition = true; } - - function _handleLocationCondition(params, conditionsArray) { - if(params.location) { - var locations = []; - var location = ejs.TermsQuery('location_id', []); - - if(typeof params.location === 'array') { - for(var loc in params.location) { - locations.push(loc); - } - - } else { - locations.push(params.location); - } - location = ejs.TermsQuery('location_id', locations); - conditionsArray.push(location); - } + + if (includeCondition) { + conditionsArray.push(period); + } + } + + function _handleAgeCondition(params, conditionsArray) { + var age = ejs.RangeQuery('birthdate'); + + var includeCondition = false; + + if (params.lowerAgeLimit) { + if (params.endDate) { + age = ejs + .RangeQuery('birthdate') + .lte(params.endDate + '||-' + params.lowerAgeLimit + 'y'); + } else { + age = ejs + .RangeQuery('birthdate') + .lte('now-' + params.lowerAgeLimit + 'y'); + } + includeCondition = true; + } + + if (params.upperAgeLimit) { + if (params.endDate) { + age = ejs + .RangeQuery('birthdate') + .gte(params.endDate + '||-' + params.upperAgeLimit + 'y'); + } else { + age = ejs + .RangeQuery('birthdate') + .gte('now-' + params.upperAgeLimit + 'y'); + } + includeCondition = true; + } + + if (includeCondition) { + conditionsArray.push(age); } - - function _handleGenderCondition(params, conditionsArray) { - if(params.gender) { - var gender = ejs.TermQuery('gender', params.gender); - conditionsArray.push(gender); + } + + function _handleLocationCondition(params, conditionsArray) { + if (params.location) { + var locations = []; + var location = ejs.TermsQuery('location_id', []); + + if (typeof params.location === 'array') { + for (var loc in params.location) { + locations.push(loc); } + } else { + locations.push(params.location); + } + location = ejs.TermsQuery('location_id', locations); + conditionsArray.push(location); } - - function _handleVoidedCondition(params, conditionsArray) { - var voided = params.voided || false; - conditionsArray.push(ejs.TermQuery('voided',voided)); + } + + function _handleGenderCondition(params, conditionsArray) { + if (params.gender) { + var gender = ejs.TermQuery('gender', params.gender); + conditionsArray.push(gender); } - - return { - enrolledInCareQuery: enrolledInCareQuery, - activeInCareQuery: activeInCareQuery, - transferOutQuery: transferOutQuery - }; + } + + function _handleVoidedCondition(params, conditionsArray) { + var voided = params.voided || false; + conditionsArray.push(ejs.TermQuery('voided', voided)); + } + + return { + enrolledInCareQuery: enrolledInCareQuery, + activeInCareQuery: activeInCareQuery, + transferOutQuery: transferOutQuery + }; })(); diff --git a/elastic/queries/concept.ids.js b/elastic/queries/concept.ids.js index 45d30c6eb..dc6cd06a7 100755 --- a/elastic/queries/concept.ids.js +++ b/elastic/queries/concept.ids.js @@ -1,8 +1,8 @@ -module.exports = (function(){ - return { - HIV_NEGATIVE: 1946, - YES: 1065, - REASON_EXITED: 1596, - TRANSFERED: 1285 - } +module.exports = (function () { + return { + HIV_NEGATIVE: 1946, + YES: 1065, + REASON_EXITED: 1596, + TRANSFERED: 1285 + }; })(); diff --git a/elastic/routes/care.treatment.routes.js b/elastic/routes/care.treatment.routes.js index 81c8701b7..ba347f9ab 100755 --- a/elastic/routes/care.treatment.routes.js +++ b/elastic/routes/care.treatment.routes.js @@ -1,52 +1,56 @@ -module.exports = (function(){ - 'use strict'; - var elasticAccess = require('../elastic.access.js'); - - function enrolledHandler(request, reply) { - elasticAccess.getEnrolledInCare({},function(data){ - //Create json - var response = { - total: data - }; - reply(JSON.stringify(response)); - }); +module.exports = (function () { + 'use strict'; + var elasticAccess = require('../elastic.access.js'); + + function enrolledHandler(request, reply) { + elasticAccess.getEnrolledInCare({}, function (data) { + //Create json + var response = { + total: data + }; + reply(JSON.stringify(response)); + }); + } + + function enrolledInCareMohHandler(request, reply) { + elasticAccess.getEnrolledInCareMOh(request.query, function (data) { + reply(data); + }); + } + + function activeInCareMohHandler(request, reply) { + elasticAccess.getActiveInCareMoh(request.query, function (data) { + reply(data); + }); + } + + return [ + { + method: 'GET', + path: '/home', + handler: function (request, reply) { + var server = { + name: 'Indicators Rest Server', + version: '0.0.1', + description: 'You know for blazing fast speeds ...' + }; + reply(JSON.stringify(server)); + } + }, + { + method: 'GET', + path: '/enrolled-in-care', + handler: enrolledHandler + }, + { + method: 'GET', + path: '/enrolled-in-care/moh', + handler: enrolledInCareMohHandler + }, + { + method: 'GET', + path: '/active-in-care/moh', + handler: activeInCareMohHandler } - - function enrolledInCareMohHandler(request, reply) { - elasticAccess.getEnrolledInCareMOh(request.query, function(data) { - reply(data); - }); - } - - function activeInCareMohHandler(request, reply) { - elasticAccess.getActiveInCareMoh(request.query, function(data) { - reply(data); - }); - } - - - return [{ - method: 'GET', - path: '/home', - handler: function (request, reply) { - var server = { - name: 'Indicators Rest Server', - version: '0.0.1', - description: 'You know for blazing fast speeds ...' - } - reply(JSON.stringify(server)); - } - }, { - method: 'GET', - path: '/enrolled-in-care', - handler: enrolledHandler - }, { - method: 'GET', - path: '/enrolled-in-care/moh', - handler: enrolledInCareMohHandler - }, { - method: 'GET', - path: '/active-in-care/moh', - handler: activeInCareMohHandler - }]; + ]; })(); diff --git a/encounter-type/encounter-type-service.js b/encounter-type/encounter-type-service.js index 06f7e4cf9..e608e923a 100755 --- a/encounter-type/encounter-type-service.js +++ b/encounter-type/encounter-type-service.js @@ -1,103 +1,82 @@ -var Promise = require("bluebird"); +var Promise = require('bluebird'); var encounterTypeDao = require('../dao/encounter-type/encounter-type-dao'); const _ = require('lodash'); var encounterTypes = []; var encounterUuidIdMap = new Map(); var def = { - getAllEncounterTypes: getAllEncounterTypes, - mapEncounterUuidToId: mapEncounterUuidToId, - loadAndMapEncounterUuidToId : loadAndMapEncounterUuidToId, - getEncounterIdFromUuid: getEncounterIdFromUuid + getAllEncounterTypes: getAllEncounterTypes, + mapEncounterUuidToId: mapEncounterUuidToId, + loadAndMapEncounterUuidToId: loadAndMapEncounterUuidToId, + getEncounterIdFromUuid: getEncounterIdFromUuid }; module.exports = def; - -function getAllEncounterTypes(){ - - /* +function getAllEncounterTypes() { + /* returns a list of all encunter-types with their id and uuid */ return new Promise(function (resolve, reject) { - - if(encounterTypes.length > 0){ - - // console.log('Encounter Type length > 0'); - - resolve(encounterTypes); - - }else{ - - // console.log('Encounter Type length < 0'); - - encounterTypeDao.getEncounterTypes().then(function (result) { - if(result){ - encounterTypes = result; - resolve(encounterTypes); - }else{ - reject('error'); - } - }) - .catch(function (error) { - reject('error'); - }); - - - } - - - - }); - - - + if (encounterTypes.length > 0) { + // console.log('Encounter Type length > 0'); + + resolve(encounterTypes); + } else { + // console.log('Encounter Type length < 0'); + + encounterTypeDao + .getEncounterTypes() + .then(function (result) { + if (result) { + encounterTypes = result; + resolve(encounterTypes); + } else { + reject('error'); + } + }) + .catch(function (error) { + reject('error'); + }); + } + }); } -function mapEncounterUuidToId(encounterTypes){ - // console.log('Got EncounterTypes', encounterTypes); +function mapEncounterUuidToId(encounterTypes) { + // console.log('Got EncounterTypes', encounterTypes); - _.each(encounterTypes,(encounterType, index) => { - // console.log('Specific Encounter Type', encounterType) - encounterUuidIdMap.set( encounterType.uuid ,encounterType.encounter_type_id); - }); - - return encounterUuidIdMap; + _.each(encounterTypes, (encounterType, index) => { + // console.log('Specific Encounter Type', encounterType) + encounterUuidIdMap.set(encounterType.uuid, encounterType.encounter_type_id); + }); + return encounterUuidIdMap; } -function getEncounterIdFromUuid(encounterUuid){ - - var encounterObj = encounterUuidIdMap.get(encounterUuid); - - if(typeof encounterObj === 'undefined'){ - return -1; - }else{ - return encounterObj; - } +function getEncounterIdFromUuid(encounterUuid) { + var encounterObj = encounterUuidIdMap.get(encounterUuid); + if (typeof encounterObj === 'undefined') { + return -1; + } else { + return encounterObj; + } } -function loadAndMapEncounterUuidToId(){ - - return new Promise(function (resolve, reject) { - - getAllEncounterTypes() - .then((result) => { - if(result){ - encounterUuidIdMap = mapEncounterUuidToId(result); - resolve(encounterUuidIdMap); - } - }) - .catch(((error) =>{ - reject('Error'); - })); - - }); - +function loadAndMapEncounterUuidToId() { + return new Promise(function (resolve, reject) { + getAllEncounterTypes() + .then((result) => { + if (result) { + encounterUuidIdMap = mapEncounterUuidToId(result); + resolve(encounterUuidIdMap); + } + }) + .catch((error) => { + reject('Error'); + }); + }); } - - diff --git a/etl-broadcast.js b/etl-broadcast.js index 1c8d9b9d9..1610a5b02 100755 --- a/etl-broadcast.js +++ b/etl-broadcast.js @@ -2,45 +2,45 @@ var redis = require('redis'); var client = redis.createClient(); -function getOptions(server){ - return { - onConnection:function(socket){ - console.log('a client just connected', socket.id) - //retrieve latest message from redis and send it to client - client.get("broadcast:messages:latest", function(err, reply){ - if(reply){ - socket.send(JSON.parse(reply), function (err) { - // console.log('this message (latest) was sent successfully', reply, 'to ' + socket.id); - }); - } else { - // console.log('No message or message expired.'); - } - }); - }, - onDisconnection: function(socket){ - console.log('a client has disconnected', socket.id); - }, - onMessage:function(socket, message, next){ - // console.log('SOCKET AUTH:', socket.auth) - console.log('client', socket.id, 'has sent message',message) - //save the message to redis - var str = JSON.stringify(message); - client.RPUSH("broadcast:messages", str); // notification history - client.LRANGE("broadcast:messages",0 , -1, function(err, data){ - if(data) { - var lastElement = data[data.length - 1]; - var jsonMessage = JSON.parse(lastElement); - client.set("broadcast:messages:latest", lastElement, redis.print); - client.expire("broadcast:messages:latest", jsonMessage.expire); - } - }); - //relay the message to connected clients - server.broadcast(message); - }, - auth: {type:'direct'}, - headers: '*' - } +function getOptions(server) { + return { + onConnection: function (socket) { + console.log('a client just connected', socket.id); + //retrieve latest message from redis and send it to client + client.get('broadcast:messages:latest', function (err, reply) { + if (reply) { + socket.send(JSON.parse(reply), function (err) { + // console.log('this message (latest) was sent successfully', reply, 'to ' + socket.id); + }); + } else { + // console.log('No message or message expired.'); + } + }); + }, + onDisconnection: function (socket) { + console.log('a client has disconnected', socket.id); + }, + onMessage: function (socket, message, next) { + // console.log('SOCKET AUTH:', socket.auth) + console.log('client', socket.id, 'has sent message', message); + //save the message to redis + var str = JSON.stringify(message); + client.RPUSH('broadcast:messages', str); // notification history + client.LRANGE('broadcast:messages', 0, -1, function (err, data) { + if (data) { + var lastElement = data[data.length - 1]; + var jsonMessage = JSON.parse(lastElement); + client.set('broadcast:messages:latest', lastElement, redis.print); + client.expire('broadcast:messages:latest', jsonMessage.expire); + } + }); + //relay the message to connected clients + server.broadcast(message); + }, + auth: { type: 'direct' }, + headers: '*' + }; } module.exports = { - getOptions:getOptions + getOptions: getOptions }; diff --git a/etl-dao.js b/etl-dao.js index 405e8885c..066795cd8 100755 --- a/etl-dao.js +++ b/etl-dao.js @@ -8,17 +8,17 @@ var patient = require('./dao/patient/etl-patient-dao'); var eid = require('./dao/eid/etl-eid-dao'); var session = require('./dao/session/session'); var labCohorts = require('./dao/lab-cohorts/lab-cohorts-dao'); -var formErrors = require('./dao/form-entry/errors-dao.js') +var formErrors = require('./dao/form-entry/errors-dao.js'); -module.exports = function() { - var dao ={}; - _.extend(dao,analytics); - _.extend(dao,patientCareStatus); - _.extend(dao,clinic); - _.extend(dao,patient); - _.extend(dao,eid); - _.extend(dao,session); - _.extend(dao,labCohorts); - _.extend(dao, formErrors); +module.exports = (function () { + var dao = {}; + _.extend(dao, analytics); + _.extend(dao, patientCareStatus); + _.extend(dao, clinic); + _.extend(dao, patient); + _.extend(dao, eid); + _.extend(dao, session); + _.extend(dao, labCohorts); + _.extend(dao, formErrors); return dao; -}(); +})(); diff --git a/etl-db.js b/etl-db.js index 555a2f9d1..10b571b92 100755 --- a/etl-db.js +++ b/etl-db.js @@ -6,428 +6,461 @@ var mysql = require('mysql'); var squel = require('squel'); var _ = require('underscore'); var config = require('./conf/config'); -var moment=require('moment'); +var moment = require('moment'); var errorHandler = function (errorType, error) { - var currentdate = new Date(); - var datetime = currentdate.getDate() + "/" - + (currentdate.getMonth() + 1) + "/" - + currentdate.getFullYear() + " @ " - + currentdate.getHours() + ":" - + currentdate.getMinutes() + ":" - + currentdate.getSeconds(); - var errorDescription = errorType + ' occurred at ' + datetime; + var currentdate = new Date(); + var datetime = + currentdate.getDate() + + '/' + + (currentdate.getMonth() + 1) + + '/' + + currentdate.getFullYear() + + ' @ ' + + currentdate.getHours() + + ':' + + currentdate.getMinutes() + + ':' + + currentdate.getSeconds(); + var errorDescription = errorType + ' occurred at ' + datetime; }; -module.exports = function () { - var pool = mysql.createPool(config.mysql); - var getServerConnection = function (connectHandler) { - pool.getConnection(function (err, connection) { - if (err) { - errorHandler('exports:Database connection error', err); - return connectHandler(err, null); - } - return connectHandler(null, connection); - }); - }; - var queryLimit = 300; - var queryOffset = 0; - - function _updateJoins(join, s, sq) { - if (sq) { - if(_.isUndefined(join.joinExpression) || join.joinExpression === '') { - if (join.joinType == 'JOIN') s.join(sq, join.alias); - if (join.joinType == 'INNER JOIN') s.join(sq, join.alias); - if (join.joinType == 'OUTER JOIN') s.outer_join(sq, join.alias); - if (join.joinType == 'LEFT OUTER JOIN') s.left_outer_join(sq, join.alias); - } else { - if (join.joinType == 'JOIN') s.join(sq, join.alias, join.joinExpression); - if (join.joinType == 'INNER JOIN') s.join(sq, join.alias, join.joinExpression); - if (join.joinType == 'OUTER JOIN') s.outer_join(sq, join.alias, join.joinExpression); - if (join.joinType == 'LEFT OUTER JOIN') s.left_outer_join(sq, join.alias, join.joinExpression); - } +module.exports = (function () { + var pool = mysql.createPool(config.mysql); + var getServerConnection = function (connectHandler) { + pool.getConnection(function (err, connection) { + if (err) { + errorHandler('exports:Database connection error', err); + return connectHandler(err, null); + } + return connectHandler(null, connection); + }); + }; + var queryLimit = 300; + var queryOffset = 0; + + function _updateJoins(join, s, sq) { + if (sq) { + if (_.isUndefined(join.joinExpression) || join.joinExpression === '') { + if (join.joinType == 'JOIN') s.join(sq, join.alias); + if (join.joinType == 'INNER JOIN') s.join(sq, join.alias); + if (join.joinType == 'OUTER JOIN') s.outer_join(sq, join.alias); + if (join.joinType == 'LEFT OUTER JOIN') + s.left_outer_join(sq, join.alias); } else { - if(_.isUndefined(join.joinExpression) || join.joinExpression === '') { - if (join.joinType == 'JOIN') s.join(join.schema + '.' + join.tableName, join.alias); - if (join.joinType == 'INNER JOIN') s.join(join.schema + '.' + join.tableName, join.alias); - if (join.joinType == 'OUTER JOIN') s.outer_join(join.schema + '.' + join.tableName, join.alias); - if (join.joinType == 'LEFT OUTER JOIN') s.left_outer_join(join.schema + '.' + join.tableName, join.alias); + if (join.joinType == 'JOIN') + s.join(sq, join.alias, join.joinExpression); + if (join.joinType == 'INNER JOIN') + s.join(sq, join.alias, join.joinExpression); + if (join.joinType == 'OUTER JOIN') + s.outer_join(sq, join.alias, join.joinExpression); + if (join.joinType == 'LEFT OUTER JOIN') + s.left_outer_join(sq, join.alias, join.joinExpression); + } + } else { + if (_.isUndefined(join.joinExpression) || join.joinExpression === '') { + if (join.joinType == 'JOIN') + s.join(join.schema + '.' + join.tableName, join.alias); + if (join.joinType == 'INNER JOIN') + s.join(join.schema + '.' + join.tableName, join.alias); + if (join.joinType == 'OUTER JOIN') + s.outer_join(join.schema + '.' + join.tableName, join.alias); + if (join.joinType == 'LEFT OUTER JOIN') + s.left_outer_join(join.schema + '.' + join.tableName, join.alias); + } else { + if (join.joinType == 'JOIN') + s.join( + join.schema + '.' + join.tableName, + join.alias, + join.joinExpression + ); + if (join.joinType == 'INNER JOIN') + s.join( + join.schema + '.' + join.tableName, + join.alias, + join.joinExpression + ); + if (join.joinType == 'OUTER JOIN') + s.outer_join( + join.schema + '.' + join.tableName, + join.alias, + join.joinExpression + ); + if (join.joinType == 'LEFT OUTER JOIN') + s.left_outer_join( + join.schema + '.' + join.tableName, + join.alias, + join.joinExpression + ); + } + } + } + + function queryReportServer(sql, callback) { + var result = {}; + getServerConnection(function (err, connection) { + if (err) { + errorHandler('ExecuteMultiReport: Database connection error', err); + return; + } + connection.query(sql.query, sql.sqlParams, function (err, rows, fields) { + if (err) { + errorHandler('Error querying server', err); + result.errorMessage = 'Error querying server'; + result.error = err; + result.sql = sql.query; + result.sqlParams = sql.sqlParams; } else { - if (join.joinType == 'JOIN') s.join(join.schema + '.' + join.tableName, join.alias, join.joinExpression); - if (join.joinType == 'INNER JOIN') s.join(join.schema + '.' + join.tableName, join.alias, join.joinExpression); - if (join.joinType == 'OUTER JOIN') s.outer_join(join.schema + '.' + join.tableName, join.alias, join.joinExpression); - if (join.joinType == 'LEFT OUTER JOIN') s.left_outer_join(join.schema + '.' + join.tableName, join.alias, join.joinExpression); + result.startIndex = sql.offset || queryOffset; + result.size = rows.length; + result.result = rows; + result.sql = sql.query; + result.sqlParams = sql.sqlParams; } + callback(result); + connection.release(); + }); + }); + } + + function queryServer(queryParts, callback) { + var result = {}; + var sql = queryParts.sql; + var values = queryParts.values; + + getServerConnection(function (err, connection) { + if (err) { + errorHandler('queryServer: Database connection error', err); + return; } - } - - function queryReportServer(sql, callback) { - var result = {}; - getServerConnection(function (err, connection) { - if (err) { - errorHandler('ExecuteMultiReport: Database connection error', err); - return; - } - connection.query(sql.query, sql.sqlParams, function (err, rows, fields) { - if (err) { - errorHandler('Error querying server', err); - result.errorMessage = "Error querying server"; - result.error = err; - result.sql = sql.query; - result.sqlParams = sql.sqlParams; - } - else { - result.startIndex = sql.offset || queryOffset; - result.size = rows.length; - result.result = rows; - result.sql = sql.query; - result.sqlParams = sql.sqlParams; - } - callback(result); - connection.release(); - }); + connection.query(sql, values, function (err, rows, fields) { + if (err) { + errorHandler('queryServer: Error querying server', err); + result.errorMessage = 'Error querying server'; + result.error = err; + } else { + result.startIndex = queryOffset; + result.size = rows.length; + result.result = rows; + } + callback(result); + connection.release(); }); + }); + } + + function createQuery(queryParts, sq) { + var result = {}; + var multiquery = ''; + var multuvalues = []; + var tableAlias = 't1'; + if (queryParts['alias']) tableAlias = queryParts['alias']; + if (queryParts['indexExpression']) + tableAlias += ' ' + queryParts['indexExpression']; + var s; + if (sq) { + s = squel.select().from(sq, tableAlias); + } else { + s = squel.select(); + if (queryParts['indexExpression']) + s = squel.select({ autoQuoteAliasNames: false }); + s.from(queryParts.table, tableAlias); } - - function queryServer(queryParts, callback) { - var result = {}; - var sql = queryParts.sql; - var values = queryParts.values; - - getServerConnection(function (err, connection) { - if (err) { - errorHandler('queryServer: Database connection error', err); - return; - } - - connection.query(sql, values, function (err, rows, fields) { - if (err) { - errorHandler('queryServer: Error querying server', err); - result.errorMessage = "Error querying server"; - result.error = err; - } - else { - result.startIndex = queryOffset; - result.size = rows.length; - result.result = rows; - } - callback(result); - connection.release(); - }); - }); - } - - function createQuery(queryParts, sq) { - var result = {}; - var multiquery = ""; - var multuvalues = []; - var tableAlias = 't1'; - if (queryParts['alias'])tableAlias = queryParts['alias']; - if (queryParts['indexExpression'])tableAlias += ' '+queryParts['indexExpression']; - var s; - if (sq) { - s = squel.select() - .from(sq, tableAlias); - + _.each(queryParts['joins'], function (join) { + if (join.joinedQuerParts) { + var joinedParts = join.joinedQuerParts; + var sq = ''; + if ( + joinedParts.nestedParts !== undefined && + joinedParts.nestedParts !== '' + ) { + // This is for cases where joined reports has some a sub query + sq = createQuery(joinedParts, createQuery(joinedParts.nestedParts)); + } else { + sq = createQuery(joinedParts); + } + _updateJoins(join, s, sq); } else { - s = squel.select(); - if (queryParts['indexExpression']) s = squel.select({autoQuoteAliasNames: false }); - s.from(queryParts.table, tableAlias); + _updateJoins(join, s); } - _.each(queryParts['joins'], function (join) { - if (join.joinedQuerParts) { - var joinedParts = join.joinedQuerParts - var sq = ''; - if (joinedParts.nestedParts !== undefined && joinedParts.nestedParts !== '') { - // This is for cases where joined reports has some a sub query - sq = createQuery(joinedParts, createQuery(joinedParts.nestedParts)); - } else { - sq = createQuery(joinedParts); - } - _updateJoins(join, s, sq); - } else { - _updateJoins(join, s); - } - }); - + }); - if (queryParts.columns && queryParts.columns !== "*") { - if (typeof queryParts.columns === "string") { - // if (queryParts.columns.substring(0, 1) === "(") - // queryParts.columns = queryParts.columns.substring(1, -1); - queryParts.columns = queryParts.columns.split(','); - } - var i = 0; - _.each(queryParts.columns, function (columnName) { - if (i === 0 && columnName.substring(0, 1) === "(") - s.field(columnName.split("(")[1]); - else if (i === queryParts.columns.length - 1) { - var col = columnName; - var n = columnName.split(")").length - 1; - if (n === 1 && !_.contains(col, "(")) - s.field(columnName.split(")")[0]); - else s.field(col); - } - else s.field(columnName); - i++; - }); + if (queryParts.columns && queryParts.columns !== '*') { + if (typeof queryParts.columns === 'string') { + // if (queryParts.columns.substring(0, 1) === "(") + // queryParts.columns = queryParts.columns.substring(1, -1); + queryParts.columns = queryParts.columns.split(','); } - if (queryParts.concatColumns && queryParts.concatColumns !== "*") { - if (typeof queryParts.concatColumns === "string") { - // if (queryParts.columns.substring(0, 1) === "(") - // queryParts.columns = queryParts.columns.substring(1, -1); - queryParts.concatColumns = queryParts.concatColumns.split(';'); - } - var i = 0; - _.each(queryParts.concatColumns, function (columnName) { - if (i === 0 && columnName.substring(0, 1) === "(") - s.field(columnName.split("(")[1]); - else if (i === queryParts.concatColumns.length - 1) { - var col = columnName; - var n = columnName.split(")").length - 1; - if (n === 1 && !_.contains(col, "(")) - s.field(columnName.split(")")[0]); - else s.field(col); - } - else s.field(columnName); - i++; - }); - } - - - s.where.apply(this, queryParts['where']); - _.each(queryParts['order'], function (param) { - s.order(param.column, param.asc); + var i = 0; + _.each(queryParts.columns, function (columnName) { + if (i === 0 && columnName.substring(0, 1) === '(') + s.field(columnName.split('(')[1]); + else if (i === queryParts.columns.length - 1) { + var col = columnName; + var n = columnName.split(')').length - 1; + if (n === 1 && !_.contains(col, '(')) + s.field(columnName.split(')')[0]); + else s.field(col); + } else s.field(columnName); + i++; }); - s.limit(queryParts['limit'] || queryLimit); - s.offset(queryParts['offset'] || queryOffset); - _.each(queryParts['group'], function (col) { - s.group(col); - }); - - if(queryParts['having'][0] !== '') s.having(queryParts['having'][0]); - - return s; } - - function transformQueryPartsToSql(queryParts) { - var tableAlias = 't1'; - if (queryParts['alias'])tableAlias = queryParts['alias']; - var s = squel.select() - .from(queryParts['table'], tableAlias); - - _.each(queryParts['joins'], function (join) { - s.join(join[0], join[1], join[2]); - }); - - _.each(queryParts['outerJoins'], function (join) { - s.outer_join(join[0], join[1], join[2]); - }); - - _.each(queryParts['leftOuterJoins'], function (join) { - s.left_outer_join(join[0], join[1], join[2]); - }); - - if (queryParts.columns && queryParts.columns !== "*") { - if (typeof queryParts.columns === "string") { - // if (queryParts.columns.substring(0, 1) === "(") - // queryParts.columns = queryParts.columns.substring(1, -1); - queryParts.columns = queryParts.columns.split(','); - } - var i = 0; - _.each(queryParts.columns, function (columnName) { - if (i === 0 && columnName.substring(0, 1) === "(") - s.field(columnName.split("(")[1]); - else if (i === queryParts.columns.length - 1) { - var col = columnName; - var n = columnName.split(")").length - 1; - if (n === 1 && !_.contains(col, "(")) - s.field(columnName.split(")")[0]); - else s.field(col); - - } - else s.field(columnName); - i++; - }); + if (queryParts.concatColumns && queryParts.concatColumns !== '*') { + if (typeof queryParts.concatColumns === 'string') { + // if (queryParts.columns.substring(0, 1) === "(") + // queryParts.columns = queryParts.columns.substring(1, -1); + queryParts.concatColumns = queryParts.concatColumns.split(';'); } - if (queryParts.concatColumns && queryParts.concatColumns !== "*") { - if (typeof queryParts.concatColumns === "string") { - // if (queryParts.columns.substring(0, 1) === "(") - // queryParts.columns = queryParts.columns.substring(1, -1); - queryParts.concatColumns = queryParts.concatColumns.split(';'); - } - var i = 0; - _.each(queryParts.concatColumns, function (columnName) { - if (i === 0 && columnName.substring(0, 1) === "(") - s.field(columnName.split("(")[1]); - else if (i === queryParts.concatColumns.length - 1) { - var col = columnName; - var n = columnName.split(")").length - 1; - if (n === 1 && !_.contains(col, "(")) - s.field(columnName.split(")")[0]); - else s.field(col); - } - else s.field(columnName); - i++; - }); - } - - - s.where.apply(this, queryParts['where']); - _.each(queryParts['order'], function (param) { - s.order(param.column, param.asc); + var i = 0; + _.each(queryParts.concatColumns, function (columnName) { + if (i === 0 && columnName.substring(0, 1) === '(') + s.field(columnName.split('(')[1]); + else if (i === queryParts.concatColumns.length - 1) { + var col = columnName; + var n = columnName.split(')').length - 1; + if (n === 1 && !_.contains(col, '(')) + s.field(columnName.split(')')[0]); + else s.field(col); + } else s.field(columnName); + i++; }); - s.limit(queryParts['limit'] || queryLimit); - s.offset(queryParts['offset'] || queryOffset); - _.each(queryParts['group'], function (col) { - s.group(col); - }); - - - var q = s.toParam(); - - console.log(q.text.replace("\\", "")); - console.log(q.values); - - var sql = q.text.replace("\\", ""); - var values = q.values; - return {query: sql, sqlParams: values, offset: queryParts['offset'] || queryOffset} } - function transformReportQueryPartsToSql(queryPartsArray) { - var query = ""; - var sqlParams = []; - var s; - //The queryPartsArray may never have more than one element and - // that is why we just need to get the sql - _.each(queryPartsArray, function (queryParts) { - if (queryParts !== undefined) { - if (queryParts.nestedParts !== undefined && queryParts.nestedParts !== '') { - // This is done so that we can always pick up sub queries - s = createQuery(queryParts, createQuery(queryParts.nestedParts)); - } else { - s = createQuery(queryParts); - } - var q = s.toParam(); - var sql = q.text.replace("\\", ""); - var values = q.values; - query = sql; - _.each(values, function (res) { - sqlParams.push(res); - }); - } + s.where.apply(this, queryParts['where']); + _.each(queryParts['order'], function (param) { + s.order(param.column, param.asc); + }); + s.limit(queryParts['limit'] || queryLimit); + s.offset(queryParts['offset'] || queryOffset); + _.each(queryParts['group'], function (col) { + s.group(col); + }); + + if (queryParts['having'][0] !== '') s.having(queryParts['having'][0]); + + return s; + } + + function transformQueryPartsToSql(queryParts) { + var tableAlias = 't1'; + if (queryParts['alias']) tableAlias = queryParts['alias']; + var s = squel.select().from(queryParts['table'], tableAlias); + + _.each(queryParts['joins'], function (join) { + s.join(join[0], join[1], join[2]); + }); + + _.each(queryParts['outerJoins'], function (join) { + s.outer_join(join[0], join[1], join[2]); + }); + + _.each(queryParts['leftOuterJoins'], function (join) { + s.left_outer_join(join[0], join[1], join[2]); + }); + + if (queryParts.columns && queryParts.columns !== '*') { + if (typeof queryParts.columns === 'string') { + // if (queryParts.columns.substring(0, 1) === "(") + // queryParts.columns = queryParts.columns.substring(1, -1); + queryParts.columns = queryParts.columns.split(','); + } + var i = 0; + _.each(queryParts.columns, function (columnName) { + if (i === 0 && columnName.substring(0, 1) === '(') + s.field(columnName.split('(')[1]); + else if (i === queryParts.columns.length - 1) { + var col = columnName; + var n = columnName.split(')').length - 1; + if (n === 1 && !_.contains(col, '(')) + s.field(columnName.split(')')[0]); + else s.field(col); + } else s.field(columnName); + i++; }); - - return {query: query, sqlParams: sqlParams, offset: queryPartsArray[0]['offset'] || queryOffset} } - - function reportQueryServer (queryPartsArray, callback) { - var sql = transformReportQueryPartsToSql(queryPartsArray); - queryReportServer(sql, function (result) { - callback(result); - }); - } - - function queryServer_test(queryParts, callback) { - var sql = transformQueryPartsToSql(queryParts); - queryReportServer(sql, function (result) { - callback(result); - }); - } - - function queryServer_testToPromisify(queryParts, callback) { - var sql = transformQueryPartsToSql(queryParts); - queryReportServer(sql, function (result) { - callback(null,result); - }); + if (queryParts.concatColumns && queryParts.concatColumns !== '*') { + if (typeof queryParts.concatColumns === 'string') { + // if (queryParts.columns.substring(0, 1) === "(") + // queryParts.columns = queryParts.columns.substring(1, -1); + queryParts.concatColumns = queryParts.concatColumns.split(';'); + } + var i = 0; + _.each(queryParts.concatColumns, function (columnName) { + if (i === 0 && columnName.substring(0, 1) === '(') + s.field(columnName.split('(')[1]); + else if (i === queryParts.concatColumns.length - 1) { + var col = columnName; + var n = columnName.split(')').length - 1; + if (n === 1 && !_.contains(col, '(')) + s.field(columnName.split(')')[0]); + else s.field(col); + } else s.field(columnName); + i++; + }); } - function saveRecord(table, fields) { - return new Promise(function(resolve, reject) { + s.where.apply(this, queryParts['where']); + _.each(queryParts['order'], function (param) { + s.order(param.column, param.asc); + }); + s.limit(queryParts['limit'] || queryLimit); + s.offset(queryParts['offset'] || queryOffset); + _.each(queryParts['group'], function (col) { + s.group(col); + }); - try { + var q = s.toParam(); - var query = squel.insert() - .into(table) - .setFieldsRows(fields) - .toParam(); + console.log(q.text.replace('\\', '')); + console.log(q.values); - saveQueryServer(query, function(response) { - resolve(response); - }); - - } catch(e) { - reject(e); + var sql = q.text.replace('\\', ''); + var values = q.values; + return { + query: sql, + sqlParams: values, + offset: queryParts['offset'] || queryOffset + }; + } + + function transformReportQueryPartsToSql(queryPartsArray) { + var query = ''; + var sqlParams = []; + var s; + //The queryPartsArray may never have more than one element and + // that is why we just need to get the sql + _.each(queryPartsArray, function (queryParts) { + if (queryParts !== undefined) { + if ( + queryParts.nestedParts !== undefined && + queryParts.nestedParts !== '' + ) { + // This is done so that we can always pick up sub queries + s = createQuery(queryParts, createQuery(queryParts.nestedParts)); + } else { + s = createQuery(queryParts); } - }); - } - function insertQueryServer(queryParts, callback) { - var column1=queryParts.columns[0]; - var column2=queryParts.columns[1]; - var column3=queryParts.columns[2]; - var value1=queryParts.values[0]; - var s=squel.insert() - .into(queryParts['table']) - .setFieldsRows([ - { person_uuid:value1,date_updated:moment(new Date()).format('YYYY-MM-DDTHH:mm:ss.SSSZZ'), - date_created:moment(new Date()).format('YYYY-MM-DDTHH:mm:ss.SSSZZ')} - ]) - .toParam(); - saveQueryServer(s,function(response){ - callback(response); - }); - } - function updateQueryServer(queryParts, callback){ - var value1=queryParts.values[0]; - var value2=moment(new Date()).format('YYYY-MM-DDTHH:mm:ss.SSSZZ'); - var s=squel.update() - .table(queryParts['table']) - .set("date_updated",value2) - .where("person_uuid=?",value1) - .toParam(); - saveQueryServer(s,function(response){ - callback(response); + var q = s.toParam(); + var sql = q.text.replace('\\', ''); + var values = q.values; + query = sql; + _.each(values, function (res) { + sqlParams.push(res); }); - } - function saveQueryServer(sql,callback){ - var result={}; - getServerConnection(function (err, connection) { - if (err) { - errorHandler('ExecuteMultiReport: Database connection error', err); - return; - } - connection.query(sql.text, sql.values, function (err, rows, fields) { - if (err) { - errorHandler('Error querying server', err); - result.errorMessage = "Error querying server"; - result.error = err; - result.sql = sql.text; - result.sqlParams = sql.values; - } - else { - result.size = rows.length; - result.sql = sql.text; - result.sqlParams = sql.values; - } - callback(result); - connection.release(); - }); - }); - } + } + }); + return { - queryReportServer: queryReportServer, - queryServer: queryServer, - createQuery: createQuery, - transformQueryPartsToSql: transformQueryPartsToSql, - transformReportQueryPartsToSql: transformReportQueryPartsToSql, - reportQueryServer: reportQueryServer, - queryServer_test: queryServer_test, - queryDb: Promise.promisify(queryServer_testToPromisify), - insertQueryServer: insertQueryServer, - saveRecord: saveRecord, - saveQueryServer: saveQueryServer, - updateQueryServer: updateQueryServer + query: query, + sqlParams: sqlParams, + offset: queryPartsArray[0]['offset'] || queryOffset }; -}(); + } + + function reportQueryServer(queryPartsArray, callback) { + var sql = transformReportQueryPartsToSql(queryPartsArray); + queryReportServer(sql, function (result) { + callback(result); + }); + } + + function queryServer_test(queryParts, callback) { + var sql = transformQueryPartsToSql(queryParts); + queryReportServer(sql, function (result) { + callback(result); + }); + } + + function queryServer_testToPromisify(queryParts, callback) { + var sql = transformQueryPartsToSql(queryParts); + queryReportServer(sql, function (result) { + callback(null, result); + }); + } + function saveRecord(table, fields) { + return new Promise(function (resolve, reject) { + try { + var query = squel.insert().into(table).setFieldsRows(fields).toParam(); + + saveQueryServer(query, function (response) { + resolve(response); + }); + } catch (e) { + reject(e); + } + }); + } + function insertQueryServer(queryParts, callback) { + var column1 = queryParts.columns[0]; + var column2 = queryParts.columns[1]; + var column3 = queryParts.columns[2]; + var value1 = queryParts.values[0]; + var s = squel + .insert() + .into(queryParts['table']) + .setFieldsRows([ + { + person_uuid: value1, + date_updated: moment(new Date()).format('YYYY-MM-DDTHH:mm:ss.SSSZZ'), + date_created: moment(new Date()).format('YYYY-MM-DDTHH:mm:ss.SSSZZ') + } + ]) + .toParam(); + saveQueryServer(s, function (response) { + callback(response); + }); + } + function updateQueryServer(queryParts, callback) { + var value1 = queryParts.values[0]; + var value2 = moment(new Date()).format('YYYY-MM-DDTHH:mm:ss.SSSZZ'); + var s = squel + .update() + .table(queryParts['table']) + .set('date_updated', value2) + .where('person_uuid=?', value1) + .toParam(); + saveQueryServer(s, function (response) { + callback(response); + }); + } + function saveQueryServer(sql, callback) { + var result = {}; + getServerConnection(function (err, connection) { + if (err) { + errorHandler('ExecuteMultiReport: Database connection error', err); + return; + } + connection.query(sql.text, sql.values, function (err, rows, fields) { + if (err) { + errorHandler('Error querying server', err); + result.errorMessage = 'Error querying server'; + result.error = err; + result.sql = sql.text; + result.sqlParams = sql.values; + } else { + result.size = rows.length; + result.sql = sql.text; + result.sqlParams = sql.values; + } + callback(result); + connection.release(); + }); + }); + } + return { + queryReportServer: queryReportServer, + queryServer: queryServer, + createQuery: createQuery, + transformQueryPartsToSql: transformQueryPartsToSql, + transformReportQueryPartsToSql: transformReportQueryPartsToSql, + reportQueryServer: reportQueryServer, + queryServer_test: queryServer_test, + queryDb: Promise.promisify(queryServer_testToPromisify), + insertQueryServer: insertQueryServer, + saveRecord: saveRecord, + saveQueryServer: saveQueryServer, + updateQueryServer: updateQueryServer + }; +})(); diff --git a/etl-factory.js b/etl-factory.js index 317431596..b5658b6da 100755 --- a/etl-factory.js +++ b/etl-factory.js @@ -1,6 +1,6 @@ -"use strict"; +'use strict'; var _ = require('underscore'); -var s = require("underscore.string"); +var s = require('underscore.string'); var walk = require('walk'); var helpers = require('./etl-helpers'); var indicatorHandlersDefinition = require('./etl-processors.js'); @@ -13,859 +13,1074 @@ var reportList = []; //iterate the report folder picking files satisfying regex *report.json reportList.push.apply(reportList, require('./reports/hiv-summary-report.json')); // MOH-731 Legacy -reportList.push.apply(reportList, require('./reports/moh-731-legacy/moh-731-report.json')); -reportList.push.apply(reportList, require('./reports/moh-731-legacy/moh-731-cohort-report.json')); -reportList.push.apply(reportList, require('./reports/moh-731-legacy/moh-731-indicator-report.json')); +reportList.push.apply( + reportList, + require('./reports/moh-731-legacy/moh-731-report.json') +); +reportList.push.apply( + reportList, + require('./reports/moh-731-legacy/moh-731-cohort-report.json') +); +reportList.push.apply( + reportList, + require('./reports/moh-731-legacy/moh-731-indicator-report.json') +); // MOH-731 2017 -reportList.push.apply(reportList, require('./reports/moh-731-2017/moh-731-report.json')); -reportList.push.apply(reportList, require('./reports/moh-731-2017/moh-731-cohort-report.json')); -reportList.push.apply(reportList, require('./reports/moh-731-2017/moh-731-indicator-report.json')); - -reportList.push.apply(reportList, require('./reports/patient-register-report.json')); -reportList.push.apply(reportList, require('./reports/clinic-calander-report-v2.json')); -reportList.push.apply(reportList, require('./reports/daily-visits-appointment.report.json')); -reportList.push.apply(reportList, require('./reports/clinical-reminder-report.json')); -reportList.push.apply(reportList, require('./reports/dataentry-statistics.json')); -reportList.push.apply(reportList, require('./reports/clinical-overview-visualization-report.json')); -reportList.push.apply(reportList, require('./reports/hiv-summary-monthly-report.json')); -reportList.push.apply(reportList, require('./reports/patient-flow-report.json')); -reportList.push.apply(reportList, require('./reports/clinic-comparator-report.json')); +reportList.push.apply( + reportList, + require('./reports/moh-731-2017/moh-731-report.json') +); +reportList.push.apply( + reportList, + require('./reports/moh-731-2017/moh-731-cohort-report.json') +); +reportList.push.apply( + reportList, + require('./reports/moh-731-2017/moh-731-indicator-report.json') +); + +reportList.push.apply( + reportList, + require('./reports/patient-register-report.json') +); +reportList.push.apply( + reportList, + require('./reports/clinic-calander-report-v2.json') +); +reportList.push.apply( + reportList, + require('./reports/daily-visits-appointment.report.json') +); +reportList.push.apply( + reportList, + require('./reports/clinical-reminder-report.json') +); +reportList.push.apply( + reportList, + require('./reports/dataentry-statistics.json') +); +reportList.push.apply( + reportList, + require('./reports/clinical-overview-visualization-report.json') +); +reportList.push.apply( + reportList, + require('./reports/hiv-summary-monthly-report.json') +); +reportList.push.apply( + reportList, + require('./reports/patient-flow-report.json') +); +reportList.push.apply( + reportList, + require('./reports/clinic-comparator-report.json') +); reportList.push.apply(reportList, require('./reports/labs-report.json')); -reportList.push.apply(reportList, require('./reports/viral-load-monitoring-report.json')); -reportList.push.apply(reportList, require('./reports/medical-history-report.json')); -reportList.push.apply(reportList, require('./reports/clinic-lab-orders-report.json')); -reportList.push.apply(reportList, require('./reports/patient-status-change-tracker-report.json')); -reportList.push.apply(reportList, require('./reports/datasets/pep-dataset-report.json')); -reportList.push.apply(reportList, require('./reports/patient-monthly-care-status.json')); -reportList.push.apply(reportList, require('./reports/patient-daily-care-status.json')); +reportList.push.apply( + reportList, + require('./reports/viral-load-monitoring-report.json') +); +reportList.push.apply( + reportList, + require('./reports/medical-history-report.json') +); +reportList.push.apply( + reportList, + require('./reports/clinic-lab-orders-report.json') +); +reportList.push.apply( + reportList, + require('./reports/patient-status-change-tracker-report.json') +); +reportList.push.apply( + reportList, + require('./reports/datasets/pep-dataset-report.json') +); +reportList.push.apply( + reportList, + require('./reports/patient-monthly-care-status.json') +); +reportList.push.apply( + reportList, + require('./reports/patient-daily-care-status.json') +); reportList.push.apply(reportList, require('./reports/cohort-report.json')); -reportList.push.apply(reportList, require('./reports/patient-care-cascade-report.json')); -reportList.push.apply(reportList, require('./reports/patient-referral-report.json')); +reportList.push.apply( + reportList, + require('./reports/patient-care-cascade-report.json') +); +reportList.push.apply( + reportList, + require('./reports/patient-referral-report.json') +); //etl-factory builds and generates queries dynamically in a generic way using indicator-schema and report-schema json files -module.exports = function () { - var reports = []; - var indicatorsSchema = []; - var indicatorHandlers; - initialize(reportList, indicatorsSchemaDefinition, indicatorHandlersDefinition, patientLevelIndicatorsSchema); - return { - buildPatientListExpression: buildPatientListExpression, - buildIndicatorsSchema: buildIndicatorsSchema, - buildIndicatorsSchemaWithSections: buildIndicatorsSchemaWithSections, - singleReportToSql: singleReportToSql, - resolveIndicators: resolveIndicators, - buildPatientListReportExpression: buildPatientListReportExpression, - buildETLPatientLabOrdersExpression: buildETLPatientLabOrdersExpression, - indicatorsSchema: indicatorsSchema, - reports: reports - }; +module.exports = (function () { + var reports = []; + var indicatorsSchema = []; + var indicatorHandlers; + initialize( + reportList, + indicatorsSchemaDefinition, + indicatorHandlersDefinition, + patientLevelIndicatorsSchema + ); + return { + buildPatientListExpression: buildPatientListExpression, + buildIndicatorsSchema: buildIndicatorsSchema, + buildIndicatorsSchemaWithSections: buildIndicatorsSchemaWithSections, + singleReportToSql: singleReportToSql, + resolveIndicators: resolveIndicators, + buildPatientListReportExpression: buildPatientListReportExpression, + buildETLPatientLabOrdersExpression: buildETLPatientLabOrdersExpression, + indicatorsSchema: indicatorsSchema, + reports: reports + }; - function initialize(_reports, _indicatorsSchema, _indicatorHandlers, _patientLevelIndicatorsSchema) { - reports = _reports; - indicatorsSchema = []; - indicatorsSchema.push.apply(indicatorsSchema, _indicatorsSchema); - indicatorsSchema.push.apply(indicatorsSchema, _patientLevelIndicatorsSchema); - indicatorHandlers = _indicatorHandlers; - // disaggregation fixed indicators - indicatorProcessor.disaggregateFixedIndicators(reports, indicatorsSchema); - // remove duplicates - indicatorsSchema= _.uniq(indicatorsSchema, 'name'); - - } - function getExpression(){ - var expression =s.replaceAll(filterOption.expression,filterOption.options); - _.each(report.disintegrationFilterOptions, function (filterOption) { + function initialize( + _reports, + _indicatorsSchema, + _indicatorHandlers, + _patientLevelIndicatorsSchema + ) { + reports = _reports; + indicatorsSchema = []; + indicatorsSchema.push.apply(indicatorsSchema, _indicatorsSchema); + indicatorsSchema.push.apply( + indicatorsSchema, + _patientLevelIndicatorsSchema + ); + indicatorHandlers = _indicatorHandlers; + // disaggregation fixed indicators + indicatorProcessor.disaggregateFixedIndicators(reports, indicatorsSchema); + // remove duplicates + indicatorsSchema = _.uniq(indicatorsSchema, 'name'); + } + function getExpression() { + var expression = s.replaceAll( + filterOption.expression, + filterOption.options + ); + _.each(report.disintegrationFilterOptions, function (filterOption) {}); + } + function resolveIndicators(reportName, result, requestIndicators) { + _.each(reports, function (report) { + if (report.name === reportName) { + _.each(report.indicatorHandlers, function (handler) { + indicatorHandlers[handler.processor]( + handler.indicators, + result, + requestIndicators + ); }); - } - + } + }); + return result; + } + function buildPatientListExpression(queryParams, successCallback) { + //Check for undefined params + if (queryParams === null || queryParams === undefined) return ''; + //Initialize returned obj + var result = { + whereClause: '', + resource: '' + }; + var whereClause = ''; + //create WhereClause + _.each(indicatorsSchema, function (indicator) { + _.each(queryParams.reportIndicator.split(','), function (indicatorName) { + if (indicator.name === indicatorName) { + if (indicator.expression !== '') { + var indicatorExpression = indicatorProcessor.replaceIndicatorParam( + indicator.expression, + queryParams + ); + whereClause += '(' + indicatorExpression + ') or '; + } + } + }); + }); + var lastIndex = whereClause.lastIndexOf(' or '); + whereClause = whereClause.substring(0, lastIndex); + if (whereClause !== '') result.whereClause = ' and ' + whereClause; + //identify resource/table + _.each(reports, function (report) { + if (report.name === queryParams.reportName) { + result.resource = + report.table['schema'] + '.' + report.table['tableName']; + } + }); + successCallback(result); + } - - function resolveIndicators(reportName, result, requestIndicators) { - _.each(reports, function (report) { - if (report.name === reportName) { - _.each(report.indicatorHandlers, function (handler) { - indicatorHandlers[handler.processor](handler.indicators, result, requestIndicators); - }); - + function buildIndicatorsSchema(queryParams, successCallback) { + //Check for undefined params + if (queryParams === null || queryParams === undefined) return ''; + var result = []; + //Load json schema into the query builder + _.each(reports, function (report) { + if (report.name === queryParams.reportName) { + _.each(report.indicators, function (reportIndicator) { + _.each(indicatorsSchema, function (indicator) { + if (indicator.name === reportIndicator.expression) { + result.push(indicator); } + }); }); - return result; - } + } + }); + successCallback(result); + } - function buildPatientListExpression(queryParams, successCallback) { - //Check for undefined params - if (queryParams === null || queryParams === undefined) return ""; - //Initialize returned obj - var result = { - whereClause: '', - resource: '' - }; - var whereClause = ''; - //create WhereClause - _.each(indicatorsSchema, function (indicator) { - _.each(queryParams.reportIndicator.split(','), function (indicatorName) { - if (indicator.name === indicatorName) { - if (indicator.expression !== '') { - var indicatorExpression = indicatorProcessor.replaceIndicatorParam(indicator.expression, queryParams); - whereClause += '(' + indicatorExpression + ') or '; - } + /** + Returns the report json schema,resolved from request parameter reportName + **/ + function buildIndicatorsSchemaWithSections(queryParams, successCallback) { + //Check for undefined params + var allReportSections; + if (queryParams === null || queryParams === undefined) return ''; + var result = []; + //Load json schema into the query builder + _.each(reports, function (report) { + if (report.name === queryParams.reportName) { + allReportSections = report.sections; + _.each(report.indicators, function (reportIndicator) { + _.each(indicatorsSchema, function (indicator) { + if (indicator.name === reportIndicator.expression) { + //add section infor + try { + if (reportIndicator.section !== undefined) { + var res = { + section_key: reportIndicator.section, + indicator_key: indicator + }; + } else { + var res = { + section_key: '', + indicator_key: indicator + }; } - }); - }); - var lastIndex = whereClause.lastIndexOf(' or '); - whereClause = whereClause.substring(0, lastIndex); - if (whereClause !== '') result.whereClause = ' and ' + whereClause; - //identify resource/table - _.each(reports, function (report) { - if (report.name === queryParams.reportName) { - result.resource = report.table['schema'] + '.' + report.table['tableName']; + result.push(res); + } catch (e) { + result.push(indicator); + } } + }); }); - successCallback(result); - } + } + }); + successCallback([result, allReportSections]); + } - function buildIndicatorsSchema(queryParams, successCallback) { - //Check for undefined params - if (queryParams === null || queryParams === undefined) return ""; - var result = []; - //Load json schema into the query builder - _.each(reports, function (report) { - if (report.name === queryParams.reportName) { - _.each(report.indicators, function (reportIndicator) { - _.each(indicatorsSchema, function (indicator) { - if (indicator.name === reportIndicator.expression) { - result.push(indicator); - } - }); - }); - } - }); - successCallback(result); + function _buildQueryParts(requestParams, reportName, queryPartsArray) { + if (reportName) { + reportName = reportName; + } else { + reportName = requestParams.reportName; } - /** - Returns the report json schema,resolved from request parameter reportName - **/ - function buildIndicatorsSchemaWithSections(queryParams, successCallback) { - //Check for undefined params - var allReportSections; - if (queryParams === null || queryParams === undefined) return ""; - var result = []; - //Load json schema into the query builder - _.each(reports, function (report) { - if (report.name === queryParams.reportName) { - allReportSections = report.sections; - _.each(report.indicators, function (reportIndicator) { - _.each(indicatorsSchema, function (indicator) { - if (indicator.name === reportIndicator.expression) { - //add section infor - try { - if (reportIndicator.section !== undefined) { - var res = { - section_key: reportIndicator.section, - indicator_key: indicator - }; - } else { - - var res = { - section_key: "", - indicator_key: indicator - }; - } - result.push(res); - - } catch (e) { - result.push(indicator); - } - } - }); - }); - } - }); - successCallback([result, allReportSections]); - } + var queryParts; + _.each(reports, function (report) { + if (report.name === reportName) { + var nestedParts = ''; + var tableName = ''; + if ( + report.table.dynamicDataset && + report.table.dynamicDataset !== reportName + ) { + _buildQueryParts( + requestParams, + report.table.dynamicDataset, + queryPartsArray + ); + //get the last item of the array + var n = queryPartsArray.length; + nestedParts = queryPartsArray[n - 1]; + //remove the object from the array + queryPartsArray.splice(n - 1, 1); + } else { + nestedParts = undefined; + } - function _buildQueryParts(requestParams, reportName, queryPartsArray) { - if (reportName) { - reportName = reportName; + if (report.table['tableName'] === '@tableName') { + tableName = requestParams.tableName; } else { - reportName = requestParams.reportName; + tableName = report.table['tableName']; } + var queryParts = { + columns: indicatorsToColumns( + report, + requestParams.countBy, + requestParams + ), + concatColumns: concatColumnsToColumns(report), + table: report.table['schema'] + '.' + tableName, + alias: report.table['alias'], + indexExpression: report.table['indexExpression'] || null, + nestedParts: nestedParts, + joins: joinsToSql(report.joins, requestParams), + where: filtersToSql( + requestParams.whereParams, + report.parameters, + report.filters + ), + group: groupClauseToSql( + report.groupClause, + requestParams.groupBy, + report.parameters + ), + having: filtersToSql( + requestParams.whereParams, + report.parameters, + report.having + ), + order: orderByToSql(report), + offset: requestParams.offset, + limit: requestParams.limit + }; + queryPartsArray.push(queryParts); + } + }); + } + + function singleReportToSql(requestParams, reportName) { + if (requestParams === null || requestParams === undefined) return ''; + var queryPartsArray = []; + _buildQueryParts(requestParams, reportName, queryPartsArray); + return queryPartsArray; + } + + function orderByToSql(report) { + var order = []; + if (!report.orderBy) return null; + _.each(report.orderBy, function (orderBy) { + order.push({ + column: orderBy.column, + asc: orderBy.order.toLowerCase() === 'asc' + }); + }); + return order; + } - var queryParts; - _.each(reports, function (report) { - - if (report.name === reportName) { - var nestedParts = ''; - var tableName = ''; - if (report.table.dynamicDataset && report.table.dynamicDataset !== reportName) { - _buildQueryParts(requestParams, report.table.dynamicDataset, queryPartsArray); - //get the last item of the array - var n = queryPartsArray.length; - nestedParts = queryPartsArray[n - 1]; - //remove the object from the array - queryPartsArray.splice(n - 1, 1); + //converts a set of indicators into sql columns + function indicatorsToColumns(report, countBy, requestParam) { + // console.log('request parameters', requestParam); + var result = []; + //converts a set of supplementColumns into sql columns + _.each(supplementColumnsToColumns(report), function (column) { + result.push(column); + }); + //converts set of indicators to sql columns + _.each(report.indicators, function (singleIndicator) { + _.each(indicatorsSchema, function (indicator) { + if (requestParam.requestIndicators) { + //compare request params indicator list corresponds to the singleIndicator + _.each(requestParam.requestIndicators.split(','), function ( + requestIndicatorName + ) { + if (indicator.name === requestIndicatorName) { + if (indicator.name === singleIndicator.expression) { + //Determine indicator type, whether it is derived or an independent indicator + if (singleIndicator.sql.match(/\[(.*?)\]/)) { + result.push( + processesDerivedIndicator( + report, + singleIndicator, + indicator, + requestParam + ) + ); } else { - nestedParts = undefined; + var column = + singleIndicator.sql + ' as ' + singleIndicator.label; + //check if indicator expression has endDate and startDate parameters + var indicatorExpression = indicatorProcessor.replaceIndicatorParam( + indicator.expression, + requestParam + ); + column = column.replace('$expression', indicatorExpression); + result.push(column); } + } + } + }); + } else { + if (indicator.name === singleIndicator.expression) { + //Determine indicator type, whether it is derived or an independent indicator + if (singleIndicator.sql.match(/\[(.*?)\]/)) { + result.push( + processesDerivedIndicator( + report, + singleIndicator, + indicator, + requestParam + ) + ); + } else { + var column = singleIndicator.sql + ' as ' + indicator.name; + //check if indicator expression has endDate and startDate parameters + var indicatorExpression = indicatorProcessor.replaceIndicatorParam( + indicator.expression, + requestParam + ); + column = column.replace('$expression', indicatorExpression); + result.push(column); + } + } + } + }); + }); + // add dynamically derived indicators + var dynamicIndicators = indicatorProcessor.disaggregateDynamicIndicators( + report, + indicatorsSchema, + requestParam + ); + result.push.apply(result, dynamicIndicators); + return result; + } - if(report.table['tableName'] === '@tableName'){ - tableName = requestParams.tableName; - } else{ - tableName = report.table['tableName']; - } - var queryParts = { - columns: indicatorsToColumns(report, requestParams.countBy, requestParams), - concatColumns: concatColumnsToColumns(report), - table: report.table['schema'] + '.' + tableName, - alias: report.table['alias'], - indexExpression: report.table['indexExpression'] || null, - nestedParts: nestedParts, - joins: joinsToSql(report.joins, requestParams), - where: filtersToSql(requestParams.whereParams, report.parameters, report.filters), - group: groupClauseToSql(report.groupClause, requestParams.groupBy, report.parameters), - having: filtersToSql(requestParams.whereParams, report.parameters, report.having), - order: orderByToSql(report), - offset: requestParams.offset, - limit: requestParams.limit - }; - queryPartsArray.push(queryParts); + //converts set of derived indicators to sql columns + function processesDerivedIndicator( + report, + derIndicator, + indicator, + requestParam + ) { + var reg = /[\[\]']/g; //regex [] indicator + var matches = []; + var derivedIndicator = _.assign({}, derIndicator); + derivedIndicator.sql.replace(/\[(.*?)\]/g, function (g0, g1) { + matches.push(g1); + }); + derivedIndicator.sql = derivedIndicator.sql.replace(reg, ''); + _.each(matches, function (indicatorKey) { + _.each(report.indicators, function (singleIndicator) { + if (indicatorKey === singleIndicator.expression) { + _.each(indicatorsSchema, function (indicator) { + if (indicator.name === indicatorKey) { + var column = singleIndicator.sql; + // console.log('Derived Indicator request param', requestParam); + var indicatorExpression = indicatorProcessor.replaceIndicatorParam( + indicator.expression, + requestParam + ); + column = column.replace('$expression', indicatorExpression); + derivedIndicator.sql = derivedIndicator.sql.replace( + indicatorKey, + column + ); } - }); - } + }); + } + }); + }); + // console.log('track derived indicator', derivedIndicator.sql); + return derivedIndicator.sql + ' as ' + indicator.name; + } - function singleReportToSql(requestParams, reportName) { - if (requestParams === null || requestParams === undefined) return ""; - var queryPartsArray = []; - _buildQueryParts(requestParams, reportName, queryPartsArray); - return queryPartsArray; - } + //converts a set of supplement columns of type single into sql columns + function supplementColumnsToColumns(report) { + var result = []; + _.each(report.supplementColumns, function (supplementColumn) { + if (supplementColumn.type === 'single') { + var column = supplementColumn.sql + ' as ' + supplementColumn.label; + result.push(column); + } else if (supplementColumn.type === 'all') { + var column = supplementColumn.sql; + result.push(column); + } + }); + return result; + } - function orderByToSql(report) { - var order = []; - if (!report.orderBy) return null; - _.each(report.orderBy, function (orderBy) { - order.push({ - column: orderBy.column, - asc: (orderBy.order.toLowerCase() === "asc") - }); - }); - return order; - } + //converts a set of supplement columns of type multiple into sql columns + function concatColumnsToColumns(report) { + var result = ''; + _.each(report.supplementColumns, function (supplementColumn) { + if (supplementColumn.type === 'multiple') { + var column = supplementColumn.sql + ' as ' + supplementColumn.label; + result += column; + result += ', '; + } + }); + var lastIndex = result.lastIndexOf(','); + result = result.substring(0, lastIndex); + return result; + } + //converts an array of tables into sql + function joinsToSql(joins, requestParams) { + var result = []; + _.each(joins, function (join) { + if (join.tableName) { + var r = [ + join['schema'] + '.' + join['tableName'], + join['alias'], + join['joinExpression'], + join['joinType'] + ]; + var joinOject = { + schema: join.schema, + tableName: join.tableName, + alias: join.alias, + joinExpression: join.joinExpression, + joinType: join.joinType + }; + result.push(joinOject); + } else { + var queryParts = singleReportToSql(requestParams, join.dynamicDataset); + // console.log('show the query parts here:', queryParts.length); + var joinOject = { + schema: join.schema, + tableName: join.tableName, + alias: join.alias, + joinExpression: join.joinExpression, + joinType: join.joinType, + joinedQuerParts: queryParts[0] + }; + // console.log('testing dynamicDataset', joinOject); + result.push(joinOject); + //var r = [join['schema'] + '.' + join['tableName'], join['alias'], join['joinExpression'], join['joinType']]; + } + }); + return result; + } - + //converts an array of group clause into squel consumable + function groupClauseToSql(groupClauses, groupBy, reportParams) { + var result = []; + _.each(groupBy.split(','), function (by) { + _.each(groupClauses, function (groupClause) { + if (groupClause['parameter'] === by || groupClause['processForce']) { + _.each(reportParams, function (reportParam) { + if (reportParam['name'] === groupClause['parameter']) { + _.each(reportParam['defaultValue'], function (value) { + result.push(value['expression']); + }); + } + }); + } + }); + }); + return result; + } - //converts a set of indicators into sql columns - function indicatorsToColumns(report, countBy, requestParam) { - // console.log('request parameters', requestParam); - var result = []; - //converts a set of supplementColumns into sql columns - _.each(supplementColumnsToColumns(report), function (column) { - result.push(column); - }); - //converts set of indicators to sql columns - _.each(report.indicators, function (singleIndicator) { - _.each(indicatorsSchema, function (indicator) { - if (requestParam.requestIndicators) { - //compare request params indicator list corresponds to the singleIndicator - _.each(requestParam.requestIndicators.split(','), function (requestIndicatorName) { - if (indicator.name === requestIndicatorName) { - if (indicator.name === singleIndicator.expression) { - //Determine indicator type, whether it is derived or an independent indicator - if (singleIndicator.sql.match(/\[(.*?)\]/)) { - result.push(processesDerivedIndicator(report, singleIndicator, indicator, requestParam)); - } else { - var column = singleIndicator.sql + ' as ' + singleIndicator.label; - //check if indicator expression has endDate and startDate parameters - var indicatorExpression = indicatorProcessor.replaceIndicatorParam(indicator.expression, requestParam); - column = column.replace('$expression', indicatorExpression); - result.push(column); - } - } - } - }); - } else { - if (indicator.name === singleIndicator.expression) { - //Determine indicator type, whether it is derived or an independent indicator - if (singleIndicator.sql.match(/\[(.*?)\]/)) { - result.push(processesDerivedIndicator(report, singleIndicator, indicator, requestParam)); - } else { - var column = singleIndicator.sql + ' as ' + indicator.name; - //check if indicator expression has endDate and startDate parameters - var indicatorExpression = indicatorProcessor.replaceIndicatorParam(indicator.expression, requestParam); - column = column.replace('$expression', indicatorExpression); - result.push(column); - } - } - } - }); - }); - // add dynamically derived indicators - var dynamicIndicators = indicatorProcessor.disaggregateDynamicIndicators(report, indicatorsSchema, requestParam); - result.push.apply(result,dynamicIndicators); - return result; + function _getMatchingWhereExpression(whereParams, reportFilter) { + var matchingWhereExpression = _.find(whereParams, function (whereParam) { + if ( + (whereParam['name'] === reportFilter['parameter'] && + whereParam['value']) || + reportFilter['processForce'] === true + ) { + return whereParam; + } + }); + return matchingWhereExpression; + } - } + //converts an array of filters into sql + function filtersToSql(whereParams, reportParams, reportFilters) { + var result = []; + var expression = ''; + var parameters = []; + // console.log('Report/Json Params', reportParams); + // console.log('Report/Filters', reportFilters); + // console.log('Web/Client Params', whereParams); + _.each(reportFilters, function (reportFilter) { + // console.log('final report--->', reportFilter); + //search in the web/Client params to see if there is a matching Param + //Process an array of Parameters in the report filters + var reportFilterParam = reportFilter['parameter']; + var reportFilterParamArray = []; + if (s.include(reportFilterParam, ',')) { + reportFilterParamArray = reportFilterParam.split(','); + } + var matchingWhereExpression; - //converts set of derived indicators to sql columns - function processesDerivedIndicator(report, derIndicator, indicator, requestParam) { - var reg = /[\[\]']/g; //regex [] indicator - var matches = []; - var derivedIndicator = _.assign({},derIndicator); - derivedIndicator.sql.replace(/\[(.*?)\]/g, function (g0, g1) { - matches.push(g1); - }); - derivedIndicator.sql = derivedIndicator.sql.replace(reg, ''); - _.each(matches, function (indicatorKey) { - _.each(report.indicators, function (singleIndicator) { - if (indicatorKey === singleIndicator.expression) { - _.each(indicatorsSchema, function (indicator) { - if (indicator.name === indicatorKey) { - var column = singleIndicator.sql; - // console.log('Derived Indicator request param', requestParam); - var indicatorExpression = indicatorProcessor.replaceIndicatorParam(indicator.expression, requestParam); - column = column.replace('$expression', indicatorExpression); - derivedIndicator.sql = derivedIndicator.sql.replace(indicatorKey, column); - } - }); - } + if (reportFilterParamArray.length > 1) { + for (var i in reportFilterParamArray) { + var dummyReportFilter = { + parameter: reportFilterParamArray[i], + processForce: reportFilter['processForce'] + }; + matchingWhereExpression = _getMatchingWhereExpression( + whereParams, + dummyReportFilter + ); + if (!_.isUndefined(matchingWhereExpression) && i === '0') { + expression += reportFilter['expression']; + expression += ' and '; + } + if (!_.isUndefined(matchingWhereExpression)) { + var matchingReportParam = _.find(reportParams, function ( + reportParam + ) { + if (reportParam['name'] === matchingWhereExpression['name']) + return reportParam; }); - }); - // console.log('track derived indicator', derivedIndicator.sql); - return derivedIndicator.sql + ' as ' + indicator.name; - } - //converts a set of supplement columns of type single into sql columns - function supplementColumnsToColumns(report) { - var result = []; - _.each(report.supplementColumns, function (supplementColumn) { - if (supplementColumn.type === 'single') { - var column = supplementColumn.sql + ' as ' + supplementColumn.label; - result.push(column); - } else if (supplementColumn.type === 'all') { - var column = supplementColumn.sql - result.push(column); + if ( + !_.isUndefined(matchingReportParam) && + reportFilter['processForce'] !== true + ) { + parameters.push(matchingWhereExpression['value']); } - }); - return result; - } + } + } + } else { + matchingWhereExpression = _getMatchingWhereExpression( + whereParams, + reportFilter + ); + if (!_.isUndefined(matchingWhereExpression)) { + expression += reportFilter['expression']; + expression += ' and '; - //converts a set of supplement columns of type multiple into sql columns - function concatColumnsToColumns(report) { - var result = ''; - _.each(report.supplementColumns, function (supplementColumn) { - if (supplementColumn.type === 'multiple') { - var column = supplementColumn.sql + ' as ' + supplementColumn.label; - result += column; - result += ', '; - } - }); - var lastIndex = result.lastIndexOf(','); - result = result.substring(0, lastIndex); - return result; - } + var matchingReportParam = _.find(reportParams, function ( + reportParam + ) { + if (reportParam['name'] === matchingWhereExpression['name']) + return reportParam; + }); + // console.log('final params-report', matchingReportParam); + // console.log('final params-where', matchingWhereExpression); + if ( + !_.isUndefined(matchingReportParam) && + reportFilter['processForce'] !== true + ) { + parameters.push(matchingWhereExpression['value']); + } + } + } + }); + var lastIndex = expression.lastIndexOf('and'); + expression = expression.substring(0, lastIndex); + result.push(expression); + // console.log('final results', result); + // console.log('final paras', parameters); + result.push.apply(result, parameters); - //converts an array of tables into sql - function joinsToSql(joins, requestParams) { - var result = []; - _.each(joins, function (join) { - if (join.tableName) { - var r = [join['schema'] + '.' + join['tableName'], join['alias'], join['joinExpression'], join['joinType']]; - var joinOject = { - schema: join.schema, - tableName: join.tableName, - alias: join.alias, - joinExpression: join.joinExpression, - joinType: join.joinType - } - result.push(joinOject); - } else { - var queryParts = singleReportToSql(requestParams, join.dynamicDataset) - // console.log('show the query parts here:', queryParts.length); - var joinOject = { - schema: join.schema, - tableName: join.tableName, - alias: join.alias, - joinExpression: join.joinExpression, - joinType: join.joinType, - joinedQuerParts: queryParts[0] - }; - // console.log('testing dynamicDataset', joinOject); - result.push(joinOject); - //var r = [join['schema'] + '.' + join['tableName'], join['alias'], join['joinExpression'], join['joinType']]; - } - }); - return result; - } + return result; + } - //converts an array of group clause into squel consumable - function groupClauseToSql(groupClauses, groupBy, reportParams) { - var result = []; - _.each(groupBy.split(','), function (by) { - _.each(groupClauses, function (groupClause) { - if (groupClause["parameter"] === by || groupClause["processForce"]) { - _.each(reportParams, function (reportParam) { - if (reportParam["name"] === groupClause["parameter"]) { - _.each(reportParam["defaultValue"], function (value) { - result.push(value["expression"]); - }); - } - }); + //converts a set of indicators into sql columns + function indicatorsToFilter(report, requestParam) { + // console.log('request parameters', requestParam); + var result = ''; + //converts set of indicators to sql columns + _.each(report.indicators, function (singleIndicator) { + _.each(indicatorsSchema, function (indicator) { + if (requestParam.requestIndicators) { + //compare request params indicator list corresponds to the singleIndicator + _.each(requestParam.requestIndicators.split(','), function ( + requestIndicatorName + ) { + if (indicator.name === requestIndicatorName) { + if (indicator.name === singleIndicator.expression) { + //Determine indicator type, whether it is derived or an independent indicator + if (singleIndicator.sql.match(/\[(.*?)\]/)) { + //result.push(processesDerivedIndicator(report, singleIndicator, indicator)); + } else { + //check if indicator expression has endDate and startDate parameters + var indicatorExpression = indicatorProcessor.replaceIndicatorParam( + indicator.expression, + requestParam + ); + result += '(' + indicatorExpression + ') or '; } - }); - }); - return result; - } - - - function _getMatchingWhereExpression(whereParams, reportFilter) { - - var matchingWhereExpression = _.find(whereParams, function (whereParam) { - if ((whereParam["name"] === reportFilter["parameter"] && - whereParam["value"]) || reportFilter["processForce"] === true) { - return whereParam; + } } + }); + } + }); + }); + var lastIndex = result.lastIndexOf(' or '); + result = result.substring(0, lastIndex); + return result; + } - }); - return matchingWhereExpression; - } + function reportWhereClauseToFilter(queryParams, reportName) { + var reportParams = queryParams; + // + var whereClause = ''; + var table = ''; + _.each(reports, function (report) { + if (report.name === reportName) { + // reportParams.reportName = reportName; + var reportWhereClause = filtersToSql( + reportParams.whereParams, + report.parameters, + report.filters + ); + if (report.table.schema !== '' && report.table.table !== '') { + table = report.table['schema'] + '.' + report.table['tableName']; + } + var indicatorWhereClause = indicatorsToFilter(report, reportParams); + if (reportWhereClause[0]) { + reportWhereClause[0] = + reportWhereClause[0] + ' and ' + indicatorWhereClause; + } else { + reportWhereClause[0] = indicatorWhereClause; + } + if (indicatorWhereClause) whereClause = reportWhereClause; + } + }); - //converts an array of filters into sql - function filtersToSql(whereParams, reportParams, reportFilters) { - var result = []; - var expression = ''; - var parameters = []; - // console.log('Report/Json Params', reportParams); - // console.log('Report/Filters', reportFilters); - // console.log('Web/Client Params', whereParams); - _.each(reportFilters, function (reportFilter) { - - // console.log('final report--->', reportFilter); - //search in the web/Client params to see if there is a matching Param - //Process an array of Parameters in the report filters - var reportFilterParam = reportFilter["parameter"]; - var reportFilterParamArray = []; - if (s.include(reportFilterParam, ',')) { - reportFilterParamArray = reportFilterParam.split(','); - } - var matchingWhereExpression; - - if (reportFilterParamArray.length > 1) { - - for (var i in reportFilterParamArray) { - var dummyReportFilter = { - parameter: reportFilterParamArray[i], - processForce: reportFilter["processForce"] - }; - matchingWhereExpression = _getMatchingWhereExpression(whereParams, dummyReportFilter); - if (!_.isUndefined(matchingWhereExpression) && i === '0') { - expression += reportFilter["expression"]; - expression += ' and '; - } - if (!_.isUndefined(matchingWhereExpression)) { - var matchingReportParam = _.find(reportParams, function (reportParam) { - if (reportParam["name"] === matchingWhereExpression["name"]) - return reportParam; - }); - - if (!_.isUndefined(matchingReportParam) && reportFilter["processForce"] !== true) { - parameters.push(matchingWhereExpression["value"]); - } - } - } + return { + whereClause: whereClause, + table: table + }; + } - } else { - matchingWhereExpression = _getMatchingWhereExpression(whereParams, reportFilter); - if (!_.isUndefined(matchingWhereExpression)) { - expression += reportFilter["expression"]; - expression += ' and '; - - var matchingReportParam = _.find(reportParams, function (reportParam) { - if (reportParam["name"] === matchingWhereExpression["name"]) - return reportParam; - }); - // console.log('final params-report', matchingReportParam); - // console.log('final params-where', matchingWhereExpression); - if (!_.isUndefined(matchingReportParam) && reportFilter["processForce"] !== true) { - parameters.push(matchingWhereExpression["value"]); - } - } - } - }); - var lastIndex = expression.lastIndexOf('and'); - expression = expression.substring(0, lastIndex); - result.push(expression); - // console.log('final results', result); - // console.log('final paras', parameters); - result.push.apply(result, parameters); - - return result; + function dynamicDataSetToFilter(queryParams, reportName) { + var query = ''; + var param = []; + if (reportName !== undefined) { + var resource = reportWhereClauseToFilter(queryParams, reportName); + var filter = resource.whereClause; + if (filter) { + query += filter[0] + ' and '; + filter.shift(); + param.push.apply(param, filter); + } + var lastIndex = query.lastIndexOf(' and '); + query = query.substring(0, lastIndex); } + return { + query: query, + params: param + }; + } - //converts a set of indicators into sql columns - function indicatorsToFilter(report, requestParam) { - // console.log('request parameters', requestParam); - var result = ''; - //converts set of indicators to sql columns - _.each(report.indicators, function (singleIndicator) { - _.each(indicatorsSchema, function (indicator) { - if (requestParam.requestIndicators) { - //compare request params indicator list corresponds to the singleIndicator - _.each(requestParam.requestIndicators.split(','), function (requestIndicatorName) { - if (indicator.name === requestIndicatorName) { - if (indicator.name === singleIndicator.expression) { - //Determine indicator type, whether it is derived or an independent indicator - if (singleIndicator.sql.match(/\[(.*?)\]/)) { - //result.push(processesDerivedIndicator(report, singleIndicator, indicator)); - } else { - //check if indicator expression has endDate and startDate parameters - var indicatorExpression = indicatorProcessor.replaceIndicatorParam(indicator.expression, requestParam); - result += '(' + indicatorExpression + ') or '; - } - } - } - }); - } - }); + function getAllDatasets(reportName, allReports) { + _.each(reports, function (report) { + if (report.name === reportName) { + _.each(report.joins, function (join) { + if (join.dynamicDataset) { + allReports.push(join.dynamicDataset); + getAllDatasets(join.dynamicDataset, allReports); + } }); - var lastIndex = result.lastIndexOf(' or '); - result = result.substring(0, lastIndex); - return result; - } - - function reportWhereClauseToFilter(queryParams, reportName) { - var reportParams = queryParams; - // - var whereClause = ''; - var table = ''; - _.each(reports, function (report) { - - if (report.name === reportName) { - // reportParams.reportName = reportName; - var reportWhereClause = filtersToSql(reportParams.whereParams, report.parameters, report.filters); - if (report.table.schema !== '' && report.table.table !== '') { - table = report.table['schema'] + '.' + report.table['tableName']; - } - var indicatorWhereClause = indicatorsToFilter(report, reportParams); - if (reportWhereClause[0]) { - reportWhereClause[0] = reportWhereClause[0] + ' and ' + indicatorWhereClause; - } else { - reportWhereClause[0] = indicatorWhereClause; - } - if (indicatorWhereClause) whereClause = reportWhereClause; - + if (report.table.dynamicDataset) { + allReports.push(report.table.dynamicDataset); + getAllDatasets(report.table.dynamicDataset, allReports); + } + } + }); + return allReports; + } + function buildQueryAndParams(reportName, queryParams) { + var query = ''; + var param = []; + _.each(reports, function (report) { + if (report.name === reportName) { + var filter = dynamicDataSetToFilter(queryParams, report.name); + if (filter.query !== '') { + query += filter.query + ' and '; + param.push.apply(param, filter.params); + } + _.each(report.joins, function (join) { + if (join.dynamicDataset) { + var filter = buildQueryAndParams(join.dynamicDataset, queryParams); + if (filter.query !== '') { + query += filter.query + ' and '; + param.push.apply(param, filter.params); } + } }); + if (report.table.dynamicDataset) { + var filter = buildQueryAndParams( + report.table.dynamicDataset, + queryParams, + query, + param + ); + if (filter.query !== '') { + query += filter.query + ' and '; + param.push.apply(param, filter.params); + } + } + } + }); + var lastIndex = query.lastIndexOf(' and '); + query = query.substring(0, lastIndex); + return { + query: query, + params: param + }; + } - return { - whereClause: whereClause, - table: table - - }; - } - - function dynamicDataSetToFilter(queryParams, reportName) { - var query = ''; - var param = []; - if (reportName !== undefined) { - var resource = reportWhereClauseToFilter(queryParams, reportName); - var filter = resource.whereClause; - if (filter) { - query += filter[0] + ' and '; - filter.shift(); - param.push.apply(param, filter); - } - var lastIndex = query.lastIndexOf(' and '); - query = query.substring(0, lastIndex); + function generateCohortFilters(queryParams, reportName) { + var query = ''; + var param = []; + if (reportName !== undefined) { + _.each(reports, function (report) { + if (report.name === reportName) { + var reportWhereClause = filtersToSql( + queryParams.whereParams, + report.parameters, + report.filters + ); + if (reportWhereClause) { + query += reportWhereClause[0]; + reportWhereClause.shift(); + param.push.apply(param, reportWhereClause); + } } - return { - query: query, - params: param - }; + }); } + return { + query: query, + params: param + }; + } - function getAllDatasets(reportName, allReports) { - _.each(reports, function (report) { - if (report.name === reportName) { - _.each(report.joins, function (join) { - if (join.dynamicDataset) { - allReports.push(join.dynamicDataset); - getAllDatasets(join.dynamicDataset, allReports); - } - }); - if (report.table.dynamicDataset) { - allReports.push(report.table.dynamicDataset); - getAllDatasets(report.table.dynamicDataset, allReports); - } - } - }); - return allReports; - } + function breakDownDerivedIndicator(ri) { + var matches = []; + var reportIndicator = _.assign({}, ri); + reportIndicator.sql.replace(/\[(.*?)\]/g, function (g0, g1) { + matches.push(g1); + }); + return matches; + } - function buildQueryAndParams(reportName, queryParams) { - var query = ''; - var param = []; - _.each(reports, function (report) { - if (report.name === reportName) { - var filter = dynamicDataSetToFilter(queryParams, report.name); - if (filter.query !== '') { - query += filter.query + ' and '; - param.push.apply(param, filter.params); - } - _.each(report.joins, function (join) { - if (join.dynamicDataset) { - var filter = buildQueryAndParams(join.dynamicDataset, queryParams); - if (filter.query !== '') { - query += filter.query + ' and '; - param.push.apply(param, filter.params); - } - } - }); - if (report.table.dynamicDataset) { - var filter = buildQueryAndParams(report.table.dynamicDataset, queryParams, query, param); - if (filter.query !== '') { + function generatePatientListFilter(queryParams) { + var query = ''; + var param = []; + var dataSets = getAllDatasets(queryParams.reportName, [ + queryParams.reportName + ]); + _.each(dataSets, function (dataSet) { + _.each(reports, function (report) { + if (report.name === dataSet) { + _.each(report.indicators, function (singleIndicator) { + _.each(indicatorsSchema, function (indicator) { + if (queryParams.requestIndicators) { + //compare request params indicator list corresponds to the singleIndicator + _.each(queryParams.requestIndicators.split(','), function ( + requestIndicatorName + ) { + if (indicator.name === requestIndicatorName) { + if (indicator.name === singleIndicator.expression) { + // handle derived indicators + var numeratorDenominator = breakDownDerivedIndicator( + singleIndicator + ); + if (numeratorDenominator.length > 0) { + queryParams.requestIndicators = queryParams.requestIndicators + .split(singleIndicator.expression) + .join(numeratorDenominator[0]); + } + var filter = dynamicDataSetToFilter( + queryParams, + report.name + ); + if (filter.query !== '') { query += filter.query + ' and '; param.push.apply(param, filter.params); + // generateCohortFilters + if (report.table.dynamicDataset) { + var cohortFilter = generateCohortFilters( + queryParams, + report.table.dynamicDataset + ); + if (cohortFilter.query !== '') { + query += cohortFilter.query + ' and '; + param.push.apply(param, cohortFilter.params); + } + } + } } - } - } - }); - - var lastIndex = query.lastIndexOf(' and '); - query = query.substring(0, lastIndex); - return { - query: query, - params: param - }; - - } + } + }); + } + }); + }); + } + }); + }); + var lastIndex = query.lastIndexOf(' and '); + query = query.substring(0, lastIndex); + return { + query: query, + params: param + }; + } - function generateCohortFilters(queryParams, reportName) { - var query = ''; - var param = []; - if (reportName !== undefined) { - _.each(reports, function (report) { - if (report.name === reportName) { - var reportWhereClause = filtersToSql(queryParams.whereParams, report.parameters, report.filters); - if (reportWhereClause) { - query += reportWhereClause[0]; - reportWhereClause.shift(); - param.push.apply(param, reportWhereClause); - } - } + function getReportDataSet(queryParams) { + var reportName = queryParams.reportName; + var extraPatientListColumns = [ + 'case when (timestampdiff(day,t1.vl_order_date,now()) between 0 and 14) and (t1.vl_1_date is null or t1.vl_order_date > t1.vl_1_date) then true else false end as has_pending_vl_test', + 'date_format(t1.enrollment_date,"%d-%m-%Y") as enrollment_date', + 'date_format(t1.hiv_start_date,"%d-%m-%Y") as hiv_start_date', + 't1.arv_start_location', + 'date_format(t1.arv_first_regimen_start_date,"%d-%m-%Y") as arv_first_regimen_start_date', + 'date_format(t1.arv_start_date,"%d-%m-%Y") as cur_regimen_arv_start_date', + 't1.cur_arv_line', + 't1.cur_arv_meds', + 't1.arv_first_regimen', + 't1.vl_1', + 'date_format(t1.vl_1_date,"%d-%m-%Y") as vl_1_date', + 'date_format(t1.rtc_date,"%d-%m-%Y") as rtc_date', + 'date_format(t1.tb_prophylaxis_start_date,"%d-%m-%Y") as tb_prophylaxis_start_date', + 'date_format(t1.pcp_prophylaxis_start_date,"%d-%m-%Y") as pcp_prophylaxis_start_date', + 'date_format(t1.tb_tx_start_date,"%d-%m-%Y") as tb_tx_start_date', + 't1.encounter_type', + 'date_format(t1.encounter_datetime,"%d-%m-%Y") as encounter_datetime', + 'date_format(t1.death_date,"%d-%m-%Y") as death_date', + 't1.out_of_care', + 't1.transfer_out', + 't1.patient_care_status', + 't1.prev_rtc_date', + 't1.prev_encounter_datetime_hiv' + ]; + var dataSets = getAllDatasets(queryParams.reportName, [ + queryParams.reportName + ]); + _.each(dataSets, function (dataSet) { + _.each(reports, function (report) { + if (report.name === dataSet) { + _.each(report.indicators, function (singleIndicator) { + _.each(queryParams.requestIndicators.split(','), function ( + requestIndicatorName + ) { + if (singleIndicator.expression === requestIndicatorName) { + // handle dates table + if (report.patientListColumns) + extraPatientListColumns = report.patientListColumns; + if (report.table.tableName !== 'flat_hiv_summary') + reportName = dataSet; + } }); + }); } - return { - query: query, - params: param - }; - } + }); + }); + return { + reportName: reportName, + extraPatientListColumns: extraPatientListColumns + }; + } - function breakDownDerivedIndicator(ri) { - var matches = []; - var reportIndicator = _.assign({},ri); - reportIndicator.sql.replace(/\[(.*?)\]/g, function (g0, g1) { - matches.push(g1); + function buildPatientListReportExpression(queryParams) { + var result = { + whereClause: [], + resource: '', + queryParts: [] + }; + if (queryParams === null || queryParams === undefined) return ''; + var reportDataSet = getReportDataSet(queryParams); + queryParams.reportName = reportDataSet.reportName; + var filter = generatePatientListFilter(queryParams); + result.whereClause.push(filter.query); + result.whereClause.push.apply(result.whereClause, filter.params); + result.resource = filter.table; + _.each(reports, function (report) { + if (report.name === queryParams.reportName) { + var join = joinsToSql(report.joins, queryParams) || []; + join.push({ + schema: 'amrs', + tableName: 'person_name', + alias: 'person_name', + joinExpression: + 't1.person_id = person_name.person_id and (person_name.voided is null || person_name.voided = 0)', + joinType: 'INNER JOIN' }); - return matches - } - - function generatePatientListFilter(queryParams) { - var query = ''; - var param = []; - var dataSets = getAllDatasets(queryParams.reportName, [queryParams.reportName]); - _.each(dataSets, function (dataSet) { - _.each(reports, function (report) { - if (report.name === dataSet) { - _.each(report.indicators, function (singleIndicator) { - _.each(indicatorsSchema, function (indicator) { - if (queryParams.requestIndicators) { - //compare request params indicator list corresponds to the singleIndicator - _.each(queryParams.requestIndicators.split(','), function (requestIndicatorName) { - if (indicator.name === requestIndicatorName) { - if (indicator.name === singleIndicator.expression) { - // handle derived indicators - var numeratorDenominator = breakDownDerivedIndicator(singleIndicator); - if (numeratorDenominator.length > 0) { - queryParams.requestIndicators = queryParams.requestIndicators - .split(singleIndicator.expression) - .join(numeratorDenominator[0]); - } - var filter = dynamicDataSetToFilter(queryParams, report.name); - if (filter.query !== '') { - query += filter.query + ' and '; - param.push.apply(param, filter.params); - // generateCohortFilters - if (report.table.dynamicDataset) { - var cohortFilter = generateCohortFilters(queryParams, - report.table.dynamicDataset); - if (cohortFilter.query !== '') { - query += cohortFilter.query + ' and '; - param.push.apply(param, cohortFilter.params); - } - } - } - } - } - }); - } - }); - }); - } - }); + join.push({ + schema: 'amrs', + tableName: 'patient_identifier', + alias: 'id', + joinExpression: 't1.person_id = id.patient_id', + joinType: 'LEFT OUTER JOIN' }); - var lastIndex = query.lastIndexOf(' and '); - query = query.substring(0, lastIndex); - return { - query: query, - params: param - }; - } - - function getReportDataSet(queryParams) { - var reportName = queryParams.reportName; - var extraPatientListColumns = [ - 'case when (timestampdiff(day,t1.vl_order_date,now()) between 0 and 14) and (t1.vl_1_date is null or t1.vl_order_date > t1.vl_1_date) then true else false end as has_pending_vl_test', - 'date_format(t1.enrollment_date,"%d-%m-%Y") as enrollment_date', - 'date_format(t1.hiv_start_date,"%d-%m-%Y") as hiv_start_date', - 't1.arv_start_location', - 'date_format(t1.arv_first_regimen_start_date,"%d-%m-%Y") as arv_first_regimen_start_date', - 'date_format(t1.arv_start_date,"%d-%m-%Y") as cur_regimen_arv_start_date', - 't1.cur_arv_line', - 't1.cur_arv_meds', - 't1.arv_first_regimen', - 't1.vl_1', - 'date_format(t1.vl_1_date,"%d-%m-%Y") as vl_1_date', - 'date_format(t1.rtc_date,"%d-%m-%Y") as rtc_date', - 'date_format(t1.tb_prophylaxis_start_date,"%d-%m-%Y") as tb_prophylaxis_start_date', - 'date_format(t1.pcp_prophylaxis_start_date,"%d-%m-%Y") as pcp_prophylaxis_start_date', - 'date_format(t1.tb_tx_start_date,"%d-%m-%Y") as tb_tx_start_date', - 't1.encounter_type', - 'date_format(t1.encounter_datetime,"%d-%m-%Y") as encounter_datetime', - 'date_format(t1.death_date,"%d-%m-%Y") as death_date', - 't1.out_of_care', - 't1.transfer_out', - 't1.patient_care_status', - 't1.prev_rtc_date', - 't1.prev_encounter_datetime_hiv' - ]; - var dataSets = getAllDatasets(queryParams.reportName, [queryParams.reportName]); - _.each(dataSets, function (dataSet) { - _.each(reports, function (report) { - if (report.name === dataSet) { - _.each(report.indicators, function (singleIndicator) { - _.each(queryParams.requestIndicators.split(','), function (requestIndicatorName) { - if (singleIndicator.expression === requestIndicatorName) { - // handle dates table - if (report.patientListColumns) extraPatientListColumns = report.patientListColumns; - if (report.table.tableName !== 'flat_hiv_summary') reportName = dataSet; - } - }); - - }); - } - }); + join.push({ + schema: 'amrs', + tableName: 'person', + alias: 'person', + joinExpression: 't1.person_id = person.person_id', + joinType: 'INNER JOIN' }); - return { - reportName: reportName, - extraPatientListColumns: extraPatientListColumns - }; - } - - function buildPatientListReportExpression(queryParams) { - var result = { - whereClause: [], - resource: '', - queryParts: [] - }; - if (queryParams === null || queryParams === undefined) return ""; - var reportDataSet = getReportDataSet(queryParams); - queryParams.reportName = reportDataSet.reportName; - var filter = generatePatientListFilter(queryParams); - result.whereClause.push(filter.query); - result.whereClause.push.apply(result.whereClause, filter.params); - result.resource = filter.table; - _.each(reports, function (report) { - if (report.name === queryParams.reportName) { - var join = joinsToSql(report.joins, queryParams) || []; - join.push({ - schema: 'amrs', - tableName: 'person_name', - alias: 'person_name', - joinExpression: 't1.person_id = person_name.person_id and (person_name.voided is null || person_name.voided = 0)', - joinType: 'INNER JOIN' - }); - join.push({ - schema: 'amrs', - tableName: 'patient_identifier', - alias: 'id', - joinExpression: 't1.person_id = id.patient_id', - joinType: 'LEFT OUTER JOIN' - }); - join.push({ - schema: 'amrs', - tableName: 'person', - alias: 'person', - joinExpression: 't1.person_id = person.person_id', - joinType: 'INNER JOIN' - }); - //remove dynamic datasets from joins - join = _.filter(join, function (j) { - return _.isUndefined(j.joinedQuerParts); - }); - var columns = [ - 't1.person_id', 't1.encounter_id', 't1.location_id', 't1.location_uuid', 't1.uuid as patient_uuid', - 'person.gender', 'person.birthdate', 'extract(year from (from_days(datediff(now(),person.birthdate)))) as age' - ]; - columns.push.apply(columns, reportDataSet.extraPatientListColumns); - var schema = report.table['schema'] === '' ? 'etl' : report.table['schema']; - var tableName = report.table['tableName'] === '' ? 'flat_hiv_summary' : report.table['tableName']; - var queryParts = { - columns: columns, - concatColumns: [ - "concat(COALESCE(person_name.given_name,''),' ',COALESCE(person_name.middle_name,''),' ',COALESCE(person_name.family_name,'')) as person_name", - "group_concat(distinct id.identifier separator ', ') as identifiers", - ], - table: schema + '.' + tableName, - alias: report.table['alias'], - indexExpression: report.table['indexExpression'] || null, - joins: join, - where: result.whereClause, - having: filtersToSql(queryParams.whereParams, report.parameters, report.having), - group: ['t1.person_id'], - order: [{ - column: 't1.encounter_datetime', - asc: false - }], - offset: queryParams.startIndex, - limit: queryParams.limit - }; - result.queryParts = [queryParts]; - } + //remove dynamic datasets from joins + join = _.filter(join, function (j) { + return _.isUndefined(j.joinedQuerParts); }); - return result.queryParts; - } + var columns = [ + 't1.person_id', + 't1.encounter_id', + 't1.location_id', + 't1.location_uuid', + 't1.uuid as patient_uuid', + 'person.gender', + 'person.birthdate', + 'extract(year from (from_days(datediff(now(),person.birthdate)))) as age' + ]; + columns.push.apply(columns, reportDataSet.extraPatientListColumns); + var schema = + report.table['schema'] === '' ? 'etl' : report.table['schema']; + var tableName = + report.table['tableName'] === '' + ? 'flat_hiv_summary' + : report.table['tableName']; + var queryParts = { + columns: columns, + concatColumns: [ + "concat(COALESCE(person_name.given_name,''),' ',COALESCE(person_name.middle_name,''),' ',COALESCE(person_name.family_name,'')) as person_name", + "group_concat(distinct id.identifier separator ', ') as identifiers" + ], + table: schema + '.' + tableName, + alias: report.table['alias'], + indexExpression: report.table['indexExpression'] || null, + joins: join, + where: result.whereClause, + having: filtersToSql( + queryParams.whereParams, + report.parameters, + report.having + ), + group: ['t1.person_id'], + order: [ + { + column: 't1.encounter_datetime', + asc: false + } + ], + offset: queryParams.startIndex, + limit: queryParams.limit + }; + result.queryParts = [queryParts]; + } + }); + return result.queryParts; + } - function buildETLPatientLabOrdersExpression(queryParams, successCallback) { - var result = { - columns: '', - table: '', - where: [] + function buildETLPatientLabOrdersExpression(queryParams, successCallback) { + var result = { + columns: '', + table: '', + where: [] + }; + _.each( + patientLabOrderProperties.patientLabOrderSchema.parameters, + function (parameter) { + if (parameter !== '') { + result.columns += parameter.name + ','; } - _.each(patientLabOrderProperties.patientLabOrderSchema.parameters, function (parameter) { - if (parameter !== '') { - result.columns += parameter.name + ','; - } - }); - //regular expression to remove the last comma; - result.columns = result.columns.replace(/,\s*$/, ""); - result.table = patientLabOrderProperties.patientLabOrderSchema.table.schema + '.' + patientLabOrderProperties.patientLabOrderSchema.table.tableName; - result.where.push(patientLabOrderProperties.patientLabOrderSchema.filters[0].expression); - successCallback(result); - } -}(); \ No newline at end of file + } + ); + //regular expression to remove the last comma; + result.columns = result.columns.replace(/,\s*$/, ''); + result.table = + patientLabOrderProperties.patientLabOrderSchema.table.schema + + '.' + + patientLabOrderProperties.patientLabOrderSchema.table.tableName; + result.where.push( + patientLabOrderProperties.patientLabOrderSchema.filters[0].expression + ); + successCallback(result); + } +})(); diff --git a/etl-file-logger.js b/etl-file-logger.js index d64bb7023..af63fe8f2 100755 --- a/etl-file-logger.js +++ b/etl-file-logger.js @@ -1,7 +1,7 @@ -'use strict' +'use strict'; var winston = require('winston'); var path = require('path'); -var _ = require('underscore') +var _ = require('underscore'); var moduleDefinition = { logRequestError: logRequestError, @@ -18,10 +18,10 @@ function logRequestError(message, fileName, absolutePath) { filename: fileName || 'server-request-logs.log', handleExceptions: true, json: true, - colorize: false, - }), + colorize: false + }) ], - exitOnError: false, + exitOnError: false }); logger.add(require('winston-daily-rotate-file'), { filename: absolutePath + fileName || 'server-request-logs.log' @@ -40,10 +40,10 @@ function logger(filePath) { filename: fileName || 'server-request-logs.log', handleExceptions: true, json: true, - colorize: false, - }), + colorize: false + }) ], - exitOnError: false, + exitOnError: false }); logger.add(require('winston-daily-rotate-file'), { diff --git a/etl-helpers.js b/etl-helpers.js index 9c8153e0a..b42caea2d 100755 --- a/etl-helpers.js +++ b/etl-helpers.js @@ -2,574 +2,655 @@ 'use strict'; var _ = require('underscore'); var moment = require('moment'); -module.exports = function () { - - return { - getReportParams: function getReportParams(reportName, whereClause, queryParams) { - let whereParams = []; - - // format dates to avoid timezone errors - queryParams.startDate = (queryParams.startDate || new Date().toISOString().substring(0, 10)).split('T')[0]; - queryParams.endDate = (queryParams.endDate || new Date().toISOString().substring(0, 10)).split('T')[0]; - queryParams.referenceDate = (queryParams.referenceDate || new Date().toISOString().substring(0, 10)).split('T')[0]; - - // format cohort filters - queryParams.startAge = queryParams.startAge || 0; - queryParams.endAge = queryParams.endAge || 150; - queryParams.gender = (queryParams.gender || 'M,F').split(','); - queryParams.genders = (queryParams.genders || 'M,F').split(','); - - // resolve requested indicators parameter name - queryParams.requestIndicators = queryParams.indicators; - - // format location TODO: Remove location ids on reports and params in order to avoid resolutions - var locations = []; - if (queryParams.locations) { - _.each(queryParams.locations.split(','), function (loc) { - locations.push(Number(loc)); - }); - queryParams.locations = locations; - } - - // format locationUuids - var locationUuids = []; - if (queryParams.locationUuids) { - _.each(queryParams.locationUuids.split(','), function (loc) { - if (loc == '' || loc == 'undefined' || loc == undefined) { - console.log(loc); - } else { - locationUuids.push(String(loc)); - } - - }); - - if (locationUuids.length > 0) { - queryParams.locationUuids = locationUuids; - } else { - delete queryParams['locationUuids']; - } - - } - - // format programUuids - var programUuids = []; - if (queryParams.programUuids) { - _.each(queryParams.programUuids.split(','), function (program) { - programUuids.push(String(program)); - }); - queryParams.programUuids = programUuids || ["*"]; - } - var stateUuids = []; - if (queryParams.stateUuids) { - _.each(queryParams.stateUuids.split(','), function (state) { - stateUuids.push(String(state)); - }); - queryParams.stateUuids = stateUuids || ["*"]; - } - - var providerUuids = []; - if (queryParams.providerUuids) { - _.each(queryParams.providerUuids.split(','), function (provider) { - if (provider == '' || provider == 'undefined' || provider == undefined) { - console.log(provider); - } else { - providerUuids.push(String(provider)); - } - - }); - - if (providerUuids.length > 0) { - queryParams.providerUuids = providerUuids - } else { - delete queryParams['providerUuids']; - } - } - - // format conceptUuid - var conceptUuids = []; - if (queryParams.conceptUuids) { - _.each(queryParams.conceptUuids.split(','), function (state) { - conceptUuids.push(String(state)); - }); - queryParams.conceptUuids = conceptUuids; - } - // - for (let filter of whereClause) { - whereParams.push({ - "name": filter, - "value": queryParams[filter] - }); - } - var reportParams = { - reportName: reportName, - whereParams: whereParams, - countBy: queryParams.countBy || 'num_persons', - groupBy: queryParams.groupBy || 'groupByLocation', - offset: queryParams.startIndex, - limit: queryParams.limit, - requestIndicators: queryParams.indicators, - requestParams: queryParams - }; - return reportParams; +module.exports = (function () { + return { + getReportParams: function getReportParams( + reportName, + whereClause, + queryParams + ) { + let whereParams = []; + + // format dates to avoid timezone errors + queryParams.startDate = ( + queryParams.startDate || new Date().toISOString().substring(0, 10) + ).split('T')[0]; + queryParams.endDate = ( + queryParams.endDate || new Date().toISOString().substring(0, 10) + ).split('T')[0]; + queryParams.referenceDate = ( + queryParams.referenceDate || new Date().toISOString().substring(0, 10) + ).split('T')[0]; + + // format cohort filters + queryParams.startAge = queryParams.startAge || 0; + queryParams.endAge = queryParams.endAge || 150; + queryParams.gender = (queryParams.gender || 'M,F').split(','); + queryParams.genders = (queryParams.genders || 'M,F').split(','); + + // resolve requested indicators parameter name + queryParams.requestIndicators = queryParams.indicators; + + // format location TODO: Remove location ids on reports and params in order to avoid resolutions + var locations = []; + if (queryParams.locations) { + _.each(queryParams.locations.split(','), function (loc) { + locations.push(Number(loc)); + }); + queryParams.locations = locations; + } + + // format locationUuids + var locationUuids = []; + if (queryParams.locationUuids) { + _.each(queryParams.locationUuids.split(','), function (loc) { + if (loc == '' || loc == 'undefined' || loc == undefined) { + console.log(loc); + } else { + locationUuids.push(String(loc)); + } + }); + + if (locationUuids.length > 0) { + queryParams.locationUuids = locationUuids; + } else { + delete queryParams['locationUuids']; + } + } + + // format programUuids + var programUuids = []; + if (queryParams.programUuids) { + _.each(queryParams.programUuids.split(','), function (program) { + programUuids.push(String(program)); + }); + queryParams.programUuids = programUuids || ['*']; + } + var stateUuids = []; + if (queryParams.stateUuids) { + _.each(queryParams.stateUuids.split(','), function (state) { + stateUuids.push(String(state)); + }); + queryParams.stateUuids = stateUuids || ['*']; + } + + var providerUuids = []; + if (queryParams.providerUuids) { + _.each(queryParams.providerUuids.split(','), function (provider) { + if ( + provider == '' || + provider == 'undefined' || + provider == undefined + ) { + console.log(provider); + } else { + providerUuids.push(String(provider)); + } + }); + + if (providerUuids.length > 0) { + queryParams.providerUuids = providerUuids; + } else { + delete queryParams['providerUuids']; + } + } + + // format conceptUuid + var conceptUuids = []; + if (queryParams.conceptUuids) { + _.each(queryParams.conceptUuids.split(','), function (state) { + conceptUuids.push(String(state)); + }); + queryParams.conceptUuids = conceptUuids; + } + // + for (let filter of whereClause) { + whereParams.push({ + name: filter, + value: queryParams[filter] + }); + } + var reportParams = { + reportName: reportName, + whereParams: whereParams, + countBy: queryParams.countBy || 'num_persons', + groupBy: queryParams.groupBy || 'groupByLocation', + offset: queryParams.startIndex, + limit: queryParams.limit, + requestIndicators: queryParams.indicators, + requestParams: queryParams + }; + return reportParams; + }, + getSortOrder: function getSortOrder(param) { + if (!param) return null; + var parts; + var order = []; + _.each(param.split(','), function (order_by) { + parts = order_by.split('|'); + order.push({ + column: parts[0], + asc: parts[1].toLowerCase() === 'asc' + }); + }); + return order; + }, + getFilters: function getFilters(filters) { + var s = ''; + var vals = [], + column; + _.each(filters, function (item) { + column = item.column; + for (var f in item.filters) { + if ( + item.filters[f] === undefined || + item.filters[f] === null || + item.filters[f] === '' + ) + continue; + console.log(item.filters[f]); + s += column; + if (f === 'start') s += ' >= ?'; + else if (f === 'end') s += ' <= ?'; + else s += ' like ?'; + vals.push(item.filters[f]); + s += ' AND '; + } + }); + s = s.substring(0, s.length - 5); + if (s !== '') s = '(' + s + ')'; + console.log(s); + console.log(vals); + return { + s: s, + vals: vals + }; + }, + getConceptName: function getConceptName(code) { + if (code === null || code === undefined) return ''; + var concepts = { + 221: 'RHEUMATIC HEART DISEASE', + 9842: 'DUCTAL CELL CARCINOMA', + 664: 'NEGATIVE', + 703: 'POSITIVE', + 1115: 'NORMAL', + 1116: 'ABNORMAL', + 1118: 'NOT DONE', + 1136: 'PULMONARY EFFUSION', + 1137: 'MILIARY CHANGES', + 1138: 'INDETERMINATE', + 1304: 'POOR SAMPLE QUALITY', + 1530: 'CARDIAC ARRHYTHMIA', + 1531: 'ATRIAL FIBRILLATION', + 1532: 'LEFT VENTRICULAR HYPERTROPHY', + 1533: 'RIGHT VENTRICULAR HYPERTROPHY', + 1538: 'DILATED CARDIOMYOPATHY', + 1539: 'PERICARDIAL EFFUSION', + 1540: 'MURAL THROMBI', + 1541: 'PULMONARY HYPERTENSION', + 1542: 'VENTRICULAR SEPTAL DEFECT', + 5158: 'EVIDENCE OF CARDIAC ENLARGEMENT', + 5622: 'OTHER NON-CODED', + 6049: 'INFILTRATE', + 6050: 'DIFFUSE NON-MILIARY CHANGES', + 6052: 'CAVITARY LESION', + 1098: 'MONTHLY', + 1099: 'WEEKLY', + 1639: 'MORNING', + 1640: 'NOON', + 1641: 'AFTERNOON', + 1730: 'EVENING', + 1888: 'TWICE A DAY', + 1889: 'THREE TIMES A DAY', + 1890: 'FOUR TIMES A DAY', + 1891: 'ONCE A DAY', + 1899: 'NUMBER OF MILLIGRAM', + 2176: 'EVERY NIGHT', + 2178: 'STAT', + 7682: 'ONCE EVERY TWO WEEKS', + 7772: 'AS NEEDED', + 8909: 'ONCE A WEEK', + 8927: 'ONCE', + 9933: 'ONCE EVERY THREE WEEKS', + 10091: 'FIVE TIMES DAILY', + 10092: 'TWICE A WEEK', + 10093: 'THREE TIMES A WEEK', + 10094: 'FOUR TIMES A WEEK', + 1256: 'START', + 1257: 'CONTINUE', + 1259: 'CHANGE', + 1260: 'STOP', + 2261: 'METFORMIN', + 2257: 'GLIBENCLAMIDE', + 2254: '70% NPH INSULIN WITH 30% REGULAR INSULIN', + 2256: 'INSULIN LISPRO', + 2255: 'INSULIN NPH', + 2258: 'GLICLAZIDE', + 2259: 'CHLORPROPAMIDE', + 2260: 'GLIMEPIRIDE', + 279: 'INSULIN, LENTE', + 282: 'INSULIN, REGULAR', + 2270: 'PIOGLITAZONE', + 2271: 'ROSIGLITAZONE', + 2279: 'GLIBENCLAMIDE AND METFORMIN', + 1107: 'NONE', + 7281: 'NEW DM PATIENT', + 7282: 'KNOWN DM PATIENT', + 7285: 'NEW HTN PATIENT', + 7286: 'KNOWN HTN PATIENT', + 1878: 'STROKE', + 8076: 'T.I.A', + 1456: 'HEART FAILURE', + 8077: 'ISCHEMIC H.D ', + 821: 'PERIPHERAL NEUROPATHY', + 8084: 'DIABETIC RETINOPATHY', + 8085: 'GASTROPATHY', + 8086: 'AUTONOMIC NEUROPATHY', + 70: 'CATARACTS', + 1885: 'KIDNEY FAILURE', + 6730: 'VISUAL IMPAIREMENT', + // ONCOLOGY CONCEPTS + 8480: 'LENALIDOMIDE', + 6555: 'MULTIPLE MYELOMA', + 6902: 'BONE MARROW ASPIRATION', + 10206: 'DURIE-SALMON SYSTEM', + 9851: 'STAGE 0', + 9852: 'STAGE I', + 9853: 'STAGE IA', + 9854: 'STAGE IB', + 9855: 'STAGE IC', + 9856: 'STAGE II', + 9857: 'STAGE IIA', + 9858: 'STAGE IIB', + 9859: 'STAGE IIC', + 9860: 'STAGE III', + 9861: 'STAGE IIIA', + 9862: 'STAGE IIIB', + 9863: 'STAGE IIIC', + 9864: 'STAGE IV', + 9865: 'STAGE IVA', + 9867: 'STAGE IVC', + 9866: 'STAGE IVB', + 6575: 'CHEMOTHERAPY', + 10078: 'INTRATHECAL, DRUG ROUTE', + 8479: 'THALIDOMIDE', + 6566: 'COMPLETE STAGING', + 6536: 'GYNECOLOGIC CANCER TYPE', + 7213: 'MELPHALAN', + 6485: 'SARCOMA', + 6537: 'CERVICAL CANCER', + 9918: 'CHEMO MEDS', + 8478: 'IMATINIB', + 7217: 'PALLIATIVE TAMOXIFEN', + 7203: 'CYCLOPHOSPHAMIDE', + 7215: 'METHOTREXATE', + 7223: 'FLUOROURACIL', + 7198: 'HYDROXYDAUNORUBICIN (ADRIAMYCIN)', + 491: 'PREDNISONE', + 7199: 'BLEOMYCIN', + 7218: 'VINBLASTINE', + 7205: 'DACARBAZINE', + 7212: '5FU / LEUCOVORIN', + 8513: 'ANASTRAZOLE', + 7202: 'CISPLATIN', + 7209: 'ETOPOSIDE', + 7197: 'ACTINOMYCIN D', + 7219: 'VINCRISTINE', + 8506: 'PACLITAXEL', + 7210: 'GEMCITABINE (GEMZAR)', + 8499: 'IFOSFAMIDE', + 8492: 'CARBOPLATINUM', + 8522: 'INTERFERON ALFA', + 8510: 'CAPECITABINE', + 8511: 'EPIRUBICIN', + 9919: 'MESNA', + 8518: 'LEUPROLIDE', + 8516: 'BICALUTAMIDE', + 8481: 'SORAFENIB', + 7207: 'DEXAMETHASONE', + 7204: 'CYTARABINE', + 7201: 'CHLORAMBUCIL', + 8519: 'ZOLADEX/GOSERELIN', + 8507: 'TAXOTERE', + 10139: 'OXALIPLATIN', + 10140: 'ZOLEDRONIC ACID', + 8515: 'LETROZOLE', + 8514: 'EXEMESTANE', + 8486: 'BORTEZOMIB', + 1895: 'MEDICATION ADDED', + 10198: 'OTHER MEDS GIVEN', + 88: 'BABY ASA', + 8598: 'VIT. B12 INJECTION', + 8597: 'VIT D SUPPLEMETATION', + 1195: 'ANTIBIOTICS', + 8410: 'ANTICOAGULATION', + 7458: 'IV FLUIDS', + 9710: 'SICKLE CELL DRUGS', + 7211: 'HYDROXYUREA', + 257: 'FOLATE/FOLIC ACID', + 784: 'PEN-V', + 97: 'PALLUDRINE', + 8723: 'ONCOLOGY TREATMENT PLAN', + 7465: 'SURGERY', + 8427: 'RADIATION THERAPY', + 9626: 'HORMONE REPLACEMENT THERAPY', + 10038: 'BIOLOGIC THERAPY', + 10232: 'TARGETED THERAPY', + 10039: 'OTHER ONCOLOGY TREATMENT PLAN', + 10586: 'IN REMISSION', + 8725: 'REASONS FOR SURGERY', + 8428: 'CURATIVE CARE', + 8724: 'PALLIATIVE CARE', + 8727: 'DIAGNOSTIC', + 2206: 'CHEMOTHERAPY INTENT', + 9219: 'NEO ADJUVANT INTENT', + 9218: 'ADJUVANT INTENT', + 9220: 'SYMPTOM CONTROL', + 9869: 'CHEMOTHERAPY PLAN', + 6576: 'CHEMOTHERAPY REGIMEN MODIFICATION', + 1190: 'CHEMOTHERAPY START DATE', + 6643: 'CURRENT CHEMOTHERAPY CYCLE', + 7463: 'DRUG ROUTE', + 10079: 'INTRA OMMAYA', + 7597: 'SUBCUTANEOUS INJECTION', + 7581: 'INTRAMUSCULAR INJECTION', + 7609: 'INTRARTERIAL INJECTION', + 7447: 'ORAL ADMINISTRATION', + 6042: 'DIAGNOSIS', + 9728: 'DIAGNOSIS DATE', + 9868: 'OVERALL CANCER STAGE GROUP', + 7176: 'CANCER TYPE', + 9847: 'NON-CANCER', + 9841: 'BREAST CANCER TYPE', + 6582: 'CANCER STAGE', + 6504: 'DIAGNOSIS METHOD', + 507: "KAPOSI'S SARCOMA", + 6486: 'SOFT TISSUE SARCOMA', + 6487: 'OSTEOGENIC SARCOMA', + 6488: "EWING'S SARCOMA", + 6489: 'RHABDOMYOSARCOMA', + 6490: 'OTHER SARCOMA', + 1065: 'YES', + 9849: 'NEW CANCER PATIENT', + 9850: 'CANCER RECURRENCE', + 6484: 'SOLID CANCER', + 7175: 'HEMATOLOGIC CANCER', + 6529: 'THYROID CANCER', + 6522: 'GASTRIC CANCER', + 9636: 'ENDOMETRIAL CANCER', + 9637: 'BONE OR SOFT TISSUE CANCER', + 9638: 'ADRENOCORTICAL CARCINOMA', + 9639: 'BRAIN CANCER', + 9640: 'ACUTE LEUKEMIA', + 6544: 'BREAST CANCER', + 6545: 'INFLAMMATORY BREAST CANCER', + 9846: 'OTHER SOLID CANCER TYPE', + 6514: 'GENITOURINARY CANCER', + 6520: 'GASTROINTESTINAL CANCER', + 6528: 'HEAD AND NECK CANCER', + 6551: 'LYMPHOMA CANCER TYPE', + 6540: 'SKIN CANCER TYPE', + 216: 'LEUKEMIA', + 10129: 'NON SMALL CELL LUNG CANCER', + 10130: 'SMALL CELL LUNG CANCER', + 8424: 'RETINOBLASTOMA', + 8425: 'NEUROBLASTOMA', + 9845: 'LUNG CANCER', + 6515: 'BLADDER CANCER', + 6516: 'RENAL CELL CANCER', + 6517: "WILM'S TUMOR", + 6518: 'PROSTATE CANCER', + 6519: 'TESTES CANCER', + 6521: 'ESOPHAGEAL CANCER', + 6523: 'PANCREATIC CANCER', + 6524: 'CHOLANGIOCARCINOMA', + 6525: 'COLON CANCER', + 6526: 'RECTAL CANCER', + 6527: 'ANAL CANCER', + 6568: 'HEPATOCELLULAR CANCER', + 6530: 'NASOPHARYNGEAL SQUAMOUS CELL CANCER', + 6531: 'OROPHARYNGEAL SQUAMOUS CELL CANCER', + 6532: 'HYPOPHARYNGEAL SQUAMOUS CELL CANCER', + 6533: 'LARYNGEAL SQUAMOUS CELL CANCER', + 6534: 'HEAD AND NECK SQUAMOUS CELL CANCER, SITE NOT SPECIFIED', + 6535: 'POSTERIOR NASAL SPACE TUMOR', + 6538: 'UTERINE CANCER', + 6539: 'OVARIAN CANCER', + 6553: "NON-HODGKIN'S LYMPHOMA", + 6552: "HODGKIN'S LYMPHOMA", + 8423: "BURKITT'S LYMPHOMA", + 6541: 'SKIN SQUAMOUS CELL CANCER', + 6542: 'BASAL CELL CANCER', + 6543: 'MELANOMA', + 7422: 'ADENOCARCINOMA', + 7421: 'SQUAMOUS CELL CARCINOMA, NOT OTHERWISE SPECIFIED', + 10131: 'LARGE CELL CARCINOMA', + 10209: 'MIXED SQUAMOUS', + 6547: 'CHRONIC MYELOGENOUS LEUKEMIA', + 6548: 'CHRONIC LYMPHOCYTIC LEUKEMIA', + 6549: 'ACUTE MYELOGENOUS LEUKEMIA', + 6550: 'ACUTE LYMPHOCYTIC LEUKEMIA' + }; + return concepts[code]; + }, + getARVNames: function getARVNames(str) { + if ( + str === null || + str === undefined || + str === 'unknown' || + str === '-1' + ) { + return ''; + } + var arvs = { + 625: { mapped_to_ids: '625', name: 'STAVUDINE' }, + 628: { mapped_to_ids: '628', name: 'LAMIVUDINE' }, + 630: { mapped_to_ids: '628;797', name: 'ZIDOVUDINE AND LAMIVUDINE' }, + 631: { mapped_to_ids: '631', name: 'NEVIRAPINE' }, + 633: { mapped_to_ids: '633', name: 'EFAVIRENZ' }, + 635: { mapped_to_ids: '635', name: 'NELFINAVIR' }, + 749: { mapped_to_ids: '749', name: 'INDINAVIR' }, + 791: { mapped_to_ids: '791', name: 'EMTRICITABINE' }, + 792: { + mapped_to_ids: '625;628;631', + name: 'STAVUDINE LAMIVUDINE AND NEVIRAPINE' }, - getSortOrder: function getSortOrder(param) { - if (!param) return null; - var parts; - var order = []; - _.each(param.split(','), function (order_by) { - parts = order_by.split('|'); - order.push({ - column: parts[0], - asc: (parts[1].toLowerCase() === "asc") - }); - }); - return order; + 794: { mapped_to_ids: '794', name: 'LOPINAVIR AND RITONAVIR' }, + 795: { mapped_to_ids: '795', name: 'RITONAVIR' }, + 796: { mapped_to_ids: '796', name: 'DIDANOSINE' }, + 797: { mapped_to_ids: '797', name: 'ZIDOVUDINE' }, + 802: { mapped_to_ids: '802', name: 'TENOFOVIR' }, + 814: { mapped_to_ids: '814', name: 'ABACAVIR' }, + 817: { + mapped_to_ids: '628;797;814', + name: 'ABACAVIR LAMIVUDINE AND ZIDOVUDINE' }, - getFilters: function getFilters(filters) { - var s = ""; - var vals = [], - column; - _.each(filters, function (item) { - column = item.column; - for (var f in item.filters) { - if (item.filters[f] === undefined || item.filters[f] === null || item.filters[f] === "") continue; - console.log(item.filters[f]); - s += column; - if (f === "start") s += " >= ?"; - else if (f === "end") s += " <= ?"; - else s += " like ?"; - vals.push(item.filters[f]); - s += " AND "; - } - }); - s = s.substring(0, s.length - 5); - if (s !== "") - s = "(" + s + ")"; - console.log(s); - console.log(vals); - return { - s: s, - vals: vals - }; + 1065: { mapped_to_ids: '1065', name: 'YES' }, + 1066: { mapped_to_ids: '1066', name: 'NO' }, + 1107: { mapped_to_ids: '1107', name: 'NONE' }, + 1400: { mapped_to_ids: '628;802', name: 'LAMIVUDINE AND TENOFOVIR' }, + 5424: { mapped_to_ids: '5424', name: 'OTHER ANTIRETROVIRAL DRUG' }, + 5811: { mapped_to_ids: '5811', name: 'UNKNOWN ANTIRETROVIRAL DRUG' }, + 6156: { mapped_to_ids: '6156', name: 'RALTEGRAVIR' }, + 6157: { mapped_to_ids: '6157', name: 'DARUNAVIR' }, + 6158: { mapped_to_ids: '6158', name: 'ETRAVIRINE' }, + 6159: { mapped_to_ids: '6159', name: 'ATAZANAVIR' }, + 6160: { mapped_to_ids: '795;6159', name: 'ATAZANAVIR AND RITONAVIR' }, + 6180: { mapped_to_ids: '791;802', name: 'EMTRICITABINE AND TENOFOVIR' }, + 6467: { + mapped_to_ids: '628;631;633', + name: 'NEVIRAPINE LAMIVUDINE AND ZIDOVUDINE' }, - getConceptName: function getConceptName(code) { - if (code === null || code === undefined) return ""; - var concepts = { - 221: "RHEUMATIC HEART DISEASE", - 9842: "DUCTAL CELL CARCINOMA", - 664: "NEGATIVE", - 703: "POSITIVE", - 1115: "NORMAL", - 1116: "ABNORMAL", - 1118: "NOT DONE", - 1136: "PULMONARY EFFUSION", - 1137: "MILIARY CHANGES", - 1138: "INDETERMINATE", - 1304: "POOR SAMPLE QUALITY", - 1530: "CARDIAC ARRHYTHMIA", - 1531: "ATRIAL FIBRILLATION", - 1532: "LEFT VENTRICULAR HYPERTROPHY", - 1533: "RIGHT VENTRICULAR HYPERTROPHY", - 1538: "DILATED CARDIOMYOPATHY", - 1539: "PERICARDIAL EFFUSION", - 1540: "MURAL THROMBI", - 1541: "PULMONARY HYPERTENSION", - 1542: "VENTRICULAR SEPTAL DEFECT", - 5158: "EVIDENCE OF CARDIAC ENLARGEMENT", - 5622: "OTHER NON-CODED", - 6049: "INFILTRATE", - 6050: "DIFFUSE NON-MILIARY CHANGES", - 6052: "CAVITARY LESION", - 1098: "MONTHLY", - 1099: "WEEKLY", - 1639: "MORNING", - 1640: "NOON", - 1641: "AFTERNOON", - 1730: "EVENING", - 1888: "TWICE A DAY", - 1889: "THREE TIMES A DAY", - 1890: "FOUR TIMES A DAY", - 1891: "ONCE A DAY", - 1899: "NUMBER OF MILLIGRAM", - 2176: "EVERY NIGHT", - 2178: "STAT", - 7682: "ONCE EVERY TWO WEEKS", - 7772: "AS NEEDED", - 8909: "ONCE A WEEK", - 8927: "ONCE", - 9933: "ONCE EVERY THREE WEEKS", - 10091: "FIVE TIMES DAILY", - 10092: "TWICE A WEEK", - 10093: "THREE TIMES A WEEK", - 10094: "FOUR TIMES A WEEK", - 1256: "START", - 1257: "CONTINUE", - 1259: "CHANGE", - 1260: "STOP", - 2261: "METFORMIN", - 2257: "GLIBENCLAMIDE", - 2254: "70% NPH INSULIN WITH 30% REGULAR INSULIN", - 2256: "INSULIN LISPRO", - 2255: "INSULIN NPH", - 2258: "GLICLAZIDE", - 2259: "CHLORPROPAMIDE", - 2260: "GLIMEPIRIDE", - 279: "INSULIN, LENTE", - 282: "INSULIN, REGULAR", - 2270: "PIOGLITAZONE", - 2271: "ROSIGLITAZONE", - 2279: "GLIBENCLAMIDE AND METFORMIN", - 1107: "NONE", - 7281: "NEW DM PATIENT", - 7282: "KNOWN DM PATIENT", - 7285: "NEW HTN PATIENT", - 7286: "KNOWN HTN PATIENT", - 1878: "STROKE", - 8076: "T.I.A", - 1456: "HEART FAILURE", - 8077: "ISCHEMIC H.D ", - 821: "PERIPHERAL NEUROPATHY", - 8084: "DIABETIC RETINOPATHY", - 8085: "GASTROPATHY", - 8086: "AUTONOMIC NEUROPATHY", - 70: "CATARACTS", - 1885: "KIDNEY FAILURE", - 6730: "VISUAL IMPAIREMENT", - // ONCOLOGY CONCEPTS - 8480: "LENALIDOMIDE", - 6555: "MULTIPLE MYELOMA", - 6902: "BONE MARROW ASPIRATION", - 10206: "DURIE-SALMON SYSTEM", - 9851: "STAGE 0", - 9852: "STAGE I", - 9853: "STAGE IA", - 9854: "STAGE IB", - 9855: "STAGE IC", - 9856: "STAGE II", - 9857: "STAGE IIA", - 9858: "STAGE IIB", - 9859: "STAGE IIC", - 9860: "STAGE III", - 9861: "STAGE IIIA", - 9862: "STAGE IIIB", - 9863: "STAGE IIIC", - 9864: "STAGE IV", - 9865: "STAGE IVA", - 9867: "STAGE IVC", - 9866: "STAGE IVB", - 6575: "CHEMOTHERAPY", - 10078: "INTRATHECAL, DRUG ROUTE", - 8479: "THALIDOMIDE", - 6566: "COMPLETE STAGING", - 6536: "GYNECOLOGIC CANCER TYPE", - 7213: "MELPHALAN", - 6485: "SARCOMA", - 6537: "CERVICAL CANCER", - 9918: "CHEMO MEDS", - 8478: "IMATINIB", - 7217: "PALLIATIVE TAMOXIFEN", - 7203: "CYCLOPHOSPHAMIDE", - 7215: "METHOTREXATE", - 7223: "FLUOROURACIL", - 7198: "HYDROXYDAUNORUBICIN (ADRIAMYCIN)", - 491: "PREDNISONE", - 7199: "BLEOMYCIN", - 7218: "VINBLASTINE", - 7205: "DACARBAZINE", - 7212: "5FU / LEUCOVORIN", - 8513: "ANASTRAZOLE", - 7202: "CISPLATIN", - 7209: "ETOPOSIDE", - 7197: "ACTINOMYCIN D", - 7219: "VINCRISTINE", - 8506: "PACLITAXEL", - 7210: "GEMCITABINE (GEMZAR)", - 8499: "IFOSFAMIDE", - 8492: "CARBOPLATINUM", - 8522: "INTERFERON ALFA", - 8510: "CAPECITABINE", - 8511: "EPIRUBICIN", - 9919: "MESNA", - 8518: "LEUPROLIDE", - 8516: "BICALUTAMIDE", - 8481: "SORAFENIB", - 7207: "DEXAMETHASONE", - 7204: "CYTARABINE", - 7201: "CHLORAMBUCIL", - 8519: "ZOLADEX/GOSERELIN", - 8507: "TAXOTERE", - 10139: "OXALIPLATIN", - 10140: "ZOLEDRONIC ACID", - 8515: "LETROZOLE", - 8514: "EXEMESTANE", - 8486: "BORTEZOMIB", - 1895: "MEDICATION ADDED", - 10198: "OTHER MEDS GIVEN", - 88: "BABY ASA", - 8598: "VIT. B12 INJECTION", - 8597: "VIT D SUPPLEMETATION", - 1195: "ANTIBIOTICS", - 8410: "ANTICOAGULATION", - 7458: "IV FLUIDS", - 9710: "SICKLE CELL DRUGS", - 7211: "HYDROXYUREA", - 257: "FOLATE/FOLIC ACID", - 784: "PEN-V", - 97: "PALLUDRINE", - 8723: "ONCOLOGY TREATMENT PLAN", - 7465: "SURGERY", - 8427: "RADIATION THERAPY", - 9626: "HORMONE REPLACEMENT THERAPY", - 10038: "BIOLOGIC THERAPY", - 10232: "TARGETED THERAPY", - 10039: "OTHER ONCOLOGY TREATMENT PLAN", - 10586: "IN REMISSION", - 8725: "REASONS FOR SURGERY", - 8428: "CURATIVE CARE", - 8724: "PALLIATIVE CARE", - 8727: "DIAGNOSTIC", - 2206: "CHEMOTHERAPY INTENT", - 9219: "NEO ADJUVANT INTENT", - 9218: "ADJUVANT INTENT", - 9220: "SYMPTOM CONTROL", - 9869: "CHEMOTHERAPY PLAN", - 6576: "CHEMOTHERAPY REGIMEN MODIFICATION", - 1190: "CHEMOTHERAPY START DATE", - 6643: "CURRENT CHEMOTHERAPY CYCLE", - 7463: "DRUG ROUTE", - 10079: "INTRA OMMAYA", - 7597: "SUBCUTANEOUS INJECTION", - 7581: "INTRAMUSCULAR INJECTION", - 7609: "INTRARTERIAL INJECTION", - 7447: "ORAL ADMINISTRATION", - 6042: "DIAGNOSIS", - 9728: "DIAGNOSIS DATE", - 9868: "OVERALL CANCER STAGE GROUP", - 7176: "CANCER TYPE", - 9847: "NON-CANCER", - 9841: "BREAST CANCER TYPE", - 6582: "CANCER STAGE", - 6504: "DIAGNOSIS METHOD", - 507: "KAPOSI'S SARCOMA", - 6486: "SOFT TISSUE SARCOMA", - 6487: "OSTEOGENIC SARCOMA", - 6488: "EWING'S SARCOMA", - 6489: "RHABDOMYOSARCOMA", - 6490: "OTHER SARCOMA", - 1065: "YES", - 9849: "NEW CANCER PATIENT", - 9850: "CANCER RECURRENCE", - 6484: "SOLID CANCER", - 7175: "HEMATOLOGIC CANCER", - 6529: "THYROID CANCER", - 6522: "GASTRIC CANCER", - 9636: "ENDOMETRIAL CANCER", - 9637: "BONE OR SOFT TISSUE CANCER", - 9638: "ADRENOCORTICAL CARCINOMA", - 9639: "BRAIN CANCER", - 9640: "ACUTE LEUKEMIA", - 6544: "BREAST CANCER", - 6545: "INFLAMMATORY BREAST CANCER", - 9846: "OTHER SOLID CANCER TYPE", - 6514: "GENITOURINARY CANCER", - 6520: "GASTROINTESTINAL CANCER", - 6528: "HEAD AND NECK CANCER", - 6551: "LYMPHOMA CANCER TYPE", - 6540: "SKIN CANCER TYPE", - 216: "LEUKEMIA", - 10129: "NON SMALL CELL LUNG CANCER", - 10130: "SMALL CELL LUNG CANCER", - 8424: "RETINOBLASTOMA", - 8425: "NEUROBLASTOMA", - 9845: "LUNG CANCER", - 6515: "BLADDER CANCER", - 6516: "RENAL CELL CANCER", - 6517: "WILM'S TUMOR", - 6518: "PROSTATE CANCER", - 6519: "TESTES CANCER", - 6521: "ESOPHAGEAL CANCER", - 6523: "PANCREATIC CANCER", - 6524: "CHOLANGIOCARCINOMA", - 6525: "COLON CANCER", - 6526: "RECTAL CANCER", - 6527: "ANAL CANCER", - 6568: "HEPATOCELLULAR CANCER", - 6530: "NASOPHARYNGEAL SQUAMOUS CELL CANCER", - 6531: "OROPHARYNGEAL SQUAMOUS CELL CANCER", - 6532: "HYPOPHARYNGEAL SQUAMOUS CELL CANCER", - 6533: "LARYNGEAL SQUAMOUS CELL CANCER", - 6534: "HEAD AND NECK SQUAMOUS CELL CANCER, SITE NOT SPECIFIED", - 6535: "POSTERIOR NASAL SPACE TUMOR", - 6538: "UTERINE CANCER", - 6539: "OVARIAN CANCER", - 6553: "NON-HODGKIN'S LYMPHOMA", - 6552: "HODGKIN'S LYMPHOMA", - 8423: "BURKITT'S LYMPHOMA", - 6541: "SKIN SQUAMOUS CELL CANCER", - 6542: "BASAL CELL CANCER", - 6543: "MELANOMA", - 7422: "ADENOCARCINOMA", - 7421: "SQUAMOUS CELL CARCINOMA, NOT OTHERWISE SPECIFIED", - 10131: "LARGE CELL CARCINOMA", - 10209: "MIXED SQUAMOUS", - 6547: "CHRONIC MYELOGENOUS LEUKEMIA", - 6548: "CHRONIC LYMPHOCYTIC LEUKEMIA", - 6549: "ACUTE MYELOGENOUS LEUKEMIA", - 6550: "ACUTE LYMPHOCYTIC LEUKEMIA" - }; - return concepts[code]; + 6679: { mapped_to_ids: '628;814', name: 'ABACAVIR AND LAMIVUDINE' }, + 6964: { + mapped_to_ids: '628;633;802', + name: 'TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ' }, - getARVNames: function getARVNames(str) { - if (str === null || str === undefined || str === 'unknown' || str === '-1') { - return ""; - } - var arvs = { - 625: {mapped_to_ids: "625", name: "STAVUDINE"}, - 628: {mapped_to_ids: "628", name: "LAMIVUDINE"}, - 630: {mapped_to_ids: "628;797", name: "ZIDOVUDINE AND LAMIVUDINE"}, - 631: {mapped_to_ids: "631", name: "NEVIRAPINE"}, - 633: {mapped_to_ids: "633", name: "EFAVIRENZ"}, - 635: {mapped_to_ids: "635", name: "NELFINAVIR"}, - 749: {mapped_to_ids: "749", name: "INDINAVIR"}, - 791: {mapped_to_ids: "791", name: "EMTRICITABINE"}, - 792: {mapped_to_ids: "625;628;631", name: "STAVUDINE LAMIVUDINE AND NEVIRAPINE"}, - 794: {mapped_to_ids: "794", name: "LOPINAVIR AND RITONAVIR"}, - 795: {mapped_to_ids: "795", name: "RITONAVIR"}, - 796: {mapped_to_ids: "796", name: "DIDANOSINE"}, - 797: {mapped_to_ids: "797", name: "ZIDOVUDINE"}, - 802: {mapped_to_ids: "802", name: "TENOFOVIR"}, - 814: {mapped_to_ids: "814", name: "ABACAVIR"}, - 817: {mapped_to_ids: "628;797;814", name: "ABACAVIR LAMIVUDINE AND ZIDOVUDINE"}, - 1065: {mapped_to_ids: "1065", name: "YES"}, - 1066: {mapped_to_ids: "1066", name: "NO"}, - 1107: {mapped_to_ids: "1107", name: "NONE"}, - 1400: {mapped_to_ids: "628;802", name: "LAMIVUDINE AND TENOFOVIR"}, - 5424: {mapped_to_ids: "5424", name: "OTHER ANTIRETROVIRAL DRUG"}, - 5811: {mapped_to_ids: "5811", name: "UNKNOWN ANTIRETROVIRAL DRUG"}, - 6156: {mapped_to_ids: "6156", name: "RALTEGRAVIR"}, - 6157: {mapped_to_ids: "6157", name: "DARUNAVIR"}, - 6158: {mapped_to_ids: "6158", name: "ETRAVIRINE"}, - 6159: {mapped_to_ids: "6159", name: "ATAZANAVIR"}, - 6160: {mapped_to_ids: "795;6159", name: "ATAZANAVIR AND RITONAVIR"}, - 6180: {mapped_to_ids: "791;802", name: "EMTRICITABINE AND TENOFOVIR"}, - 6467: {mapped_to_ids: "628;631;633", name: "NEVIRAPINE LAMIVUDINE AND ZIDOVUDINE"}, - 6679: {mapped_to_ids: "628;814", name: "ABACAVIR AND LAMIVUDINE"}, - 6964: {mapped_to_ids: "628;633;802", name: "TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ"}, - 6965: {mapped_to_ids: "625;628", name: "LAMIVUDINE AND STAVUDINE"}, - 9435: {mapped_to_ids: "9435", name: "EVIPLERA"}, - 9759: {mapped_to_ids: "9759", name: "DOLUTEGRAVIR"}, - 9026: {mapped_to_ids: "9026", name: "LOPINAVIR"}, - 10090: {mapped_to_ids: "10090", name: "RILPIVIRINE"} - }; - var arvCodes = str.split(" ## "); - var arvNames = []; - var sortedArvCodes = arvCodes.sort().join(';'); - var matchingName = _.find(arvs, function (arv) { - if (arv["mapped_to_ids"] === sortedArvCodes) { - return arv; - } - - }); - _.each(arvCodes, function (code) { - if (arvs[code]) { - arvNames.push(arvs[code].name); - } else { - arvNames.push(code); - } - - }); - return matchingName ? matchingName.name : arvNames.join(', '); + 6965: { mapped_to_ids: '625;628', name: 'LAMIVUDINE AND STAVUDINE' }, + 9435: { mapped_to_ids: '9435', name: 'EVIPLERA' }, + 9759: { mapped_to_ids: '9759', name: 'DOLUTEGRAVIR' }, + 9026: { mapped_to_ids: '9026', name: 'LOPINAVIR' }, + 10090: { mapped_to_ids: '10090', name: 'RILPIVIRINE' } + }; + var arvCodes = str.split(' ## '); + var arvNames = []; + var sortedArvCodes = arvCodes.sort().join(';'); + var matchingName = _.find(arvs, function (arv) { + if (arv['mapped_to_ids'] === sortedArvCodes) { + return arv; + } + }); + _.each(arvCodes, function (code) { + if (arvs[code]) { + arvNames.push(arvs[code].name); + } else { + arvNames.push(code); + } + }); + return matchingName ? matchingName.name : arvNames.join(', '); + }, + + getContraceptiveMethod: function getContraceptiveMethod(str) { + if (str === null || str === undefined) + return { concept: 1107, name: 'NONE', period: null }; + var contraceptives = [ + { concept: 190, name: 'CONDOMS', period: 'Short term' }, + { concept: 780, name: 'ORAL CONTRACEPTION', period: 'Short term' }, + { + concept: 907, + name: 'MEDROXYPROGESTERONE ACETATE', + period: 'Short term' }, - - getContraceptiveMethod: function getContraceptiveMethod(str) { - if (str === null || str === undefined) return { concept: 1107, name: "NONE", period: null }; - var contraceptives = [ - { concept: 190, name: "CONDOMS", period: "Short term" }, - { concept: 780, name: "ORAL CONTRACEPTION", period: "Short term" }, - { concept: 907, name: "MEDROXYPROGESTERONE ACETATE", period: "Short term" }, - { concept: 5278, name: "DIAPHRAGM", period: "Short term" }, - { concept: 5279, name: "INJECTABLE CONTRACEPTIVE", period: "Long term" }, - { concept: 5622, name: "OTHER NON-CODED", period: null }, - { concept: 5275, name: "INTRAUTERINE DEVICE", period: "Long term" }, - { concept: 5276, name: "FEMALE STERILIZATION", period: "Long term" }, - { concept: 5277, name: "NATURAL FAMILY PLANNING", period: null }, - { concept: 1107, name: "NONE", period: null }, - { concept: 6220, name: "CONTRACEPTIVE IMPLANT", period: "Long term" }, - { concept: 6218, name: "COMBINED HORMONE ORAL CONTRACEPTIVE PILL", period: "Short term" }, - { concept: 6219, name: "PERIODIC ABSTINENCE", period: null }, - { concept: 6217, name: "PROGESTIN PILLS", period: "Short term" }, - { concept: 6700, name: "TUBAL LIGATION", period: "Long term" }, - { concept: 6701, name: "VASECTOMY", period: "Long term" }, - { concept: 5841, name: "HERBAL TRADITIONAL MEDICATIONS", period: "Short term" }, - { concept: 6717, name: "FEMALE CONDOMS", period: "Short term" }, - { concept: 6718, name: "MALE CONDOMS", period: "Short term" }, - { concept: 6725, name: "EMERGENCY CONTRACEPTIVE PILLS", period: "Short term" }, - { concept: 8134, name: "CONTRACEPTIVE SPONGE", period: "Short term" }, - { concept: 5274, name: "FAMILY PLANNING VIA ORAL CONTRACEPTIVE PILLS", period: "Short term" }, - { concept: 1624, name: "DO NOT KNOW", period: null }, - { concept: 6707, name: "UNDECIDED", period: null }, - { concept: 8300, name: "LACTATIONAL AMENORRHEA METHOD", period: "Short term" }, - { concept: 9510, name: "3-YEAR CONTRACEPTIVE IMPLANT", period: "Long term" }, - { concept: 9511, name: "5-YEAR CONTRACEPTIVE IMPLANT", period: "Long term" }, - { concept: 1067, name: "UNKNOWN", period: null }, - { concept: 9734, name: "COPPER INTRAUTERINE DEVICE", period: "Long term" }, - { concept: 9735, name: "HORMONAL INTRAUTERINE DEVICE", period: "Long term" }, - { concept: 10956, name: "CONTRACEPTION METHOD UNDECIDED", period: null }, - { concept: 10817, name: "NORPLANT(IMPLANTABLE CONTRACEPTIVE)", period: "Long term" } - ] - var contraceptiveMethod = {} | null; - _.each(contraceptives, function (contraceptive) { - if (contraceptive.concept === str) { - contraceptiveMethod = contraceptive; - } - }); - if (contraceptiveMethod === 0 || typeof (contraceptiveMethod) != "object") return { concept: str, name: "UNKNOWN", period: null } - return contraceptiveMethod; + { concept: 5278, name: 'DIAPHRAGM', period: 'Short term' }, + { + concept: 5279, + name: 'INJECTABLE CONTRACEPTIVE', + period: 'Long term' }, - - getTestsOrderedNames: function getTestsOrderedNames(str) { - if (str === null || str === undefined) return ""; - var tests = { - 678: "WBC", - 21: "Hb", - 790: "Cr", - 654: "ALT", - 653: "AST", - 5497: "CD4", - 730: "CD4%", - 856: "Viral Load", - 1040: "Rapid HIV", - 1030: "HIV DNA PCR", - 2323: "TB PCR", - 2311: "Sputum Culture", - 307: "Sputum AFB", - 8064: "Sputum Gene Xpert", - 8070: "MTB Finding", - 8071: "RIF Resistant Finding", - 299: "VDRL", - 729: "Platelets", - 851: "MCV", - 12: "Chest Xray", - 1019: "Complete Blood Count", - 657: "CD4 PANEL", - 6126: "HbA1c", - 887: "RBS", - 6252: "FBS", - 1537: "EKG", - 857: "UREA" - - - }; - var testsCodes = str.toString().split(" ## "); - var testsNames = []; - _.each(testsCodes, function (code) { - testsNames.push(tests[code]); - }); - return testsNames.join(","); + { concept: 5622, name: 'OTHER NON-CODED', period: null }, + { concept: 5275, name: 'INTRAUTERINE DEVICE', period: 'Long term' }, + { concept: 5276, name: 'FEMALE STERILIZATION', period: 'Long term' }, + { concept: 5277, name: 'NATURAL FAMILY PLANNING', period: null }, + { concept: 1107, name: 'NONE', period: null }, + { concept: 6220, name: 'CONTRACEPTIVE IMPLANT', period: 'Long term' }, + { + concept: 6218, + name: 'COMBINED HORMONE ORAL CONTRACEPTIVE PILL', + period: 'Short term' + }, + { concept: 6219, name: 'PERIODIC ABSTINENCE', period: null }, + { concept: 6217, name: 'PROGESTIN PILLS', period: 'Short term' }, + { concept: 6700, name: 'TUBAL LIGATION', period: 'Long term' }, + { concept: 6701, name: 'VASECTOMY', period: 'Long term' }, + { + concept: 5841, + name: 'HERBAL TRADITIONAL MEDICATIONS', + period: 'Short term' }, - getCDMNames: function getCDMNames(tests, str) { - if (str === null || str === undefined) return ""; - /*var tests = { + { concept: 6717, name: 'FEMALE CONDOMS', period: 'Short term' }, + { concept: 6718, name: 'MALE CONDOMS', period: 'Short term' }, + { + concept: 6725, + name: 'EMERGENCY CONTRACEPTIVE PILLS', + period: 'Short term' + }, + { concept: 8134, name: 'CONTRACEPTIVE SPONGE', period: 'Short term' }, + { + concept: 5274, + name: 'FAMILY PLANNING VIA ORAL CONTRACEPTIVE PILLS', + period: 'Short term' + }, + { concept: 1624, name: 'DO NOT KNOW', period: null }, + { concept: 6707, name: 'UNDECIDED', period: null }, + { + concept: 8300, + name: 'LACTATIONAL AMENORRHEA METHOD', + period: 'Short term' + }, + { + concept: 9510, + name: '3-YEAR CONTRACEPTIVE IMPLANT', + period: 'Long term' + }, + { + concept: 9511, + name: '5-YEAR CONTRACEPTIVE IMPLANT', + period: 'Long term' + }, + { concept: 1067, name: 'UNKNOWN', period: null }, + { + concept: 9734, + name: 'COPPER INTRAUTERINE DEVICE', + period: 'Long term' + }, + { + concept: 9735, + name: 'HORMONAL INTRAUTERINE DEVICE', + period: 'Long term' + }, + { + concept: 10956, + name: 'CONTRACEPTION METHOD UNDECIDED', + period: null + }, + { + concept: 10817, + name: 'NORPLANT(IMPLANTABLE CONTRACEPTIVE)', + period: 'Long term' + } + ]; + var contraceptiveMethod = {} | null; + _.each(contraceptives, function (contraceptive) { + if (contraceptive.concept === str) { + contraceptiveMethod = contraceptive; + } + }); + if (contraceptiveMethod === 0 || typeof contraceptiveMethod != 'object') + return { concept: str, name: 'UNKNOWN', period: null }; + return contraceptiveMethod; + }, + + getTestsOrderedNames: function getTestsOrderedNames(str) { + if (str === null || str === undefined) return ''; + var tests = { + 678: 'WBC', + 21: 'Hb', + 790: 'Cr', + 654: 'ALT', + 653: 'AST', + 5497: 'CD4', + 730: 'CD4%', + 856: 'Viral Load', + 1040: 'Rapid HIV', + 1030: 'HIV DNA PCR', + 2323: 'TB PCR', + 2311: 'Sputum Culture', + 307: 'Sputum AFB', + 8064: 'Sputum Gene Xpert', + 8070: 'MTB Finding', + 8071: 'RIF Resistant Finding', + 299: 'VDRL', + 729: 'Platelets', + 851: 'MCV', + 12: 'Chest Xray', + 1019: 'Complete Blood Count', + 657: 'CD4 PANEL', + 6126: 'HbA1c', + 887: 'RBS', + 6252: 'FBS', + 1537: 'EKG', + 857: 'UREA' + }; + var testsCodes = str.toString().split(' ## '); + var testsNames = []; + _.each(testsCodes, function (code) { + testsNames.push(tests[code]); + }); + return testsNames.join(','); + }, + getCDMNames: function getCDMNames(tests, str) { + if (str === null || str === undefined) return ''; + /*var tests = { 99:"LASIX", 250:"NIFEDIPINE", 920:"TAGRETOL", @@ -690,163 +771,168 @@ module.exports = function () { 620:"HEADACHE" };*/ - var testsCodes = str.toString().split(" ## "); - var testsNames = []; - _.each(testsCodes, function (code) { - code = code.trim(); - testsNames.push(tests[code]); - }); - return testsNames.join(","); - }, - transformMedicalRefillToClinical: function transformMedicalRefillToClinical(hivSummaries) { - let transfromedArray = []; - _.each(hivSummaries, (hivSummary) => { - if (hivSummary.encounter_type == 186) { - // console.log('summarytest',hivSummary); - hivSummary.is_clinical_encounter = 1; - // console.log('summarytest',hivSummary); - } - transfromedArray.push(hivSummary); - }); - - return transfromedArray; - - }, - getConceptNames: function getCDMNames(concepts, str) { - if (str === null || str === undefined) return ""; - var testsCodes = str.toString().split(" ## "); - var testsNames = []; - _.each(testsCodes, function (code) { - code = code.trim(); - testsNames.push(concepts[code]); - }); - return testsNames.join(","); - }, - resolvedLabOrderErrors: function resolvedLabOrderErrors(vlerror, cd4eror, pcrerror) { - var message = ''; - - if (vlerror === 1) - message = 'Error processing Viral Load'; - if (cd4eror === 1) { - if (message !== '') - message = message + ', ' + 'Error processing cd4'; - else - message = 'Error processing cd4'; - } - - if (pcrerror === 1) { - - if (message !== '') - message = message + ', ' + 'Error processing hiv dna pcr'; - else - message = 'Error processing hiv dna pcr'; - } - - return message - - }, - - buildWhereClauseForDataEntryIndicators: function buildWhereClauseForDataEntryIndicators(queryParams, where) { - if (queryParams.locations) { - var locations = []; - _.each(queryParams.locations.split(','), function (loc) { - locations.push(Number(loc)); - }); - where[0] = where[0] + " and t2.location_id in ?"; - where.push(locations); - } - if (queryParams.provideruuid) { - where[0] = where[0] + " and t4.uuid = ?"; - where.push(queryParams.provideruuid); - } - if (queryParams.creatoruuid) { - where[0] = where[0] + " and t5.uuid = ?"; - where.push(queryParams.creatoruuid); - } - if (queryParams.encounterTypeIds) { - var encounterTypes = []; - _.each(queryParams.encounterTypeIds.split(','), function (encType) { - encounterTypes.push(Number(encType)); - }); - where[0] = where[0] + " and t2.encounter_type in ?"; - where.push(encounterTypes); - } - if (queryParams.formIds) { - var formIds = []; - _.each(queryParams.formIds.split(','), function (formid) { - formIds.push(Number(formid)); - }); - where[0] = where[0] + " and t2.form_id in ?"; - where.push(formIds); - } - }, - decodeBase64Image: function decodeBase64Image(dataString) { - var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/), - response = {}; - - if (matches.length !== 3) { - return new Error('Invalid input string'); - } - - response.type = matches[1]; - response.data = new Buffer(matches[2], 'base64'); - - return response; - }, - buildWhereParamsDataEntryIndicators: function buildWhereParamsDataEntryIndicators(queryParams, where) { - if (queryParams.locations) { - var locations = []; - _.each(queryParams.locations.split(','), function (loc) { - locations.push(Number(loc)); - }); - where.locations = locations; - } - if (queryParams.provideruuid) { - where.providerUuid = queryParams.provideruuid; - } - if (queryParams.creatoruuid) { - var creatorUuids = []; - _.each(queryParams.creatoruuid.split(','), function (creator) { - creatorUuids.push(creator); - }); - where.creator = creatorUuids; - } - if (queryParams.encounterTypeIds) { - var encounterTypes = []; - _.each(queryParams.encounterTypeIds.split(','), function (encType) { - encounterTypes.push(Number(encType)); - }); - where.encounterTypes = encounterTypes; - } - if (queryParams.visitTypeIds) { - var visitTypes = []; - _.each(queryParams.visitTypeIds.split(','), function (visitType) { - visitTypes.push(Number(visitType)); - }); - where.visitTypes = visitTypes; - } - if (queryParams.formIds) { - var formIds = []; - _.each(queryParams.formIds.split(','), function (formid) { - formIds.push(Number(formid)); - }); - where.formIds = formIds; - } - }, - filterDate: function filterDate(date) { - if (!_.isNull(date)) { - return moment(date).format('DD-MM-YYYY'); - } - return date; - }, - titleCase: function titleCase(name) { - if (name) { - name = name.toLowerCase().split(" "); - for (var i = 0; i < name.length; i++) { - name[i] = name[i].charAt(0).toUpperCase() + name[i].slice(1); - } - return name.join(" "); - } - } - }; -}(); + var testsCodes = str.toString().split(' ## '); + var testsNames = []; + _.each(testsCodes, function (code) { + code = code.trim(); + testsNames.push(tests[code]); + }); + return testsNames.join(','); + }, + transformMedicalRefillToClinical: function transformMedicalRefillToClinical( + hivSummaries + ) { + let transfromedArray = []; + _.each(hivSummaries, (hivSummary) => { + if (hivSummary.encounter_type == 186) { + // console.log('summarytest',hivSummary); + hivSummary.is_clinical_encounter = 1; + // console.log('summarytest',hivSummary); + } + transfromedArray.push(hivSummary); + }); + + return transfromedArray; + }, + getConceptNames: function getCDMNames(concepts, str) { + if (str === null || str === undefined) return ''; + var testsCodes = str.toString().split(' ## '); + var testsNames = []; + _.each(testsCodes, function (code) { + code = code.trim(); + testsNames.push(concepts[code]); + }); + return testsNames.join(','); + }, + resolvedLabOrderErrors: function resolvedLabOrderErrors( + vlerror, + cd4eror, + pcrerror + ) { + var message = ''; + + if (vlerror === 1) message = 'Error processing Viral Load'; + if (cd4eror === 1) { + if (message !== '') message = message + ', ' + 'Error processing cd4'; + else message = 'Error processing cd4'; + } + + if (pcrerror === 1) { + if (message !== '') + message = message + ', ' + 'Error processing hiv dna pcr'; + else message = 'Error processing hiv dna pcr'; + } + + return message; + }, + + buildWhereClauseForDataEntryIndicators: function buildWhereClauseForDataEntryIndicators( + queryParams, + where + ) { + if (queryParams.locations) { + var locations = []; + _.each(queryParams.locations.split(','), function (loc) { + locations.push(Number(loc)); + }); + where[0] = where[0] + ' and t2.location_id in ?'; + where.push(locations); + } + if (queryParams.provideruuid) { + where[0] = where[0] + ' and t4.uuid = ?'; + where.push(queryParams.provideruuid); + } + if (queryParams.creatoruuid) { + where[0] = where[0] + ' and t5.uuid = ?'; + where.push(queryParams.creatoruuid); + } + if (queryParams.encounterTypeIds) { + var encounterTypes = []; + _.each(queryParams.encounterTypeIds.split(','), function (encType) { + encounterTypes.push(Number(encType)); + }); + where[0] = where[0] + ' and t2.encounter_type in ?'; + where.push(encounterTypes); + } + if (queryParams.formIds) { + var formIds = []; + _.each(queryParams.formIds.split(','), function (formid) { + formIds.push(Number(formid)); + }); + where[0] = where[0] + ' and t2.form_id in ?'; + where.push(formIds); + } + }, + decodeBase64Image: function decodeBase64Image(dataString) { + var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/), + response = {}; + + if (matches.length !== 3) { + return new Error('Invalid input string'); + } + + response.type = matches[1]; + response.data = new Buffer(matches[2], 'base64'); + + return response; + }, + buildWhereParamsDataEntryIndicators: function buildWhereParamsDataEntryIndicators( + queryParams, + where + ) { + if (queryParams.locations) { + var locations = []; + _.each(queryParams.locations.split(','), function (loc) { + locations.push(Number(loc)); + }); + where.locations = locations; + } + if (queryParams.provideruuid) { + where.providerUuid = queryParams.provideruuid; + } + if (queryParams.creatoruuid) { + var creatorUuids = []; + _.each(queryParams.creatoruuid.split(','), function (creator) { + creatorUuids.push(creator); + }); + where.creator = creatorUuids; + } + if (queryParams.encounterTypeIds) { + var encounterTypes = []; + _.each(queryParams.encounterTypeIds.split(','), function (encType) { + encounterTypes.push(Number(encType)); + }); + where.encounterTypes = encounterTypes; + } + if (queryParams.visitTypeIds) { + var visitTypes = []; + _.each(queryParams.visitTypeIds.split(','), function (visitType) { + visitTypes.push(Number(visitType)); + }); + where.visitTypes = visitTypes; + } + if (queryParams.formIds) { + var formIds = []; + _.each(queryParams.formIds.split(','), function (formid) { + formIds.push(Number(formid)); + }); + where.formIds = formIds; + } + }, + filterDate: function filterDate(date) { + if (!_.isNull(date)) { + return moment(date).format('DD-MM-YYYY'); + } + return date; + }, + titleCase: function titleCase(name) { + if (name) { + name = name.toLowerCase().split(' '); + for (var i = 0; i < name.length; i++) { + name[i] = name[i].charAt(0).toUpperCase() + name[i].slice(1); + } + return name.join(' '); + } + } + }; +})(); diff --git a/etl-processors.js b/etl-processors.js index ec891b703..1f03ab54c 100755 --- a/etl-processors.js +++ b/etl-processors.js @@ -1,25 +1,24 @@ -"use strict"; -var _ = require('underscore'); -var __ = require('lodash'); -var helpers = require('./etl-helpers'); -var patientFlowProcessor = require('./report-post-processors/patient-flow-processor'); +'use strict'; +var _ = require('underscore'); +var __ = require('lodash'); +var helpers = require('./etl-helpers'); +var patientFlowProcessor = require('./report-post-processors/patient-flow-processor'); var clinicalComparatorProcessor = require('./report-post-processors/clinic-comparator-processor'); -var patientReferralProcessor = require('./report-post-processors/patient-referral-processor'); -var concept_name_dao = require('./dao/concepts/concept-name-dao.js'); +var patientReferralProcessor = require('./report-post-processors/patient-referral-processor'); +var concept_name_dao = require('./dao/concepts/concept-name-dao.js'); -module.exports = function () { +module.exports = (function () { return { - convertConceptIdToName : convertConceptIdToName, + convertConceptIdToName: convertConceptIdToName, convertCdmConceptIdToName: convertCdmConceptIdToName, - cdmMedicationChange : cdmMedicationChange, - processPatientFlow : processPatientFlow, + cdmMedicationChange: cdmMedicationChange, + processPatientFlow: processPatientFlow, processClinicalComparator: processClinicalComparator, - findChanges : findChanges, - processPatientReferral : processPatientReferral, + findChanges: findChanges, + processPatientReferral: processPatientReferral }; - - function convertConceptIdToName (indicators, queryResults, requestIndicators) { - + + function convertConceptIdToName(indicators, queryResults, requestIndicators) { _.each(indicators, function (indicator) { _.each(queryResults.result, function (row) { row[indicator] = helpers.getARVNames(row[indicator]); @@ -27,60 +26,80 @@ module.exports = function () { }); return queryResults; } - - function convertCdmConceptIdToName (indicators, queryResults, requestIndicators) { + + function convertCdmConceptIdToName( + indicators, + queryResults, + requestIndicators + ) { return new Promise(function (resolve, reject) { - concept_name_dao.getConceptNames().then(function (tests) { - _.each(indicators, function (indicator) { - _.each(queryResults.result, function (row) { - row[indicator + '_name'] = helpers.getCDMNames(tests, row[indicator]); + concept_name_dao + .getConceptNames() + .then(function (tests) { + _.each(indicators, function (indicator) { + _.each(queryResults.result, function (row) { + row[indicator + '_name'] = helpers.getCDMNames( + tests, + row[indicator] + ); + }); }); + resolve(queryResults); + }) + .catch(function (err) { + reject(err); }); - resolve(queryResults); - }).catch(function (err) { - reject(err); - }); }); } - - function findChanges (indicators, queryResults, requestIndicators) { + + function findChanges(indicators, queryResults, requestIndicators) { var rows = []; _.each(queryResults.result, function (row) { - var current = row.current_regimen ? row.current_regimen.split('##') : null; - var previous = row.previous_regimen ? row.previous_regimen.split('##').sort() : null; + var current = row.current_regimen + ? row.current_regimen.split('##') + : null; + var previous = row.previous_regimen + ? row.previous_regimen.split('##').sort() + : null; if (!arraysEqual(current, previous)) { rows.push(row); } }); return rows; } - - function cdmMedicationChange (results) { - - var rows = []; + + function cdmMedicationChange(results) { + var rows = []; var med_results = results.result; - med_results = __.reverse(med_results); + med_results = __.reverse(med_results); _.each(med_results, function (row, index) { var row_promise = new Promise(function (resolve, reject) { - var current = row.prescriptions ? row.prescriptions.split('##').sort() : null; + var current = row.prescriptions + ? row.prescriptions.split('##').sort() + : null; var previous = ''; if (index > 0) { var previousRow = med_results[index - 1]; - previous = previousRow.prescriptions ? previousRow.prescriptions.split('##').sort(): null; + previous = previousRow.prescriptions + ? previousRow.prescriptions.split('##').sort() + : null; } - var diff =_.difference(previous,current); - if(diff.length>0){ + var diff = _.difference(previous, current); + if (diff.length > 0) { if (row.prescriptions) { - addCdmMedicationChangeStatus(row).then(function (presc) { - resolve({prescriptions: presc, encounter_datetime: row.encounter_datetime}); - }).catch(function (err) { - }); + addCdmMedicationChangeStatus(row) + .then(function (presc) { + resolve({ + prescriptions: presc, + encounter_datetime: row.encounter_datetime + }); + }) + .catch(function (err) {}); } else { - resolve({prescriptions: null, encounter_datetime: null}); + resolve({ prescriptions: null, encounter_datetime: null }); } - } else { - resolve({prescriptions: null, encounter_datetime: null}); + resolve({ prescriptions: null, encounter_datetime: null }); } }); rows.push(row_promise); @@ -89,128 +108,161 @@ module.exports = function () { var fiData = __.uniqBy(_rows, function (e) { return e.encounter_datetime; }); - + results.result = __.reverse(fiData); return Promise.resolve(results); }); - - } - - function addCdmMedicationChangeStatus (dataRow) { - var prescription = dataRow.prescriptions; - var DRUG_DOSE = 1899; - var FREQUENCY = 1896; - var DIABETES_TREATMENT_PLAN = 7306; - var HTN_TREATMENT_PLAN = 7333; + + function addCdmMedicationChangeStatus(dataRow) { + var prescription = dataRow.prescriptions; + var DRUG_DOSE = 1899; + var FREQUENCY = 1896; + var DIABETES_TREATMENT_PLAN = 7306; + var HTN_TREATMENT_PLAN = 7333; var DIABETES_TREATMENT_STARTED = 7304; var HTN_TREATMENT_STARTED = 7332; - var rows = []; - var prescriptions = prescription.split('$'); - + var rows = []; + var prescriptions = prescription.split('$'); + return new Promise(function (resolve, reject) { - concept_name_dao.getConceptNames().then(function (concepts) { - _.each(prescriptions, function (row) { - var prescription_details = row.split('##'); - var result = { - medication_plan: '', - meds : '', - dose : '', - frequency : '', - date : '' - }; - _.each(prescription_details, function (details) { - - var hasStatus = details.includes(DIABETES_TREATMENT_PLAN); - var hasHtnStatus = details.includes(HTN_TREATMENT_PLAN); - result['original_prescription'] = dataRow.prescriptions; - result['dm_meds'] = dataRow.dm_meds; - result['htn_meds'] = dataRow.htn_meds; - - if (hasStatus || hasHtnStatus) { - var status = details.split('=')[1].replace('!!', '').trim(); - result['medication_plan'] = helpers.getConceptNames(concepts,status) ? helpers.getConceptNames(concepts,status) : status; - - } - - var meds = details.includes(DIABETES_TREATMENT_STARTED); - var htnMeds = details.includes(HTN_TREATMENT_STARTED); - if (meds || htnMeds) { - var med = details.split('=')[1].replace('!!', '').trim(); - result['meds'] = helpers.getConceptNames(concepts, med) ? helpers.getConceptNames(concepts, med) : med; - } - - var dosed = details.includes(DRUG_DOSE); - if (dosed) { - var dose = details.split('=')[1].replace('!!', '').trim(); - result['dose'] = dose ? dose : ' '; - } - - var drug_frequency = details.includes(FREQUENCY); - if (drug_frequency) { - var drugFrequency = details.split('=')[1].replace('!!', '').trim(); - result['frequency'] = helpers.getConceptNames(concepts, drugFrequency) ? helpers.getConceptNames(concepts, drugFrequency) : drugFrequency; - } + concept_name_dao + .getConceptNames() + .then(function (concepts) { + _.each(prescriptions, function (row) { + var prescription_details = row.split('##'); + var result = { + medication_plan: '', + meds: '', + dose: '', + frequency: '', + date: '' + }; + _.each(prescription_details, function (details) { + var hasStatus = details.includes(DIABETES_TREATMENT_PLAN); + var hasHtnStatus = details.includes(HTN_TREATMENT_PLAN); + result['original_prescription'] = dataRow.prescriptions; + result['dm_meds'] = dataRow.dm_meds; + result['htn_meds'] = dataRow.htn_meds; + + if (hasStatus || hasHtnStatus) { + var status = details.split('=')[1].replace('!!', '').trim(); + result['medication_plan'] = helpers.getConceptNames( + concepts, + status + ) + ? helpers.getConceptNames(concepts, status) + : status; + } + + var meds = details.includes(DIABETES_TREATMENT_STARTED); + var htnMeds = details.includes(HTN_TREATMENT_STARTED); + if (meds || htnMeds) { + var med = details.split('=')[1].replace('!!', '').trim(); + result['meds'] = helpers.getConceptNames(concepts, med) + ? helpers.getConceptNames(concepts, med) + : med; + } + + var dosed = details.includes(DRUG_DOSE); + if (dosed) { + var dose = details.split('=')[1].replace('!!', '').trim(); + result['dose'] = dose ? dose : ' '; + } + + var drug_frequency = details.includes(FREQUENCY); + if (drug_frequency) { + var drugFrequency = details + .split('=')[1] + .replace('!!', '') + .trim(); + result['frequency'] = helpers.getConceptNames( + concepts, + drugFrequency + ) + ? helpers.getConceptNames(concepts, drugFrequency) + : drugFrequency; + } + }); + rows.push(result); }); - rows.push(result); + + resolve(rows); + }) + .catch(function (err) { + reject(err); }); - - resolve(rows); - }).catch(function (err) { - reject(err); - }); }); } - - function arraysEqual (a, b) { + + function arraysEqual(a, b) { if (a === b) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; - + // If you don't care about the order of the elements inside // the array, you should sort both arrays here. - + for (var i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } - - function processPatientFlow (indicators, queryResults, requestIndicators) { + + function processPatientFlow(indicators, queryResults, requestIndicators) { //use processor helpers here - queryResults.result = - patientFlowProcessor.groupResultsByVisitId(queryResults.result); - queryResults.averageWaitingTime = - patientFlowProcessor.calculateAverageWaitingTime(queryResults.result); - queryResults.medianWaitingTime = - patientFlowProcessor.calculateMedianWaitingTime(queryResults.result); - queryResults.incompleteVisitsCount = - patientFlowProcessor.getIncompleteVisitsCount(queryResults.result); - queryResults.completeVisitsCount = - patientFlowProcessor.getCompleteVisitsCount(queryResults.result); - queryResults.totalVisitsCount = - patientFlowProcessor.getTotalVisitsCount(queryResults.result); - queryResults.resultsByLocation = patientFlowProcessor.splitResultsByLocation(queryResults.result); - queryResults.statsByLocation = patientFlowProcessor.calculateStatisticsByLocation(queryResults.resultsByLocation); - queryResults.hourlyStats = patientFlowProcessor.calculateHourlyStatistics(queryResults.result); - + queryResults.result = patientFlowProcessor.groupResultsByVisitId( + queryResults.result + ); + queryResults.averageWaitingTime = patientFlowProcessor.calculateAverageWaitingTime( + queryResults.result + ); + queryResults.medianWaitingTime = patientFlowProcessor.calculateMedianWaitingTime( + queryResults.result + ); + queryResults.incompleteVisitsCount = patientFlowProcessor.getIncompleteVisitsCount( + queryResults.result + ); + queryResults.completeVisitsCount = patientFlowProcessor.getCompleteVisitsCount( + queryResults.result + ); + queryResults.totalVisitsCount = patientFlowProcessor.getTotalVisitsCount( + queryResults.result + ); + queryResults.resultsByLocation = patientFlowProcessor.splitResultsByLocation( + queryResults.result + ); + queryResults.statsByLocation = patientFlowProcessor.calculateStatisticsByLocation( + queryResults.resultsByLocation + ); + queryResults.hourlyStats = patientFlowProcessor.calculateHourlyStatistics( + queryResults.result + ); + return queryResults; - } - function processClinicalComparator(indicators, queryResults, requestIndicators) { - let result = - clinicalComparatorProcessor.groupResultsByMonth(queryResults, requestIndicators); + function processClinicalComparator( + indicators, + queryResults, + requestIndicators + ) { + let result = clinicalComparatorProcessor.groupResultsByMonth( + queryResults, + requestIndicators + ); return result; } - - function processPatientReferral (indicators, queryResults, requestIndicators) { - queryResults.result = - patientReferralProcessor.UngroupResults(queryResults.results); - queryResults.groupedResult = - patientReferralProcessor.groupResultsByLocation(queryResults.result); - + + function processPatientReferral(indicators, queryResults, requestIndicators) { + queryResults.result = patientReferralProcessor.UngroupResults( + queryResults.results + ); + queryResults.groupedResult = patientReferralProcessor.groupResultsByLocation( + queryResults.result + ); + return queryResults; } -}(); +})(); diff --git a/etl-routes.js b/etl-routes.js index 16642c3bc..d3980c4a1 100755 --- a/etl-routes.js +++ b/etl-routes.js @@ -1,5 +1,5 @@ /*jshint -W003, -W098, -W117, -W026 */ -"use strict"; +'use strict'; // var dao = require('./etl-dao'); var dao = require('./etl-dao'); var patientList = require('./dao/patient-list/patient-list-dao'); @@ -65,4875 +65,5729 @@ import { LungCancerTreatmentSummary } from './service/lung-cancer-treatment-summ import { SurgeService } from './service/surge-reports/surge-report.service'; var patientReminderService = require('./service/patient-reminder.service.js'); -var kibanaService = require('./service/kibana.service'); +var kibanaService = require('./service/kibana.service'); import { HeiSummaryService } from './service/moh-408-service'; -import { - RetentionAppointmentTracingService -} from './service/retention-appointment-tracing-service'; +import { RetentionAppointmentTracingService } from './service/retention-appointment-tracing-service'; import { PatientGainLosesService } from './service/patient-gain-loses.service'; - -module.exports = function () { - - var routes = - [ - { - method: 'GET', - path: '/', - config: { - plugins: { - 'hapiAuthorization': false - }, - handler: function (request, reply) { - - console.log('default rote', request.path); - - reply('Welcome to Ampath ETL service.'); - //return reply(Boom.forbidden('Not this end point bruh')); - }, - description: 'Home', - notes: 'Returns a message that shows ETL service is running.', - tags: ['api'], - } - }, - { - method: 'POST', - path: '/etl/user-feedback', - config: { - plugins: { - 'hapiAuthorization': false - }, - auth: false, - handler: function (request, reply) { - var message = request.payload; - let service = new SlackService(); - service.postFeedbackToPoc(message).then((success) => { - reply(success); - }).catch((err) => { - reply(Boom.badData(error)); - }); - }, - description: 'Endpoint that receives feedback from a private channel', - notes: 'Specify the private channel name,message count and oldest timestamp in the url parameters', - tags: ['api', 'feedback'], - } - }, - { - method: 'GET', - path: '/etl/clinic-lab-orders', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - if (request.query.locationUuids) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - request.query.groupBy = 'groupByPerson,groupByd'; - let compineRequestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('clinic-lab-orders-report', ['startDate', 'endDate', 'locations', 'groupBy'], compineRequestParams); - - dao.runReport(reportParams).then((result) => { - _.each(result.result, (row) => { - row.order_type = etlHelpers.getTestsOrderedNames(row.order_type); - row.cur_meds = etlHelpers.getARVNames(row.cur_meds); - }); - reply(result); - }).catch((error) => { - reply(error); - }) - }); - } - }, - description: 'Get a list of patients who made lab orders on a selected date', - notes: 'Returns a list of patients patients who made lab orders through selected clinics on a selected date', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/poc-user-feedback/{count*2}', - config: { - auth: false, - handler: function (request, reply) { - let service = new SlackService(); - const urlparts = request.params.count.split('/'); - service.getPocMessages(encodeURIComponent(urlparts[0]), encodeURIComponent(urlparts[1])) - .then((res) => { - reply(res); - }).catch((error) => { - reply(Boom.badData(error)); - }); - }, - description: 'Endpoint that gets user feedback from poc', - notes: 'Specify message count and oldest timestamp in the url parameters', - tags: ['api', 'feedback'], - } - }, - { - method: 'POST', - path: '/etl/posttochannel', - config: { - plugins: { - 'hapiAuthorization': false - }, - auth: false, - handler: function (request, reply) { - var message = request.payload; - var channel = request.payload.channel; - let service = new SlackService(); - service.postToChannels(message, channel).then(function (success) { - reply(success); - }).catch((err) => { - reply(Boom.badData(error)); - }); - }, - description: 'Endpoint that post user feedback from client to a public slack channel', - notes: 'Specify the public channel name in the payload', - tags: ['api', 'feedback'], - } - }, - { - method: 'POST', - path: '/etl/posttogroup', - config: { - plugins: { - 'hapiAuthorization': false - }, - auth: false, - handler: function (request, reply) { - var message = request.payload; - var channel = request.payload.group; - let service = new SlackService(); - service.postToGroups(message, channel).then(function (success) { - reply(success); - }).catch((err) => { - reply(Boom.badData(error)); - }); - }, - description: 'Endpoint that post user feedback from client to a private slack channel', - notes: 'Specify the private channel name in the payload', - tags: ['api', 'feedback'], - } - }, - - { - method: 'GET', - path: '/etl/channel-user-feedback/{count*2}', - /* /etl/channel-user-feedback/10/1504081732.000145 */ - config: { - auth: false, - handler: function (request, reply) { - let service = new SlackService(); - const urlparts = request.params.count.split('/'); - service.getChannelMessages(encodeURIComponent(urlparts[0]), encodeURIComponent(urlparts[1])) - .then((res) => { - reply(res); - }).catch((error) => { - reply(Boom.badData(error)); - }); - }, - description: 'Endpoint that receives feedback from a public channel', - notes: 'Specify message count and oldest timestamp in the url parameters', - tags: ['api', 'feedback'], - } - }, - { - method: 'GET', - path: '/etl/channel-user-feedback/{count*3}', - /* /etl/channel-user-feedback/poc-user-feedback/10/1504081732.000145 */ - config: { - auth: false, - handler: function (request, reply) { - let service = new SlackService(); - const urlparts = request.params.count.split('/'); - service.getFromChannel(encodeURIComponent(urlparts[0]), encodeURIComponent(urlparts[1]), encodeURIComponent(urlparts[2])) - .then((res) => { - reply(res); - }).catch((error) => { - reply(Boom.badData(error)); - }); - }, - description: 'Endpoint that receives feedback from a public channel', - notes: 'Specify the public channel name,message count and oldest timestamp in the url parameters', - tags: ['api', 'feedback'], - } - }, - { - method: 'GET', - path: '/etl/group-user-feedback/{count*3}', - /* /etl/channel-user-feedback/poc-user-feedback/10/1504081732.000145 */ - config: { - auth: false, - handler: function (request, reply) { - let service = new SlackService(); - const urlparts = request.params.count.split('/'); - service.getFromGroup(encodeURIComponent(urlparts[0]), encodeURIComponent(urlparts[1]), encodeURIComponent(urlparts[2])) - .then((res) => { - reply(JSON.parse(res)); - }).catch((error) => { - reply(Boom.badData(error)); - }); - }, - description: 'Endpoint that receives feedback from a private channel', - notes: 'Specify the private channel name,message count and oldest timestamp in the url parameters', - tags: ['api', 'feedback'], - } - }, - { - method: 'GET', - path: '/etl/get-monthly-schedule', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - if (request.query.locationUuids) { - programVisitEncounterResolver.resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) - .then((resolve) => { - let encounterIds = resolve.encounterTypeIds; - let visitTypeIds = resolve.visitTypesIds; - let programTypeIds = resolve.programTypeIds; - if (encounterIds.length > 0) { - request.query.encounterIds = encounterIds; - } - if (visitTypeIds.length > 0) { - request.query.visitTypeIds = visitTypeIds; - } - if (programTypeIds.length > 0) { - request.query.programTypeIds = programTypeIds; - } - - return resolveLocationUuidToId.resolveLocationUuidsParamsToIds(request.query); - }) - .then((result) => { - let locationIds = result; - request.query.locations = locationIds; - let combineRequestParams = Object.assign({}, request.query, request.params); - let service = new MonthlyScheduleService(); - service.getMonthlyScheduled(combineRequestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }) - - }).then((error) => { - console.log(error); - }); - - } - }, - description: 'Get monthly schedule', - notes: 'Returns a list of appointments,visits and has not returned', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/daily-appointments/{startDate}', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - if (request.query.locationUuids) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - request.query.groupBy = 'groupByPerson,groupByd'; - programVisitEncounterResolver.resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) - .then((resolve) => { - // console.log('Daily appointments', resolve); - let encounterIds = resolve.encounterTypeIds; - let visitTypeIds = resolve.visitTypesIds; - let programTypeIds = resolve.programTypeIds; - if (programTypeIds.length > 0) { - request.query.programTypeIds = programTypeIds; - } - if (visitTypeIds.length > 0) { - request.query.visitTypeIds = visitTypeIds; - } - if (encounterIds.length > 0) { - request.query.encounterIds = encounterIds; - } - - let combineRequestParams = Object.assign({}, request.query, request.params); - // let reportParams = etlHelpers.getReportParams('daily-appointments', ['startDate', 'locations', 'encounterIds', 'visitTypeIds', 'programTypeIds', 'groupBy'], compineRequestParams); - combineRequestParams.limitParam = combineRequestParams.limit; - combineRequestParams.offSetParam = combineRequestParams.startIndex; - combineRequestParams.endDate = combineRequestParams.startDate; - let service = new PatientlistMysqlReport('dailyAppointmentsAggregate', combineRequestParams); - service.generatePatientListReport(['patients']).then((result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - _.each(returnedResult.result, (item) => { - item.cur_meds = etlHelpers.getARVNames(item.cur_meds); - }); - reply(returnedResult); - }).catch((error) => { - reply(error); - }) - }).catch((error) => { - console.log(error); - }); - }); - } - }, - description: 'Get daily appointments list', - notes: 'Returns a list of patients with appointments', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/daily-visits/{startDate}', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - if (request.query.locationUuids) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - request.query.groupBy = 'groupByPerson,groupByd'; - programVisitEncounterResolver.resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) - .then((resolve) => { - let encounterIds = resolve.encounterTypeIds; - let visitTypeIds = resolve.visitTypesIds; - let programTypeIds = resolve.programTypeIds; - if (programTypeIds.length > 0) { - request.query.programTypeIds = programTypeIds; - } - if (visitTypeIds.length > 0) { - request.query.visitTypeIds = visitTypeIds; - } - if (encounterIds.length > 0) { - request.query.encounterIds = encounterIds; - } - let compineRequestParams = Object.assign({}, request.query, request.params); - compineRequestParams.limitParam = compineRequestParams.limit; - compineRequestParams.offSetParam = compineRequestParams.startIndex; - let service = new PatientlistMysqlReport('dailyAttendanceAggregate', compineRequestParams); - service.generatePatientListReport(['patients']).then((result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - _.each(returnedResult.result, (item) => { - item.cur_meds = etlHelpers.getARVNames(item.cur_meds); - }); - reply(returnedResult); - }).catch((error) => { - reply(error); - }) - }).catch((error) => { - console.log(error); - }); - }); - } - }, - description: 'Get daily attendance list', - notes: 'Returns a facility daily attendance list', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/daily-has-not-returned/{startDate}', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - if (request.query.locationUuids) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - request.query.groupBy = 'groupByPerson,groupByd'; - programVisitEncounterResolver.resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) - .then((resolve) => { - let encounterIds = resolve.encounterTypeIds; - let visitTypeIds = resolve.visitTypesIds; - let programTypeIds = resolve.programTypeIds; - if (programTypeIds.length > 0) { - request.query.programTypeIds = programTypeIds; - } - if (visitTypeIds.length > 0) { - request.query.visitTypeIds = visitTypeIds; - } - if (encounterIds.length > 0) { - request.query.encounterIds = encounterIds; - } - let combineRequestParams = Object.assign({}, request.query, request.params); - combineRequestParams.limitParam = combineRequestParams.limit; - combineRequestParams.offSetParam = combineRequestParams.startIndex; - combineRequestParams.endDate = combineRequestParams.startDate; - //let reportParams = etlHelpers.getReportParams('daily-has-not-returned', ['startDate', 'locations', 'encounterIds', 'visitTypeIds', 'programTypeIds', 'groupBy'], compineRequestParams); - //reportParams.limit = 100000; - let service = new PatientlistMysqlReport('dailyHasNotReturnedAggregate', combineRequestParams); - service.generatePatientListReport(['patients']).then((result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - _.each(returnedResult.result, (item) => { - item.cur_meds = etlHelpers.getARVNames(item.cur_meds); - }); - reply(returnedResult); - }).catch((error) => { - reply(error); - }); - - }) - .catch((error) => { - console.log('Error', error); - reply(error); - }); - - }); - } - }, - description: 'Get a list of patients who did not attend a scheduled visit', - notes: 'Returns a list of patients who did not attend their scheduled visits on the selected date', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/clinic-lab-orders/{dateActivated}', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - if (request.query.locationUuids) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - request.query.groupBy = 'groupByPerson,groupByd'; - let compineRequestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('clinic-lab-orders-report', ['dateActivated', 'locations', 'groupBy'], compineRequestParams); - let report = new BaseMysqlReport('clinicLabOrdersReport', reportParams.requestParams); - report.generateReport().then((results) => { - _.each(results.results.results, (row) => { - row.order_type = etlHelpers.getTestsOrderedNames(row.order_type); - }); - results.result = results.results.results; - delete results['results']; - reply(results); - }).catch((error) => { - reply(error); - }) - }); - } - }, - description: 'Get a list of patients who made lab orders on a selected date', - notes: 'Returns a list of patients patients who made lab orders through selected clinics on a selected date', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/defaulter-list', - config: { - auth: 'simple', - handler: function (request, reply) { - dao.getDefaulterList(request, reply); - }, - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - description: "Get a location's defaulter list", - notes: "Returns a location's defaulter list.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - } - } - } - }, - { - method: 'GET', - path: '/etl/patient/{patientUuids}/cdm-summary', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let requestParams = Object.assign({}, request.query, request.params); - let service = new CDMReportingService(); - service.getPatientSummaryReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: 'Get patient CDM summary', - notes: "Returns a list of historical patient's HIV summary with the given patient uuid. " + - "A patient's CDM summary includes details such as last visit date, " + - "current medication regimen etc. as at that encounter's date. ", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - patientUuids: Joi.string() - .required() - .description("The patient's uuid(universally unique identifier)."), - } +module.exports = (function () { + var routes = [ + { + method: 'GET', + path: '/', + config: { + plugins: { + hapiAuthorization: false + }, + handler: function (request, reply) { + console.log('default rote', request.path); + + reply('Welcome to Ampath ETL service.'); + //return reply(Boom.forbidden('Not this end point bruh')); + }, + description: 'Home', + notes: 'Returns a message that shows ETL service is running.', + tags: ['api'] + } + }, + { + method: 'POST', + path: '/etl/user-feedback', + config: { + plugins: { + hapiAuthorization: false + }, + auth: false, + handler: function (request, reply) { + var message = request.payload; + let service = new SlackService(); + service + .postFeedbackToPoc(message) + .then((success) => { + reply(success); + }) + .catch((err) => { + reply(Boom.badData(error)); + }); + }, + description: 'Endpoint that receives feedback from a private channel', + notes: + 'Specify the private channel name,message count and oldest timestamp in the url parameters', + tags: ['api', 'feedback'] + } + }, + { + method: 'GET', + path: '/etl/clinic-lab-orders', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + request.query.groupBy = 'groupByPerson,groupByd'; + let compineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'clinic-lab-orders-report', + ['startDate', 'endDate', 'locations', 'groupBy'], + compineRequestParams + ); + + dao + .runReport(reportParams) + .then((result) => { + _.each(result.result, (row) => { + row.order_type = etlHelpers.getTestsOrderedNames( + row.order_type + ); + row.cur_meds = etlHelpers.getARVNames(row.cur_meds); + }); + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + } + }, + description: + 'Get a list of patients who made lab orders on a selected date', + notes: + 'Returns a list of patients patients who made lab orders through selected clinics on a selected date', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/poc-user-feedback/{count*2}', + config: { + auth: false, + handler: function (request, reply) { + let service = new SlackService(); + const urlparts = request.params.count.split('/'); + service + .getPocMessages( + encodeURIComponent(urlparts[0]), + encodeURIComponent(urlparts[1]) + ) + .then((res) => { + reply(res); + }) + .catch((error) => { + reply(Boom.badData(error)); + }); + }, + description: 'Endpoint that gets user feedback from poc', + notes: + 'Specify message count and oldest timestamp in the url parameters', + tags: ['api', 'feedback'] + } + }, + { + method: 'POST', + path: '/etl/posttochannel', + config: { + plugins: { + hapiAuthorization: false + }, + auth: false, + handler: function (request, reply) { + var message = request.payload; + var channel = request.payload.channel; + let service = new SlackService(); + service + .postToChannels(message, channel) + .then(function (success) { + reply(success); + }) + .catch((err) => { + reply(Boom.badData(error)); + }); + }, + description: + 'Endpoint that post user feedback from client to a public slack channel', + notes: 'Specify the public channel name in the payload', + tags: ['api', 'feedback'] + } + }, + { + method: 'POST', + path: '/etl/posttogroup', + config: { + plugins: { + hapiAuthorization: false + }, + auth: false, + handler: function (request, reply) { + var message = request.payload; + var channel = request.payload.group; + let service = new SlackService(); + service + .postToGroups(message, channel) + .then(function (success) { + reply(success); + }) + .catch((err) => { + reply(Boom.badData(error)); + }); + }, + description: + 'Endpoint that post user feedback from client to a private slack channel', + notes: 'Specify the private channel name in the payload', + tags: ['api', 'feedback'] + } + }, + + { + method: 'GET', + path: '/etl/channel-user-feedback/{count*2}', + /* /etl/channel-user-feedback/10/1504081732.000145 */ + config: { + auth: false, + handler: function (request, reply) { + let service = new SlackService(); + const urlparts = request.params.count.split('/'); + service + .getChannelMessages( + encodeURIComponent(urlparts[0]), + encodeURIComponent(urlparts[1]) + ) + .then((res) => { + reply(res); + }) + .catch((error) => { + reply(Boom.badData(error)); + }); + }, + description: 'Endpoint that receives feedback from a public channel', + notes: + 'Specify message count and oldest timestamp in the url parameters', + tags: ['api', 'feedback'] + } + }, + { + method: 'GET', + path: '/etl/channel-user-feedback/{count*3}', + /* /etl/channel-user-feedback/poc-user-feedback/10/1504081732.000145 */ + config: { + auth: false, + handler: function (request, reply) { + let service = new SlackService(); + const urlparts = request.params.count.split('/'); + service + .getFromChannel( + encodeURIComponent(urlparts[0]), + encodeURIComponent(urlparts[1]), + encodeURIComponent(urlparts[2]) + ) + .then((res) => { + reply(res); + }) + .catch((error) => { + reply(Boom.badData(error)); + }); + }, + description: 'Endpoint that receives feedback from a public channel', + notes: + 'Specify the public channel name,message count and oldest timestamp in the url parameters', + tags: ['api', 'feedback'] + } + }, + { + method: 'GET', + path: '/etl/group-user-feedback/{count*3}', + /* /etl/channel-user-feedback/poc-user-feedback/10/1504081732.000145 */ + config: { + auth: false, + handler: function (request, reply) { + let service = new SlackService(); + const urlparts = request.params.count.split('/'); + service + .getFromGroup( + encodeURIComponent(urlparts[0]), + encodeURIComponent(urlparts[1]), + encodeURIComponent(urlparts[2]) + ) + .then((res) => { + reply(JSON.parse(res)); + }) + .catch((error) => { + reply(Boom.badData(error)); + }); + }, + description: 'Endpoint that receives feedback from a private channel', + notes: + 'Specify the private channel name,message count and oldest timestamp in the url parameters', + tags: ['api', 'feedback'] + } + }, + { + method: 'GET', + path: '/etl/get-monthly-schedule', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + programVisitEncounterResolver + .resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) + .then((resolve) => { + let encounterIds = resolve.encounterTypeIds; + let visitTypeIds = resolve.visitTypesIds; + let programTypeIds = resolve.programTypeIds; + if (encounterIds.length > 0) { + request.query.encounterIds = encounterIds; + } + if (visitTypeIds.length > 0) { + request.query.visitTypeIds = visitTypeIds; + } + if (programTypeIds.length > 0) { + request.query.programTypeIds = programTypeIds; + } + + return resolveLocationUuidToId.resolveLocationUuidsParamsToIds( + request.query + ); + }) + .then((result) => { + let locationIds = result; + request.query.locations = locationIds; + let combineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new MonthlyScheduleService(); + service + .getMonthlyScheduled(combineRequestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }) + .then((error) => { + console.log(error); + }); + } + }, + description: 'Get monthly schedule', + notes: 'Returns a list of appointments,visits and has not returned', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/daily-appointments/{startDate}', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + request.query.groupBy = 'groupByPerson,groupByd'; + programVisitEncounterResolver + .resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) + .then((resolve) => { + // console.log('Daily appointments', resolve); + let encounterIds = resolve.encounterTypeIds; + let visitTypeIds = resolve.visitTypesIds; + let programTypeIds = resolve.programTypeIds; + if (programTypeIds.length > 0) { + request.query.programTypeIds = programTypeIds; + } + if (visitTypeIds.length > 0) { + request.query.visitTypeIds = visitTypeIds; + } + if (encounterIds.length > 0) { + request.query.encounterIds = encounterIds; + } + + let combineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + // let reportParams = etlHelpers.getReportParams('daily-appointments', ['startDate', 'locations', 'encounterIds', 'visitTypeIds', 'programTypeIds', 'groupBy'], compineRequestParams); + combineRequestParams.limitParam = combineRequestParams.limit; + combineRequestParams.offSetParam = + combineRequestParams.startIndex; + combineRequestParams.endDate = combineRequestParams.startDate; + let service = new PatientlistMysqlReport( + 'dailyAppointmentsAggregate', + combineRequestParams + ); + service + .generatePatientListReport(['patients']) + .then((result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + _.each(returnedResult.result, (item) => { + item.cur_meds = etlHelpers.getARVNames(item.cur_meds); + }); + reply(returnedResult); + }) + .catch((error) => { + reply(error); + }); + }) + .catch((error) => { + console.log(error); + }); + }); + } + }, + description: 'Get daily appointments list', + notes: 'Returns a list of patients with appointments', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/daily-visits/{startDate}', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + request.query.groupBy = 'groupByPerson,groupByd'; + programVisitEncounterResolver + .resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) + .then((resolve) => { + let encounterIds = resolve.encounterTypeIds; + let visitTypeIds = resolve.visitTypesIds; + let programTypeIds = resolve.programTypeIds; + if (programTypeIds.length > 0) { + request.query.programTypeIds = programTypeIds; + } + if (visitTypeIds.length > 0) { + request.query.visitTypeIds = visitTypeIds; + } + if (encounterIds.length > 0) { + request.query.encounterIds = encounterIds; + } + let compineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + compineRequestParams.limitParam = compineRequestParams.limit; + compineRequestParams.offSetParam = + compineRequestParams.startIndex; + let service = new PatientlistMysqlReport( + 'dailyAttendanceAggregate', + compineRequestParams + ); + service + .generatePatientListReport(['patients']) + .then((result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + _.each(returnedResult.result, (item) => { + item.cur_meds = etlHelpers.getARVNames(item.cur_meds); + }); + reply(returnedResult); + }) + .catch((error) => { + reply(error); + }); + }) + .catch((error) => { + console.log(error); + }); + }); + } + }, + description: 'Get daily attendance list', + notes: 'Returns a facility daily attendance list', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/daily-has-not-returned/{startDate}', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + request.query.groupBy = 'groupByPerson,groupByd'; + programVisitEncounterResolver + .resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) + .then((resolve) => { + let encounterIds = resolve.encounterTypeIds; + let visitTypeIds = resolve.visitTypesIds; + let programTypeIds = resolve.programTypeIds; + if (programTypeIds.length > 0) { + request.query.programTypeIds = programTypeIds; + } + if (visitTypeIds.length > 0) { + request.query.visitTypeIds = visitTypeIds; + } + if (encounterIds.length > 0) { + request.query.encounterIds = encounterIds; + } + let combineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + combineRequestParams.limitParam = combineRequestParams.limit; + combineRequestParams.offSetParam = + combineRequestParams.startIndex; + combineRequestParams.endDate = combineRequestParams.startDate; + //let reportParams = etlHelpers.getReportParams('daily-has-not-returned', ['startDate', 'locations', 'encounterIds', 'visitTypeIds', 'programTypeIds', 'groupBy'], compineRequestParams); + //reportParams.limit = 100000; + let service = new PatientlistMysqlReport( + 'dailyHasNotReturnedAggregate', + combineRequestParams + ); + service + .generatePatientListReport(['patients']) + .then((result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + _.each(returnedResult.result, (item) => { + item.cur_meds = etlHelpers.getARVNames(item.cur_meds); + }); + reply(returnedResult); + }) + .catch((error) => { + reply(error); + }); + }) + .catch((error) => { + console.log('Error', error); + reply(error); + }); + }); + } + }, + description: + 'Get a list of patients who did not attend a scheduled visit', + notes: + 'Returns a list of patients who did not attend their scheduled visits on the selected date', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/clinic-lab-orders/{dateActivated}', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + request.query.groupBy = 'groupByPerson,groupByd'; + let compineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'clinic-lab-orders-report', + ['dateActivated', 'locations', 'groupBy'], + compineRequestParams + ); + let report = new BaseMysqlReport( + 'clinicLabOrdersReport', + reportParams.requestParams + ); + report + .generateReport() + .then((results) => { + _.each(results.results.results, (row) => { + row.order_type = etlHelpers.getTestsOrderedNames( + row.order_type + ); + }); + results.result = results.results.results; + delete results['results']; + reply(results); + }) + .catch((error) => { + reply(error); + }); + }); + } + }, + description: + 'Get a list of patients who made lab orders on a selected date', + notes: + 'Returns a list of patients patients who made lab orders through selected clinics on a selected date', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/defaulter-list', + config: { + auth: 'simple', + handler: function (request, reply) { + dao.getDefaulterList(request, reply); + }, + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + description: "Get a location's defaulter list", + notes: "Returns a location's defaulter list.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + } + } + } + }, + { + method: 'GET', + path: '/etl/patient/{patientUuids}/cdm-summary', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + let requestParams = Object.assign({}, request.query, request.params); + let service = new CDMReportingService(); + service + .getPatientSummaryReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get patient CDM summary', + notes: + "Returns a list of historical patient's HIV summary with the given patient uuid. " + + "A patient's CDM summary includes details such as last visit date, " + + "current medication regimen etc. as at that encounter's date. ", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + patientUuids: Joi.string() + .required() + .description("The patient's uuid(universally unique identifier).") + } + } + } + }, + { + method: 'GET', + path: '/etl/patient/{patientUuids}/medication-change', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + let requestParams = Object.assign({}, request.query, request.params); + let service = new CDMReportingService(); + service + .getPatientMedicationHistoryReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get patient medication history', + notes: + "Returns a list of historical patient's HIV summary with the given patient uuid. " + + "A patient's medication history details such as medication by encounter, " + + "current medication etc. as at that encounter's date. ", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + patientUuids: Joi.string() + .required() + .description("The patient's uuid(universally unique identifier).") + } + } + } + }, + { + method: 'GET', + path: '/etl/patient/{patientUuid}/hiv-clinical-reminder/{referenceDate}', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + let EIDLabReminderService = require('./service/eid/eid-lab-reminder.service'); + EIDLabReminderService.pendingEIDReminders( + request.params, + config.hivLabSystem + ) + .then((eidReminders) => { + let combineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + combineRequestParams.limitParam = 1; + let reportParams = etlHelpers.getReportParams( + 'clinical-reminder-report', + ['referenceDate', 'patientUuid', 'offSetParam', 'limitParam'], + combineRequestParams + ); + + let report = new BaseMysqlReport( + 'clinicalReminderReport', + reportParams.requestParams + ); + report + .generateReport() + .then((results) => { + try { + if (results.results.results.length > 0) { + let processedResults = patientReminderService.generateReminders( + results.results.results, + eidReminders + ); + results.result = processedResults; + } else { + results.result = { + person_uuid: combineRequestParams.person_uuid, + reminders: [] + }; } - } - }, - { - method: 'GET', - path: '/etl/patient/{patientUuids}/medication-change', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let requestParams = Object.assign({}, request.query, request.params); - let service = new CDMReportingService(); - service.getPatientMedicationHistoryReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: 'Get patient medication history', - notes: "Returns a list of historical patient's HIV summary with the given patient uuid. " + - "A patient's medication history details such as medication by encounter, " + - "current medication etc. as at that encounter's date. ", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - patientUuids: Joi.string() - .required() - .description("The patient's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/patient/{patientUuid}/hiv-clinical-reminder/{referenceDate}', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let EIDLabReminderService = require('./service/eid/eid-lab-reminder.service'); - EIDLabReminderService.pendingEIDReminders(request.params, config.hivLabSystem) - .then((eidReminders) => { - let combineRequestParams = Object.assign({}, request.query, request.params); - combineRequestParams.limitParam = 1; - let reportParams = etlHelpers.getReportParams('clinical-reminder-report', ['referenceDate', 'patientUuid', 'offSetParam', 'limitParam'], combineRequestParams); - - let report = new BaseMysqlReport('clinicalReminderReport', reportParams.requestParams); - report.generateReport().then((results) => { - try { - if (results.results.results.length > 0) { - let processedResults = patientReminderService.generateReminders(results.results.results, eidReminders); - results.result = processedResults; - } else { - results.result = { - person_uuid: combineRequestParams.person_uuid, - reminders: [] - }; - } - reply(results); - } catch (error) { - console.log('Error generating reminders', error); - reply(Boom.badImplementation('An internal error occurred')); - } - }).catch((error) => { - console.log('Error generating reminders', error); - reply(Boom.badImplementation('An internal error occurred')); - }); - }).catch((err) => { - console.log('EID lab results err', err); - reply(err); - }); - - }, - description: 'Get a list of reminders for selected patient and indicators', - notes: 'Returns a list of reminders for selected patient and indicators on a given reference date', - tags: ['api'], - } + reply(results); + } catch (error) { + console.log('Error generating reminders', error); + reply(Boom.badImplementation('An internal error occurred')); + } + }) + .catch((error) => { + console.log('Error generating reminders', error); + reply(Boom.badImplementation('An internal error occurred')); + }); + }) + .catch((err) => { + console.log('EID lab results err', err); + reply(err); + }); + }, + description: + 'Get a list of reminders for selected patient and indicators', + notes: + 'Returns a list of reminders for selected patient and indicators on a given reference date', + tags: ['api'] + } + }, + { + method: 'POST', + path: '/etl/forms/error', + config: { + auth: 'simple', + handler: function (request, reply) { + dao.logError(request, reply); + } + } + }, + { + method: 'POST', + path: '/javascript-errors', + config: { + handler: function (request, reply) { + if (request.payload) { + var logger = new winston.Logger({ + transports: [ + new winston.transports.File({ + level: 'info', + filename: 'client-logs.log', + handleExceptions: true, + json: true, + colorize: false + }) + ], + exitOnError: false + }); + logger.add(require('winston-daily-rotate-file'), { + filename: path.join(__dirname, 'logs', 'client-logs.log') + }); + logger.info(request.payload); + } + + reply({ + message: 'ok' + }); + } + } + }, + { + method: 'GET', + path: '/etl/patient/{uuid}', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + dao.getPatient(request, reply); + } + } + }, + { + method: 'GET', + path: '/etl/program-visit-configs', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + // var requestParams = Object.assign({}, request.query, request.params); + reply(patientProgramService.getAllProgramsConfig()); + }, + description: 'Get a list of programs ', + notes: 'Returns a list of programs', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + // patientUuid: Joi.string() + // .required() + // .description("The patient's uuid(universally unique identifier)."), + } + } + } + }, + { + method: 'GET', + path: + '/etl/patient/{patientUuid}/program/{programUuid}/enrollment/{enrollmentUuid}', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + var requestParams = Object.assign({}, request.query, request.params); + var patientUuid = requestParams.patientUuid; + var programUuid = requestParams.programUuid; + var enrollment = requestParams.enrollmentUuid; + var locationUuid = requestParams.intendedLocationUuid || ''; + + patientProgramService + .getPatientProgramVisits( + patientUuid, + programUuid, + enrollment, + locationUuid + ) + .then((programVisits) => { + reply(programVisits); + }) + .catch((error) => { + reply(Boom.badImplementation('An internal error occurred')); + }); + }, + description: 'Get program config of a patient', + notes: 'Returns program config of a patient', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + patientUuid: Joi.string() + .required() + .description( + "The patient's uuid(universally unique identifier)." + ), + programUuid: Joi.string() + .required() + .description('program Uuid (universally unique identifier).'), + enrollmentUuid: Joi.string() + .required() + .description( + 'program enrollment Uuid (universally unique identifier).' + ) + } + } + } + }, + { + method: 'GET', + path: '/etl/patient/{uuid}/clinical-notes', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + dao.getClinicalNotes(request, reply); + }, + description: 'Get patient clinical notes', + notes: + 'Returns a list of notes constructed from several ' + + 'patient information sources, particularly encounters', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description("The patient's uuid(universally unique identifier).") + } + } + } + }, + { + method: 'GET', + path: '/etl/patient/{uuid}/hiv-patient-clinical-summary', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] + } + }, + handler: function (request, reply) { + dao.getHivPatientClinicalSummary(request, reply); + } + } + }, + { + method: 'GET', + path: '/etl/location/{id}/hiv-patient-clinical-summary', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] + } + }, + handler: function (request, reply) { + dao.getHivPatientClinicalSummary(request, reply); + } + } + }, + { + method: 'GET', + path: '/etl/patient/{uuid}/vitals', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + dao.getPatientVitals(request, reply); + }, + description: 'Get patient vitals', + notes: + "Returns a list of historical patient's vitals with the given patient uuid.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description("The patient's uuid(universally unique identifier).") + } + } + } + }, + { + method: 'GET', + path: '/etl/patient/{uuid}/data', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + dao.getPatientData(request, reply); + }, + description: 'Get patient lab test data', + notes: + 'Returns a list of historical lab tests data of a patient with the given patient uuid.', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description("The patient's uuid(universally unique identifier).") + } + } + } + }, + { + method: 'GET', + path: '/etl/patient/{uuid}/hiv-summary', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + dao.getPatientHivSummary(request).then((summary) => { + // console.log('Summary', summary); + if (summary.result && summary.result.length > 0) { + const transformed = etlHelpers.transformMedicalRefillToClinical( + summary.result + ); + summary.result = transformed; } - , - { - method: 'POST', - path: '/etl/forms/error', - config: { - auth: 'simple', - handler: function (request, reply) { - - dao.logError(request, reply); - } - } - }, - { - method: 'POST', - path: '/javascript-errors', - config: { - handler: function (request, reply) { - if (request.payload) { - var logger = new winston.Logger({ - transports: [ - new winston.transports.File({ - level: 'info', - filename: 'client-logs.log', - handleExceptions: true, - json: true, - colorize: false, - }), - ], - exitOnError: false, - }); - logger.add(require('winston-daily-rotate-file'), { - filename: path.join(__dirname, 'logs', 'client-logs.log') - }); - logger.info(request.payload); - } - - reply({ - message: 'ok' - }); - } - - } - }, - { - method: 'GET', - path: '/etl/patient/{uuid}', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - dao.getPatient(request, reply); - } - } - }, - { - method: 'GET', - path: '/etl/program-visit-configs', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - // var requestParams = Object.assign({}, request.query, request.params); - reply(patientProgramService.getAllProgramsConfig()); - }, - description: 'Get a list of programs ', - notes: 'Returns a list of programs', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - // patientUuid: Joi.string() - // .required() - // .description("The patient's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/patient/{patientUuid}/program/{programUuid}/enrollment/{enrollmentUuid}', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - var requestParams = Object.assign({}, request.query, request.params); - var patientUuid = requestParams.patientUuid; - var programUuid = requestParams.programUuid; - var enrollment = requestParams.enrollmentUuid; - var locationUuid = requestParams.intendedLocationUuid || ''; - - patientProgramService.getPatientProgramVisits(patientUuid, programUuid, enrollment, locationUuid) - .then((programVisits) => { - reply(programVisits); - }) - .catch((error) => { - reply(Boom.badImplementation('An internal error occurred')); - }); - - }, - description: 'Get program config of a patient', - notes: 'Returns program config of a patient', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - patientUuid: Joi.string() - .required() - .description("The patient's uuid(universally unique identifier)."), - programUuid: Joi.string() - .required() - .description("program Uuid (universally unique identifier)."), - enrollmentUuid: Joi.string() - .required() - .description("program enrollment Uuid (universally unique identifier).") - } - } - } - }, - { - method: 'GET', - path: '/etl/patient/{uuid}/clinical-notes', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - dao.getClinicalNotes(request, reply); - }, - description: 'Get patient clinical notes', - notes: 'Returns a list of notes constructed from several ' + - 'patient information sources, particularly encounters', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The patient's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/patient/{uuid}/hiv-patient-clinical-summary', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] - } - }, - handler: function (request, reply) { - dao.getHivPatientClinicalSummary(request, reply); - } - - } - }, - { - method: 'GET', - path: '/etl/location/{id}/hiv-patient-clinical-summary', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] - } - }, - handler: function (request, reply) { - dao.getHivPatientClinicalSummary(request, reply); - } - - } - }, - { - method: 'GET', - path: '/etl/patient/{uuid}/vitals', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - dao.getPatientVitals(request, reply); - }, - description: 'Get patient vitals', - notes: "Returns a list of historical patient's vitals with the given patient uuid.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The patient's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/patient/{uuid}/data', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - dao.getPatientData(request, reply); - }, - description: 'Get patient lab test data', - notes: 'Returns a list of historical lab tests data of a patient with the given patient uuid.', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The patient's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/patient/{uuid}/hiv-summary', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - dao.getPatientHivSummary(request) - .then(summary => { - // console.log('Summary', summary); - if (summary.result && summary.result.length > 0) { - const transformed = etlHelpers.transformMedicalRefillToClinical(summary.result); - summary.result = transformed; - } - reply(summary); - }); - - }, - description: 'Get patient HIV summary', - notes: "Returns a list of historical patient's HIV summary with the given patient uuid. " + - "A patient's HIV summary includes details such as last appointment date, " + - "current ARV regimen etc. as at that encounter's date. ", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The patient's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/patient/{uuid}/oncology/summary', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - dao.getPatientOncologySummary(request, reply); - }, - description: 'Get patient Oncology summary', - notes: "Returns a list of patient's Oncology summary with the given patient uuid. " + - "A patient's Oncology summary includes details such as last appointment date, " + - "most recent diagnosis etc. as at that encounter's date. ", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The patient's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/location/{uuid}/clinic-encounter-data', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - dao.getClinicEncounterData(request, reply); - } - } - }, - { - method: 'GET', - path: '/etl/patient-program-config', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - var requestParams = Object.assign({}, request.query); - if (!requestParams.patientUuid) { - reply(Boom.badImplementation('The patient\'s uuid(universally unique ' + - 'identifier must be provided as a query param')); - } - patientProgramService.validateEnrollmentOptions(requestParams.patientUuid) - .then(function (programConfigs) { - reply(programConfigs); - }).catch(function (err) { - console.log('there is an error', err); - reply(Boom.badImplementation(err)); - }); - }, - description: 'Get a list of programs ', - notes: 'Returns a list of programs', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } - } - }, - { - method: 'GET', - path: '/etl/location/{uuid}/monthly-appointment-visits', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - dao.getClinicMonthlySummary(request, reply); - }, - description: "Get a location's monthly appointment visits", - notes: "Returns a location's monthly appointment visits with the given location uuid.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The location's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/location/{uuid}/hiv-summary-indicators', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewDataAnalytics - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - dao.getClinicHivSummayIndicators(request, reply); - }, - description: "Get a location's HIV summary indicators", - notes: "Returns a location's HIV summary indicators.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The location's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/clinical-hiv-comparative-overview', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewDataAnalytics - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'clinical-hiv-comparative-overview-report'; - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let compineRequestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('clinical-hiv-comparative-overview-report', ['startDate', 'endDate', 'indicator', 'locationUuids', 'locations', 'order', 'gender'], compineRequestParams); - console.log('Params', compineRequestParams); - let service = new hivComparativeOverviewService(); - service.getAggregateReport(compineRequestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - }, - description: "Get the clinical hiv comparative overview summary", - notes: "Returns a comparative summary of various indicator eg enrollement, on_art,and vl suppression", - tags: ['api'], - validate: {} - } - }, - { - method: 'GET', - path: '/etl/clinical-hiv-comparative-overview/patient-list', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'clinical-hiv-comparative-overview-report'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - requestParams.limitParam = requestParams.limit; - requestParams.offSetParam = requestParams.startIndex; - let service = new hivComparativeOverviewService(); - service.getPatientListReport(requestParams).then((result) => { - _.each(result.result, (item) => { - item.cur_meds = etlHelpers.getARVNames(item.cur_meds); - }); - reply(result); - }).catch((error) => { - reply(error); - }); - }); - }, - description: "Get the clinical hiv comparative overview patient", - notes: "Returns the patient list for various indicators in the clinical hiv comparative summary", - tags: ['api'], - validate: { - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - reportName: Joi.string() - .optional() - .description("the name of the report you want patient list"), - startDate: Joi.string() - .optional() - .description("The start date to filter by"), - endDate: Joi.string() - .optional() - .description("The end date to filter by"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination") - } - } - } - }, - { - method: 'GET', - path: '/etl/patient-referrals', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }], - aggregateReport: [ //set this if you want to validation checks for certain aggregate reports - { - type: 'query', //can be in either query or params so you have to specify - name: 'reportName', //name of the parameter - value: 'patient-referral-report' //parameter value - } - ] - } - }, - handler: function (request, reply) { - //security check - request.query.reportName = 'patient-referral-report'; - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new PatientReferralService(); - // remove gender filter - delete requestParams['gender']; - service.getAggregateReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - - }, - description: "Get patient referral for selected clinic", - notes: "Returns a list of patient referral for the selected clinic(s),start date, end date", - tags: ['api'], - validate: { - query: { - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .optional() - .description("The start date to filter by"), - endDate: Joi.string() - .optional() - .description("The end date to filter by"), - programUuids: Joi.string() - .optional() - .description("The program to filter by"), - department: Joi.string() - .optional() - .description("The department to filter by") - } - } - } - }, - { - method: 'GET', - path: '/etl/referral-patient-list', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }], - aggregateReport: [ //set this if you want to validation checks for certain aggregate reports - { - type: 'query', //can be in either query or params so you have to specify - name: 'reportName', //name of the parameter - value: 'patient-referral-report' //parameter value - } - ] - } - }, - handler: function (request, reply) { - //security check - request.query.reportName = 'patient-referral-report'; - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - let requestParams = Object.assign({}, request.query, request.params); - requestParams.reportName = 'referralAggregate'; - let service = new PatientReferralService(); - service.getReferralPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: "Get patient referral for selected clinic", - notes: "Returns patient referral for the selected clinic(s),start date, end date", - tags: ['api'], - validate: { - query: { - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .optional() - .description("The start date to filter by"), - endDate: Joi.string() - .optional() - .description("The end date to filter by"), - programUuids: Joi.string() - .optional() - .description("The program to filter by"), - limit: Joi.string() - .optional() - .description("The limit to indicate number of rows"), - department: Joi.string() - .optional() - .description("The department to filter by") - - } - } - } - }, - { - method: 'GET', - path: '/etl/patient-referral-details/{locationUuid}/{enrollmentUuid}', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - patientReferralDao.getPatientReferralByEnrollmentUuid( - request.params['locationUuid'], request.params['enrollmentUuid']) - .then(function (referralLocation) { - reply(referralLocation); - }) - .catch(function (error) { - reply(Boom.create(500, 'Internal server error.', error)); - }); - }, - description: "Get patient referral details by program enrollment uuid", - notes: "Api endpoint that returns additional patient referral details by program enrollement uuid", - tags: ['api'], - } - }, - { - method: 'POST', - path: '/etl/patient-referral', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - patientReferralDao.createPatientReferral(request.payload) - .then(function (newCohortReferral) { - reply(newCohortReferral); - }) - .catch(function (error) { - if (error && error.isValid === false) { - reply(Boom.badRequest('Validation errors:' + JSON.stringify(error))); - } else { - console.error(error); - reply(Boom.create(500, 'Internal server error.', error)); - } - }); - }, - description: "Post patient referrals for a given referral", - notes: "Api endpoint that posts patient referrals", - tags: ['api'], - } - }, - { - method: 'POST', - path: '/etl/patient-referral/{patientReferralId}', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - // console.log('xxxxxxxxxxxx', request) - patientReferralDao.updatePatientReferralNotification(request.params['patientReferralId'], request.payload) - .then(function (updatedPatientReferral) { - reply(updatedPatientReferral); - }) - .catch(function (error) { - if (error && error.isValid === false) { - reply(Boom.badRequest('Validation errors:' + JSON.stringify(error))); - } else { - reply(Boom.create(500, 'Internal server error.', error)); - } - }); - }, - description: "Update patient referral notification status", - notes: "Api endpoint that updates patient referral of by the provided id", - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/clinical-patient-care-status-overview', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewDataAnalytics - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'clinical-patient-care-status-overview-report'; - let compineRequestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('clinical-patient-care-status-overview-report', ['startDate', 'endDate', 'indicator', 'locationUuids', 'order', 'gender'], compineRequestParams); - - let service = new clinicalPatientCareStatusOverviewService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: "Get the clinical patint care status patient list", - notes: "Returns a comparative summary of all patient status indicators eg on_art,out_of_care,in_care,transferred_out.....", - tags: ['api'], - validate: {} - } - }, - { - method: 'GET', - path: '/etl/clinical-patient-care-status-overview/patient-list', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - - request.query.reportName = 'clinical-patient-care-status-overview-report'; - let requestParams = Object.assign({}, request.query, request.params); - let service = new PatientStatusChangeTrackerService(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: "Get the clinical-patient-care-status-overview patient list", - notes: "Returns the patient list for various indicators in the clinical-patient-care-status-overview", - tags: ['api'], - validate: { - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination"), - analysis: Joi.string() - .optional() - .description("analysis type"), - } - } - } - }, - { - method: 'GET', - path: '/etl/clinical-art-overview', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewDataAnalytics - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - - request.query.reportName = 'clinical-art-overview-report'; - let compineRequestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('clinical-art-overview-report', ['startDate', 'endDate', 'indicator', 'locationUuids', 'order', 'gender'], compineRequestParams); - - let service = new clinicalArtOverviewService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: "Get the clinical art overview summary", - notes: "Returns the a comparative summary of art drugs used by patients", - tags: ['api'], - validate: {} - } - }, - { - method: 'GET', - path: '/etl/clinical-art-overview/patient-list', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - - request.query.reportName = 'clinical-art-overview-report'; - let requestParams = Object.assign({}, request.query, request.params); - let service = new clinicalArtOverviewService(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: "Get the clinical art overview patient list", - notes: "Returns the patient list for clinical-art-overview report", - tags: ['api'], - validate: { - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - reportName: Joi.string() - .optional() - .description("the name of the report you want patient list"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination") - - } - } - } - }, - { - method: 'GET', - path: '/etl/location/{uuid}/appointment-schedule', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - dao.getClinicAppointmentSchedule(request, reply); - }, - description: "Get a location's appointment schedule", - notes: "Returns a location's appointment-schedule with the given location uuid.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The location's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/patient-flow-data', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - dao.getPatientFlowData(request, reply); - }); - }, - description: "Get a location's patient movement and waiting time data", - notes: "Returns a location's patient flow with the given location uuid.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } - } - }, - { - method: 'GET', - path: '/etl/clinic-lab-orders-data', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - dao.getClinicLabOrdersData(request, reply); - }); - }, - description: "Get a location's lab orders data", - notes: "Returns a location's lab orders data with the given location uuid.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } - } - }, - { - method: 'GET', - path: '/etl/patient/{patient_uuid}/monthly-care-status', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let history = new PatientMonthlyStatusHistory(); - history.getPatientMonthlyStatusHistory(request.params.patient_uuid, request.query.startDate, request.query.endDate).then((result) => { - reply(result); - }); - }, - description: "Get the the care status of patient on a monthly basis", - notes: "Returns a list showing care status of a patient at the end of every month in a given period", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } - } - }, - { - method: 'GET', - path: '/etl/patient/{patient_uuid}/daily-care-status', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - let requestParams = Object.assign({}, request.query, request.params); - // let reportParams = etlHelpers.getReportParams('patient-daily-care-status', ['referenceDate', 'patient_uuid'], - // requestParams); - reportParams.limitParam = reportParams.limit; - reportParams.offSetParam = reportParams.startIndex; - let report = new BaseMysqlReport('patientDailyCareStatus', reportParams); - report.generateReport().then((results) => { - results.result = results.results.results; - delete results['results']; - reply(results); - }).catch((error) => { - reply(error); - }); - }, - description: "Get the the care status of patient on a given date", - notes: "Returns the care status of a patient on a given day", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } - } - }, - { - method: 'GET', - path: '/etl/location/{uuid}/daily-visits', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - dao.getClinicDailyVisits(request, reply); - }, - description: "Get a location's daily visits", - notes: "Returns a location's daily visits with the given parameter uuid.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The location's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/location/{uuid}/has-not-returned', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - dao.getHasNotReturned(request, reply); - }, - description: "Get a location's not returned visits", - notes: "Returns a location's not returned visits with the given parameter uuid.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The location's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/location/{uuid}/monthly-appointment-schedule', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - dao.getClinicMonthlyAppointmentSchedule(request, reply); - }, - description: "Get a location's monthly appointment schedule", - notes: "Returns a location's monthly appointment schedule.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The location's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/location/{uuid}/monthly-visits', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - dao.getClinicMonthlyVisits(request, reply); - }, - description: "Get a location's monthly visits", - notes: "Returns the actual number of patient visits for each day in a given month and location.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The location's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'GET', - path: '/etl/location/{uuid}/defaulter-list', - config: { - auth: 'simple', - handler: function (request, reply) { - dao.getClinicDefaulterList(request, reply); - }, - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - description: "Get a location's defaulter list", - notes: "Returns a location's defaulter list.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - uuid: Joi.string() - .required() - .description("The location's uuid(universally unique identifier)."), - } - } - } - }, - { - method: 'OPTIONS', - path: '/{param*}', - handler: function (request, reply) { - // echo request headers back to caller (allow any requested) - var additionalHeaders = []; - if (request.headers['access-control-request-headers']) { - additionalHeaders = request.headers['access-control-request-headers'].split(', '); - } - var headers = _.union('Authorization, Content-Type, If-None-Match'.split(', '), additionalHeaders); - - reply().type('text/plain') - .header('Access-Control-Allow-Headers', headers.join(', ')); - } - }, - { - method: 'GET', - path: '/etl/custom_data/{userParams*3}', - config: { - auth: 'simple', - handler: function (request, reply) { - dao.getCustomData(request, reply); - } - /* + reply(summary); + }); + }, + description: 'Get patient HIV summary', + notes: + "Returns a list of historical patient's HIV summary with the given patient uuid. " + + "A patient's HIV summary includes details such as last appointment date, " + + "current ARV regimen etc. as at that encounter's date. ", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description("The patient's uuid(universally unique identifier).") + } + } + } + }, + { + method: 'GET', + path: '/etl/patient/{uuid}/oncology/summary', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + dao.getPatientOncologySummary(request, reply); + }, + description: 'Get patient Oncology summary', + notes: + "Returns a list of patient's Oncology summary with the given patient uuid. " + + "A patient's Oncology summary includes details such as last appointment date, " + + "most recent diagnosis etc. as at that encounter's date. ", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description("The patient's uuid(universally unique identifier).") + } + } + } + }, + { + method: 'GET', + path: '/etl/location/{uuid}/clinic-encounter-data', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + dao.getClinicEncounterData(request, reply); + } + } + }, + { + method: 'GET', + path: '/etl/patient-program-config', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + var requestParams = Object.assign({}, request.query); + if (!requestParams.patientUuid) { + reply( + Boom.badImplementation( + "The patient's uuid(universally unique " + + 'identifier must be provided as a query param' + ) + ); + } + patientProgramService + .validateEnrollmentOptions(requestParams.patientUuid) + .then(function (programConfigs) { + reply(programConfigs); + }) + .catch(function (err) { + console.log('there is an error', err); + reply(Boom.badImplementation(err)); + }); + }, + description: 'Get a list of programs ', + notes: 'Returns a list of programs', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/location/{uuid}/monthly-appointment-visits', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + dao.getClinicMonthlySummary(request, reply); + }, + description: "Get a location's monthly appointment visits", + notes: + "Returns a location's monthly appointment visits with the given location uuid.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + } + } + } + }, + { + method: 'GET', + path: '/etl/location/{uuid}/hiv-summary-indicators', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewDataAnalytics + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + dao.getClinicHivSummayIndicators(request, reply); + }, + description: "Get a location's HIV summary indicators", + notes: "Returns a location's HIV summary indicators.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + } + } + } + }, + { + method: 'GET', + path: '/etl/clinical-hiv-comparative-overview', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewDataAnalytics + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'clinical-hiv-comparative-overview-report'; + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let compineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'clinical-hiv-comparative-overview-report', + [ + 'startDate', + 'endDate', + 'indicator', + 'locationUuids', + 'locations', + 'order', + 'gender' + ], + compineRequestParams + ); + console.log('Params', compineRequestParams); + let service = new hivComparativeOverviewService(); + service + .getAggregateReport(compineRequestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'Get the clinical hiv comparative overview summary', + notes: + 'Returns a comparative summary of various indicator eg enrollement, on_art,and vl suppression', + tags: ['api'], + validate: {} + } + }, + { + method: 'GET', + path: '/etl/clinical-hiv-comparative-overview/patient-list', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'clinical-hiv-comparative-overview-report'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + requestParams.limitParam = requestParams.limit; + requestParams.offSetParam = requestParams.startIndex; + let service = new hivComparativeOverviewService(); + service + .getPatientListReport(requestParams) + .then((result) => { + _.each(result.result, (item) => { + item.cur_meds = etlHelpers.getARVNames(item.cur_meds); + }); + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'Get the clinical hiv comparative overview patient', + notes: + 'Returns the patient list for various indicators in the clinical hiv comparative summary', + tags: ['api'], + validate: { + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + reportName: Joi.string() + .optional() + .description('the name of the report you want patient list'), + startDate: Joi.string() + .optional() + .description('The start date to filter by'), + endDate: Joi.string() + .optional() + .description('The end date to filter by'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination') + } + } + } + }, + { + method: 'GET', + path: '/etl/patient-referrals', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ], + aggregateReport: [ + //set this if you want to validation checks for certain aggregate reports + { + type: 'query', //can be in either query or params so you have to specify + name: 'reportName', //name of the parameter + value: 'patient-referral-report' //parameter value + } + ] + } + }, + handler: function (request, reply) { + //security check + request.query.reportName = 'patient-referral-report'; + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new PatientReferralService(); + // remove gender filter + delete requestParams['gender']; + service + .getAggregateReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'Get patient referral for selected clinic', + notes: + 'Returns a list of patient referral for the selected clinic(s),start date, end date', + tags: ['api'], + validate: { + query: { + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .optional() + .description('The start date to filter by'), + endDate: Joi.string() + .optional() + .description('The end date to filter by'), + programUuids: Joi.string() + .optional() + .description('The program to filter by'), + department: Joi.string() + .optional() + .description('The department to filter by') + } + } + } + }, + { + method: 'GET', + path: '/etl/referral-patient-list', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ], + aggregateReport: [ + //set this if you want to validation checks for certain aggregate reports + { + type: 'query', //can be in either query or params so you have to specify + name: 'reportName', //name of the parameter + value: 'patient-referral-report' //parameter value + } + ] + } + }, + handler: function (request, reply) { + //security check + request.query.reportName = 'patient-referral-report'; + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + let requestParams = Object.assign({}, request.query, request.params); + requestParams.reportName = 'referralAggregate'; + let service = new PatientReferralService(); + service + .getReferralPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get patient referral for selected clinic', + notes: + 'Returns patient referral for the selected clinic(s),start date, end date', + tags: ['api'], + validate: { + query: { + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .optional() + .description('The start date to filter by'), + endDate: Joi.string() + .optional() + .description('The end date to filter by'), + programUuids: Joi.string() + .optional() + .description('The program to filter by'), + limit: Joi.string() + .optional() + .description('The limit to indicate number of rows'), + department: Joi.string() + .optional() + .description('The department to filter by') + } + } + } + }, + { + method: 'GET', + path: '/etl/patient-referral-details/{locationUuid}/{enrollmentUuid}', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + patientReferralDao + .getPatientReferralByEnrollmentUuid( + request.params['locationUuid'], + request.params['enrollmentUuid'] + ) + .then(function (referralLocation) { + reply(referralLocation); + }) + .catch(function (error) { + reply(Boom.create(500, 'Internal server error.', error)); + }); + }, + description: 'Get patient referral details by program enrollment uuid', + notes: + 'Api endpoint that returns additional patient referral details by program enrollement uuid', + tags: ['api'] + } + }, + { + method: 'POST', + path: '/etl/patient-referral', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + patientReferralDao + .createPatientReferral(request.payload) + .then(function (newCohortReferral) { + reply(newCohortReferral); + }) + .catch(function (error) { + if (error && error.isValid === false) { + reply( + Boom.badRequest('Validation errors:' + JSON.stringify(error)) + ); + } else { + console.error(error); + reply(Boom.create(500, 'Internal server error.', error)); + } + }); + }, + description: 'Post patient referrals for a given referral', + notes: 'Api endpoint that posts patient referrals', + tags: ['api'] + } + }, + { + method: 'POST', + path: '/etl/patient-referral/{patientReferralId}', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + // console.log('xxxxxxxxxxxx', request) + patientReferralDao + .updatePatientReferralNotification( + request.params['patientReferralId'], + request.payload + ) + .then(function (updatedPatientReferral) { + reply(updatedPatientReferral); + }) + .catch(function (error) { + if (error && error.isValid === false) { + reply( + Boom.badRequest('Validation errors:' + JSON.stringify(error)) + ); + } else { + reply(Boom.create(500, 'Internal server error.', error)); + } + }); + }, + description: 'Update patient referral notification status', + notes: + 'Api endpoint that updates patient referral of by the provided id', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/clinical-patient-care-status-overview', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewDataAnalytics + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = + 'clinical-patient-care-status-overview-report'; + let compineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'clinical-patient-care-status-overview-report', + [ + 'startDate', + 'endDate', + 'indicator', + 'locationUuids', + 'order', + 'gender' + ], + compineRequestParams + ); + + let service = new clinicalPatientCareStatusOverviewService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get the clinical patint care status patient list', + notes: + 'Returns a comparative summary of all patient status indicators eg on_art,out_of_care,in_care,transferred_out.....', + tags: ['api'], + validate: {} + } + }, + { + method: 'GET', + path: '/etl/clinical-patient-care-status-overview/patient-list', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = + 'clinical-patient-care-status-overview-report'; + let requestParams = Object.assign({}, request.query, request.params); + let service = new PatientStatusChangeTrackerService(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: + 'Get the clinical-patient-care-status-overview patient list', + notes: + 'Returns the patient list for various indicators in the clinical-patient-care-status-overview', + tags: ['api'], + validate: { + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination'), + analysis: Joi.string().optional().description('analysis type') + } + } + } + }, + { + method: 'GET', + path: '/etl/clinical-art-overview', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewDataAnalytics + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'clinical-art-overview-report'; + let compineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'clinical-art-overview-report', + [ + 'startDate', + 'endDate', + 'indicator', + 'locationUuids', + 'order', + 'gender' + ], + compineRequestParams + ); + + let service = new clinicalArtOverviewService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get the clinical art overview summary', + notes: + 'Returns the a comparative summary of art drugs used by patients', + tags: ['api'], + validate: {} + } + }, + { + method: 'GET', + path: '/etl/clinical-art-overview/patient-list', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'clinical-art-overview-report'; + let requestParams = Object.assign({}, request.query, request.params); + let service = new clinicalArtOverviewService(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get the clinical art overview patient list', + notes: 'Returns the patient list for clinical-art-overview report', + tags: ['api'], + validate: { + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + reportName: Joi.string() + .optional() + .description('the name of the report you want patient list'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination') + } + } + } + }, + { + method: 'GET', + path: '/etl/location/{uuid}/appointment-schedule', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + dao.getClinicAppointmentSchedule(request, reply); + }, + description: "Get a location's appointment schedule", + notes: + "Returns a location's appointment-schedule with the given location uuid.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + } + } + } + }, + { + method: 'GET', + path: '/etl/patient-flow-data', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + dao.getPatientFlowData(request, reply); + }); + }, + description: "Get a location's patient movement and waiting time data", + notes: + "Returns a location's patient flow with the given location uuid.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/clinic-lab-orders-data', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + dao.getClinicLabOrdersData(request, reply); + }); + }, + description: "Get a location's lab orders data", + notes: + "Returns a location's lab orders data with the given location uuid.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/patient/{patient_uuid}/monthly-care-status', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + let history = new PatientMonthlyStatusHistory(); + history + .getPatientMonthlyStatusHistory( + request.params.patient_uuid, + request.query.startDate, + request.query.endDate + ) + .then((result) => { + reply(result); + }); + }, + description: 'Get the the care status of patient on a monthly basis', + notes: + 'Returns a list showing care status of a patient at the end of every month in a given period', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/patient/{patient_uuid}/daily-care-status', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + let requestParams = Object.assign({}, request.query, request.params); + // let reportParams = etlHelpers.getReportParams('patient-daily-care-status', ['referenceDate', 'patient_uuid'], + // requestParams); + reportParams.limitParam = reportParams.limit; + reportParams.offSetParam = reportParams.startIndex; + let report = new BaseMysqlReport( + 'patientDailyCareStatus', + reportParams + ); + report + .generateReport() + .then((results) => { + results.result = results.results.results; + delete results['results']; + reply(results); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get the the care status of patient on a given date', + notes: 'Returns the care status of a patient on a given day', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/location/{uuid}/daily-visits', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + dao.getClinicDailyVisits(request, reply); + }, + description: "Get a location's daily visits", + notes: + "Returns a location's daily visits with the given parameter uuid.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + } + } + } + }, + { + method: 'GET', + path: '/etl/location/{uuid}/has-not-returned', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + dao.getHasNotReturned(request, reply); + }, + description: "Get a location's not returned visits", + notes: + "Returns a location's not returned visits with the given parameter uuid.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + } + } + } + }, + { + method: 'GET', + path: '/etl/location/{uuid}/monthly-appointment-schedule', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + dao.getClinicMonthlyAppointmentSchedule(request, reply); + }, + description: "Get a location's monthly appointment schedule", + notes: "Returns a location's monthly appointment schedule.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + } + } + } + }, + { + method: 'GET', + path: '/etl/location/{uuid}/monthly-visits', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + dao.getClinicMonthlyVisits(request, reply); + }, + description: "Get a location's monthly visits", + notes: + 'Returns the actual number of patient visits for each day in a given month and location.', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + } + } + } + }, + { + method: 'GET', + path: '/etl/location/{uuid}/defaulter-list', + config: { + auth: 'simple', + handler: function (request, reply) { + dao.getClinicDefaulterList(request, reply); + }, + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + description: "Get a location's defaulter list", + notes: "Returns a location's defaulter list.", + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + uuid: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + } + } + } + }, + { + method: 'OPTIONS', + path: '/{param*}', + handler: function (request, reply) { + // echo request headers back to caller (allow any requested) + var additionalHeaders = []; + if (request.headers['access-control-request-headers']) { + additionalHeaders = request.headers[ + 'access-control-request-headers' + ].split(', '); + } + var headers = _.union( + 'Authorization, Content-Type, If-None-Match'.split(', '), + additionalHeaders + ); + + reply() + .type('text/plain') + .header('Access-Control-Allow-Headers', headers.join(', ')); + } + }, + { + method: 'GET', + path: '/etl/custom_data/{userParams*3}', + config: { + auth: 'simple', + handler: function (request, reply) { + dao.getCustomData(request, reply); + } + /* the rest request and query expression should be /table/filter_column/filter/filter_value or /table/filter_column/filter/filter_value?fields=(field1,field2,fieldn) or */ - } - }, - { - method: 'GET', - path: '/etl/patient/creation/statistics', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - roles: [privileges.canViewDataEntryStats, privileges.canViewPatient] - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - dao.getPatientCountGroupedByLocation(request, reply); - }, - description: "Get patients created by period", - notes: "Returns a list of patients created within a specified time period in all locations.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - query: { - startDate: Joi.string() - .optional() - .description("The start date to filter by"), - endDate: Joi.string() - .optional() - .description("The end date to filter by"), - } - } - } - }, - { - method: 'GET', - path: '/etl/location/{location}/patient/creation/statistics', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - roles: [privileges.canViewDataEntryStats, privileges.canViewPatient] - } - }, - handler: function (request, reply) { - dao.getPatientDetailsGroupedByLocation(request, reply); - }, - description: "Get details of patient created in a location", - notes: "Returns details of patient created in a location", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - location: Joi.string() - .required() - .description("The location's uuid(universally unique identifier)."), - } - } - } - }, - { - /** + } + }, + { + method: 'GET', + path: '/etl/patient/creation/statistics', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + roles: [privileges.canViewDataEntryStats, privileges.canViewPatient] + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + dao.getPatientCountGroupedByLocation(request, reply); + }, + description: 'Get patients created by period', + notes: + 'Returns a list of patients created within a specified time period in all locations.', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + query: { + startDate: Joi.string() + .optional() + .description('The start date to filter by'), + endDate: Joi.string() + .optional() + .description('The end date to filter by') + } + } + } + }, + { + method: 'GET', + path: '/etl/location/{location}/patient/creation/statistics', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + roles: [privileges.canViewDataEntryStats, privileges.canViewPatient] + } + }, + handler: function (request, reply) { + dao.getPatientDetailsGroupedByLocation(request, reply); + }, + description: 'Get details of patient created in a location', + notes: 'Returns details of patient created in a location', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + location: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + } + } + } + }, + { + /** endpoint to get Reports @todo Rename to get-report-by-name,count by{patient/encounters},filter-params{location/starting date/ end date} @todo ,groupby params{location/monthly} **/ - method: 'GET', - path: '/etl/get-report-by-report-name', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }], - exemptedParameter: [ //set this if you want to prevent validation checks for certain reports - { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'clinical-reminder-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'patient-register-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'medical-history-report' //parameter value - } - ], - aggregateReport: [ //set this if you want to validation checks for certain aggregate reports - { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'hiv-summary-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'hiv-summary-monthly-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'MOH-731-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'MOH-731-allsites-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'clinic-comparator-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'clinical-hiv-comparative-overview-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'clinical-art-overview-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'report', //name of the parameter - value: 'clinical-patient-care-status-overview-report' //parameter value - }, - - ] - } - }, - handler: function (request, reply) { - //security check - if (!authorizer.hasReportAccess(request.query.report)) { - return reply(Boom.forbidden('Unauthorized')); - } - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams(request.query.report, ['startDate', 'endDate', 'indicator', 'locationUuids', 'locations', 'referenceDate', - 'patientUuid', 'startAge', 'endAge', 'age', 'order', 'gender' - ], - requestParams); - - dao.runReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - }, - description: 'Get report ', - notes: "General api endpoint that returns a report by passing " + - "the report name parameter and a list of custom parameters " + - "depending on the report e.g start date, end date for MOH-731 report.", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - query: { - report: Joi.string() - .required() - .description("The name of the report to get indicators") - } - } - - } - }, - { - method: 'GET', - path: '/etl/MOH-731-report', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }], - aggregateReport: [ //set this if you want to validation checks for certain aggregate reports - { - type: 'query', //can be in either query or params so you have to specify - name: 'reportName', //name of the parameter - value: 'MOH-731-report' //parameter value - }, { - type: 'query', //can be in either query or params so you have to specify - name: 'reportName', //name of the parameter - value: 'MOH-731-report-2017' //parameter value - } - ] - } - }, - handler: function (request, reply) { - //security check - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - // console.log('requestParams', requestParams); - let reportParams = etlHelpers.getReportParams(request.query.reportName, ['startDate', 'endDate', 'locationUuids', 'locations', 'isAggregated'], requestParams); - console.log('report params=>>', reportParams); - - if (request.query.reportName === 'MOH-731-report-2017') { - let moh731 = new Moh731Report('MOH-731-greencard', reportParams.requestParams); - - moh731.generateReport().then((results) => { - reply(results); - }) - .catch((err) => { - reply(Boom.internal('An error occured', err)); - }); - } else { - let moh731 = new Moh731Report('MOH-731-bluecard', reportParams.requestParams); - - moh731.generateReport().then((results) => { - reply(results); - }) - .catch((err) => { - reply(Boom.internal('An error occured', err)); - }); - - } - - }); - }, - description: "Get the MOH 731 report", - notes: "Api endpoint that returns MOH 731 report. It includes both MOH versions (legacy and 2017).", - tags: ['api'], - validate: { - query: { - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - reportName: Joi.string() - .required() - .description("the name of the report you want patient list"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - isAggregated: Joi.boolean() - .optional() - .description("Boolean checking if report is aggregated"), - exclude: Joi.string() - .optional() - .description("Validates which report should be returned") - - } - } - } - }, - { - method: 'GET', - path: '/etl/MOH-731-report/patient-list', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - //security check - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - - let requestCopy = _.cloneDeep(requestParams); - // console.log('requestParams', requestParams); - let reportParams = etlHelpers.getReportParams(request.query.reportName, ['startDate', 'endDate', 'locationUuids', 'locations', 'isAggregated'], requestParams); - requestCopy.locations = reportParams.requestParams.locations; - // console.log('report params', reportParams) - requestCopy.limitParam = requestParams.limit; - requestCopy.offSetParam = requestParams.startIndex; - if (request.query.reportName === 'MOH-731-report-2017') { - let moh731 = new Moh731Report('MOH-731-greencard', requestCopy); - - moh731.generatePatientListReport(requestParams.indicator.split(',')).then((results) => { - reply(results); - }) - .catch((err) => { - reply(Boom.internal('An error occured', err)); - }); - } else { - let moh731 = new Moh731Report('MOH-731-bluecard', requestCopy); - - moh731.generatePatientListReport(requestParams.indicator.split(',')).then((results) => { - reply(results); - }) - .catch((err) => { - reply(Boom.internal('An error occured', err)); - }); - } - }); - }, - description: "Get the MOH 731 patient list", - notes: "Returns the patient list for MOH 731", - tags: ['api'], - validate: { - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - reportName: Joi.string() - .required() - .description("the name of the report you want patient list"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination") - - } - } - } - }, - { - method: 'GET', - path: '/etl/patient-status-change-tracking', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }], - aggregateReport: [ //set this if you want to validation checks for certain aggregate reports - { - type: 'query', //can be in either query or params so you have to specify - name: 'reportName', //name of the parameter - value: 'patient-status-change-tracker-report' //parameter value - } - ] - } - }, - handler: function (request, reply) { - request.query.reportName = 'patient-status-change-tracker-report'; - //security check - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - if (request.query.locationUuids) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams(request.query.reportName, ['startDate', 'endDate', 'locationUuids', 'locations', 'analysis'], requestParams); - - let service = new PatientStatusChangeTrackerService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - } - }, - description: "Get the Patient Status report", - notes: "Api endpoint that returns Patient Status Change Tracker Report", - tags: ['api'], - validate: { - query: { - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - analysis: Joi.string() - .optional() - .description("analysis type report") - } - } - } - }, - { - method: 'GET', - path: '/etl/patient-status-change-tracking/patient-list', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - }, - }, - handler: function (request, reply) { - request.query.reportName = 'patient-status-change-tracker-report'; - if (request.query.locationUuids) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new PatientStatusChangeTrackerService(); - service.getPatientListReport(requestParams).then((result) => { - _.each(result.result, (item) => { - item.cur_meds = etlHelpers.getARVNames(item.cur_meds); - }); - reply(result); - }).catch((error) => { - reply(error); - }); - }); - } - }, - description: "Get Patient Status report patient list", - notes: "Returns the patient list for Patient Status report", - tags: ['api'], - validate: { - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - analysis: Joi.string() - .optional() - .description("analysis type report"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination") - - } - } - } - }, - { - method: 'GET', - path: '/etl/user-cohorts', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - request.query.reportName = 'cohort-report'; - //security check - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - request.params.limit = 1000; - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('cohort-report', ['userUuid'], requestParams); - - let service = new cohortUserService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: "Get cohort(s) based on user uuid", - notes: "Api endpoint that returns cohort(s) based on the user uuid", - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/cohort-user/{cohortUserId}', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - patientList.getCohortUser(request.params['cohortUserId']) - .then(function (cohortUser) { - if (cohortUser === null) { - reply(Boom.notFound('Resource does not exist')); - } else { - reply(cohortUser); - } - }) - .catch(function (error) { - reply(Boom.create(500, 'Internal server error.', error)); - }); - }, - description: "Get cohort users for a certain cohort", - notes: "Api endpoint that returns cohort users based on the cohort uuid", - tags: ['api'], - } - }, - { - method: 'DELETE', - path: '/etl/cohort-user/{cohortUserId}', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - patientList.voidCohortUser(request.params['cohortUserId']) - .then(function (message) { - reply(message); - }) - .catch(function (error) { - reply(Boom.create(500, 'Internal server error.', error)); - }); - }, - description: "Get cohort users for a certain cohort", - notes: "Api endpoint that returns cohort users based on the cohort uuid", - tags: ['api'], - } - }, - { - method: 'POST', - path: '/etl/cohort-user/{cohortUserId}', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - patientList.updateCohortUser(request.params['cohortUserId'], request.payload) - .then(function (updatedCohortUser) { - reply(updatedCohortUser); - }) - .catch(function (error) { - if (error && error.isValid === false) { - reply(Boom.badRequest('Validation errors:' + JSON.stringify(error))); - } else { - reply(Boom.create(500, 'Internal server error.', error)); - } - }); - }, - description: "Get cohort users for a certain cohort", - notes: "Api endpoint that returns cohort users based on the cohort uuid", - tags: ['api'], - } - }, - { - method: 'POST', - path: '/etl/cohort-user', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - patientList.createCohortUser(request.payload) - .then(function (newCohortUser) { - reply(newCohortUser); - }) - .catch(function (error) { - if (error && error.isValid === false) { - reply(Boom.badRequest('Validation errors:' + JSON.stringify(error))); - } else { - console.error(error); - reply(Boom.create(500, 'Internal server error.', error)); - } - }); - }, - description: "Get cohort users for a certain cohort", - notes: "Api endpoint that returns cohort users based on the cohort uuid", - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/cohort/{cohortUuid}/cohort-users', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - patientList.getCohortUsersByCohortUuid(request.params['cohortUuid']) - .then(function (cohortUsers) { - reply(cohortUsers); - }) - .catch(function (error) { - reply(Boom.create(500, 'Internal server error.', error)); - }); - }, - description: "Get cohort users for a certain cohort", - notes: "Api endpoint that returns cohort users based on the cohort uuid", - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/patient-register-report', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'params', //can be in either query or params so you have to specify - name: 'uuid' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - if (request.query.locationUuids) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams(request.query.reportName, ['startDate', 'endDate', 'indicators', 'locationUuids', 'groupBy', - 'limit', 'startAge', 'endAge', 'order', 'gender', 'countBy' - ], requestParams); - - let service = new PatientRegisterReportService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - } - }, - description: "Get the Patient Register report", - notes: "Api endpoint that returns Patient Register report.", - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/hiv-summary-indicators', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }], - aggregateReport: [ //set this if you want to validation checks for certain aggregate reports - { - type: 'query', //can be in either query or params so you have to specify - name: 'reportName', //name of the parameter - value: 'hiv-summary-report' //parameter value - } - ] - } - }, - handler: function (request, reply) { - //security check - request.query.reportName = 'hiv-summary-report'; - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('hiv-summary-report', ['startDate', 'endDate', 'locationUuids', 'indicators', 'gender', 'startAge', 'endAge'], requestParams); - - let service = new HivSummaryIndicatorsService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - console.error('Error loading HIV Summary:', error); - reply(error); - }); - }); - }, - description: "Get hiv summary indicators for selected clinic", - notes: "Returns hiv summary indicators for the selected clinic(s),start date, end date", - tags: ['api'], - validate: { - query: { - indicators: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .required() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - gender: Joi.string() - .optional() - .description("The gender to filter by"), - startAge: Joi.string() - .optional() - .description("The start age to filter by"), - endAge: Joi.string() - .optional() - .description("The end age to filter by") - - } - } - } - }, - { - method: 'GET', - path: '/etl/hiv-summary-indicators/patient-list', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - - request.query.reportName = 'hiv-summary-report'; - let requestParams = Object.assign({}, request.query, request.params); - let service = new HivSummaryIndicatorsService(); - service.getPatientListReport(requestParams).then((result) => { - _.each(result.result, (item) => { - item.cur_meds = etlHelpers.getARVNames(item.cur_meds); - }); - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: "Get hiv summary indicator's patient list for selected clinic", - notes: "Returns hiv summary indicator's patient list for the selected clinic,start date, end date", - tags: ['api'], - validate: { - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .required() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination"), - startAge: Joi.string() - .optional() - .description("The start age to filter by"), - endAge: Joi.string() - .optional() - .description("The end age to filter by"), - gender: Joi.string() - .optional() - .description("The gender to filter by"), - } - } - } - }, - { - method: 'GET', - path: '/etl/hiv-summary-monthly-indicators', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }], - aggregateReport: [ //set this if you want to validation checks for certain aggregate reports - { - type: 'query', //can be in either query or params so you have to specify - name: 'reportName', //name of the parameter - value: 'hiv-summary-monthly-report' //parameter value - } - ] - } - }, - handler: function (request, reply) { - //security check - request.query.reportName = 'hiv-summary-monthly-report'; - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('hiv-summary-monthly-report', ['startDate', 'endDate', 'locationUuids', 'indicators', 'gender', 'startAge', 'endAge'], requestParams); - - let service = new HivSummaryMonthlyIndicatorsService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - console.error('Error fetching HIV summary', error); - reply(Boom.badImplementation('An error occured', error)); - }); - }); - }, - description: "Get hiv summary monthly indicators for selected clinic", - notes: "Returns hiv summary monthly indicators for the selected clinic(s),start date, end date", - tags: ['api'], - validate: { - query: { - indicators: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .required() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - gender: Joi.string() - .optional() - .description("The gender to filter by"), - startAge: Joi.string() - .optional() - .description("The start age to filter by"), - endAge: Joi.string() - .optional() - .description("The end age to filter by") - - } - } - } - }, - { - method: 'GET', - path: '/etl/hiv-summary-monthly-indicators/patient-list', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - - request.query.reportName = 'hiv-summary-monthly-report'; - let requestParams = Object.assign({}, request.query, request.params); - let service = new HivSummaryMonthlyIndicatorsService(); - service.getPatientListReport(requestParams).then((result) => { - console.log('result', result); - reply(result); - }).catch((error) => { - console.error('Error fetching HIV summary', error); - reply(Boom.badImplementation('An error occured', error)); - }); - }, - description: "Get hiv summary monthly indicator's patient list for selected clinic", - notes: "Returns hiv summary monthly indicator's patient list for the selected clinic,start date, end date", - tags: ['api'], - validate: { - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .required() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination"), - startAge: Joi.string() - .optional() - .description("The start age to filter by"), - endAge: Joi.string() - .optional() - .description("The end age to filter by"), - gender: Joi.string() - .optional() - .description("The gender to filter by"), - } - } - } - }, - { - method: 'GET', - path: '/etl/location/{locationUuids}/patient-by-indicator', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] - } - }, - handler: function (request, reply) { - request.query.reportName = 'hiv-summary-report'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - dao.getPatientListReport(Object.assign({}, request.query, request.params)) - .then((result) => { - reply(result); - }).catch((error) => { - reply(Boom.badRequest(error.toString())); - }); - }); - }, - description: 'Get patient list by indicator', - notes: 'Returns a patient list by indicator for a given location.', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - locationUuids: Joi.string() - .required() - .description("The location's uuid(universally unique identifier).") - }, - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators") - } - } - } - }, - { - method: 'GET', - path: '/etl/patient-by-indicator', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] - } - }, - handler: function (request, reply) { - request.query.reportName = 'hiv-summary-monthly-report'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - dao.getPatientListReport(Object.assign({}, request.query, request.params)) - .then((result) => { - reply(result); - }).catch((error) => { - reply(Boom.badRequest(error.toString())); - }); - }); - }, - description: 'Get patient', - notes: 'Returns a patient by passing a given indicator and location.', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .required() - .description("A list of comma separated location uuids") - } - } - } - }, - { - method: 'GET', - path: '/etl/data-entry-statistics/{sub}', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewDataEntryStats - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - - if (request.params.sub === 'patientList' && - !authorizer.hasPrivilege(privileges.canViewPatient)) { - return reply(Boom.forbidden('Unauthorized')); - } - - var asyncRequests = 0; //this should be the number of async requests needed before they are triggered - - var onResolvedPromise = function (promise) { - asyncRequests--; - if (asyncRequests <= 0) { //voting process to ensure all pre-processing of request async operations are complete - dao.getDataEntryIndicators(request.params.sub, request, reply); - } - }; - - //establish the number of asyncRequests - //this is done prior to avoid any race conditions - if (request.query.formUuids) { - asyncRequests++; - } - if (request.query.encounterTypeUuids) { - asyncRequests++; - } - if (request.query.locationUuids) { - asyncRequests++; - } - - if (asyncRequests === 0) - dao.getDataEntryIndicators(request.params.sub, request, reply); - - if (request.query.formUuids) { - dao.getIdsByUuidAsyc('amrs.form', 'form_id', 'uuid', request.query.formUuids, - function (results) { - request.query.formIds = results; - }).onResolved = onResolvedPromise; - } - if (request.query.encounterTypeUuids) { - - dao.getIdsByUuidAsyc('amrs.encounter_type', 'encounter_type_id', 'uuid', request.query.encounterTypeUuids, - function (results) { - request.query.encounterTypeIds = results; - }).onResolved = onResolvedPromise; - } - if (request.query.visitTypeUuids) { - dao.getIdsByUuidAsyc('amrs.visit_type', 'visit_type_id', 'uuid', request.query.visitTypeUuids, - function (results) { - request.query.visitTypeIds = results; - }).onResolved = onResolvedPromise; - } - if (request.query.locationUuids) { - dao.getIdsByUuidAsyc('amrs.location', 'location_id', 'uuid', request.query.locationUuids, - function (results) { - request.query.locationIds = results; - }).onResolved = onResolvedPromise; - } - } - } - }, - { - /** + method: 'GET', + path: '/etl/get-report-by-report-name', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ], + exemptedParameter: [ + //set this if you want to prevent validation checks for certain reports + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'clinical-reminder-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'patient-register-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'medical-history-report' //parameter value + } + ], + aggregateReport: [ + //set this if you want to validation checks for certain aggregate reports + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'hiv-summary-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'hiv-summary-monthly-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'MOH-731-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'MOH-731-allsites-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'clinic-comparator-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'clinical-hiv-comparative-overview-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'clinical-art-overview-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'report', //name of the parameter + value: 'clinical-patient-care-status-overview-report' //parameter value + } + ] + } + }, + handler: function (request, reply) { + //security check + if (!authorizer.hasReportAccess(request.query.report)) { + return reply(Boom.forbidden('Unauthorized')); + } + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + request.query.report, + [ + 'startDate', + 'endDate', + 'indicator', + 'locationUuids', + 'locations', + 'referenceDate', + 'patientUuid', + 'startAge', + 'endAge', + 'age', + 'order', + 'gender' + ], + requestParams + ); + + dao + .runReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'Get report ', + notes: + 'General api endpoint that returns a report by passing ' + + 'the report name parameter and a list of custom parameters ' + + 'depending on the report e.g start date, end date for MOH-731 report.', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + query: { + report: Joi.string() + .required() + .description('The name of the report to get indicators') + } + } + } + }, + { + method: 'GET', + path: '/etl/MOH-731-report', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ], + aggregateReport: [ + //set this if you want to validation checks for certain aggregate reports + { + type: 'query', //can be in either query or params so you have to specify + name: 'reportName', //name of the parameter + value: 'MOH-731-report' //parameter value + }, + { + type: 'query', //can be in either query or params so you have to specify + name: 'reportName', //name of the parameter + value: 'MOH-731-report-2017' //parameter value + } + ] + } + }, + handler: function (request, reply) { + //security check + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + // console.log('requestParams', requestParams); + let reportParams = etlHelpers.getReportParams( + request.query.reportName, + [ + 'startDate', + 'endDate', + 'locationUuids', + 'locations', + 'isAggregated' + ], + requestParams + ); + console.log('report params=>>', reportParams); + + if (request.query.reportName === 'MOH-731-report-2017') { + let moh731 = new Moh731Report( + 'MOH-731-greencard', + reportParams.requestParams + ); + + moh731 + .generateReport() + .then((results) => { + reply(results); + }) + .catch((err) => { + reply(Boom.internal('An error occured', err)); + }); + } else { + let moh731 = new Moh731Report( + 'MOH-731-bluecard', + reportParams.requestParams + ); + + moh731 + .generateReport() + .then((results) => { + reply(results); + }) + .catch((err) => { + reply(Boom.internal('An error occured', err)); + }); + } + }); + }, + description: 'Get the MOH 731 report', + notes: + 'Api endpoint that returns MOH 731 report. It includes both MOH versions (legacy and 2017).', + tags: ['api'], + validate: { + query: { + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + reportName: Joi.string() + .required() + .description('the name of the report you want patient list'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + isAggregated: Joi.boolean() + .optional() + .description('Boolean checking if report is aggregated'), + exclude: Joi.string() + .optional() + .description('Validates which report should be returned') + } + } + } + }, + { + method: 'GET', + path: '/etl/MOH-731-report/patient-list', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + //security check + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + + let requestCopy = _.cloneDeep(requestParams); + // console.log('requestParams', requestParams); + let reportParams = etlHelpers.getReportParams( + request.query.reportName, + [ + 'startDate', + 'endDate', + 'locationUuids', + 'locations', + 'isAggregated' + ], + requestParams + ); + requestCopy.locations = reportParams.requestParams.locations; + // console.log('report params', reportParams) + requestCopy.limitParam = requestParams.limit; + requestCopy.offSetParam = requestParams.startIndex; + if (request.query.reportName === 'MOH-731-report-2017') { + let moh731 = new Moh731Report('MOH-731-greencard', requestCopy); + + moh731 + .generatePatientListReport(requestParams.indicator.split(',')) + .then((results) => { + reply(results); + }) + .catch((err) => { + reply(Boom.internal('An error occured', err)); + }); + } else { + let moh731 = new Moh731Report('MOH-731-bluecard', requestCopy); + + moh731 + .generatePatientListReport(requestParams.indicator.split(',')) + .then((results) => { + reply(results); + }) + .catch((err) => { + reply(Boom.internal('An error occured', err)); + }); + } + }); + }, + description: 'Get the MOH 731 patient list', + notes: 'Returns the patient list for MOH 731', + tags: ['api'], + validate: { + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + reportName: Joi.string() + .required() + .description('the name of the report you want patient list'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination') + } + } + } + }, + { + method: 'GET', + path: '/etl/patient-status-change-tracking', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ], + aggregateReport: [ + //set this if you want to validation checks for certain aggregate reports + { + type: 'query', //can be in either query or params so you have to specify + name: 'reportName', //name of the parameter + value: 'patient-status-change-tracker-report' //parameter value + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'patient-status-change-tracker-report'; + //security check + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + if (request.query.locationUuids) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + request.query.reportName, + [ + 'startDate', + 'endDate', + 'locationUuids', + 'locations', + 'analysis' + ], + requestParams + ); + + let service = new PatientStatusChangeTrackerService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + } + }, + description: 'Get the Patient Status report', + notes: 'Api endpoint that returns Patient Status Change Tracker Report', + tags: ['api'], + validate: { + query: { + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + analysis: Joi.string() + .optional() + .description('analysis type report') + } + } + } + }, + { + method: 'GET', + path: '/etl/patient-status-change-tracking/patient-list', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + request.query.reportName = 'patient-status-change-tracker-report'; + if (request.query.locationUuids) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new PatientStatusChangeTrackerService(); + service + .getPatientListReport(requestParams) + .then((result) => { + _.each(result.result, (item) => { + item.cur_meds = etlHelpers.getARVNames(item.cur_meds); + }); + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + } + }, + description: 'Get Patient Status report patient list', + notes: 'Returns the patient list for Patient Status report', + tags: ['api'], + validate: { + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + analysis: Joi.string() + .optional() + .description('analysis type report'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination') + } + } + } + }, + { + method: 'GET', + path: '/etl/user-cohorts', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + request.query.reportName = 'cohort-report'; + //security check + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + request.params.limit = 1000; + let requestParams = Object.assign({}, request.query, request.params); + let reportParams = etlHelpers.getReportParams( + 'cohort-report', + ['userUuid'], + requestParams + ); + + let service = new cohortUserService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get cohort(s) based on user uuid', + notes: 'Api endpoint that returns cohort(s) based on the user uuid', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/cohort-user/{cohortUserId}', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + patientList + .getCohortUser(request.params['cohortUserId']) + .then(function (cohortUser) { + if (cohortUser === null) { + reply(Boom.notFound('Resource does not exist')); + } else { + reply(cohortUser); + } + }) + .catch(function (error) { + reply(Boom.create(500, 'Internal server error.', error)); + }); + }, + description: 'Get cohort users for a certain cohort', + notes: + 'Api endpoint that returns cohort users based on the cohort uuid', + tags: ['api'] + } + }, + { + method: 'DELETE', + path: '/etl/cohort-user/{cohortUserId}', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + patientList + .voidCohortUser(request.params['cohortUserId']) + .then(function (message) { + reply(message); + }) + .catch(function (error) { + reply(Boom.create(500, 'Internal server error.', error)); + }); + }, + description: 'Get cohort users for a certain cohort', + notes: + 'Api endpoint that returns cohort users based on the cohort uuid', + tags: ['api'] + } + }, + { + method: 'POST', + path: '/etl/cohort-user/{cohortUserId}', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + patientList + .updateCohortUser(request.params['cohortUserId'], request.payload) + .then(function (updatedCohortUser) { + reply(updatedCohortUser); + }) + .catch(function (error) { + if (error && error.isValid === false) { + reply( + Boom.badRequest('Validation errors:' + JSON.stringify(error)) + ); + } else { + reply(Boom.create(500, 'Internal server error.', error)); + } + }); + }, + description: 'Get cohort users for a certain cohort', + notes: + 'Api endpoint that returns cohort users based on the cohort uuid', + tags: ['api'] + } + }, + { + method: 'POST', + path: '/etl/cohort-user', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + patientList + .createCohortUser(request.payload) + .then(function (newCohortUser) { + reply(newCohortUser); + }) + .catch(function (error) { + if (error && error.isValid === false) { + reply( + Boom.badRequest('Validation errors:' + JSON.stringify(error)) + ); + } else { + console.error(error); + reply(Boom.create(500, 'Internal server error.', error)); + } + }); + }, + description: 'Get cohort users for a certain cohort', + notes: + 'Api endpoint that returns cohort users based on the cohort uuid', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/cohort/{cohortUuid}/cohort-users', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + patientList + .getCohortUsersByCohortUuid(request.params['cohortUuid']) + .then(function (cohortUsers) { + reply(cohortUsers); + }) + .catch(function (error) { + reply(Boom.create(500, 'Internal server error.', error)); + }); + }, + description: 'Get cohort users for a certain cohort', + notes: + 'Api endpoint that returns cohort users based on the cohort uuid', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/patient-register-report', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'params', //can be in either query or params so you have to specify + name: 'uuid' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + request.query.reportName, + [ + 'startDate', + 'endDate', + 'indicators', + 'locationUuids', + 'groupBy', + 'limit', + 'startAge', + 'endAge', + 'order', + 'gender', + 'countBy' + ], + requestParams + ); + + let service = new PatientRegisterReportService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + } + }, + description: 'Get the Patient Register report', + notes: 'Api endpoint that returns Patient Register report.', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/hiv-summary-indicators', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ], + aggregateReport: [ + //set this if you want to validation checks for certain aggregate reports + { + type: 'query', //can be in either query or params so you have to specify + name: 'reportName', //name of the parameter + value: 'hiv-summary-report' //parameter value + } + ] + } + }, + handler: function (request, reply) { + //security check + request.query.reportName = 'hiv-summary-report'; + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'hiv-summary-report', + [ + 'startDate', + 'endDate', + 'locationUuids', + 'indicators', + 'gender', + 'startAge', + 'endAge' + ], + requestParams + ); + + let service = new HivSummaryIndicatorsService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error loading HIV Summary:', error); + reply(error); + }); + }); + }, + description: 'Get hiv summary indicators for selected clinic', + notes: + 'Returns hiv summary indicators for the selected clinic(s),start date, end date', + tags: ['api'], + validate: { + query: { + indicators: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .required() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + gender: Joi.string() + .optional() + .description('The gender to filter by'), + startAge: Joi.string() + .optional() + .description('The start age to filter by'), + endAge: Joi.string() + .optional() + .description('The end age to filter by') + } + } + } + }, + { + method: 'GET', + path: '/etl/hiv-summary-indicators/patient-list', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'hiv-summary-report'; + let requestParams = Object.assign({}, request.query, request.params); + let service = new HivSummaryIndicatorsService(); + service + .getPatientListReport(requestParams) + .then((result) => { + _.each(result.result, (item) => { + item.cur_meds = etlHelpers.getARVNames(item.cur_meds); + }); + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: + "Get hiv summary indicator's patient list for selected clinic", + notes: + "Returns hiv summary indicator's patient list for the selected clinic,start date, end date", + tags: ['api'], + validate: { + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .required() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination'), + startAge: Joi.string() + .optional() + .description('The start age to filter by'), + endAge: Joi.string() + .optional() + .description('The end age to filter by'), + gender: Joi.string() + .optional() + .description('The gender to filter by') + } + } + } + }, + { + method: 'GET', + path: '/etl/hiv-summary-monthly-indicators', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ], + aggregateReport: [ + //set this if you want to validation checks for certain aggregate reports + { + type: 'query', //can be in either query or params so you have to specify + name: 'reportName', //name of the parameter + value: 'hiv-summary-monthly-report' //parameter value + } + ] + } + }, + handler: function (request, reply) { + //security check + request.query.reportName = 'hiv-summary-monthly-report'; + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'hiv-summary-monthly-report', + [ + 'startDate', + 'endDate', + 'locationUuids', + 'indicators', + 'gender', + 'startAge', + 'endAge' + ], + requestParams + ); + + let service = new HivSummaryMonthlyIndicatorsService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error fetching HIV summary', error); + reply(Boom.badImplementation('An error occured', error)); + }); + }); + }, + description: 'Get hiv summary monthly indicators for selected clinic', + notes: + 'Returns hiv summary monthly indicators for the selected clinic(s),start date, end date', + tags: ['api'], + validate: { + query: { + indicators: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .required() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + gender: Joi.string() + .optional() + .description('The gender to filter by'), + startAge: Joi.string() + .optional() + .description('The start age to filter by'), + endAge: Joi.string() + .optional() + .description('The end age to filter by') + } + } + } + }, + { + method: 'GET', + path: '/etl/hiv-summary-monthly-indicators/patient-list', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'hiv-summary-monthly-report'; + let requestParams = Object.assign({}, request.query, request.params); + let service = new HivSummaryMonthlyIndicatorsService(); + service + .getPatientListReport(requestParams) + .then((result) => { + console.log('result', result); + reply(result); + }) + .catch((error) => { + console.error('Error fetching HIV summary', error); + reply(Boom.badImplementation('An error occured', error)); + }); + }, + description: + "Get hiv summary monthly indicator's patient list for selected clinic", + notes: + "Returns hiv summary monthly indicator's patient list for the selected clinic,start date, end date", + tags: ['api'], + validate: { + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .required() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination'), + startAge: Joi.string() + .optional() + .description('The start age to filter by'), + endAge: Joi.string() + .optional() + .description('The end age to filter by'), + gender: Joi.string() + .optional() + .description('The gender to filter by') + } + } + } + }, + { + method: 'GET', + path: '/etl/location/{locationUuids}/patient-by-indicator', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] + } + }, + handler: function (request, reply) { + request.query.reportName = 'hiv-summary-report'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + dao + .getPatientListReport( + Object.assign({}, request.query, request.params) + ) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(Boom.badRequest(error.toString())); + }); + }); + }, + description: 'Get patient list by indicator', + notes: 'Returns a patient list by indicator for a given location.', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: { + locationUuids: Joi.string() + .required() + .description( + "The location's uuid(universally unique identifier)." + ) + }, + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators') + } + } + } + }, + { + method: 'GET', + path: '/etl/patient-by-indicator', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] + } + }, + handler: function (request, reply) { + request.query.reportName = 'hiv-summary-monthly-report'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + dao + .getPatientListReport( + Object.assign({}, request.query, request.params) + ) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(Boom.badRequest(error.toString())); + }); + }); + }, + description: 'Get patient', + notes: 'Returns a patient by passing a given indicator and location.', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .required() + .description('A list of comma separated location uuids') + } + } + } + }, + { + method: 'GET', + path: '/etl/data-entry-statistics/{sub}', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewDataEntryStats + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + if ( + request.params.sub === 'patientList' && + !authorizer.hasPrivilege(privileges.canViewPatient) + ) { + return reply(Boom.forbidden('Unauthorized')); + } + + var asyncRequests = 0; //this should be the number of async requests needed before they are triggered + + var onResolvedPromise = function (promise) { + asyncRequests--; + if (asyncRequests <= 0) { + //voting process to ensure all pre-processing of request async operations are complete + dao.getDataEntryIndicators(request.params.sub, request, reply); + } + }; + + //establish the number of asyncRequests + //this is done prior to avoid any race conditions + if (request.query.formUuids) { + asyncRequests++; + } + if (request.query.encounterTypeUuids) { + asyncRequests++; + } + if (request.query.locationUuids) { + asyncRequests++; + } + + if (asyncRequests === 0) + dao.getDataEntryIndicators(request.params.sub, request, reply); + + if (request.query.formUuids) { + dao.getIdsByUuidAsyc( + 'amrs.form', + 'form_id', + 'uuid', + request.query.formUuids, + function (results) { + request.query.formIds = results; + } + ).onResolved = onResolvedPromise; + } + if (request.query.encounterTypeUuids) { + dao.getIdsByUuidAsyc( + 'amrs.encounter_type', + 'encounter_type_id', + 'uuid', + request.query.encounterTypeUuids, + function (results) { + request.query.encounterTypeIds = results; + } + ).onResolved = onResolvedPromise; + } + if (request.query.visitTypeUuids) { + dao.getIdsByUuidAsyc( + 'amrs.visit_type', + 'visit_type_id', + 'uuid', + request.query.visitTypeUuids, + function (results) { + request.query.visitTypeIds = results; + } + ).onResolved = onResolvedPromise; + } + if (request.query.locationUuids) { + dao.getIdsByUuidAsyc( + 'amrs.location', + 'location_id', + 'uuid', + request.query.locationUuids, + function (results) { + request.query.locationIds = results; + } + ).onResolved = onResolvedPromise; + } + } + } + }, + { + /** endpoint to get Reports Indicators @todo Rename to get-report-indicators by report name **/ - method: 'GET', - path: '/etl/indicators-schema', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewDataAnalytics - } - }, - handler: function (request, reply) { - //security check - if (!authorizer.hasReportAccess(request.query.report)) { - return reply(Boom.forbidden('Unauthorized')); - } - - dao.getIndicatorsSchema(request, reply); - }, - description: 'Get HIV monthly summary indicator schema', - notes: 'Returns HIV monthly summary indicator schema. ', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - query: { - report: Joi.string() - .required() - .description("The name of the report to get indicators") - } - } - } - }, - { - - - method: 'GET', - path: '/etl/indicators-schema-with-sections', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewDataAnalytics - } - }, - handler: function (request, reply) { - dao.getIndicatorsSchemaWithSections(request, reply); - } - - } - }, - { - method: 'GET', - path: '/etl/hiv-summary-data', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] - } - }, - handler: function (request, reply) { - dao.getHivSummaryData(request, reply); - } - - } - }, - { - method: 'POST', - path: '/etl/compare-patient-lists', - config: { - auth: 'simple', - handler: function (request, reply) { - var r = request; - var handler; - _.each(routes, function (route) { - if (route.path === request.payload.path) { - handler = route.config.handler; - } - }); - - var requestObject = { - query: request.payload.query, - params: request.payload.params - }; - - if (handler) { - patientListCompare.fetchAndCompareList(request.payload.patientList, - requestObject, handler) - .then(function (comparison) { - if (request.query.includeBoth === true || request.query.includeBoth === 'true') { - reply(comparison); - } else { - delete comparison.both; - reply(comparison); - } - }) - .catch(function (error) { - reply(Boom.badImplementation('An internal error occured')); - }) - } else { - reply(Boom.badRequest('Unknown patient list etl path')); - } - - } - } - }, - { - method: 'GET', - path: '/etl/patient-list-by-indicator', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] - } - }, - handler: function (request, reply) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - dao.getPatientListReport(Object.assign({}, request.query, request.params)) - .then((result) => { - reply(result); - }).catch((error) => { - reply(Boom.badRequest(JSON.stringify(error))); - }); - }); - }, - description: 'Get patient list', - notes: 'Returns a patient by passing a given indicator, report and location.', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .required() - .description("A list of comma separated location uuids"), - reportName: Joi.string() - .required() - .description("the name of the report you want patient list"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination") - } - } - } - }, - { - method: 'GET', - path: '/etl/patient-lab-orders', - config: { - auth: 'simple', - handler: function (request, reply) { - if (config.eidSyncOn === true) { - const labSyncService = new LabSyncService(); - labSyncService.syncAllLabsByPatientUuid(request.query.patientUuId, reply); - } else { - reply(Boom.notImplemented('Sorry, sync service temporarily unavailable.')); - } - } - } - }, - { - method: 'GET', - path: '/etl/sync-patient-labs', - config: { - auth: 'simple', - handler: function (request, reply) { - if (config.eidSyncOn === true) { - const labSyncService = new LabSyncService(); - labSyncService.syncAllLabsByPatientUuid(request.query.patientUuid, reply); - } - else - reply(Boom.notImplemented('Sorry, sync service temporarily unavailable.')); - } - } - }, - { - method: 'POST', - path: '/etl/eid/order/{lab}', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - if (request.params.lab !== '') { - var rawPayload = JSON.parse(JSON.stringify(request.payload)); - var labName = request.params.lab; - pocEidPayloadHelper.generatePocToEidPayLoad(rawPayload).then((eidPayLoad) => { - let configObj = config.hivLabSystem[labName]; - if (typeof configObj !== 'undefined') { - - let client = new LabClient(configObj); - return client.postLabPayload(eidPayLoad); - - } else { - console.error('Undefined Lab Configuration'); - } - }).then((result) => { - reply(result); - }).catch((error) => { - try{ - let errorObject = JSON.parse(error.error); - console.error('Error', errorObject); - reply(errorObject.error).code(error.statusCode); - } catch(err) { - console.error('Error', error); - throw Boom.badImplementation(error); - } - - }); - } else { - console.error('No Lab Specified'); - } - } - } - }, - { - method: 'GET', - path: '/etl/session/invalidate', - config: { - auth: 'simple', - handler: function (request, reply) { - dao.invalidateUserSession(request, reply); - } - } - }, - { - method: 'GET', - path: '/etl/lab-cohorts', - config: { - auth: false, - plugins: { - 'hapiAuthorization': false - }, - handler: function (request, reply) { - - var eidSyncApiKey = config.eidSyncApiKey; - var headers = request.headers; - - var h_eidSyncApiKey = request.headers.eidsyncapikey; - - if (eidSyncApiKey === h_eidSyncApiKey) { - dao.loadLabCohorts(request, reply); - } else { - reply(Boom.unauthorized('invalid api key')) - } - }, - description: 'Home', - notes: 'Returns a message that shows ETL service is running.', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - query: { - startDate: Joi.string() - .required() - .description("The start date to filter by"), - endDate: Joi.string() - .required() - .description("The end date to filter by"), - } - } - } - }, - { - method: 'GET', - path: '/etl/lab-cohorts-sync', - config: { - auth: false, - plugins: { - 'hapiAuthorization': false - }, - handler: function (request, reply) { - - var eidSyncApiKey = config.eidSyncApiKey; - var headers = request.headers; - - var h_eidSyncApiKey = request.headers.eidsyncapikey; - - if (eidSyncApiKey === h_eidSyncApiKey) { - dao.syncLabCohorts(request, reply); - } else { - reply(Boom.unauthorized('invalid api key')); - } - }, - description: 'Home', - notes: 'Returns a message that shows ETL service is running.', - tags: ['api'] - } - }, - { - method: 'GET', - path: '/etl/eid/load-order-justifications', - config: { - auth: 'simple', - handler: function (request, reply) { - - dao.loadOrderJustifications(request, reply); - }, - description: 'Justifications', - notes: 'Returns order justification(s)', - tags: ['api'] - } - }, - { - method: 'POST', - path: '/etl/fileupload', - config: { - auth: 'simple', - handler: function (request, reply) { - var replyPayload = {}; - var image = etlHelpers.decodeBase64Image(request.payload.data); - var imageTypeRegularExpression = /\/(.*?)$/; - var imageTypeDetected = image - .type - .match(imageTypeRegularExpression); - var seed = crypto.randomBytes(20); - var uniqueSHA1String = crypto - .createHash('sha1') - .update(seed) - .digest('hex'); - var userUploadedImagePath = config.etl.uploadsDirectory + - uniqueSHA1String + - '.' + - imageTypeDetected[1]; - try { - require('fs').writeFile(userUploadedImagePath, image.data, - function () { - replyPayload = { - image: uniqueSHA1String + - '.' + - imageTypeDetected[1] - }; - reply(replyPayload); - console.log('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath); - }); - } catch (error) { - console.log('ERROR:', error); - replyPayload = { - error: 'Error Uploading image' - }; - reply(replyPayload); - } - } - } - }, - { - method: 'GET', - path: '/etl/files/{param*}', - config: { - auth: 'simple', - handler: { - directory: { - path: config.etl.uploadsDirectory, - redirectToSlash: true, - index: true - } - } - } - }, - { - method: 'GET', - path: '/etl/eid/patients-with-results', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': false - }, - handler: function (request, reply) { - if (request.query.startDate && request.query.endDate) { - eidService.getPatientIdentifiersFromEIDResults(request.query.startDate, - request.query.endDate) - .then(function (response) { - reply(response); - }) - .catch(function (error) { - reply(Boom.badImplementation('A server error occured')) - }); - } else { - reply(Boom.badRequest('startDate and endDate required')); - } - - } - } - }, - { - method: 'GET', - path: '/etl/motdNotifications', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': false - }, - handler: function (request, reply) { - motd.getMotdNotifications().then(function (motdNotifications) { - - if (motdNotifications === null) { - reply(Boom.notFound('Resource does not exist')); - } else { - reply(motdNotifications); - } - }) - .catch(function (error) { - reply(Boom.create(500, 'Internal server error.', error)); - }); - - }, - description: 'Daily Message Alerts', - notes: 'Returns Messages to be shown to users on login' - } - }, - { - method: 'GET', - path: '/etl/patients-requiring-viral-load-order', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.indicator = 'needs_vl_in_period'; - request.query.reportName = 'labs-report'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new patientsRequiringVLService(); - service.getPatientListReport(requestParams).then((result) => { - _.each(result.result, (item) => { - item.cur_meds = etlHelpers.getARVNames(item.cur_meds); - }); - reply(result); - }).catch((error) => { - reply(error); - }); - }); - }, - description: "Gets patients Requiring VL list", //patientsRequiringVLService - notes: "Returns the patient list for various indicators in the labs report", - tags: ['api'], - validate: { - query: { - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .optional() - .description("The start date to filter by"), - endDate: Joi.string() - .optional() - .description("The end date to filter by"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination") - } - } - } - }, - { - method: 'GET', - path: '/etl/patient-care-cascade-analysis', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewDataAnalytics - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'patient-care-cascade-report'; - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let compineRequestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams(request.query.reportName, ['startDate', 'endDate', 'indicator', 'locationUuids', 'locations', 'order', 'gender'], compineRequestParams); - - let service = new patientCareCascadeService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - }, - description: "Gets patient-care-cascade-report", - notes: "Returns a comparative summary of various indicator eg ltfu, on_art,and vl suppression", - tags: ['api'], - validate: {} - } - }, - { - method: 'GET', - path: '/etl/patient-care-cascade-analysis/patient-list', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'patient-care-cascade-report'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new patientCareCascadeService(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - }, - description: "Get the clinical hiv comparative overview patient", - notes: "Returns the patient list for various indicators in the clinical hiv comparative summary", - tags: ['api'], - validate: { - query: { - indicator: Joi.string() - .required() - .description("A list of comma separated indicators"), - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .optional() - .description("The start date to filter by"), - endDate: Joi.string() - .optional() - .description("The end date to filter by"), - startIndex: Joi.number() - .required() - .description("The startIndex to control pagination"), - limit: Joi.number() - .required() - .description("The offset to control pagination") - } - } - } - - }, - { - method: 'GET', - path: '/etl/indicator-disaggregation-filter-options', - config: { - auth: 'simple', - handler: function (request, reply) { - reply(require('./service/indicator-processor/indicator-filter-options.json')); - }, - description: "Get indicator disaggregation options", - notes: "Returns an array of filter options", - tags: ['api'], - validate: { - query: { - - } - } - } - - }, - { - method: 'GET', - path: '/etl/patient/{patientUuid}/medical-history-report', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - request.query.groupBy = 'groupByCurArvMeds,groupByPrevArvMeds'; - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('medical-history-report', ['patientUuid'], - requestParams); - let report = new PatientMedicalHistoryService('medicalHistoryReport', reportParams.requestParams); - report.generateReport().then((result) => { - let medicalHist = new patientMedicationHistService(); - let processedResults = medicalHist.processMedicationHistory(result); - reply(processedResults); - }).catch((error) => { - reply(error); - }); - }, - description: "Get the medical history report", - notes: "Returns the the medical history of the selected patient", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } - } - }, - { - method: 'GET', - path: '/etl/departments-programs-config', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - reply(departmentProgramsService.getAllDepartmentsConfig()); - }, - description: 'Get a list of Departments and their programs ', - notes: 'Returns a list of Departments and their programs', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - - } - } - } - }, - { - method: 'GET', - path: '/etl/department-programs', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - let department = request.query.department; - let departmentPrograms = departmentProgramsService.getDepartmentPrograms(department) - .then((response) => { - reply(response); - }) - .catch((error) => { - console.error('ERROR : DepartmentPrograms Error', error); - reply(error); - }); - - }, - description: 'Get a list of Programs for a Department', - notes: 'Returns a list of Programs for a Departments', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - - } - } - } - }, - { - method: 'GET', - path: '/etl/patient-program-enrollments', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - resolveLocationUuidToId.resolveLocationUuidsParamsToIds(request.query) - .then((result) => { - - let locationIds = result; - request.query.locations = locationIds; - - resolveProgramEnrollmentFilterParams.resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) - .then((resolve) => { - - let programTypeIds = resolve.programTypeIds; - request.query.programTypeIds = programTypeIds; - enrollmentService.getActiveProgramEnrollmentSummary(request.query) - .then((result) => { - reply(result); - - }).catch((error) => { - - reply(error); - - }); - }).catch((error) => { - console.log(error); - }); - - }) - .catch((error) => { - console.log(error); - }); - }, - description: 'Get enrollment summary details based on location and time filters', - notes: 'Returns a list of active patients enrolled', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/lab-orders-by-patient', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - roles: [privileges.canViewPatient, privileges.canViewClinicDashBoard] - } - }, - handler: function (request, reply) { - request.query.reportName = 'clinic-lab-orders-report'; - //security check - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - request.params.limit = 1000; - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('clinic-lab-orders-report', ['patientUuid'], requestParams); - - let service = new labOrdersService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }, - description: "Get lab orders based on patient uuid", - notes: "Api endpoint that returns lab order(s) based on the patient uuid", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - query: { - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - patientUuid: Joi.string() - .optional() - .description("A list of comma separated patient uuids"), - } - } - } - }, - { - method: 'GET', - path: '/etl/program-enrollment/patient-list', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - resolveLocationUuidToId.resolveLocationUuidsParamsToIds(request.query) - .then((result) => { - - let locationIds = result; - request.query.locations = locationIds; - - resolveProgramEnrollmentFilterParams.resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) - .then((resolve) => { - - let programTypeIds = resolve.programTypeIds; - request.query.programTypeIds = programTypeIds; - enrollmentService.getActiveProgramEnrollmentsPatientList(request.query) - .then((result) => { - _.each(result.result, (item) => { - item.cur_meds = etlHelpers.getARVNames(item.cur_meds); - }); - reply(result); - - }).catch((error) => { - - reply(error); - - }); - }).catch((error) => { - console.log(error); - }); - - }) - .catch((error) => { - console.log(error); - }); - }, - description: 'Get a list of patients enrolled in a program in a location in a certain period', - notes: 'Returns a list of active patients enrolled', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/radiology-diagnostic-report', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - var requestParams = request.query; - console.log('requestParams', requestParams); - imagingService.getImagingResultsByPatientIdentifier(requestParams) - .then(function (results) { - if (results === null) { - reply(Boom.notFound('Resource does not exist')); - } else { - reply(results); - } - }) - .catch(function (error) { - console.error(error); - reply(error); - }); - - }, - description: "Get particular patient imaging report", - notes: "Api endpoint that returns patient imaging report based on the patient identifier", - tags: ['api'] - } - }, - { - method: 'GET', - path: '/etl/radiology-images', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - var requestParams = request.query; - // console.log('requestParams=====>>>',requestParams); - imagingService.getPatientImagesByPatientIdentifier(requestParams) - .then(function (results) { - // console.log('results',results); - imagingService.constructWadoUrl(results) - .then(function (res) { - reply(res); - - }) - }) - .catch(function (error) { - reply(error); - }); - - }, - description: "Get particular radiology patient images", - notes: "Api endpoint that returns patient images based on the patient identifier", - tags: ['api'] - } - }, - { - method: 'GET', - path: '/etl/radiology-all-patient-images', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - var requestParams = request.query; - imagingService.getAllPatientImages(requestParams) - .then(function (results) { - reply(results); - }) - .catch(function (error) { - reply(error); - }); - - }, - description: "Get particular radiology patient images", - notes: "Api endpoint that returns patient images based on the patient identifier", - tags: ['api'] - } - }, - { - method: 'POST', - path: '/etl/radiology-comments', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - var payload = request.payload; - imagingService.postRadiologyImagingComments(payload) - .then(function (results) { - reply(results); - }) - .catch(function (error) { - reply(error); - }); - - }, - description: "Post Radiology imaging comments", - notes: "Api endpoint that post comments on a particular image", - tags: ['api'] - } - }, - { - method: 'GET', - path: '/etl/oncology-reports', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - - oncologyReportsService.getOncologyReports() - .then((result) => { - reply(result); - }) - .catch((error) => { - reply(error); - }); - }, - description: 'Get a list of Oncology reports ', - notes: 'Returns a list of Oncology program reports', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - - } - } - } - }, - { - method: 'GET', - path: '/etl/oncology-report', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - - if (request.query.reportUuid) { - - let reportUuid = request.query.reportUuid; - oncologyReportsService.getSpecificOncologyReport(reportUuid) - .then((result) => { - reply(result); - }) - .catch((error) => { - reply(error); - }); - } else { - reply('ERROR:Report uuid Undefined'); - console.error('ERROR:Report uuid Undefined'); - - } - }, - description: 'Get a specific Oncology report', - notes: 'Returns a specific Oncology program report', - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: { - - } - } - } - }, - { - method: 'GET', - path: '/etl/breast-cancer-screening-numbers', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'breast-cancer-monthly-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('breast-cancer-summary-dataset', - ['startDate', 'endDate', 'period', 'locationUuids', 'indicators', 'genders', 'startAge', 'endAge'], - requestParams); - let service = new BreastCancerMonthlySummaryService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - }); - - }, - description: 'Get breast cancer monthly screening summary details based on location and time filters', - notes: 'Returns aggregates of breast cancer screening', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/breast-cancer-screening-numbers-patient-list', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'breast-cancer-monthly-screening-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new BreastCancerMonthlySummaryService(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - - }, - description: 'Get breast cancer monthly screening summary patient list based on location and time filters', - notes: 'Returns details of patients who underwent breast cancer screenings', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/combined-breast-cervical-cancer-screening-numbers', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'combined-breast-cervical-cancer-monthly-screening-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('breast-cancer-summary-dataset', - ['startDate', 'endDate', 'period', 'locationUuids', 'indicators', 'genders', 'startAge', 'endAge'], - requestParams); - let service = new CombinedBreastCervicalCancerMonthlySummary(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - }); - - }, - description: 'Get combined breast & cervical cancer monthly screening summary details based on location and time filters', - notes: 'Returns aggregates of combined breast & cervical cancer screening', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/combined-breast-cervical-cancer-screening-numbers-patient-list', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'combined-breast-cervical-cancer-monthly-screening-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new CombinedBreastCervicalCancerMonthlySummary(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - - }, - description: 'Get combined breast & cervical cancer monthly summary patient list based on location and time filters', - notes: 'Returns details of patients who underwent both breast & cervical cancer screenings', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/cervical-cancer-screening-numbers', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'cervical-cancer-monthly-screening-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('cervical-cancer-monthly-summary', - ['startDate', 'endDate', 'period', 'locationUuids', 'indicators', 'genders', 'startAge', 'endAge'], - requestParams); - let service = new CervicalCancerMonthlySummaryService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - }); - - }, - description: 'Get cervical cancer monthly screening summary based on location and time filters', - notes: 'Returns aggregates of cervical cancer screenings', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/cervical-cancer-screening-numbers-patient-list', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'cervical-cancer-monthly-screening-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new CervicalCancerMonthlySummaryService(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - - }, - description: 'Get cervical cancer monthly screening patient list based on location and time filters', - notes: 'Returns details of patients who underwent cervical cancer screenings', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/lung-cancer-screening-numbers', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'lung-cancer-monthly-screening-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('lung-cancer-monthly-summary', - ['startDate', 'endDate', 'period', 'locationUuids', 'indicators', 'genders', 'startAge', 'endAge'], - requestParams); - let service = new LungCancerMonthlySummaryService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - }); - - }, - description: 'Get lung cancer monthly screening summary based on location and time filters', - notes: 'Returns aggregates of lung cancer screenings', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/lung-cancer-screening-numbers-patient-list', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'lung-cancer-monthly-screening-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new LungCancerMonthlySummaryService(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - - }, - description: 'Get lung cancer monthly screening patient list based on location and time filters', - notes: 'Returns details of patients who underwent lung cancer screenings', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/lung-cancer-treatment-numbers', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'lung-cancer-treatment-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('breast-cancer-summary-dataset', - ['startDate', 'endDate', 'period', 'locationUuids', 'indicators', 'genders', 'startAge', 'endAge'], - requestParams); - - let service = new LungCancerTreatmentSummary(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - }); - - }, - description: 'Get lung cancer treatment summary details based on location and time filters', - notes: 'Returns aggregates of lung cancer treatment', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/lung-cancer-treatment-numbers-patient-list', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'lung-cancer-treatment-summary'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new LungCancerTreatmentSummary(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - - }, - description: 'Get Lung cancer treatment monthly patient list based on location and time filters', - notes: 'Returns details of patients who underwent lung cancer treatment', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/patient-gain-loses-numbers', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - }, - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', - name: 'locationUuids' - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'patient-gain-and-loses-report'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('patient-gain-loses-report', - ['startingMonth', 'endingMonth', 'locationUuid', 'indicators'],requestParams); - let service = new PatientGainLosesService(); - service.getAggregateReport(reportParams).then((result) => { - reply(result); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - }); - - }, - description: 'Get patient gains and loses of a specified location between indicated time (startingMonth and endingMonth) ', - notes: 'Returns aggregates of patient gains and loses', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/patient-gain-loses-patient-list', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', - name: 'locationUuids' - }] - } - }, - handler: function (request, reply) { - request.query.reportName = 'patient-gain-lose'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let service = new PatientGainLosesService(); - service.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - }); - - }, - description: 'Gets a patient list', - notes: 'Returns details of patients filterd by a specified indicator ', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/kibana-dashboards', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - } - }, - handler: function (request, reply) { - - let kibanaDashboard = kibanaService.getKibanaDashboards().then((result) => { - console.log('Kibana Dashboard', result); - reply(result); - }).catch((error) => { - reply(error); - }); - - }, - description: 'Get a list of Kibana Dashboards', - notes: 'Returns a list of links for Kibana Dashboards', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/differentiated-care-program/patient-list', - config: { - plugins: { - 'hapiAuthorization': { - role: privileges.canViewPatient - } - }, - handler: function (request, reply) { - if (request.query.locationUuids) { - resolveLocationUuidToId.resolveLocationUuidsParamsToIds(request.query) - .then((result) => { - let requestParams = Object.assign({}, request.query, request.params); - let locationUuids = request.query.locationUuids.split(',') - requestParams.startDate = requestParams.startDate.split('T')[0]; - requestParams.endDate = requestParams.endDate.split('T')[0]; - requestParams.limitParam = requestParams.limit; - requestParams.offSetParam = requestParams.startIndex; - let indicators = []; - if (requestParams.indicators) { - indicators = requestParams.indicators.split(','); - } - requestParams.locationUuids = locationUuids; - requestParams.locationIds = result; - - let report = new PatientlistMysqlReport('differentiatedCareProgramAggregate', requestParams); - report.generatePatientListReport(indicators).then((result) => { - if (result.results.results.length > 0) { - _.each(result.results.results, (item) => { - item.cur_meds = etlHelpers.getARVNames(item.cur_meds); - item.vl_1_date = moment(item.vl_1_date).format('DD-MM-YYYY'); - }); - reply(result); - } else { - reply(result); - } - - }).catch((error) => { - reply(error); - }); - }) - }; - }, - description: "Get the medical history report", - notes: "Returns the the medical history of the selected patient", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } - } - }, - { - method: 'GET', - path: '/etl/patient-referrals-peer-navigator', - config: { - auth: 'simple', - plugins: { - 'openmrsLocationAuthorizer': { - locationParameter: [{ - type: 'query', //can be in either query or params so you have to specify - name: 'locationUuids' //name of the location parameter - }], - aggregateReport: [ //set this if you want to validation checks for certain aggregate reports - { - type: 'query', //can be in either query or params so you have to specify - name: 'reportName', //name of the parameter - value: 'patient-peer-navigator-referral-report' //parameter value - } - ] - } - }, - handler: function (request, reply) { - //security check - request.query.reportName = 'patient-referral-report'; - if (!authorizer.hasReportAccess(request.query.reportName)) { - return reply(Boom.forbidden('Unauthorized')); - } - let requestParams = Object.assign({}, request.query, request.params); - requestParams.reportName = 'referral-patient-peer-navigator-list'; - let service = new PatientReferralService(); - - service.getPeerNavigatorReferralPatientList(requestParams).then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - - }, - description: 'Get the patient list for CDM strengths study', - notes: 'Returns the normal referral patient list plus some additional columns for front end processing', - tags: ['api'], - validate: { - query: { - locationUuids: Joi.string() - .optional() - .description("A list of comma separated location uuids"), - startDate: Joi.string() - .optional() - .description("The start date to filter by"), - endDate: Joi.string() - .optional() - .description("The end date to filter by"), - programUuids: Joi.string() - .optional() - .description("The program to filter by"), - limit: Joi.string() - .optional() - .description("The limit to indicate number of rows"), - department: Joi.string() - .optional() - .description("The department to filter by") - - } - } - } - }, - { - method: 'GET', - path: '/etl/surge-report', - config: { - plugins: { - 'hapiAuthorization': { - } - }, - handler: function (request, reply) { - - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('surge', - ['startDate', 'endDate', 'locationUuids'], - requestParams); - let surgeService = new SurgeService('surge', reportParams.requestParams); - surgeService.generateReport().then((result) => { - reply(result); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - - }); - - }, - description: "Get the week surge report", - notes: "Returns weekly surge report", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } - } - }, - { - method: 'GET', - path: '/etl/surge-report-patient-list', - config: { - plugins: { - 'hapiAuthorization': { - } - }, - handler: function (request, reply) { - - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - - let surgeService = new SurgeService('', requestParams); - - surgeService.getPatientListReport(requestParams).then((result) => { - reply(result); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - - }); - - }, - description: "Get the week surge report patient list", - notes: "Returns weekly surge report patient list", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } - } - }, - { - method: 'GET', - path: '/etl/retention-summary-report', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - } - }, - handler: function (request, reply) { - - if (request.query.locationUuids) { - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - - let requestParams = Object.assign({}, request.query, request.params); - // console.log('requestParams', requestParams); - let reportParams = etlHelpers.getReportParams('retention-summary-report', - ['startDate', 'endDate', 'period', 'locations', 'indicators', 'genders', 'startAge', 'endAge'], - requestParams); - let retentionService = new RetentionAppointmentTracingService('retention-report', reportParams.requestParams); - retentionService.generateReport().then((result) => { - reply(result); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - - }); - - } - - - }, - description: 'Get Retention report aggregate data', - notes: 'Returns Retention summary aggregate', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/retention-summary-report/patient-list', - config: { - auth: 'simple', - plugins: {}, - handler: function (request, reply) { - - request.query.reportName = 'retention-summary-report'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - - - let requestParams = Object.assign({}, request.query, request.params); - - let requestCopy = _.cloneDeep(requestParams); - let reportParams = etlHelpers.getReportParams(request.query.reportName, ['startDate', 'endDate', 'locationUuids', 'locations'], requestParams); - requestCopy.locations = reportParams.requestParams.locations; - - let retentionService = new RetentionAppointmentTracingService('retention-report', requestCopy); - - retentionService.generatePatientListReport(requestParams.indicators.split(',')).then((results) => { - reply(results); - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - }); - - - }, - description: 'Get Retention report Patient list', - notes: 'Returns Retention Report Patient List', - tags: ['api'], - } - - }, - { - method: 'GET', - path: '/etl/retention-summary-report/indicator-definitions', - config: { - auth: 'simple', - plugins: { - 'hapiAuthorization': { - role: privileges.canViewClinicDashBoard - } - }, - handler: function (request, reply) { - let service = new RetentionAppointmentTracingService(); - service.getIndicatorDefinitions().then((result) => { - reply(result); - }).catch((error) => { - reply(error); - }); - - }, - description: 'Get Retention report Patient list', - notes: 'Returns Retention Report Patient List', - tags: ['api'], - } - }, - { - method: 'GET', - path: '/etl/hei-monthly-summary', - config: { - plugins: { - 'hapiAuthorization': { - } - }, - handler: function (request, reply) { - - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - let reportParams = etlHelpers.getReportParams('hei-monthly-summary', - ['startDate', 'endDate', 'locationUuids'], - requestParams); - - let heiSummaryService = new HeiSummaryService('MOH-408', reportParams.requestParams); - heiSummaryService.generateReport().then((result) => { - reply(result); - - }).catch((error) => { - console.error('Error: ', error); - reply(error); - }); - }); - - }, - description: "Get the monthly hei monthly summary report", - notes: "Returns the the monthly hei summary report", - tags: ['api'], - validate: { - options: { - allowUnknown: true - }, - params: {} - } + method: 'GET', + path: '/etl/indicators-schema', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewDataAnalytics + } + }, + handler: function (request, reply) { + //security check + if (!authorizer.hasReportAccess(request.query.report)) { + return reply(Boom.forbidden('Unauthorized')); + } + + dao.getIndicatorsSchema(request, reply); + }, + description: 'Get HIV monthly summary indicator schema', + notes: 'Returns HIV monthly summary indicator schema. ', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + query: { + report: Joi.string() + .required() + .description('The name of the report to get indicators') + } + } + } + }, + { + method: 'GET', + path: '/etl/indicators-schema-with-sections', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewDataAnalytics + } + }, + handler: function (request, reply) { + dao.getIndicatorsSchemaWithSections(request, reply); + } + } + }, + { + method: 'GET', + path: '/etl/hiv-summary-data', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] + } + }, + handler: function (request, reply) { + dao.getHivSummaryData(request, reply); + } + } + }, + { + method: 'POST', + path: '/etl/compare-patient-lists', + config: { + auth: 'simple', + handler: function (request, reply) { + var r = request; + var handler; + _.each(routes, function (route) { + if (route.path === request.payload.path) { + handler = route.config.handler; + } + }); + + var requestObject = { + query: request.payload.query, + params: request.payload.params + }; + + if (handler) { + patientListCompare + .fetchAndCompareList( + request.payload.patientList, + requestObject, + handler + ) + .then(function (comparison) { + if ( + request.query.includeBoth === true || + request.query.includeBoth === 'true' + ) { + reply(comparison); + } else { + delete comparison.both; + reply(comparison); + } + }) + .catch(function (error) { + reply(Boom.badImplementation('An internal error occured')); + }); + } else { + reply(Boom.badRequest('Unknown patient list etl path')); + } + } + } + }, + { + method: 'GET', + path: '/etl/patient-list-by-indicator', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + roles: [privileges.canViewPatient, privileges.canViewDataAnalytics] + } + }, + handler: function (request, reply) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + dao + .getPatientListReport( + Object.assign({}, request.query, request.params) + ) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(Boom.badRequest(JSON.stringify(error))); + }); + }); + }, + description: 'Get patient list', + notes: + 'Returns a patient by passing a given indicator, report and location.', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .required() + .description('A list of comma separated location uuids'), + reportName: Joi.string() + .required() + .description('the name of the report you want patient list'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination') + } + } + } + }, + { + method: 'GET', + path: '/etl/patient-lab-orders', + config: { + auth: 'simple', + handler: function (request, reply) { + if (config.eidSyncOn === true) { + const labSyncService = new LabSyncService(); + labSyncService.syncAllLabsByPatientUuid( + request.query.patientUuId, + reply + ); + } else { + reply( + Boom.notImplemented( + 'Sorry, sync service temporarily unavailable.' + ) + ); + } + } + } + }, + { + method: 'GET', + path: '/etl/sync-patient-labs', + config: { + auth: 'simple', + handler: function (request, reply) { + if (config.eidSyncOn === true) { + const labSyncService = new LabSyncService(); + labSyncService.syncAllLabsByPatientUuid( + request.query.patientUuid, + reply + ); + } else + reply( + Boom.notImplemented( + 'Sorry, sync service temporarily unavailable.' + ) + ); + } + } + }, + { + method: 'POST', + path: '/etl/eid/order/{lab}', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + if (request.params.lab !== '') { + var rawPayload = JSON.parse(JSON.stringify(request.payload)); + var labName = request.params.lab; + pocEidPayloadHelper + .generatePocToEidPayLoad(rawPayload) + .then((eidPayLoad) => { + let configObj = config.hivLabSystem[labName]; + if (typeof configObj !== 'undefined') { + let client = new LabClient(configObj); + return client.postLabPayload(eidPayLoad); + } else { + console.error('Undefined Lab Configuration'); + } + }) + .then((result) => { + reply(result); + }) + .catch((error) => { + try { + let errorObject = JSON.parse(error.error); + console.error('Error', errorObject); + reply(errorObject.error).code(error.statusCode); + } catch (err) { + console.error('Error', error); + throw Boom.badImplementation(error); + } + }); + } else { + console.error('No Lab Specified'); + } + } + } + }, + { + method: 'GET', + path: '/etl/session/invalidate', + config: { + auth: 'simple', + handler: function (request, reply) { + dao.invalidateUserSession(request, reply); + } + } + }, + { + method: 'GET', + path: '/etl/lab-cohorts', + config: { + auth: false, + plugins: { + hapiAuthorization: false + }, + handler: function (request, reply) { + var eidSyncApiKey = config.eidSyncApiKey; + var headers = request.headers; + + var h_eidSyncApiKey = request.headers.eidsyncapikey; + + if (eidSyncApiKey === h_eidSyncApiKey) { + dao.loadLabCohorts(request, reply); + } else { + reply(Boom.unauthorized('invalid api key')); + } + }, + description: 'Home', + notes: 'Returns a message that shows ETL service is running.', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + query: { + startDate: Joi.string() + .required() + .description('The start date to filter by'), + endDate: Joi.string() + .required() + .description('The end date to filter by') + } + } + } + }, + { + method: 'GET', + path: '/etl/lab-cohorts-sync', + config: { + auth: false, + plugins: { + hapiAuthorization: false + }, + handler: function (request, reply) { + var eidSyncApiKey = config.eidSyncApiKey; + var headers = request.headers; + + var h_eidSyncApiKey = request.headers.eidsyncapikey; + + if (eidSyncApiKey === h_eidSyncApiKey) { + dao.syncLabCohorts(request, reply); + } else { + reply(Boom.unauthorized('invalid api key')); + } + }, + description: 'Home', + notes: 'Returns a message that shows ETL service is running.', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/eid/load-order-justifications', + config: { + auth: 'simple', + handler: function (request, reply) { + dao.loadOrderJustifications(request, reply); + }, + description: 'Justifications', + notes: 'Returns order justification(s)', + tags: ['api'] + } + }, + { + method: 'POST', + path: '/etl/fileupload', + config: { + auth: 'simple', + handler: function (request, reply) { + var replyPayload = {}; + var image = etlHelpers.decodeBase64Image(request.payload.data); + var imageTypeRegularExpression = /\/(.*?)$/; + var imageTypeDetected = image.type.match(imageTypeRegularExpression); + var seed = crypto.randomBytes(20); + var uniqueSHA1String = crypto + .createHash('sha1') + .update(seed) + .digest('hex'); + var userUploadedImagePath = + config.etl.uploadsDirectory + + uniqueSHA1String + + '.' + + imageTypeDetected[1]; + try { + require('fs').writeFile( + userUploadedImagePath, + image.data, + function () { + replyPayload = { + image: uniqueSHA1String + '.' + imageTypeDetected[1] + }; + reply(replyPayload); + console.log( + 'DEBUG - feed:message: Saved to disk image attached by user:', + userUploadedImagePath + ); + } + ); + } catch (error) { + console.log('ERROR:', error); + replyPayload = { + error: 'Error Uploading image' + }; + reply(replyPayload); + } + } + } + }, + { + method: 'GET', + path: '/etl/files/{param*}', + config: { + auth: 'simple', + handler: { + directory: { + path: config.etl.uploadsDirectory, + redirectToSlash: true, + index: true + } + } + } + }, + { + method: 'GET', + path: '/etl/eid/patients-with-results', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: false + }, + handler: function (request, reply) { + if (request.query.startDate && request.query.endDate) { + eidService + .getPatientIdentifiersFromEIDResults( + request.query.startDate, + request.query.endDate + ) + .then(function (response) { + reply(response); + }) + .catch(function (error) { + reply(Boom.badImplementation('A server error occured')); + }); + } else { + reply(Boom.badRequest('startDate and endDate required')); + } + } + } + }, + { + method: 'GET', + path: '/etl/motdNotifications', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: false + }, + handler: function (request, reply) { + motd + .getMotdNotifications() + .then(function (motdNotifications) { + if (motdNotifications === null) { + reply(Boom.notFound('Resource does not exist')); + } else { + reply(motdNotifications); + } + }) + .catch(function (error) { + reply(Boom.create(500, 'Internal server error.', error)); + }); + }, + description: 'Daily Message Alerts', + notes: 'Returns Messages to be shown to users on login' + } + }, + { + method: 'GET', + path: '/etl/patients-requiring-viral-load-order', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.indicator = 'needs_vl_in_period'; + request.query.reportName = 'labs-report'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new patientsRequiringVLService(); + service + .getPatientListReport(requestParams) + .then((result) => { + _.each(result.result, (item) => { + item.cur_meds = etlHelpers.getARVNames(item.cur_meds); + }); + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'Gets patients Requiring VL list', //patientsRequiringVLService + notes: + 'Returns the patient list for various indicators in the labs report', + tags: ['api'], + validate: { + query: { + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .optional() + .description('The start date to filter by'), + endDate: Joi.string() + .optional() + .description('The end date to filter by'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination') + } + } + } + }, + { + method: 'GET', + path: '/etl/patient-care-cascade-analysis', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewDataAnalytics + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'patient-care-cascade-report'; + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let compineRequestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + request.query.reportName, + [ + 'startDate', + 'endDate', + 'indicator', + 'locationUuids', + 'locations', + 'order', + 'gender' + ], + compineRequestParams + ); + + let service = new patientCareCascadeService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'Gets patient-care-cascade-report', + notes: + 'Returns a comparative summary of various indicator eg ltfu, on_art,and vl suppression', + tags: ['api'], + validate: {} + } + }, + { + method: 'GET', + path: '/etl/patient-care-cascade-analysis/patient-list', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'patient-care-cascade-report'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new patientCareCascadeService(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'Get the clinical hiv comparative overview patient', + notes: + 'Returns the patient list for various indicators in the clinical hiv comparative summary', + tags: ['api'], + validate: { + query: { + indicator: Joi.string() + .required() + .description('A list of comma separated indicators'), + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .optional() + .description('The start date to filter by'), + endDate: Joi.string() + .optional() + .description('The end date to filter by'), + startIndex: Joi.number() + .required() + .description('The startIndex to control pagination'), + limit: Joi.number() + .required() + .description('The offset to control pagination') + } + } + } + }, + { + method: 'GET', + path: '/etl/indicator-disaggregation-filter-options', + config: { + auth: 'simple', + handler: function (request, reply) { + reply( + require('./service/indicator-processor/indicator-filter-options.json') + ); + }, + description: 'Get indicator disaggregation options', + notes: 'Returns an array of filter options', + tags: ['api'], + validate: { + query: {} + } + } + }, + { + method: 'GET', + path: '/etl/patient/{patientUuid}/medical-history-report', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + request.query.groupBy = 'groupByCurArvMeds,groupByPrevArvMeds'; + let requestParams = Object.assign({}, request.query, request.params); + let reportParams = etlHelpers.getReportParams( + 'medical-history-report', + ['patientUuid'], + requestParams + ); + let report = new PatientMedicalHistoryService( + 'medicalHistoryReport', + reportParams.requestParams + ); + report + .generateReport() + .then((result) => { + let medicalHist = new patientMedicationHistService(); + let processedResults = medicalHist.processMedicationHistory( + result + ); + reply(processedResults); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get the medical history report', + notes: 'Returns the the medical history of the selected patient', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/departments-programs-config', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + reply(departmentProgramsService.getAllDepartmentsConfig()); + }, + description: 'Get a list of Departments and their programs ', + notes: 'Returns a list of Departments and their programs', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/department-programs', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + let department = request.query.department; + let departmentPrograms = departmentProgramsService + .getDepartmentPrograms(department) + .then((response) => { + reply(response); + }) + .catch((error) => { + console.error('ERROR : DepartmentPrograms Error', error); + reply(error); + }); + }, + description: 'Get a list of Programs for a Department', + notes: 'Returns a list of Programs for a Departments', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/patient-program-enrollments', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + resolveLocationUuidToId + .resolveLocationUuidsParamsToIds(request.query) + .then((result) => { + let locationIds = result; + request.query.locations = locationIds; + + resolveProgramEnrollmentFilterParams + .resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) + .then((resolve) => { + let programTypeIds = resolve.programTypeIds; + request.query.programTypeIds = programTypeIds; + enrollmentService + .getActiveProgramEnrollmentSummary(request.query) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }) + .catch((error) => { + console.log(error); + }); + }) + .catch((error) => { + console.log(error); + }); + }, + description: + 'Get enrollment summary details based on location and time filters', + notes: 'Returns a list of active patients enrolled', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/lab-orders-by-patient', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + roles: [ + privileges.canViewPatient, + privileges.canViewClinicDashBoard + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'clinic-lab-orders-report'; + //security check + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + request.params.limit = 1000; + let requestParams = Object.assign({}, request.query, request.params); + let reportParams = etlHelpers.getReportParams( + 'clinic-lab-orders-report', + ['patientUuid'], + requestParams + ); + + let service = new labOrdersService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get lab orders based on patient uuid', + notes: + 'Api endpoint that returns lab order(s) based on the patient uuid', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + query: { + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + patientUuid: Joi.string() + .optional() + .description('A list of comma separated patient uuids') + } + } + } + }, + { + method: 'GET', + path: '/etl/program-enrollment/patient-list', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + resolveLocationUuidToId + .resolveLocationUuidsParamsToIds(request.query) + .then((result) => { + let locationIds = result; + request.query.locations = locationIds; + + resolveProgramEnrollmentFilterParams + .resolveProgramVisitTypeEncounterUuidsParamsToIds(request.query) + .then((resolve) => { + let programTypeIds = resolve.programTypeIds; + request.query.programTypeIds = programTypeIds; + enrollmentService + .getActiveProgramEnrollmentsPatientList(request.query) + .then((result) => { + _.each(result.result, (item) => { + item.cur_meds = etlHelpers.getARVNames(item.cur_meds); + }); + reply(result); + }) + .catch((error) => { + reply(error); + }); + }) + .catch((error) => { + console.log(error); + }); + }) + .catch((error) => { + console.log(error); + }); + }, + description: + 'Get a list of patients enrolled in a program in a location in a certain period', + notes: 'Returns a list of active patients enrolled', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/radiology-diagnostic-report', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + var requestParams = request.query; + console.log('requestParams', requestParams); + imagingService + .getImagingResultsByPatientIdentifier(requestParams) + .then(function (results) { + if (results === null) { + reply(Boom.notFound('Resource does not exist')); + } else { + reply(results); + } + }) + .catch(function (error) { + console.error(error); + reply(error); + }); + }, + description: 'Get particular patient imaging report', + notes: + 'Api endpoint that returns patient imaging report based on the patient identifier', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/radiology-images', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + var requestParams = request.query; + // console.log('requestParams=====>>>',requestParams); + imagingService + .getPatientImagesByPatientIdentifier(requestParams) + .then(function (results) { + // console.log('results',results); + imagingService.constructWadoUrl(results).then(function (res) { + reply(res); + }); + }) + .catch(function (error) { + reply(error); + }); + }, + description: 'Get particular radiology patient images', + notes: + 'Api endpoint that returns patient images based on the patient identifier', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/radiology-all-patient-images', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + var requestParams = request.query; + imagingService + .getAllPatientImages(requestParams) + .then(function (results) { + reply(results); + }) + .catch(function (error) { + reply(error); + }); + }, + description: 'Get particular radiology patient images', + notes: + 'Api endpoint that returns patient images based on the patient identifier', + tags: ['api'] + } + }, + { + method: 'POST', + path: '/etl/radiology-comments', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + var payload = request.payload; + imagingService + .postRadiologyImagingComments(payload) + .then(function (results) { + reply(results); + }) + .catch(function (error) { + reply(error); + }); + }, + description: 'Post Radiology imaging comments', + notes: 'Api endpoint that post comments on a particular image', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/oncology-reports', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + oncologyReportsService + .getOncologyReports() + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get a list of Oncology reports ', + notes: 'Returns a list of Oncology program reports', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/oncology-report', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + if (request.query.reportUuid) { + let reportUuid = request.query.reportUuid; + oncologyReportsService + .getSpecificOncologyReport(reportUuid) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + } else { + reply('ERROR:Report uuid Undefined'); + console.error('ERROR:Report uuid Undefined'); + } + }, + description: 'Get a specific Oncology report', + notes: 'Returns a specific Oncology program report', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/breast-cancer-screening-numbers', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'breast-cancer-monthly-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'breast-cancer-summary-dataset', + [ + 'startDate', + 'endDate', + 'period', + 'locationUuids', + 'indicators', + 'genders', + 'startAge', + 'endAge' + ], + requestParams + ); + let service = new BreastCancerMonthlySummaryService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: + 'Get breast cancer monthly screening summary details based on location and time filters', + notes: 'Returns aggregates of breast cancer screening', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/breast-cancer-screening-numbers-patient-list', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'breast-cancer-monthly-screening-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new BreastCancerMonthlySummaryService(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: + 'Get breast cancer monthly screening summary patient list based on location and time filters', + notes: + 'Returns details of patients who underwent breast cancer screenings', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/combined-breast-cervical-cancer-screening-numbers', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = + 'combined-breast-cervical-cancer-monthly-screening-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'breast-cancer-summary-dataset', + [ + 'startDate', + 'endDate', + 'period', + 'locationUuids', + 'indicators', + 'genders', + 'startAge', + 'endAge' + ], + requestParams + ); + let service = new CombinedBreastCervicalCancerMonthlySummary(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: + 'Get combined breast & cervical cancer monthly screening summary details based on location and time filters', + notes: + 'Returns aggregates of combined breast & cervical cancer screening', + tags: ['api'] + } + }, + { + method: 'GET', + path: + '/etl/combined-breast-cervical-cancer-screening-numbers-patient-list', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = + 'combined-breast-cervical-cancer-monthly-screening-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new CombinedBreastCervicalCancerMonthlySummary(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: + 'Get combined breast & cervical cancer monthly summary patient list based on location and time filters', + notes: + 'Returns details of patients who underwent both breast & cervical cancer screenings', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/cervical-cancer-screening-numbers', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = + 'cervical-cancer-monthly-screening-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'cervical-cancer-monthly-summary', + [ + 'startDate', + 'endDate', + 'period', + 'locationUuids', + 'indicators', + 'genders', + 'startAge', + 'endAge' + ], + requestParams + ); + let service = new CervicalCancerMonthlySummaryService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: + 'Get cervical cancer monthly screening summary based on location and time filters', + notes: 'Returns aggregates of cervical cancer screenings', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/cervical-cancer-screening-numbers-patient-list', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = + 'cervical-cancer-monthly-screening-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new CervicalCancerMonthlySummaryService(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: + 'Get cervical cancer monthly screening patient list based on location and time filters', + notes: + 'Returns details of patients who underwent cervical cancer screenings', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/lung-cancer-screening-numbers', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'lung-cancer-monthly-screening-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'lung-cancer-monthly-summary', + [ + 'startDate', + 'endDate', + 'period', + 'locationUuids', + 'indicators', + 'genders', + 'startAge', + 'endAge' + ], + requestParams + ); + let service = new LungCancerMonthlySummaryService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: + 'Get lung cancer monthly screening summary based on location and time filters', + notes: 'Returns aggregates of lung cancer screenings', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/lung-cancer-screening-numbers-patient-list', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'lung-cancer-monthly-screening-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new LungCancerMonthlySummaryService(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: + 'Get lung cancer monthly screening patient list based on location and time filters', + notes: + 'Returns details of patients who underwent lung cancer screenings', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/lung-cancer-treatment-numbers', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'lung-cancer-treatment-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'breast-cancer-summary-dataset', + [ + 'startDate', + 'endDate', + 'period', + 'locationUuids', + 'indicators', + 'genders', + 'startAge', + 'endAge' + ], + requestParams + ); + + let service = new LungCancerTreatmentSummary(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: + 'Get lung cancer treatment summary details based on location and time filters', + notes: 'Returns aggregates of lung cancer treatment', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/lung-cancer-treatment-numbers-patient-list', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'lung-cancer-treatment-summary'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new LungCancerTreatmentSummary(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: + 'Get Lung cancer treatment monthly patient list based on location and time filters', + notes: + 'Returns details of patients who underwent lung cancer treatment', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/patient-gain-loses-numbers', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + }, + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', + name: 'locationUuids' + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'patient-gain-and-loses-report'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'patient-gain-loses-report', + ['startingMonth', 'endingMonth', 'locationUuid', 'indicators'], + requestParams + ); + let service = new PatientGainLosesService(); + service + .getAggregateReport(reportParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: + 'Get patient gains and loses of a specified location between indicated time (startingMonth and endingMonth) ', + notes: 'Returns aggregates of patient gains and loses', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/patient-gain-loses-patient-list', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', + name: 'locationUuids' + } + ] + } + }, + handler: function (request, reply) { + request.query.reportName = 'patient-gain-lose'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let service = new PatientGainLosesService(); + service + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }); + }, + description: 'Gets a patient list', + notes: 'Returns details of patients filterd by a specified indicator ', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/kibana-dashboards', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + } + }, + handler: function (request, reply) { + let kibanaDashboard = kibanaService + .getKibanaDashboards() + .then((result) => { + console.log('Kibana Dashboard', result); + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get a list of Kibana Dashboards', + notes: 'Returns a list of links for Kibana Dashboards', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/differentiated-care-program/patient-list', + config: { + plugins: { + hapiAuthorization: { + role: privileges.canViewPatient + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + resolveLocationUuidToId + .resolveLocationUuidsParamsToIds(request.query) + .then((result) => { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let locationUuids = request.query.locationUuids.split(','); + requestParams.startDate = requestParams.startDate.split('T')[0]; + requestParams.endDate = requestParams.endDate.split('T')[0]; + requestParams.limitParam = requestParams.limit; + requestParams.offSetParam = requestParams.startIndex; + let indicators = []; + if (requestParams.indicators) { + indicators = requestParams.indicators.split(','); + } + requestParams.locationUuids = locationUuids; + requestParams.locationIds = result; + + let report = new PatientlistMysqlReport( + 'differentiatedCareProgramAggregate', + requestParams + ); + report + .generatePatientListReport(indicators) + .then((result) => { + if (result.results.results.length > 0) { + _.each(result.results.results, (item) => { + item.cur_meds = etlHelpers.getARVNames(item.cur_meds); + item.vl_1_date = moment(item.vl_1_date).format( + 'DD-MM-YYYY' + ); + }); + reply(result); + } else { + reply(result); } - - }, - { - method: 'GET', - path: '/etl/hei-monthly-summary/patient-list', - config: { - auth: 'simple', - plugins: { - - }, - handler: function (request, reply) { - request.query.reportName = 'hei-summary-patient-list'; - preRequest.resolveLocationIdsToLocationUuids(request, - function () { - let requestParams = Object.assign({}, request.query, request.params); - - let requestCopy = _.cloneDeep(requestParams); - let reportParams = etlHelpers.getReportParams(request.query.reportName, ['startDate', 'endDate', 'locationUuids', 'locations'], requestParams); - const moh408Service = new HeiSummaryService('MOH-408', requestCopy); - - - moh408Service.generatePatientListReport(requestParams.indicators.split(',')).then((results) => { - reply(results); - }) - .catch((err) => { - reply(Boom.internal('An error occured', err)); - }); - - - }); - - }, - description: 'HEI summary Patient list', - notes: 'Returns HEI summary patient list', - tags: ['api'], - } - } - - ]; - - return routes; -}(); \ No newline at end of file + }) + .catch((error) => { + reply(error); + }); + }); + } + }, + description: 'Get the medical history report', + notes: 'Returns the the medical history of the selected patient', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/patient-referrals-peer-navigator', + config: { + auth: 'simple', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [ + { + type: 'query', //can be in either query or params so you have to specify + name: 'locationUuids' //name of the location parameter + } + ], + aggregateReport: [ + //set this if you want to validation checks for certain aggregate reports + { + type: 'query', //can be in either query or params so you have to specify + name: 'reportName', //name of the parameter + value: 'patient-peer-navigator-referral-report' //parameter value + } + ] + } + }, + handler: function (request, reply) { + //security check + request.query.reportName = 'patient-referral-report'; + if (!authorizer.hasReportAccess(request.query.reportName)) { + return reply(Boom.forbidden('Unauthorized')); + } + let requestParams = Object.assign({}, request.query, request.params); + requestParams.reportName = 'referral-patient-peer-navigator-list'; + let service = new PatientReferralService(); + + service + .getPeerNavigatorReferralPatientList(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get the patient list for CDM strengths study', + notes: + 'Returns the normal referral patient list plus some additional columns for front end processing', + tags: ['api'], + validate: { + query: { + locationUuids: Joi.string() + .optional() + .description('A list of comma separated location uuids'), + startDate: Joi.string() + .optional() + .description('The start date to filter by'), + endDate: Joi.string() + .optional() + .description('The end date to filter by'), + programUuids: Joi.string() + .optional() + .description('The program to filter by'), + limit: Joi.string() + .optional() + .description('The limit to indicate number of rows'), + department: Joi.string() + .optional() + .description('The department to filter by') + } + } + } + }, + { + method: 'GET', + path: '/etl/surge-report', + config: { + plugins: { + hapiAuthorization: {} + }, + handler: function (request, reply) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'surge', + ['startDate', 'endDate', 'locationUuids'], + requestParams + ); + let surgeService = new SurgeService( + 'surge', + reportParams.requestParams + ); + surgeService + .generateReport() + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: 'Get the week surge report', + notes: 'Returns weekly surge report', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/surge-report-patient-list', + config: { + plugins: { + hapiAuthorization: {} + }, + handler: function (request, reply) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + + let surgeService = new SurgeService('', requestParams); + + surgeService + .getPatientListReport(requestParams) + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: 'Get the week surge report patient list', + notes: 'Returns weekly surge report patient list', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/retention-summary-report', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + } + }, + handler: function (request, reply) { + if (request.query.locationUuids) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + // console.log('requestParams', requestParams); + let reportParams = etlHelpers.getReportParams( + 'retention-summary-report', + [ + 'startDate', + 'endDate', + 'period', + 'locations', + 'indicators', + 'genders', + 'startAge', + 'endAge' + ], + requestParams + ); + let retentionService = new RetentionAppointmentTracingService( + 'retention-report', + reportParams.requestParams + ); + retentionService + .generateReport() + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + } + }, + description: 'Get Retention report aggregate data', + notes: 'Returns Retention summary aggregate', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/retention-summary-report/patient-list', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + request.query.reportName = 'retention-summary-report'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + + let requestCopy = _.cloneDeep(requestParams); + let reportParams = etlHelpers.getReportParams( + request.query.reportName, + ['startDate', 'endDate', 'locationUuids', 'locations'], + requestParams + ); + requestCopy.locations = reportParams.requestParams.locations; + + let retentionService = new RetentionAppointmentTracingService( + 'retention-report', + requestCopy + ); + + retentionService + .generatePatientListReport(requestParams.indicators.split(',')) + .then((results) => { + reply(results); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: 'Get Retention report Patient list', + notes: 'Returns Retention Report Patient List', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/retention-summary-report/indicator-definitions', + config: { + auth: 'simple', + plugins: { + hapiAuthorization: { + role: privileges.canViewClinicDashBoard + } + }, + handler: function (request, reply) { + let service = new RetentionAppointmentTracingService(); + service + .getIndicatorDefinitions() + .then((result) => { + reply(result); + }) + .catch((error) => { + reply(error); + }); + }, + description: 'Get Retention report Patient list', + notes: 'Returns Retention Report Patient List', + tags: ['api'] + } + }, + { + method: 'GET', + path: '/etl/hei-monthly-summary', + config: { + plugins: { + hapiAuthorization: {} + }, + handler: function (request, reply) { + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + let reportParams = etlHelpers.getReportParams( + 'hei-monthly-summary', + ['startDate', 'endDate', 'locationUuids'], + requestParams + ); + + let heiSummaryService = new HeiSummaryService( + 'MOH-408', + reportParams.requestParams + ); + heiSummaryService + .generateReport() + .then((result) => { + reply(result); + }) + .catch((error) => { + console.error('Error: ', error); + reply(error); + }); + }); + }, + description: 'Get the monthly hei monthly summary report', + notes: 'Returns the the monthly hei summary report', + tags: ['api'], + validate: { + options: { + allowUnknown: true + }, + params: {} + } + } + }, + { + method: 'GET', + path: '/etl/hei-monthly-summary/patient-list', + config: { + auth: 'simple', + plugins: {}, + handler: function (request, reply) { + request.query.reportName = 'hei-summary-patient-list'; + preRequest.resolveLocationIdsToLocationUuids(request, function () { + let requestParams = Object.assign( + {}, + request.query, + request.params + ); + + let requestCopy = _.cloneDeep(requestParams); + let reportParams = etlHelpers.getReportParams( + request.query.reportName, + ['startDate', 'endDate', 'locationUuids', 'locations'], + requestParams + ); + const moh408Service = new HeiSummaryService('MOH-408', requestCopy); + + moh408Service + .generatePatientListReport(requestParams.indicators.split(',')) + .then((results) => { + reply(results); + }) + .catch((err) => { + reply(Boom.internal('An error occured', err)); + }); + }); + }, + description: 'HEI summary Patient list', + notes: 'Returns HEI summary patient list', + tags: ['api'] + } + } + ]; + + return routes; +})(); diff --git a/etl-server.js b/etl-server.js index e2b35e5e9..ed18e8c9b 100755 --- a/etl-server.js +++ b/etl-server.js @@ -48,7 +48,7 @@ try { } if (config.testMode === true) { - process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; + process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; } server.connection({ @@ -63,13 +63,13 @@ try { try { //Openmrs context var openmrsAppName = config.openmrs.applicationName || 'amrs'; - var authBuffer = new Buffer(username + ":" + password).toString("base64"); + var authBuffer = new Buffer(username + ':' + password).toString('base64'); var options = { hostname: config.openmrs.host, port: config.openmrs.port, path: '/' + openmrsAppName + '/ws/rest/v1/session', headers: { - 'Authorization': "Basic " + authBuffer + Authorization: 'Basic ' + authBuffer } }; var key = username; @@ -81,51 +81,63 @@ try { options.headers['Cookie'] = session.session; delete options.headers.Authorization; } - https.get(options, function (res) { - var body = ''; - res.on('data', function (chunk) { - body += chunk; - }); - res.on('end', function () { - var result; - try{ - result = JSON.parse(body); - } catch(err) { - if(session !== null ) { - cache.removeFromCache(key); - return validate(username, password, callback); + https + .get(options, function (res) { + var body = ''; + res.on('data', function (chunk) { + body += chunk; + }); + res.on('end', function () { + var result; + try { + result = JSON.parse(body); + } catch (err) { + if (session !== null) { + cache.removeFromCache(key); + return validate(username, password, callback); + } else { + return callback(null, false); + } + } + if (result.authenticated === true) { + authorizer.setUser(result.user); + authorizer.getUserAuthorizedLocations( + result.user.userProperties, + function (authorizedLocations) { + var currentUser = { + username: username, + role: authorizer.isSuperUser() + ? authorizer.getAllPrivilegesArray() + : authorizer.getCurrentUserPreviliges(), + authorizedLocations: authorizedLocations + }; + var sessionCookie = + res.headers['set-cookie'] && + res.headers['set-cookie'].length > 0 + ? res.headers['set-cookie'][0] + : session.session; + cache.saveToCache(key, { + result: result, + currentUser: currentUser, + session: sessionCookie + }); + currentUser.session = sessionCookie; + requestConfig.setAuthorization(sessionCookie); + callback(null, result.authenticated, currentUser); + } + ); } else { - return callback(null, false); + console.log( + 'An error occurred while trying to validate; user is not authenticated' + ); + callback(null, false); } - } - if (result.authenticated === true) { - authorizer.setUser(result.user); - authorizer.getUserAuthorizedLocations(result.user.userProperties, function (authorizedLocations) { - var currentUser = { - username: username, - role: authorizer.isSuperUser() ? - authorizer.getAllPrivilegesArray() : authorizer.getCurrentUserPreviliges(), - authorizedLocations: authorizedLocations - }; - var sessionCookie = res.headers["set-cookie"] && res.headers["set-cookie"].length > 0 ? res.headers["set-cookie"][0] : session.session; - cache.saveToCache(key, { - result: result, - currentUser: currentUser, - session: sessionCookie - }); - currentUser.session = sessionCookie; - requestConfig.setAuthorization(sessionCookie); - callback(null, result.authenticated, currentUser); - }); - } else { - console.log('An error occurred while trying to validate; user is not authenticated'); - callback(null, false); - } + }); + }) + .on('error', function (error) { + //console.log(error); + callback(null, false); }); - }).on('error', function (error) { - //console.log(error); - callback(null, false); - }); } catch (ex) { console.log('An error occurred while trying to validate', ex); callback(null, false); @@ -134,55 +146,63 @@ try { var HapiSwaggerOptions = { info: { - 'title': 'REST API Documentation', - 'version': Pack.version, + title: 'REST API Documentation', + version: Pack.version }, - tags: [{ - 'name': 'patient' - }, { - 'name': 'location' - }], + tags: [ + { + name: 'patient' + }, + { + name: 'location' + } + ], sortEndpoints: 'path' }; - server.register([ - Inert, - Vision, { - 'register': HapiSwagger, - 'options': HapiSwaggerOptions - }, - { - register: require('hapi-routes'), - options: { - dir: `${__dirname}/app/routes`, + server.register( + [ + Inert, + Vision, + { + register: HapiSwagger, + options: HapiSwaggerOptions }, - }, - { - register: Basic, - options: {} - }, { - register: hapiAuthorization, - options: { - roles: authorizer.getAllPrivilegesArray() - } - }, { - register: Good, - options: { - reporters: [] + { + register: require('hapi-routes'), + options: { + dir: `${__dirname}/app/routes` + } + }, + { + register: Basic, + options: {} + }, + { + register: hapiAuthorization, + options: { + roles: authorizer.getAllPrivilegesArray() + } + }, + { + register: Good, + options: { + reporters: [] + } + }, + { + register: locationAuthorizer, + options: {} } - }, { - register: locationAuthorizer, - options: {} - } - // { - // 'register': Nes, - // 'options': etlBroadcast.getOptions(server) - // } - ], + // { + // 'register': Nes, + // 'options': etlBroadcast.getOptions(server) + // } + ], function (err) { if (err) { - console.error(err) + console.error(err); throw err; // something bad happened loading the plugin } server.auth.strategy('simple', 'basic', 'required', { @@ -193,8 +213,7 @@ try { for (var route in routes) { try { server.route(routes[route]); - } - catch (badThing) { + } catch (badThing) { console.error(badThing); } } @@ -205,24 +224,31 @@ try { server.on('response', function (request) { if (request.response === undefined || request.response === null) { - console.log("No response"); + console.log('No response'); } else { var user = ''; if (request.auth && request.auth.credentials) user = request.auth.credentials.username; console.log( 'Username:', - user + '\n' + - moment().local().format("YYYY-MM-DD HH:mm:ss") + ': ' + server.info.uri + ': ' + request.method.toUpperCase() + ' ' + request.url.path + ' \n ' + request.response.statusCode + user + + '\n' + + moment().local().format('YYYY-MM-DD HH:mm:ss') + + ': ' + + server.info.uri + + ': ' + + request.method.toUpperCase() + + ' ' + + request.url.path + + ' \n ' + + request.response.statusCode ); - } }); server.ext('onPreResponse', corsHeaders); if (config.clusteringEnabled === true && cluster.isMaster) { - for (var i = 0; i < numCPUs; i++) { cluster.fork(); } @@ -231,21 +257,17 @@ try { //refork the cluster //cluster.fork(); }); - } else { //TODO start HAPI server here server.start(function () { console.log('info', 'Server running at: ' + server.info.uri); server.log('info', 'Server running at: ' + server.info.uri); }); - } - - }); + } + ); module.exports = server; - } catch (error) { console.log('error-starting', error); throw error; } - diff --git a/expression-runner/expression-runner.js b/expression-runner/expression-runner.js index 04639d8b3..9edb41ff2 100755 --- a/expression-runner/expression-runner.js +++ b/expression-runner/expression-runner.js @@ -1,35 +1,44 @@ var def = { - run: run + run: run }; module.exports = def; function run(expression, scope) { - var paramList = ''; - var argList = ''; + var paramList = ''; + var argList = ''; - for (var o in scope) { - paramList = paramList === "" ? paramList + o : paramList + ',' + o; - argList = argList === "" ? argList + "scope['" + o + "']" : argList + ",scope['" + o + "']"; - } + for (var o in scope) { + paramList = paramList === '' ? paramList + o : paramList + ',' + o; + argList = + argList === '' + ? argList + "scope['" + o + "']" + : argList + ",scope['" + o + "']"; + } - // prevent more than one return statements - if (expression.indexOf('return') === -1) { - expression = '"return ' + expression + '"'; - } + // prevent more than one return statements + if (expression.indexOf('return') === -1) { + expression = '"return ' + expression + '"'; + } - var funcDeclarationCode = 'var afeDynamicFunc = new Function("' + paramList + '", ' + expression + ');'; - var funcCallCode = 'afeDynamicFunc.call(this ' + (argList === '' ? '' : ',' + argList) + ');'; + var funcDeclarationCode = + 'var afeDynamicFunc = new Function("' + + paramList + + '", ' + + expression + + ');'; + var funcCallCode = + 'afeDynamicFunc.call(this ' + (argList === '' ? '' : ',' + argList) + ');'; - try { - if (Object.keys(scope).indexOf('undefined') >= 0) { - console.warn('Missing reference found', expression, scope); - return false; - } - // console.info('results: ', expression, eval(funcDeclarationCode + funcCallCode)); - return eval(funcDeclarationCode + funcCallCode); - } catch (e) { - console.error('error occured running epxression', e); - return undefined; + try { + if (Object.keys(scope).indexOf('undefined') >= 0) { + console.warn('Missing reference found', expression, scope); + return false; } -} \ No newline at end of file + // console.info('results: ', expression, eval(funcDeclarationCode + funcCallCode)); + return eval(funcDeclarationCode + funcCallCode); + } catch (e) { + console.error('error occured running epxression', e); + return undefined; + } +} diff --git a/hiv-summary.js b/hiv-summary.js index 3c224ad26..accf272c0 100755 --- a/hiv-summary.js +++ b/hiv-summary.js @@ -6,123 +6,125 @@ var _ = require('underscore'); var pool = mysql.createPool(config.mysql); - function queryServer(query, values) { - pool.getConnection(function (err, connection) { - if (err) { - result.errorMessage = "Database Connection Error"; - result.error = err; - console.log('Database Connection Error'); - callback(result); - return; - } - connection.query(query, values, - function (err, rows, fields) { - connection.release(); - if (err) { - result.errorMessage = "Error querying server" - result.error = err; - } - else { - result.startIndex = queryParts.offset || queryOffset; - result.size = rows.length; - result.result = rows; - } - callback(result); - }); + pool.getConnection(function (err, connection) { + if (err) { + result.errorMessage = 'Database Connection Error'; + result.error = err; + console.log('Database Connection Error'); + callback(result); + return; + } + connection.query(query, values, function (err, rows, fields) { + connection.release(); + if (err) { + result.errorMessage = 'Error querying server'; + result.error = err; + } else { + result.startIndex = queryParts.offset || queryOffset; + result.size = rows.length; + result.result = rows; + } + callback(result); }); + }); } function dateDiff(d1, d2, interval) { - if (typeof d1 === "string") d1 = new Date(d1); - if (typeof d2 === "string") d2 = new Date(d2); - if (interval === undefined || interval.toLowerCase() === "day") return (d1 - d2) / (24 * 60 * 60 * 1000); - if (interval.toLowerCase() === "week") return (d1 - d2) / (7 * 24 * 60 * 60 * 1000); - if (interval.toLowerCase() === "year") return (d1 - d2) / (52 * 7 * 24 * 60 * 60 * 1000); + if (typeof d1 === 'string') d1 = new Date(d1); + if (typeof d2 === 'string') d2 = new Date(d2); + if (interval === undefined || interval.toLowerCase() === 'day') + return (d1 - d2) / (24 * 60 * 60 * 1000); + if (interval.toLowerCase() === 'week') + return (d1 - d2) / (7 * 24 * 60 * 60 * 1000); + if (interval.toLowerCase() === 'year') + return (d1 - d2) / (52 * 7 * 24 * 60 * 60 * 1000); } - var hivSummary = function (uuid) { - var that = this; - this.data = []; - this.uuid = uuid; - this.functions = ["getFirstEvidencePatientPregnant"]; - - this.document = { - patient: uuid, - name: "hivSummary", - dateCreated: new Date() - } - - this.getData = function () { - var q = "select * from etl.flat_obs where uuid='" + uuid + "' order by encounter_datetime"; - queryServer(query, null, function (data) { - that.data = data; - }); - } - - this.toJson = function () { - return ""; - } - - - this.calculate = function () { - var calculations = []; - var prev, cur, result, key; - _.each(data, function (row) { - cur = []; - _.each(that.functions, function (f) { - result = f(row, prev); - key = result.key; - cur.push({key: result.value}); - }); - calculations.push(cur); - prev = cur; - }); - this.document.calculations = calculations; - } - - this.functions.getFirstEvidencePatientPregnant = function (curRow, prevCalc) { - var value = prevCalc["firstEvidencePatientPregnant"]; - var edd = prevCalc.edd; - if (value === undefined && ([32, 33, 44, 10].indexOf(curEncounter.encounter_type) !== -1 || /\b1279=|\b5596=/.test(curRow.obs))) - value = curRow.encounter_datetime; - else if (value && - ([11, 47, 34].indexOf(curRow.encounter_type) !== -1 - || dateDiff(value, curRow.encounter_datetime, "week") > 40 - || datediff(value, curRow.encounter_datetime, "week") > 40 - || "/b5599=|/b1156=1065".test(curRow.obs))) { - value = null; - } - - return {key: firstEvidencePatientPregnant, value: value}; + var that = this; + this.data = []; + this.uuid = uuid; + this.functions = ['getFirstEvidencePatientPregnant']; + + this.document = { + patient: uuid, + name: 'hivSummary', + dateCreated: new Date() + }; + + this.getData = function () { + var q = + "select * from etl.flat_obs where uuid='" + + uuid + + "' order by encounter_datetime"; + queryServer(query, null, function (data) { + that.data = data; + }); + }; + + this.toJson = function () { + return ''; + }; + + this.calculate = function () { + var calculations = []; + var prev, cur, result, key; + _.each(data, function (row) { + cur = []; + _.each(that.functions, function (f) { + result = f(row, prev); + key = result.key; + cur.push({ key: result.value }); + }); + calculations.push(cur); + prev = cur; + }); + this.document.calculations = calculations; + }; + + this.functions.getFirstEvidencePatientPregnant = function (curRow, prevCalc) { + var value = prevCalc['firstEvidencePatientPregnant']; + var edd = prevCalc.edd; + if ( + value === undefined && + ([32, 33, 44, 10].indexOf(curEncounter.encounter_type) !== -1 || + /\b1279=|\b5596=/.test(curRow.obs)) + ) + value = curRow.encounter_datetime; + else if ( + value && + ([11, 47, 34].indexOf(curRow.encounter_type) !== -1 || + dateDiff(value, curRow.encounter_datetime, 'week') > 40 || + datediff(value, curRow.encounter_datetime, 'week') > 40 || + '/b5599=|/b1156=1065'.test(curRow.obs)) + ) { + value = null; } -} - + return { key: firstEvidencePatientPregnant, value: value }; + }; +}; var schema = { - personUuid: "", - encounterDatetime: "", - hivSummary: { - - lastCD4: {result: 1, date: ""}, - lastVL: {result: 1, date: ""}, - edd: "", - arv_regimen: {}, - }, - vitals: { - systolic: "", - diastolic: "", - pulse: "", - oxygenSat: "", - height: "", - weight: "" - } - , - labData: [ - {obsUuid: "", obsDatetime: "", value: "", name: "", conceptUuid: ""} - ], - imagingData: {}, - medications: {}, - -} + personUuid: '', + encounterDatetime: '', + hivSummary: { + lastCD4: { result: 1, date: '' }, + lastVL: { result: 1, date: '' }, + edd: '', + arv_regimen: {} + }, + vitals: { + systolic: '', + diastolic: '', + pulse: '', + oxygenSat: '', + height: '', + weight: '' + }, + labData: [ + { obsUuid: '', obsDatetime: '', value: '', name: '', conceptUuid: '' } + ], + imagingData: {}, + medications: {} +}; diff --git a/location/location.service.js b/location/location.service.js index a830152b3..8fb20e5fe 100755 --- a/location/location.service.js +++ b/location/location.service.js @@ -1,104 +1,82 @@ -var Promise = require("bluebird"); +var Promise = require('bluebird'); var locationDao = require('../dao/location/location-dao'); const _ = require('lodash'); var locations = []; var locationUuidIdMap = new Map(); var def = { - getAlllocations : getAlllocations, - maplocationUuidToId: maplocationUuidToId, - loadAndMaplocationUuidToId : loadAndMaplocationUuidToId, - getlocationIdFromUuid: getlocationIdFromUuid + getAlllocations: getAlllocations, + maplocationUuidToId: maplocationUuidToId, + loadAndMaplocationUuidToId: loadAndMaplocationUuidToId, + getlocationIdFromUuid: getlocationIdFromUuid }; module.exports = def; - -function getAlllocations(){ - - /* +function getAlllocations() { + /* returns a list of all encunter-types with their id and uuid */ return new Promise(function (resolve, reject) { - - if(locations.length > 0){ - - // console.log('location length > 0'); - - resolve(locations); - - }else{ - - // console.log('Locations Service : location length < 0'); - - locationDao.getLocations().then(function (result) { - if(result){ - // console.log('Locations from dao', result); - locations = result; - resolve(locations); - }else{ - // console.log('Locations from dao error: '); - reject('error'); - } - }) - .catch(function (error) { - // console.log('Locations from dao error: ', error); - reject('error'); - }); - - - } - - - - }); - - - + if (locations.length > 0) { + // console.log('location length > 0'); + + resolve(locations); + } else { + // console.log('Locations Service : location length < 0'); + + locationDao + .getLocations() + .then(function (result) { + if (result) { + // console.log('Locations from dao', result); + locations = result; + resolve(locations); + } else { + // console.log('Locations from dao error: '); + reject('error'); + } + }) + .catch(function (error) { + // console.log('Locations from dao error: ', error); + reject('error'); + }); + } + }); } -function maplocationUuidToId(locations){ - - _.each(locations,(location, index) => { - locationUuidIdMap.set( location.uuid ,location.location_id); - }); - - return locationUuidIdMap; +function maplocationUuidToId(locations) { + _.each(locations, (location, index) => { + locationUuidIdMap.set(location.uuid, location.location_id); + }); + return locationUuidIdMap; } -function getlocationIdFromUuid(locationUuid){ - - var locationId = locationUuidIdMap.get(locationUuid); - - if(typeof locationId === undefined){ - return null; - }else{ - return locationId; - } +function getlocationIdFromUuid(locationUuid) { + var locationId = locationUuidIdMap.get(locationUuid); + if (typeof locationId === undefined) { + return null; + } else { + return locationId; + } } -function loadAndMaplocationUuidToId(){ - - return new Promise(function (resolve, reject) { - - getAlllocations() - .then((result) => { - if(result){ - locationUuidIdMap = maplocationUuidToId(result); - resolve(locationUuidIdMap); - } - }) - .catch(((error) =>{ - reject('Error'); - })); - - }); - +function loadAndMaplocationUuidToId() { + return new Promise(function (resolve, reject) { + getAlllocations() + .then((result) => { + if (result) { + locationUuidIdMap = maplocationUuidToId(result); + resolve(locationUuidIdMap); + } + }) + .catch((error) => { + reject('Error'); + }); + }); } - - diff --git a/location/resolve-location-uuid-to-id.js b/location/resolve-location-uuid-to-id.js index 557fda5f2..4370c65d1 100755 --- a/location/resolve-location-uuid-to-id.js +++ b/location/resolve-location-uuid-to-id.js @@ -1,136 +1,99 @@ -"use strict"; +'use strict'; -var Promise = require("bluebird"); +var Promise = require('bluebird'); const _ = require('lodash'); const dao = require('../etl-dao'); var locationService = require('./location.service'); var locationMapping; var locationDef = { - getLocationUUidIdMap: getLocationUUidIdMap, - resolveLocationUuidsParamsToIds: resolveLocationUuidsParamsToIds, - + getLocationUUidIdMap: getLocationUUidIdMap, + resolveLocationUuidsParamsToIds: resolveLocationUuidsParamsToIds }; - module.exports = locationDef; - // Get a map of locations uuids and ids -function getLocationUUidIdMap(){ - - var locationMap = new Map(); - var resolveCount = 0; - - return new Promise(function (resolve, reject) { - - function checkResolveCount(){ - if(resolveCount == 1){ - - resolve(locationMapping); - - } - } - - //first get the location map - - locationService.loadAndMaplocationUuidToId() - .then((result)=>{ - locationMapping = result; - resolveCount++; - checkResolveCount(); - // console.log('All Locations', result); - }) - .catch(function(e) { - resolveCount++; - checkResolveCount(); - console.error('ERROR: loadAndMaplocationUuidToId', e); - });; - - - }); +function getLocationUUidIdMap() { + var locationMap = new Map(); + var resolveCount = 0; + return new Promise(function (resolve, reject) { + function checkResolveCount() { + if (resolveCount == 1) { + resolve(locationMapping); + } + } + + //first get the location map + + locationService + .loadAndMaplocationUuidToId() + .then((result) => { + locationMapping = result; + resolveCount++; + checkResolveCount(); + // console.log('All Locations', result); + }) + .catch(function (e) { + resolveCount++; + checkResolveCount(); + console.error('ERROR: loadAndMaplocationUuidToId', e); + }); + }); } -function resolveLocationUuidsParamsToIds(request){ - - var locationMap = {}; - var resolvedLocationIds = []; - var resolvedLocation = []; - var resolveCount = 0; - var locationUuids = []; - - if(typeof request.locationUuids !== 'undefined'){ - - var locations = request.locationUuids; - - if(locations.length > 0){ - locationUuids = locations.split(','); - } - +function resolveLocationUuidsParamsToIds(request) { + var locationMap = {}; + var resolvedLocationIds = []; + var resolvedLocation = []; + var resolveCount = 0; + var locationUuids = []; + + if (typeof request.locationUuids !== 'undefined') { + var locations = request.locationUuids; + + if (locations.length > 0) { + locationUuids = locations.split(','); + } + } + + return new Promise(function (resolve, reject) { + function checkResolveCount() { + // console.log('Check Location Resolve Count'); + if (resolveCount > 0) { + resolve(resolvedLocationIds); + } else { + reject('Error'); } - - return new Promise(function (resolve, reject) { - - function checkResolveCount(){ - // console.log('Check Location Resolve Count'); - if(resolveCount > 0){ - resolve(resolvedLocationIds); - }else{ - reject('Error') - } - } - - getLocationUUidIdMap(). - then((result)=>{ - locationMap = result; - if (locationUuids.length > 0) { - - _.each(locationUuids, (specificLocation) => { - - var locationUuid = specificLocation; - var locationId = locationMapping.get(locationUuid); - if(typeof locationId !== 'undefined'){ - - resolvedLocation.push(locationId); - - }else{ - - console.error('ERROR : Undefined Location UUID', locationUuid); - } - - - }); - - - - }else{ - - // console.log('locations.length === 0'); - - } - - - resolvedLocationIds = _.uniq(resolvedLocation) - - resolveCount++; - - - checkResolveCount(); - }) - .catch(function(e) { - console.log("handled error", e); - });; - - }); - + } + + getLocationUUidIdMap() + .then((result) => { + locationMap = result; + if (locationUuids.length > 0) { + _.each(locationUuids, (specificLocation) => { + var locationUuid = specificLocation; + var locationId = locationMapping.get(locationUuid); + if (typeof locationId !== 'undefined') { + resolvedLocation.push(locationId); + } else { + console.error('ERROR : Undefined Location UUID', locationUuid); + } + }); + } else { + // console.log('locations.length === 0'); + } + + resolvedLocationIds = _.uniq(resolvedLocation); + + resolveCount++; + + checkResolveCount(); + }) + .catch(function (e) { + console.log('handled error', e); + }); + }); } - - - - - - - - diff --git a/oncology-reports/oncology-patient-list-cols.json b/oncology-reports/oncology-patient-list-cols.json index 226dad477..818597cf4 100644 --- a/oncology-reports/oncology-patient-list-cols.json +++ b/oncology-reports/oncology-patient-list-cols.json @@ -2208,4 +2208,4 @@ } ] } -} \ No newline at end of file +} diff --git a/oncology-reports/oncology-reports-config.json b/oncology-reports/oncology-reports-config.json index f33b32fdc..c59694094 100644 --- a/oncology-reports/oncology-reports-config.json +++ b/oncology-reports/oncology-reports-config.json @@ -2,46 +2,56 @@ { "program": "Breast Cancer Screening", "uuid": "142939b0-28a9-4649-baf9-a9d012bf3b3d", - "reports": [{ - "name": "B1. Breast cancer screening numbers", - "type": "breast-cancer-screening-numbers", - "description": "Breast cancer screening numbers contains the following indicators - total breast screened, normal breast screened, abnormal breast screening findings, breast call rate, biopsy within 2 weeks, clients staged before treatment and total referred for follow up" - }] + "reports": [ + { + "name": "B1. Breast cancer screening numbers", + "type": "breast-cancer-screening-numbers", + "description": "Breast cancer screening numbers contains the following indicators - total breast screened, normal breast screened, abnormal breast screening findings, breast call rate, biopsy within 2 weeks, clients staged before treatment and total referred for follow up" + } + ] }, { "program": "Cervical Cancer Screening", "uuid": "cad71628-692c-4d8f-8dac-b2e20bece27f", - "reports": [{ - "name": "C1. Cervical cancer screening numbers", - "type": "cervical-cancer-screening-numbers", - "description": "Cervical cancer screening numbers contains the following indicators - total cervical screened, normal cervical screened,abnormal cervical screening findings, cervical call rate, biopsy within 2 weeks, clients staged before treatment and total referred for follow up" - }] + "reports": [ + { + "name": "C1. Cervical cancer screening numbers", + "type": "cervical-cancer-screening-numbers", + "description": "Cervical cancer screening numbers contains the following indicators - total cervical screened, normal cervical screened,abnormal cervical screening findings, cervical call rate, biopsy within 2 weeks, clients staged before treatment and total referred for follow up" + } + ] }, - { + { "program": "Lung Cancer Screening", "uuid": "b2db2bdf-67e9-42c5-858c-c7e435742ef5", - "reports": [{ - "name": "L1. Lung cancer screening numbers", - "type": "lung-cancer-screening-numbers", - "description": "Lung cancer screening numbers contains the following indicators - total screened, walk-in, referred from clinic, cigarette smoking, tobacco smoking, chemical exposure, asbestos exposure, HIV positive, HIV negative, HIV status unknown, TB treatment received, no TB treatment, normal X-ray results, abnormal X-ray results, normal CT-scan results, indication of lung mass from CT findings, indication of mediastial mass from CT findings indication of pleural mass from CT findings, biopsy done, biopsy not done, non-respiratory disease, non-small-cell lung cancer, small-cell-lung cancer" - }] + "reports": [ + { + "name": "L1. Lung cancer screening numbers", + "type": "lung-cancer-screening-numbers", + "description": "Lung cancer screening numbers contains the following indicators - total screened, walk-in, referred from clinic, cigarette smoking, tobacco smoking, chemical exposure, asbestos exposure, HIV positive, HIV negative, HIV status unknown, TB treatment received, no TB treatment, normal X-ray results, abnormal X-ray results, normal CT-scan results, indication of lung mass from CT findings, indication of mediastial mass from CT findings indication of pleural mass from CT findings, biopsy done, biopsy not done, non-respiratory disease, non-small-cell lung cancer, small-cell-lung cancer" + } + ] }, { "program": "Lung Cancer Treatment", "uuid": "1a5a9a8d-f4a8-4c48-b63a-22f84530b4b9", - "reports": [{ - "name": "L2. Lung cancer treatment numbers", - "type": "lung-cancer-treatment-numbers", - "description": "Lung cancer treatment numbers contains the following indicators - total patients, walk-in, referred from clinic, diagnosis without procedures done, diagnosis with procedures, non-small cell lung cancer, epidermoid carcinoma / squamous cell carcinoma, adenocarcinoma, large cell carcinoma, mixed squamous, small cell lung cancer, stage I, stage II, stage III, stage IV, limited stage, extensive stage, chemotherapy, radiotherapy, surgery" - }] + "reports": [ + { + "name": "L2. Lung cancer treatment numbers", + "type": "lung-cancer-treatment-numbers", + "description": "Lung cancer treatment numbers contains the following indicators - total patients, walk-in, referred from clinic, diagnosis without procedures done, diagnosis with procedures, non-small cell lung cancer, epidermoid carcinoma / squamous cell carcinoma, adenocarcinoma, large cell carcinoma, mixed squamous, small cell lung cancer, stage I, stage II, stage III, stage IV, limited stage, extensive stage, chemotherapy, radiotherapy, surgery" + } + ] }, { "program": "Breast and Cervical Cancer Screening", "uuid": "b2837614-e144-4bec-abc2-e9f5e3116bb9", - "reports": [{ - "name": "BC1. Breast and Cervical cancer screening numbers", - "type": "combined-breast-cervical-cancer-screening-numbers", - "description": "Combined breast and cervical cancer screening numbers contains the following indicators - total breast screened, total cervical screened, total breast and cervical screened" - }] + "reports": [ + { + "name": "BC1. Breast and Cervical cancer screening numbers", + "type": "combined-breast-cervical-cancer-screening-numbers", + "description": "Combined breast and cervical cancer screening numbers contains the following indicators - total breast screened, total cervical screened, total breast and cervical screened" + } + ] } -] \ No newline at end of file +] diff --git a/oncology-reports/oncology-reports-service.js b/oncology-reports/oncology-reports-service.js index 164c72a5d..8469aedfe 100644 --- a/oncology-reports/oncology-reports-service.js +++ b/oncology-reports/oncology-reports-service.js @@ -1,8 +1,8 @@ -"use strict"; -const _ = require("lodash"); +'use strict'; +const _ = require('lodash'); -const oncologyReportsConfig = require("./oncology-reports-config.json"); -const oncologyPatientListCols = require("./oncology-patient-list-cols.json"); +const oncologyReportsConfig = require('./oncology-reports-config.json'); +const oncologyPatientListCols = require('./oncology-patient-list-cols.json'); var serviceDefinition = { getOncologyReports: getOncologyReports, @@ -13,7 +13,7 @@ var serviceDefinition = { module.exports = serviceDefinition; function getOncologyReports() { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { resolve(JSON.parse(JSON.stringify(oncologyReportsConfig))); }); } @@ -21,8 +21,8 @@ function getOncologyReports() { function getSpecificOncologyReport(reportUuid) { let specificReport = []; - return new Promise(function(resolve, reject) { - _.each(oncologyReportsConfig, report => { + return new Promise(function (resolve, reject) { + _.each(oncologyReportsConfig, (report) => { let programUuid = report.uuid; if (programUuid === reportUuid) { specificReport = report; @@ -37,8 +37,8 @@ function getPatientListCols(indicator, programUuid) { let patientCols = []; let specificReport = oncologyPatientListCols[programUuid]; return new Promise((resolve, reject) => { - _.each(specificReport, report => { - _.each(report, programReport => { + _.each(specificReport, (report) => { + _.each(report, (programReport) => { let reportIndicator = programReport.indicator; if (reportIndicator === indicator) { let patientListCols = programReport.patientListCols; diff --git a/package-lock.json b/package-lock.json index 578abea21..c92d908ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,75 @@ "lockfileVersion": 1, "requires": true, "dependencies": { + "@babel/code-frame": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", + "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", + "dev": true, + "requires": { + "@babel/highlight": "^7.10.4" + } + }, + "@babel/helper-validator-identifier": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.4.tgz", + "integrity": "sha512-3U9y+43hz7ZM+rzG24Qe2mufW5KhvFg/NhnNph+i9mgCtdTCtMJuI1TMkrIUiK7Ix4PYlRF9I5dhqaLYA/ADXw==", + "dev": true + }, + "@babel/highlight": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.10.4.tgz", + "integrity": "sha512-i6rgnR/YgPEQzZZnbTHHuZdlE8qyoBNalD6F+q4vAFlcMEcqmkoG+mPqJYJCo63qPf74+Y1UZsl3l6f7/RIkmA==", + "dev": true, + "requires": { + "@babel/helper-validator-identifier": "^7.10.4", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + } + } + }, "@sindresorhus/is": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", @@ -97,6 +166,11 @@ "resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.29.tgz", "integrity": "sha512-kmVtnxTuUuhCET669irqQmPAez4KFnFVKvpleVRyfC3g+SHD1hIkFZcWLim9BVcwUBLO59o8VZE4yGCmTif8Yw==" }, + "@types/color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==" + }, "@types/events": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz", @@ -152,6 +226,12 @@ "p-retry": "*" } }, + "@types/parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA==", + "dev": true + }, "@types/retry": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", @@ -208,6 +288,16 @@ "humanize-ms": "^1.2.1" } }, + "aggregate-error": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "dev": true, + "requires": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + } + }, "ajv": { "version": "6.12.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.0.tgz", @@ -279,6 +369,12 @@ "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", "dev": true }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, "string-width": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", @@ -306,6 +402,15 @@ "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==" }, + "ansi-escapes": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.1.tgz", + "integrity": "sha512-JWF7ocqNrp8u9oqpgV+wH5ftbt+cfvv+PTjOvKLT3AdYly/LmORARfEVT1iyjwN+4MqE5UmVKoAdIBqeoCHgLA==", + "dev": true, + "requires": { + "type-fest": "^0.11.0" + } + }, "ansi-regex": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", @@ -427,6 +532,12 @@ "dev": true, "optional": true }, + "astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "dev": true + }, "async": { "version": "2.6.3", "resolved": "https://registry.npmjs.org/async/-/async-2.6.3.tgz", @@ -1619,6 +1730,12 @@ "requires": { "has-flag": "^4.0.0" } + }, + "type-fest": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", + "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "dev": true } } }, @@ -1763,6 +1880,12 @@ "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.1.tgz", "integrity": "sha1-JtII6onje1y95gJQoV8DHBak1ms=" }, + "callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true + }, "camelcase": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", @@ -2078,6 +2201,12 @@ } } }, + "clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "dev": true + }, "cli": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cli/-/cli-1.0.1.tgz", @@ -2093,6 +2222,59 @@ "integrity": "sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw==", "dev": true }, + "cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "requires": { + "restore-cursor": "^3.1.0" + } + }, + "cli-truncate": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", + "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", + "dev": true, + "requires": { + "slice-ansi": "^3.0.0", + "string-width": "^4.2.0" + }, + "dependencies": { + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "string-width": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "dev": true, + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + } + }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, + "requires": { + "ansi-regex": "^5.0.0" + } + } + } + }, "cliui": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", @@ -2108,6 +2290,32 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + }, "string-width": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", @@ -2125,6 +2333,16 @@ "requires": { "ansi-regex": "^4.1.0" } + }, + "wrap-ansi": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", + "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "requires": { + "ansi-styles": "^3.2.0", + "string-width": "^3.0.0", + "strip-ansi": "^5.0.0" + } } } }, @@ -2166,6 +2384,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, "requires": { "color-name": "~1.1.4" } @@ -2173,7 +2392,8 @@ "color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true }, "colors": { "version": "0.6.2", @@ -2194,6 +2414,12 @@ "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==", "dev": true }, + "compare-versions": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-3.6.0.tgz", + "integrity": "sha512-W6Af2Iw1z4CB7q4uU4hv646dW9GQuBM+YpC0UvUCWSD8w90SJjp+ujJuXaEMtAXBtSqGfMPuFOVn4/+FlaqfBA==", + "dev": true + }, "component-emitter": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.1.2.tgz", @@ -2348,6 +2574,19 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" }, + "cosmiconfig": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.0.tgz", + "integrity": "sha512-pondGvTuVYDk++upghXJabWzL6Kxu6f26ljFw64Swq9v6sQPUL3EUlVDV56diOjpCayKihL6hVe8exIACU4XcA==", + "dev": true, + "requires": { + "@types/parse-json": "^4.0.0", + "import-fresh": "^3.2.1", + "parse-json": "^5.0.0", + "path-type": "^4.0.0", + "yaml": "^1.10.0" + } + }, "create-thenable": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/create-thenable/-/create-thenable-1.0.2.tgz", @@ -2479,6 +2718,12 @@ "mimic-response": "^1.0.0" } }, + "dedent": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", + "integrity": "sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw=", + "dev": true + }, "deep-eql": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-0.1.3.tgz", @@ -2710,9 +2955,10 @@ } }, "emoji-regex": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", - "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true }, "encodeurl": { "version": "1.0.2", @@ -2728,11 +2974,29 @@ "once": "^1.4.0" } }, + "enquirer": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", + "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", + "dev": true, + "requires": { + "ansi-colors": "^4.1.1" + } + }, "entities": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/entities/-/entities-1.0.0.tgz", "integrity": "sha1-sph6o4ITR/zeZCsk/fyeT7cSvyY=" }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, "es-abstract": { "version": "1.17.4", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.4.tgz", @@ -3022,6 +3286,15 @@ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha1-h0v2nG9ATCtdmcSBNBOZ/VWJJjM=" }, + "figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, "file-uri-to-path": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", @@ -3094,14 +3367,24 @@ } }, "find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, "requires": { - "locate-path": "^6.0.0", + "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, + "find-versions": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/find-versions/-/find-versions-3.2.0.tgz", + "integrity": "sha512-P8WRou2S+oe222TOCHitLy8zj+SIsVJh52VP4lvXkaFVnOFFdoWv1H1Jjvel1aI6NCFOAaeAVm8qrI0odiLcww==", + "dev": true, + "requires": { + "semver-regex": "^2.0.0" + } + }, "finity": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/finity/-/finity-0.5.4.tgz", @@ -3773,6 +4056,12 @@ "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", "dev": true }, + "get-own-enumerable-property-symbols": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz", + "integrity": "sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==", + "dev": true + }, "get-stream": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", @@ -4458,6 +4747,12 @@ "resolved": "https://registry.npmjs.org/https/-/https-1.0.0.tgz", "integrity": "sha1-PDfHrhqO65ZpBKKtHpdaGUt+06Q=" }, + "human-signals": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-1.1.1.tgz", + "integrity": "sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==", + "dev": true + }, "humanize-ms": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", @@ -4466,6 +4761,88 @@ "ms": "^2.0.0" } }, + "husky": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/husky/-/husky-4.3.0.tgz", + "integrity": "sha512-tTMeLCLqSBqnflBZnlVDhpaIMucSGaYyX6855jM4AguGeWCeSzNdb1mfyWduTZ3pe3SJVvVWGL0jO1iKZVPfTA==", + "dev": true, + "requires": { + "chalk": "^4.0.0", + "ci-info": "^2.0.0", + "compare-versions": "^3.6.0", + "cosmiconfig": "^7.0.0", + "find-versions": "^3.2.0", + "opencollective-postinstall": "^2.0.2", + "pkg-dir": "^4.2.0", + "please-upgrade-node": "^3.2.0", + "slash": "^3.0.0", + "which-pm-runs": "^1.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "ci-info": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", + "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", + "dev": true + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, "i": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/i/-/i-0.3.6.tgz", @@ -4485,6 +4862,16 @@ "integrity": "sha1-SMptcvbGo68Aqa1K5odr44ieKwk=", "dev": true }, + "import-fresh": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.2.1.tgz", + "integrity": "sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ==", + "dev": true, + "requires": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + } + }, "import-lazy": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", @@ -4497,6 +4884,12 @@ "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", "dev": true }, + "indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true + }, "inert": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/inert/-/inert-3.2.1.tgz", @@ -4612,6 +5005,12 @@ "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.0.4.tgz", "integrity": "sha1-P6+WbHy6D/Q3+zH2JQCC/PBEjPM=" }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, "is-binary-path": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", @@ -4835,6 +5234,12 @@ "has": "^1.0.3" } }, + "is-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", + "integrity": "sha1-/S2INUXEa6xaYz57mgnof6LLUGk=", + "dev": true + }, "is-set": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.1.tgz", @@ -5035,6 +5440,12 @@ "integrity": "sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg=", "dev": true }, + "json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true + }, "json-schema": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", @@ -5108,21 +5519,323 @@ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", "integrity": "sha1-B8BQNKbDSfoG4k+jWqdttFgM5N0=" }, - "latest-version": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-5.1.0.tgz", - "integrity": "sha512-weT+r0kTkRQdCdYCNtkMwWXQTMEswKrFBkm4ckQOMVhhqhIMI1UT2hMj+1iigIhgSZm5gTmrRXBNoGUgaTY1xA==", + "lines-and-columns": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", + "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=", + "dev": true + }, + "lint-staged": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-10.3.0.tgz", + "integrity": "sha512-an3VgjHqmJk0TORB/sdQl0CTkRg4E5ybYCXTTCSJ5h9jFwZbcgKIx5oVma5e7wp/uKt17s1QYFmYqT9MGVosGw==", + "dev": true, + "requires": { + "chalk": "^4.1.0", + "cli-truncate": "^2.1.0", + "commander": "^6.0.0", + "cosmiconfig": "^7.0.0", + "debug": "^4.1.1", + "dedent": "^0.7.0", + "enquirer": "^2.3.6", + "execa": "^4.0.3", + "listr2": "^2.6.0", + "log-symbols": "^4.0.0", + "micromatch": "^4.0.2", + "normalize-path": "^3.0.0", + "please-upgrade-node": "^3.2.0", + "string-argv": "0.3.1", + "stringify-object": "^3.3.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "requires": { + "fill-range": "^7.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "commander": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-6.1.0.tgz", + "integrity": "sha512-wl7PNrYWd2y5mp1OK/LhTlv8Ff4kQJQRXXAvF+uU/TPNiVJUxZLRYGj/B0y/lPGAVcSbJqH2Za/cvHmrPMC8mA==", + "dev": true + }, + "cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dev": true, + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "execa": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.3.tgz", + "integrity": "sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A==", + "dev": true, + "requires": { + "cross-spawn": "^7.0.0", + "get-stream": "^5.0.0", + "human-signals": "^1.1.1", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.0", + "onetime": "^5.1.0", + "signal-exit": "^3.0.2", + "strip-final-newline": "^2.0.0" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "dev": true, + "requires": { + "pump": "^3.0.0" + } + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true + }, + "is-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==", + "dev": true + }, + "micromatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", + "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==", + "dev": true, + "requires": { + "braces": "^3.0.1", + "picomatch": "^2.0.5" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + }, + "npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "requires": { + "path-key": "^3.0.0" + } + }, + "onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "requires": { + "is-number": "^7.0.0" + } + }, + "which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "listr2": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-2.6.2.tgz", + "integrity": "sha512-6x6pKEMs8DSIpA/tixiYY2m/GcbgMplMVmhQAaLFxEtNSKLeWTGjtmU57xvv6QCm2XcqzyNXL/cTSVf4IChCRA==", "dev": true, "requires": { - "package-json": "^6.3.0" + "chalk": "^4.1.0", + "cli-truncate": "^2.1.0", + "figures": "^3.2.0", + "indent-string": "^4.0.0", + "log-update": "^4.0.0", + "p-map": "^4.0.0", + "rxjs": "^6.6.2", + "through": "^2.3.8" + }, + "dependencies": { + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } } }, "locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, "requires": { - "p-locate": "^5.0.0" + "p-locate": "^4.1.0" } }, "lodash": { @@ -5157,10 +5870,11 @@ }, "dependencies": { "ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", "requires": { + "@types/color-name": "^1.1.1", "color-convert": "^2.0.1" } }, @@ -5173,6 +5887,19 @@ "supports-color": "^7.1.0" } }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, "has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -5188,6 +5915,62 @@ } } }, + "log-update": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-4.0.0.tgz", + "integrity": "sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg==", + "dev": true, + "requires": { + "ansi-escapes": "^4.3.0", + "cli-cursor": "^3.1.0", + "slice-ansi": "^4.0.0", + "wrap-ansi": "^6.2.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + }, + "slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + } + } + } + }, "lolex": { "version": "2.7.5", "resolved": "https://registry.npmjs.org/lolex/-/lolex-2.7.5.tgz", @@ -5274,6 +6057,12 @@ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true + }, "methods": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/methods/-/methods-0.0.1.tgz", @@ -5338,6 +6127,12 @@ "mime-db": "1.43.0" } }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true + }, "mimic-response": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", @@ -5574,6 +6369,15 @@ "to-regex-range": "^5.0.1" } }, + "find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "requires": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + } + }, "fsevents": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.3.tgz", @@ -5641,6 +6445,14 @@ "esprima": "^4.0.0" } }, + "locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "requires": { + "p-locate": "^5.0.0" + } + }, "mocha": { "version": "8.1.3", "resolved": "https://registry.npmjs.org/mocha/-/mocha-8.1.3.tgz", @@ -5683,6 +6495,22 @@ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==" }, + "p-limit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.0.2.tgz", + "integrity": "sha512-iwqZSOoWIW+Ew4kAGUlN16J4M7OB3ysMLSZtnhmqx7njIHFPlxWBX8xo3lVTyFVq6mI/lL9qt2IsN1sHwaxJkg==", + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "requires": { + "p-limit": "^3.0.2" + } + }, "readdirp": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.4.0.tgz", @@ -8889,19 +9717,30 @@ "integrity": "sha1-B+nG0iwx+cZ4TLTx4UVKebbZ4tY=" }, "p-limit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.0.2.tgz", - "integrity": "sha512-iwqZSOoWIW+Ew4kAGUlN16J4M7OB3ysMLSZtnhmqx7njIHFPlxWBX8xo3lVTyFVq6mI/lL9qt2IsN1sHwaxJkg==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, "requires": { "p-try": "^2.0.0" } }, "p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, "requires": { - "p-limit": "^3.0.2" + "p-limit": "^2.2.0" + } + }, + "p-map": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", + "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", + "dev": true, + "requires": { + "aggregate-error": "^3.0.0" } }, "p-queue": { @@ -8942,6 +9781,15 @@ } } }, + "parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "requires": { + "callsites": "^3.0.0" + } + }, "parse-glob": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/parse-glob/-/parse-glob-3.0.4.tgz", @@ -8955,6 +9803,18 @@ "is-glob": "^2.0.0" } }, + "parse-json": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.1.0.tgz", + "integrity": "sha512-+mi/lmVVNKFNVyLXV31ERiy2CY5E1/F6QtJFEzoChPRwwngMNXRDQ9GJ5WdE2Z2P4AujsOi0/+2qHID68KwfIQ==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + } + }, "parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -8982,6 +9842,12 @@ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" }, + "path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true + }, "pathval": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.0.tgz", @@ -9029,6 +9895,24 @@ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==" }, + "pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "requires": { + "find-up": "^4.0.0" + } + }, + "please-upgrade-node": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", + "integrity": "sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==", + "dev": true, + "requires": { + "semver-compare": "^1.0.0" + } + }, "podium": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/podium/-/podium-1.3.0.tgz", @@ -9089,6 +9973,12 @@ "dev": true, "optional": true }, + "prettier": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.1.1.tgz", + "integrity": "sha512-9bY+5ZWCfqj3ghYBLxApy2zf6m+NJo5GzmLTpr9FsApsfjriNnS2dahWReHMi7qNPhhHl9SYHJs2cHZLgexNIw==", + "dev": true + }, "private": { "version": "0.1.8", "resolved": "https://registry.npmjs.org/private/-/private-0.1.8.tgz", @@ -9813,6 +10703,12 @@ "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, + "resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true + }, "resolve-url": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", @@ -9829,6 +10725,27 @@ "lowercase-keys": "^1.0.0" } }, + "restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "requires": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "dependencies": { + "onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "requires": { + "mimic-fn": "^2.1.0" + } + } + } + }, "ret": { "version": "0.1.15", "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", @@ -9846,6 +10763,15 @@ "resolved": "https://registry.npmjs.org/router-ips/-/router-ips-0.2.0.tgz", "integrity": "sha1-IPbld0Ih5RkZdjndmsBLe63sls0=" }, + "rxjs": { + "version": "6.6.3", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.3.tgz", + "integrity": "sha512-trsQc+xYYXZ3urjOiJOuCOa5N3jAZ3eiSpQB5hIT8zGlL2QfnHLJ2r7GMkBGuIausdJN1OneaI6gQlsqNHHmZQ==", + "dev": true, + "requires": { + "tslib": "^1.9.0" + } + }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", @@ -9877,6 +10803,12 @@ "integrity": "sha1-qVT5Ma66UI0we78Gnv8MAclhFvc=", "dev": true }, + "semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha1-De4hahyUGrN+nvsXiPavxf9VN/w=", + "dev": true + }, "semver-diff": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-3.1.1.tgz", @@ -9894,6 +10826,12 @@ } } }, + "semver-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/semver-regex/-/semver-regex-2.0.0.tgz", + "integrity": "sha512-mUdIBBvdn0PLOeP3TEkMH7HHeUP3GjsXCwKarjv/kGmUFOYg1VqEemKhoQpWMu6X2I8kHeuVdGibLGkVK+/5Qw==", + "dev": true + }, "send": { "version": "0.17.1", "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", @@ -10105,6 +11043,50 @@ "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=", "dev": true }, + "slice-ansi": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", + "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", + "dev": true, + "requires": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true + } + } + }, "snapdragon": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", @@ -10547,6 +11529,12 @@ "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-0.1.2.tgz", "integrity": "sha1-gIudDlb8Jz2Am6VzOOkpkZoanxo=" }, + "string-argv": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.1.tgz", + "integrity": "sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg==", + "dev": true + }, "string-width": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", @@ -10594,6 +11582,25 @@ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" }, + "stringify-object": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", + "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", + "dev": true, + "requires": { + "get-own-enumerable-property-symbols": "^3.0.0", + "is-obj": "^1.0.1", + "is-regexp": "^1.0.0" + }, + "dependencies": { + "is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", + "dev": true + } + } + }, "strip-ansi": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", @@ -10602,6 +11609,12 @@ "ansi-regex": "^2.0.0" } }, + "strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true + }, "strip-json-comments": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz", @@ -10668,6 +11681,12 @@ "integrity": "sha512-a6sumDlzyHVJWb8+YofY4TW112G6p2FCPEAFk+59gIYHv3XHRhm9ltVQ9kli4hNWeQBwSpe8cRN25x0ROunMOw==", "dev": true }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, "through2": { "version": "0.6.5", "resolved": "https://registry.npmjs.org/through2/-/through2-0.6.5.tgz", @@ -10889,9 +11908,9 @@ "integrity": "sha1-diIXzAbbJY7EiQihKY6LlRIejqI=" }, "type-fest": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz", - "integrity": "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==", + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.11.0.tgz", + "integrity": "sha512-OdjXJxnCN1AvyLSzeKIgXTXxV+99ZuXl3Hpo9XpJAv9MBcHrrJOQ5kV7ypXOuQie+AmWG25hLbiKdwYTifzcfQ==", "dev": true }, "type-is": { @@ -11109,6 +12128,15 @@ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true }, + "latest-version": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-5.1.0.tgz", + "integrity": "sha512-weT+r0kTkRQdCdYCNtkMwWXQTMEswKrFBkm4ckQOMVhhqhIMI1UT2hMj+1iigIhgSZm5gTmrRXBNoGUgaTY1xA==", + "dev": true, + "requires": { + "package-json": "^6.3.0" + } + }, "supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -11274,6 +12302,12 @@ "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=" }, + "which-pm-runs": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/which-pm-runs/-/which-pm-runs-1.0.0.tgz", + "integrity": "sha1-Zws6+8VS4LVd9rd4DKdGFfI60cs=", + "dev": true + }, "wide-align": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz", @@ -11380,57 +12414,71 @@ "integrity": "sha512-fU2OcNA/GVAJLLyKUoHkAgIhKb0JoCpSjLC/G2vYKxUjVmQwGbRVeoPJ1a8U4pnVofz4AQV5Y/NEw8oKqxEBtA==" }, "wrap-ansi": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", - "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dev": true, "requires": { - "ansi-styles": "^3.2.0", - "string-width": "^3.0.0", - "strip-ansi": "^5.0.0" + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" }, "dependencies": { "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "dev": true }, "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "dev": true, "requires": { - "color-convert": "^1.9.0" + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" } }, "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, "requires": { - "color-name": "1.1.3" + "color-name": "~1.1.4" } }, "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true }, "string-width": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.0.tgz", + "integrity": "sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==", + "dev": true, "requires": { - "emoji-regex": "^7.0.1", - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^5.1.0" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" } }, "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dev": true, "requires": { - "ansi-regex": "^4.1.0" + "ansi-regex": "^5.0.0" } } } @@ -11500,6 +12548,12 @@ "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==" }, + "yaml": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.0.tgz", + "integrity": "sha512-yr2icI4glYaNG+KWONODapy2/jDdMSDnrONSjblABjD9B4Z5LgiircSt8m8sRZFNi08kG9Sm0uSHtEmP3zaEGg==", + "dev": true + }, "yargs": { "version": "13.3.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.2.tgz", @@ -11527,6 +12581,11 @@ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + }, "find-up": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", @@ -11624,6 +12683,11 @@ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + }, "find-up": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", diff --git a/package.json b/package.json index 9def72b03..20c4df8e3 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,17 @@ "start": "babel-node etl-server.js --presets es2015,stage-2", "test": "mocha --require babel-core/register --colors --recursive ./test/**/*.test.js", "test:watch": "mocha --require babel-core/register --colors -w --recursive ./test/**/*.test.js", - "watch": "npm-watch" + "watch": "npm-watch", + "prettier:check": "prettier --check .", + "prettier:write": "prettier --write ." + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.{js,css,md}": "prettier --write" }, "pre-commit": "npm test", "author": "AMPATH DEVS", @@ -98,9 +108,12 @@ "babel-register": "^6.26.0", "chai": "^3.4.1", "chai-as-promised": "^5.3.0", + "husky": "^4.3.0", + "lint-staged": "^10.3.0", "mocha": "^2.3.3", "nock": "^10.0.6", "npm-watch": "^0.7.0", + "prettier": "2.1.1", "sinon": "^4.4.4", "sinon-as-promised": "^4.0.0", "sinon-chai": "^2.8.0" diff --git a/patient-lab-orders.json b/patient-lab-orders.json index 28577644e..eeabe8bf9 100755 --- a/patient-lab-orders.json +++ b/patient-lab-orders.json @@ -1,19 +1,17 @@ { - "patientLabOrderSchema":{ - "name": "patient-lab-orders", - "table":{"schema":"amrs","tableName":"obs ","alias":"t1"}, - "joins":[], - "parameters": [ - {"name":"person_id", "defaultValue":["defaultValue"]}, - {"name":"encounter_id", "defaultValue":["defaultValue"]}, - {"name":"location_id","defaultValue":["defaultValue"]}, - {"name":"obs_datetime", "defaultValue":["defaultValue"]} - ], - "filters": [ - {"expression":"t1.person_id= ?", "parameter":"person_id"} - ], - "groupClause":[], - "indicators": [], - "supplementColumns":[] - } + "patientLabOrderSchema": { + "name": "patient-lab-orders", + "table": { "schema": "amrs", "tableName": "obs ", "alias": "t1" }, + "joins": [], + "parameters": [ + { "name": "person_id", "defaultValue": ["defaultValue"] }, + { "name": "encounter_id", "defaultValue": ["defaultValue"] }, + { "name": "location_id", "defaultValue": ["defaultValue"] }, + { "name": "obs_datetime", "defaultValue": ["defaultValue"] } + ], + "filters": [{ "expression": "t1.person_id= ?", "parameter": "person_id" }], + "groupClause": [], + "indicators": [], + "supplementColumns": [] + } } diff --git a/pm2-AUTO-ENROLL.json b/pm2-AUTO-ENROLL.json index a5f85f0ce..0935f6c74 100644 --- a/pm2-AUTO-ENROLL.json +++ b/pm2-AUTO-ENROLL.json @@ -1,16 +1,18 @@ { - "apps" : [ - { - "name" : "eid-sync", - "script" : "/opt/etl/worker/auto-enroll-veremia.js", - "watch" : false, - "exec_interpreter" : "babel-node", - "exec_mode" : "fork" - },{ - "name" : "etl-server", - "script" : "/opt/etl/etl-server.js", - "watch" : false, - "exec_interpreter" : "babel-node", - "exec_mode" : "fork" - }] - } + "apps": [ + { + "name": "eid-sync", + "script": "/opt/etl/worker/auto-enroll-veremia.js", + "watch": false, + "exec_interpreter": "babel-node", + "exec_mode": "fork" + }, + { + "name": "etl-server", + "script": "/opt/etl/etl-server.js", + "watch": false, + "exec_interpreter": "babel-node", + "exec_mode": "fork" + } + ] +} diff --git a/pm2-EID.json b/pm2-EID.json index 14adda070..2c5209ce0 100755 --- a/pm2-EID.json +++ b/pm2-EID.json @@ -1,17 +1,18 @@ { - "apps" : [ - { - "name" : "eid-sync", - "script" : "/opt/etl/worker/eid-sync.js", - "watch" : false, - "exec_interpreter" : "babel-node", - "exec_mode" : "fork" - },{ - "name" : "etl-server", - "script" : "/opt/etl/etl-server.js", - "watch" : false, - "exec_interpreter" : "babel-node", - "exec_mode" : "fork" - }] - } - \ No newline at end of file + "apps": [ + { + "name": "eid-sync", + "script": "/opt/etl/worker/eid-sync.js", + "watch": false, + "exec_interpreter": "babel-node", + "exec_mode": "fork" + }, + { + "name": "etl-server", + "script": "/opt/etl/etl-server.js", + "watch": false, + "exec_interpreter": "babel-node", + "exec_mode": "fork" + } + ] +} diff --git a/pm2.json b/pm2.json index fcfb7111e..89357490b 100755 --- a/pm2.json +++ b/pm2.json @@ -1,10 +1,11 @@ { - "apps" : [{ - "name" : "etl-server", - "script" : "/opt/etl/etl-server.js", - "watch" : false, - "exec_interpreter" : "babel-node", - "exec_mode" : "fork" - }] - } - \ No newline at end of file + "apps": [ + { + "name": "etl-server", + "script": "/opt/etl/etl-server.js", + "watch": false, + "exec_interpreter": "babel-node", + "exec_mode": "fork" + } + ] +} diff --git a/pre-request-processing.js b/pre-request-processing.js index bfb2fb7fb..0d19b2fbd 100755 --- a/pre-request-processing.js +++ b/pre-request-processing.js @@ -1,33 +1,37 @@ -'use strict' +'use strict'; var moment = require('moment'); var _ = require('underscore'); var dao = require('./etl-dao'); var moduleDefinition = { - resolveLocationIdsToLocationUuids: resolveLocationIdsToLocationUuids + resolveLocationIdsToLocationUuids: resolveLocationIdsToLocationUuids }; module.exports = moduleDefinition; function resolveLocationIdsToLocationUuids(request, callback) { - var asyncRequests = 0; //this should be the number of async requests needed before they are triggered - var onResolvedPromise = function (promise) { - asyncRequests--; - if (asyncRequests <= 0) { //voting process to ensure all pre-processing of request async operations are complete - callback(); - } - }; - if (request.query.locationUuids) { - asyncRequests++; - } - if (asyncRequests === 0) - callback(); - if (request.query.locationUuids) { - dao.getIdsByUuidAsyc('amrs.location', 'location_id', 'uuid', request.query.locationUuids, - function (results) { - request.query.locations = results; - }).onResolved = onResolvedPromise; + var asyncRequests = 0; //this should be the number of async requests needed before they are triggered + var onResolvedPromise = function (promise) { + asyncRequests--; + if (asyncRequests <= 0) { + //voting process to ensure all pre-processing of request async operations are complete + callback(); } + }; + if (request.query.locationUuids) { + asyncRequests++; + } + if (asyncRequests === 0) callback(); + if (request.query.locationUuids) { + dao.getIdsByUuidAsyc( + 'amrs.location', + 'location_id', + 'uuid', + request.query.locationUuids, + function (results) { + request.query.locations = results; + } + ).onResolved = onResolvedPromise; + } } - diff --git a/programs/patient-data-resolver.service.js b/programs/patient-data-resolver.service.js index d180355f8..292d1d5b4 100755 --- a/programs/patient-data-resolver.service.js +++ b/programs/patient-data-resolver.service.js @@ -6,13 +6,13 @@ const etlHivSummary = require('../dao/patient/etl-patient-hiv-summary-dao'); const encounterService = require('../service/openmrs-rest/encounter'); const availableKeys = { - 'patient': getPatient, - 'dummyPatient': getPatient, - 'enrollment': getProgramEnrollment, - 'hivLastTenClinicalEncounters': gethivLastTenClinicalEncounters, - 'hivLastEncounter': getPatientLastEncounter, - 'patientEnrollment': getPatientEnrollement, - 'patientEncounters': getPatientEncounters + patient: getPatient, + dummyPatient: getPatient, + enrollment: getProgramEnrollment, + hivLastTenClinicalEncounters: gethivLastTenClinicalEncounters, + hivLastEncounter: getPatientLastEncounter, + patientEnrollment: getPatientEnrollement, + patientEncounters: getPatientEncounters }; const def = { @@ -27,11 +27,11 @@ const def = { module.exports = def; -function getAllDataDependencies(dataDependenciesKeys, - patientUuid, params) { - return new Promise(((success, error) => { +function getAllDataDependencies(dataDependenciesKeys, patientUuid, params) { + return new Promise((success, error) => { const dataObject = {}; - Promise.reduce(dataDependenciesKeys, + Promise.reduce( + dataDependenciesKeys, function (previous, key) { return availableKeys[key](patientUuid, params) .then(function (data) { @@ -43,56 +43,56 @@ function getAllDataDependencies(dataDependenciesKeys, detail: err }; }); - }, 0) - .then(function (data) { - success(dataObject); - }) - .catch(function (err) { - error(err); - }); - })); + }, + 0 + ) + .then(function (data) { + success(dataObject); + }) + .catch(function (err) { + error(err); + }); + }); } function getPatient(patientUuid, params) { - return new Promise( - ((resolve, reject) => { - patientService.getPatientByUuid(patientUuid, { rep: 'full' }) - .then((patient) => { - resolve(patient); - }) - .catch((error) => { - reject(error); - }); - }), - ); + return new Promise((resolve, reject) => { + patientService + .getPatientByUuid(patientUuid, { rep: 'full' }) + .then((patient) => { + resolve(patient); + }) + .catch((error) => { + reject(error); + }); + }); } function getProgramEnrollment(patientUuid, params) { - return new Promise( - ((resolve, reject) => { - programService.getProgramEnrollmentByUuid(params.programEnrollmentUuid, - { - rep: 'custom:(uuid,display,voided,dateEnrolled,dateCompleted,location,' - + 'program:(uuid),states:(uuid,startDate,endDate,state:(uuid,initial,terminal,' - + 'concept:(uuid,display))))', - }) - .then((enrollment) => { - resolve(enrollment); - }) - .catch((error) => { - reject(error); - }); - }), - ); + return new Promise((resolve, reject) => { + programService + .getProgramEnrollmentByUuid(params.programEnrollmentUuid, { + rep: + 'custom:(uuid,display,voided,dateEnrolled,dateCompleted,location,' + + 'program:(uuid),states:(uuid,startDate,endDate,state:(uuid,initial,terminal,' + + 'concept:(uuid,display))))' + }) + .then((enrollment) => { + resolve(enrollment); + }) + .catch((error) => { + reject(error); + }); + }); } function getPatientEncounters(patientUuid) { const patientEncounters = encounterService.getPatientEncounters({ patientUuid, - v: 'custom:(encounterDatetime,encounterType:(uuid,display))', + v: 'custom:(encounterDatetime,encounterType:(uuid,display))' }); - return new Promise(((resolve, reject) => { + return new Promise((resolve, reject) => { patientEncounters .then((encounters) => { resolve(encounters); @@ -101,47 +101,44 @@ function getPatientEncounters(patientUuid) { console.error('An error occurred fetching encounters: ', e); reject(e); }); - })); + }); } function gethivLastTenClinicalEncounters(patientUuid, params) { - return new Promise( - ((resolve, reject) => { - etlHivSummary.getPatientHivSummary(patientUuid, true, {}, 0, 10) - .then((response) => { - resolve(response.result); - }) - .catch((error) => { - reject(error); - }); - }), - ); + return new Promise((resolve, reject) => { + etlHivSummary + .getPatientHivSummary(patientUuid, true, {}, 0, 10) + .then((response) => { + resolve(response.result); + }) + .catch((error) => { + reject(error); + }); + }); } function getPatientLastEncounter(patientUuid) { - return new Promise( - ((resolve, reject) => { - etlHivSummary.getPatientLastEncounter(patientUuid) - .then((response) => { - resolve(response.result[0]); - }) - .catch((error) => { - reject(error); - }); - }), - ); + return new Promise((resolve, reject) => { + etlHivSummary + .getPatientLastEncounter(patientUuid) + .then((response) => { + resolve(response.result[0]); + }) + .catch((error) => { + reject(error); + }); + }); } function getPatientEnrollement(patientUuid, params) { - return new Promise( - ((resolve, reject) => { - programService.getProgramEnrollmentByPatientUuid(patientUuid, params) - .then((response) => { - resolve(response.results); - }) - .catch((error) => { - reject(error); - }); - }), - ); + return new Promise((resolve, reject) => { + programService + .getProgramEnrollmentByPatientUuid(patientUuid, params) + .then((response) => { + resolve(response.results); + }) + .catch((error) => { + reject(error); + }); + }); } diff --git a/programs/patient-program-base.service.js b/programs/patient-program-base.service.js index 03196345e..fe4e2b2d4 100755 --- a/programs/patient-program-base.service.js +++ b/programs/patient-program-base.service.js @@ -20,30 +20,46 @@ function getAllProgramsConfig() { } function getPatientProgramEnrollmentVisits( - patientUuid, programUuid, enrollmentUuid, - intendedVisitLocationUuid) { - + patientUuid, + programUuid, + enrollmentUuid, + intendedVisitLocationUuid +) { const clone = getAllProgramsConfig(); return programVisitTypes.getPatientVisitTypes( - patientUuid, programUuid, enrollmentUuid, intendedVisitLocationUuid || '', clone + patientUuid, + programUuid, + enrollmentUuid, + intendedVisitLocationUuid || '', + clone ); } -function validateEnrollmentOptions (patient) { +function validateEnrollmentOptions(patient) { const clone = getAllProgramsConfig(); return programValidationService.validateEnrollmentOptions(patient, clone); } -function getPatientProgramVisits(patientUuid, programUuid, enrollment, locationUuid) { +function getPatientProgramVisits( + patientUuid, + programUuid, + enrollment, + locationUuid +) { return new Promise(function (success, error) { getPatientProgramEnrollmentVisits( - patientUuid, programUuid, enrollment, locationUuid - ).then((programVisits) => { - success(programVisits); - }).catch((err) => { - console.error('Error fetching program enrollment visits: ', err); - error(err); - }); + patientUuid, + programUuid, + enrollment, + locationUuid + ) + .then((programVisits) => { + success(programVisits); + }) + .catch((err) => { + console.error('Error fetching program enrollment visits: ', err); + error(err); + }); }); } diff --git a/programs/patient-program-config.json b/programs/patient-program-config.json index 0cc163c23..f5965980f 100755 --- a/programs/patient-program-config.json +++ b/programs/patient-program-config.json @@ -7,38 +7,45 @@ "hivLastTenClinicalEncounters" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Patient HIV status", - "enrollIf": "positive", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Patient HIV status", + "enrollIf": "positive", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "allowMultipleEnrollment": false, + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ { - "value": "negative", - "label": "Negative" - }, + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ { - "value": "exposed", - "label": "Exposed" + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true } ] - }], - "allowMultipleEnrollment": false, - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] } }, "incompatibleWith": [ @@ -52,14 +59,15 @@ "a8e7c30d-6d2f-401c-bb52-d4433689a36b", "f7793d42-11ac-4cfd-9b35-e0a21a7a7c31", "c4246ff0-b081-460c-bcc5-b0678012659e" - ], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "33d13ffb-5f0e-427e-ab80-637491fb6526", "name": "Adult HIV Initial Visit ", "allowedIf": "age >= 20 && programLocation === intendedVisitLocationUuid && isFirstAMPATHHIVVisit", "message": "Patient has to be 20yrs and above, in the location he enrolled into the HIV Care and Treatment program and there must not be prior clinical encounter.", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -106,7 +114,8 @@ "name": "Adult Transfer In Visit ", "allowedIf": "age >= 20 && programLocation === intendedVisitLocationUuid && !isFirstAMPATHHIVVisit", "message": "Patient has to be 20yrs and above , patient's program location should be equal to the last HIV clinical encounter location and should not be the first clinical encounter", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -149,7 +158,8 @@ "name": "Adult HIV Return Visit ", "allowedIf": "age >= 20 && programLocation === intendedVisitLocationUuid && !isFirstAMPATHHIVVisit", "message": "Patient has to be 20yrs and above, in the location he enrolled into the HIV Care and Treatment program and there must be a prior clinical encounter.", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -204,7 +214,8 @@ "name": "Pediatric HIV Initial Visit ", "allowedIf": "age <= 14 && programLocation === intendedVisitLocationUuid && isFirstAMPATHHIVVisit", "message": "Patient has to be 14rs and below ,in the location he enrolled into the HIV Care and Treatment program and there must not be prior clinical encounter.", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -250,7 +261,8 @@ "uuid": "2e67b87c-8843-45b7-a380-3a0e8bd58e4d", "name": "Pediatric Transfer In Visit ", "allowedIf": "age <= 14 && programLocation === intendedVisitLocationUuid && !isFirstAMPATHHIVVisit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -293,7 +305,8 @@ "name": "Pediatric HIV Return Visit ", "allowedIf": "age <= 14 && programLocation === intendedVisitLocationUuid && !isFirstAMPATHHIVVisit", "message": "Patient has to be 14yrs and below, in the location enrolled into the HIV Care and Treatment program and it must not be the initial clinical encounter.", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -340,7 +353,8 @@ "name": "Youth HIV Initial Visit ", "allowedIf": "age >= 10 && age <= 24 && programLocation === intendedVisitLocationUuid && isFirstAMPATHHIVVisit", "message": "Patient has to between 10 and 24yrs , in the location he enrolled into the HIV Care and Treatment program and must not have a prior clinical encounter", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -387,7 +401,8 @@ "name": "Youth Transfer In Visit ", "allowedIf": "age >= 10 && age <= 24 && programLocation === intendedVisitLocationUuid && !isFirstAMPATHHIVVisit", "message": "Patient has to between 10 and 24yrs , in the location he enrolled into the HIV Care and Treatment program, must have a prior clinical encounter.The program location should be different from the previous encounter location", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -430,7 +445,8 @@ "name": "Youth HIV Return Visit ", "allowedIf": "age >= 10 && age <= 24 && programLocation === intendedVisitLocationUuid && !isFirstAMPATHHIVVisit", "message": "Patient has to between 10 and 24yrs , in the location he enrolled into the HIV Care and Treatment program and must have a prior clinical encounter", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -477,7 +493,8 @@ "name": "Between Care Visit ", "allowedIf": "programLocation !== intendedVisitLocationUuid && !isFirstAMPATHHIVVisit", "message": "Patient has to be in a different location from location he was enrolled into HIV care and treatment program and must have a prior clinical encounter", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -515,7 +532,8 @@ "uuid": "578a6132-4686-4190-809f-3f8f49bdd1c6", "allowedIf": "programLocation === intendedVisitLocationUuid && isFirstAMPATHHIVVisit", "name": "Linkage Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "93b4c47b-ce5c-4d83-bef2-f941199e999d", "display": "PHCTLINKAGE" }, @@ -536,7 +554,8 @@ { "uuid": "fcc9a836-0200-45f2-81b4-b4a687a10247", "name": "Treatment Supporter Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "693559d3-4e44-4d33-83f9-bc70ca56fe34", "display": "TXSUPPORTERMEDREFILL" }, @@ -565,7 +584,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -586,7 +606,8 @@ { "uuid": "40353c46-cd54-4629-a5d1-0a1f1108b19f", "name": "Inpatient peer visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", "display": "INPATIENTPEER" }, @@ -607,7 +628,8 @@ { "uuid": "f75d41c7-e09d-4e98-9b24-78a4ca1c1229", "name": "Phone Follow Up Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", "display": "TELECARE" }, @@ -622,26 +644,26 @@ "725b5193-3452-43fc-aca3-6a80432d9bfa": { "name": " GENERAL ONCOLOGY PROGRAM", "incompatibleWith": [], - "dataDependencies": [ - "patient", - "enrollment", - "patientEncounters" - ], + "dataDependencies": ["patient", "enrollment", "patientEncounters"], "enrollmentOptions": { "requiredProgramQuestions": [], "allowMultipleEnrollment": false, "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ] } }, "visitTypes": [ @@ -654,18 +676,22 @@ { "uuid": "d17b3adc-0837-4ac6-862b-0953fc664cb8", "display": "OncologyInitial" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" - }, { + }, + { "uuid": "81166f83-1ee6-486e-8f56-aca528fc0fc0", "display": "GENCONSULTATION" } ] - }, { + }, + { "uuid": "273590f7-7c5a-494e-8b60-5be909083f4b", "name": "General Oncology Return Visit", "message": "Patient must have a prior clinical encounter.", @@ -674,15 +700,18 @@ { "uuid": "eeb9600c-314f-4071-9122-133ff3da37bb", "display": "OncologyReturn" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" } ] - }, { + }, + { "uuid": "c1be5560-5efe-493c-96f9-e40f0a724142", "name": "Oncology Lab Visit", "encounterTypes": [ @@ -691,7 +720,8 @@ "display": "ONCOLOGYLABENTRY" } ] - }, { + }, + { "uuid": "fac19544-1478-483f-8d4f-3792b1282981", "name": "Oncology Pharmacy Visit", "encounterTypes": [ @@ -716,41 +746,48 @@ "allowMultipleEnrollment": false, "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ] } }, - "visitTypes": [{ - "uuid": "5033fbfc-ddc9-4f7f-853d-379659e48bdd", - "name": "DM-HTN Health Center visit", - "allowedIf": "inCareUuid === '496cf7a6-eb2c-40b2-85e6-fbd7a885e66e'", - "message": "Patient must be `in care` state", - "encounterTypes": [{ - "uuid": "f5381269-c889-4c5a-b384-d017441eedae", - "display": "CDMTRIAGE" - }, - { - "uuid": "4f5d5b20-083b-4686-be5f-5f2cc71d74e5", - "display": "HTNDMRETRUN" - }, - { - "uuid": "9af62145-1114-4711-a2b4-1c23ae69eb46", - "display": "HTNDMINITIAL" - }, - { - "uuid": "df55584c-1350-11df-a1f1-0026b9348838", - "display": "DEATHREPORT" - } - ] - }] + "visitTypes": [ + { + "uuid": "5033fbfc-ddc9-4f7f-853d-379659e48bdd", + "name": "DM-HTN Health Center visit", + "allowedIf": "inCareUuid === '496cf7a6-eb2c-40b2-85e6-fbd7a885e66e'", + "message": "Patient must be `in care` state", + "encounterTypes": [ + { + "uuid": "f5381269-c889-4c5a-b384-d017441eedae", + "display": "CDMTRIAGE" + }, + { + "uuid": "4f5d5b20-083b-4686-be5f-5f2cc71d74e5", + "display": "HTNDMRETRUN" + }, + { + "uuid": "9af62145-1114-4711-a2b4-1c23ae69eb46", + "display": "HTNDMINITIAL" + }, + { + "uuid": "df55584c-1350-11df-a1f1-0026b9348838", + "display": "DEATHREPORT" + } + ] + } + ] }, "fc15ac01-5381-4854-bf5e-917c907aa77f": { "name": "CDM PROGRAM", @@ -760,13 +797,13 @@ "hivLastTenClinicalEncounters" ], "incompatibleWith": [], - "visitTypes": [{ - "uuid": "8072afd0-0cd9-409e-914d-1833e83943f7", - "name": "CDM Visit", - "encounterTypes": [ - - ] - }] + "visitTypes": [ + { + "uuid": "8072afd0-0cd9-409e-914d-1833e83943f7", + "name": "CDM Visit", + "encounterTypes": [] + } + ] }, "bd9a8b06-73c7-44a8-928c-5e72247f4c1d": { "name": "HTN-DM TERTIARY CARE", @@ -780,52 +817,61 @@ "allowMultipleEnrollment": false, "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }], - "referral": [{ - "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", - "name": "CDM DM-HTN Referral Form v1.1", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ], + "referral": [ + { + "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", + "name": "CDM DM-HTN Referral Form v1.1", + "required": true + } + ] } }, "incompatibleWith": [ "b731ba72-cf99-4176-9fcd-37cd186400c7", "876a154d-310d-4caf-8b58-be9dbcc7e753" ], - "visitTypes": [{ - "uuid": "67da2bee-70de-451c-8002-75429c71c46c", - "name": "DM-HTN Tertiary visit", - "encounterTypes": [{ - "uuid": "f5381269-c889-4c5a-b384-d017441eedae", - "display": "CDMTRIAGE" - }, - { - "uuid": "14c3b999-2d5c-4c2e-b173-5212b9170652", - "display": "COEDMINITIAL" - }, - { - "uuid": "0d2ff377-a3df-453e-ae20-e92da3aa3a17", - "display": "COEDMRETURN" - }, - { - "uuid": "db9b637c-6289-4259-a66a-326b2d2f2a5d", - "display": "HTNDMPEDINITIAL" - }, - { - "uuid": "f26104d5-45bc-4b19-acf9-8207e414a579", - "display": "HTNDMPEDRETURN" - } - ] - }] + "visitTypes": [ + { + "uuid": "67da2bee-70de-451c-8002-75429c71c46c", + "name": "DM-HTN Tertiary visit", + "encounterTypes": [ + { + "uuid": "f5381269-c889-4c5a-b384-d017441eedae", + "display": "CDMTRIAGE" + }, + { + "uuid": "14c3b999-2d5c-4c2e-b173-5212b9170652", + "display": "COEDMINITIAL" + }, + { + "uuid": "0d2ff377-a3df-453e-ae20-e92da3aa3a17", + "display": "COEDMRETURN" + }, + { + "uuid": "db9b637c-6289-4259-a66a-326b2d2f2a5d", + "display": "HTNDMPEDINITIAL" + }, + { + "uuid": "f26104d5-45bc-4b19-acf9-8207e414a579", + "display": "HTNDMPEDRETURN" + } + ] + } + ] }, "b731ba72-cf99-4176-9fcd-37cd186400c7": { "name": "HTN-DM SECONDARY CARE", @@ -834,7 +880,8 @@ "enrollment", "hivLastTenClinicalEncounters" ], - "HidevisibleLocations": [{ + "HidevisibleLocations": [ + { "uuid": "08feb2dc-1352-11df-a1f1-0026b9348838", "display": "Turbo" }, @@ -848,11 +895,13 @@ "allowMultipleEnrollment": false, "stateChangeEncounterTypes": { "enrollment": [], - "referral": [{ - "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", - "name": "CDM DM-HTN Referral Form v1.1", - "required": true - }], + "referral": [ + { + "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", + "name": "CDM DM-HTN Referral Form v1.1", + "required": true + } + ], "incompatible": [] } }, @@ -860,27 +909,30 @@ "876a154d-310d-4caf-8b58-be9dbcc7e753", "bd9a8b06-73c7-44a8-928c-5e72247f4c1d" ], - "visitTypes": [{ - "uuid": "5033fbfc-ddc9-4f7f-853d-379659e48bdd", - "name": "DM-HTN Secondary Visit", - "transitionStateOnVisitStart": { - "state": "inCare", - "uuid": "72443cac-4822-4dce-8460-794af7af8167" - }, - "encounterTypes": [{ - "uuid": "f5381269-c889-4c5a-b384-d017441eedae", - "display": "CDMTRIAGE" - }, - { - "uuid": "9af62145-1114-4711-a2b4-1c23ae69eb46", - "display": "HTNDMINITIAL" + "visitTypes": [ + { + "uuid": "5033fbfc-ddc9-4f7f-853d-379659e48bdd", + "name": "DM-HTN Secondary Visit", + "transitionStateOnVisitStart": { + "state": "inCare", + "uuid": "72443cac-4822-4dce-8460-794af7af8167" }, - { - "uuid": "4f5d5b20-083b-4686-be5f-5f2cc71d74e5", - "display": "HTNDMRETRUN" - } - ] - }] + "encounterTypes": [ + { + "uuid": "f5381269-c889-4c5a-b384-d017441eedae", + "display": "CDMTRIAGE" + }, + { + "uuid": "9af62145-1114-4711-a2b4-1c23ae69eb46", + "display": "HTNDMINITIAL" + }, + { + "uuid": "4f5d5b20-083b-4686-be5f-5f2cc71d74e5", + "display": "HTNDMRETRUN" + } + ] + } + ] }, "876a154d-310d-4caf-8b58-be9dbcc7e753": { "name": "HTN-DM PRIMARY CARE", @@ -898,15 +950,18 @@ "allowMultipleEnrollment": false, "stateChangeEncounterTypes": { "enrollment": [], - "referral": [{ - "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", - "name": "CDM DM-HTN Referral Form v1.1", - "required": true - }], + "referral": [ + { + "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", + "name": "CDM DM-HTN Referral Form v1.1", + "required": true + } + ], "incompatible": [] } }, - "HidevisibleLocations": [{ + "HidevisibleLocations": [ + { "uuid": "0900880a-1352-11df-a1f1-0026b9348838", "display": "Chepsaita" }, @@ -959,7 +1014,8 @@ "display": "West Clinic Health Centre" } ], - "stateChangeForms": [{ + "stateChangeForms": [ + { "type": "inCare", "uuid": "72443cac-4822-4dce-8460-794af7af8167", "forms": [] @@ -967,37 +1023,44 @@ { "type": "referred", "uuid": "0c5565c5-45cf-40ab-aa6d-5694aeabae18", - "forms": [{ - "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", - "required": true - }] + "forms": [ + { + "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", + "required": true + } + ] }, { "type": "referredBack", "uuid": "15977097-13b7-4186-80a7-a78535f27866", - "forms": [{ - "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", - "required": true - }] + "forms": [ + { + "uuid": "6a50f1d5-9f33-41ae-b2e7-7fd8267c181e", + "required": true + } + ] } ], - "visitTypes": [{ - "uuid": "8072afd0-0cd9-409e-914d-1833e83943f7", - "name": "DM-HTN Primary Care Visit", - "transitionStateOnVisitStart": { - "state": "inCare", - "uuid": "72443cac-4822-4dce-8460-794af7af8167" - }, - "encounterTypes": [{ - "uuid": "f5381269-c889-4c5a-b384-d017441eedae", - "display": "CDMTRIAGE" + "visitTypes": [ + { + "uuid": "8072afd0-0cd9-409e-914d-1833e83943f7", + "name": "DM-HTN Primary Care Visit", + "transitionStateOnVisitStart": { + "state": "inCare", + "uuid": "72443cac-4822-4dce-8460-794af7af8167" }, - { - "uuid": "1871ce37-7def-4335-972f-9861195ba683", - "display": "CDMDispensary" - } - ] - }] + "encounterTypes": [ + { + "uuid": "f5381269-c889-4c5a-b384-d017441eedae", + "display": "CDMTRIAGE" + }, + { + "uuid": "1871ce37-7def-4335-972f-9861195ba683", + "display": "CDMDispensary" + } + ] + } + ] }, "781d897a-1359-11df-a1f1-0026b9348838": { "name": "PREVENTION OF MOTHER-TO-CHILD TRANSMISSION OF HIV(pMTCT)", @@ -1010,12 +1073,14 @@ ], "enrollmentOptions": { "enrollIf": "gender === 'F'", - "requiredProgramQuestions": [{ + "requiredProgramQuestions": [ + { "qtype": "hivStatus", "name": "Patient HIV status", "enrollIf": "positive", "value": null, - "answers": [{ + "answers": [ + { "value": "positive", "label": "Positive" }, @@ -1034,7 +1099,8 @@ "name": "Pregnancy Status", "enrollIf": "positive", "value": null, - "answers": [{ + "answers": [ + { "value": "positive", "label": "Yes" }, @@ -1043,36 +1109,43 @@ "label": "No" } ], - "relatedQuestions": [{ - "qtype": "motherStatus", - "name": "Does the mother have a child <2 years?", - "enrollIf": "yes", - "showIfParent": "negative", - "value": null, - "answers": [{ - "value": "yes", - "label": "Yes" - }, - { - "value": "no", - "label": "No" - } - ] - }] + "relatedQuestions": [ + { + "qtype": "motherStatus", + "name": "Does the mother have a child <2 years?", + "enrollIf": "yes", + "showIfParent": "negative", + "value": null, + "answers": [ + { + "value": "yes", + "label": "Yes" + }, + { + "value": "no", + "label": "No" + } + ] + } + ] } ], "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ] } }, "incompatibleWith": [ @@ -1197,12 +1270,14 @@ "display": "HIVCLINICALREFERRAL" } ] - }, { + }, + { "uuid": "42de8e7e-24b2-4c16-b62b-137eb2c55ede", "message": "Patient must not have prior clinical encounter.", "allowedIf": "age > 2 && isFirstPMTCTVisit", "name": "PMTCT Antenatal Initial Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "8d5b27bc-c2cc-11de-8d13-0010c6dffd0f", "display": "ADULTINITIAL" }, @@ -1249,7 +1324,8 @@ "message": "Patient must have prior clinical encounter.", "allowedIf": "!isFirstPMTCTVisit && !isEnrolledInViremiaPMTCT", "name": "PMTCT Antenatal Return Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "8d5b2be0-c2cc-11de-8d13-0010c6dffd0f", "display": "ADULTRETURN" }, @@ -1300,7 +1376,8 @@ "message": "Patient must not have prior clinical encounter.", "allowedIf": "isFirstPMTCTVisit", "name": "PMTCT Postnatal Initial Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "8d5b27bc-c2cc-11de-8d13-0010c6dffd0f", "display": "ADULTINITIAL" }, @@ -1351,7 +1428,8 @@ "message": "Patient must have prior clinical encounter.", "allowedIf": "!isFirstPMTCTVisit && !isEnrolledInViremiaPMTCT", "name": "PMTCT Postnatal Return Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "8d5b2be0-c2cc-11de-8d13-0010c6dffd0f", "display": "ADULTRETURN" }, @@ -1402,7 +1480,8 @@ "message": "Patient must have no prior clinical encounter.", "allowedIf": "age >= 0 && age <= 2 && programLocation === intendedVisitLocationUuid && isFirstAMPATHHIVVisit", "name": "Pediatric PMTCT Initial Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "8d5b2dde-c2cc-11de-8d13-0010c6dffd0f", "display": "PEDSINITIAL" }, @@ -1443,7 +1522,8 @@ { "uuid": "18f59064-961e-4d51-9ccf-e950f04b4c66", "name": "Treatment Supporter Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "693559d3-4e44-4d33-83f9-bc70ca56fe34", "display": "TXSUPPORTERMEDREFILL" }, @@ -1472,7 +1552,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -1493,23 +1574,26 @@ { "uuid": "40353c46-cd54-4629-a5d1-0a1f1108b19f", "name": "Inpatient peer visit", - "encounterTypes": [{ - "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", - "display": "INPATIENTPEER" - }, - { - "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", - "display": "COVIDSCREENING" - }, - { - "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", - "display": "COVIDCASEREPORTING" - }] + "encounterTypes": [ + { + "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", + "display": "INPATIENTPEER" + }, + { + "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", + "display": "COVIDSCREENING" + }, + { + "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", + "display": "COVIDCASEREPORTING" + } + ] }, { "uuid": "d7fdac11-2df0-4f18-968e-ad5e064bedf1", "name": "Phone Follow Up Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", "display": "TELECARE" }, @@ -1528,16 +1612,20 @@ "allowMultipleEnrollment": false, "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "06e5321e-fc08-4995-aaa3-19c76b48cd22", - "name": "AMPATH POC OVC Exit Form V1.0", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "06e5321e-fc08-4995-aaa3-19c76b48cd22", + "name": "AMPATH POC OVC Exit Form V1.0", + "required": true + } + ] } }, "dataDependencies": [ @@ -1546,12 +1634,14 @@ "hivLastTenClinicalEncounters" ], "incompatibleWith": [], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "0883d972-4122-454d-a746-9d28ecb23b66", "name": "OVC Referral Visit", "allowedIf": "inCareUuid === '72443cac-4822-4dce-8460-794af7af8167'", "message": "Patient must be `in care` state", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", "display": "TRANSFERENCOUNTER" }, @@ -1576,7 +1666,8 @@ { "uuid": "e2c37c46-3ee9-4cff-9af6-aa5c41fb30da", "name": "OVC Visit ", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -1621,11 +1712,13 @@ "enrollmentOptions": { "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], "discharge": [] } }, @@ -1649,16 +1742,20 @@ "allowMultipleEnrollment": false, "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ] } }, "incompatibleWith": [], @@ -1673,37 +1770,44 @@ "patientEncounters" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Patient HIV status", - "enrollIf": "negative", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Patient HIV status", + "enrollIf": "negative", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ { - "value": "negative", - "label": "Negative" - }, + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ { - "value": "exposed", - "label": "Exposed" + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true } ] - }], - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] } }, "incompatibleWith": [ @@ -1792,7 +1896,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -1813,7 +1918,8 @@ { "uuid": "40353c46-cd54-4629-a5d1-0a1f1108b19f", "name": "Inpatient peer visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", "display": "INPATIENTPEER" }, @@ -1830,7 +1936,8 @@ { "uuid": "9cbec0ea-9091-4a1d-9d2d-a3bbc295a04f", "name": "Phone Follow Up Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", "display": "TELECARE" }, @@ -1851,37 +1958,44 @@ "patientEncounters" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Patient HIV status", - "enrollIf": "negative", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Patient HIV status", + "enrollIf": "negative", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ { - "value": "negative", - "label": "Negative" - }, + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ { - "value": "exposed", - "label": "Exposed" + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true } ] - }], - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] } }, "incompatibleWith": [ @@ -1900,7 +2014,8 @@ "name": "PrEP Initial Visit", "allowedIf": "isFirstPrEPVisit", "message": "Patient must not have a prior clinical encounter.", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -1947,7 +2062,8 @@ "name": "PrEP Return Visit", "allowedIf": "!isFirstPrEPVisit", "message": "Patient must have a prior clinical encounter.", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -1992,7 +2108,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -2013,7 +2130,8 @@ { "uuid": "40353c46-cd54-4629-a5d1-0a1f1108b19f", "name": "Inpatient peer visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", "display": "INPATIENTPEER" }, @@ -2030,7 +2148,8 @@ { "uuid": "c2c3cde9-5a3f-4fc3-8976-1c4d29ad0dbe", "name": "Phone Follow Up Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", "display": "TELECARE" }, @@ -2050,46 +2169,53 @@ "hivLastTenClinicalEncounters" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Patient HIV status", - "enrollIf": "positive", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Patient HIV status", + "enrollIf": "positive", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ { - "value": "negative", - "label": "Negative" - }, + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ { - "value": "exposed", - "label": "Exposed" + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true } ] - }], - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] } }, - "incompatibleWith": [ - "781d85b0-1359-11df-a1f1-0026b9348838" - ], - "visitTypes": [{ + "incompatibleWith": ["781d85b0-1359-11df-a1f1-0026b9348838"], + "visitTypes": [ + { "uuid": "dcdefd27-82b9-48e3-821b-3ffc6463564e", "name": "Resistance Clinic Visit ", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -2142,7 +2268,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -2163,7 +2290,8 @@ { "uuid": "40353c46-cd54-4629-a5d1-0a1f1108b19f", "name": "Inpatient peer visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", "display": "INPATIENTPEER" }, @@ -2180,7 +2308,8 @@ { "uuid": "e547296d-c7b2-42da-9147-3d73dc55de33", "name": "Phone Follow Up Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", "display": "TELECARE" }, @@ -2204,35 +2333,43 @@ "allowMultipleEnrollment": false, "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ] } }, "incompatibleWith": [], - "visitTypes": [{ - "uuid": "404e44e7-f2b0-4f20-bf14-bfb98bac75df", - "name": "HIV Social Work Visit ", - "encounterTypes": [{ - "uuid": "7cc419d5-b145-4315-a0a8-4614b710ff5f", - "display": "SOCIALWORKSUPPORT" - }, - { - "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", - "display": "COVIDSCREENING" - }, + "visitTypes": [ { - "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", - "display": "COVIDCASEREPORTING" - }] - }] + "uuid": "404e44e7-f2b0-4f20-bf14-bfb98bac75df", + "name": "HIV Social Work Visit ", + "encounterTypes": [ + { + "uuid": "7cc419d5-b145-4315-a0a8-4614b710ff5f", + "display": "SOCIALWORKSUPPORT" + }, + { + "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", + "display": "COVIDSCREENING" + }, + { + "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", + "display": "COVIDCASEREPORTING" + } + ] + } + ] }, "334c9e98-173f-4454-a8ce-f80b20b7fdf0": { "name": "HIV DIFFERENTIATED CARE PROGRAM", @@ -2243,12 +2380,14 @@ "hivLastEncounter" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ + "requiredProgramQuestions": [ + { "qtype": "hivStatus", "name": "Patient HIV status", "enrollIf": "positive", "value": null, - "answers": [{ + "answers": [ + { "value": "positive", "label": "Positive" }, @@ -2267,7 +2406,8 @@ "name": "Enroll to community group", "enrollIf": "", "value": "", - "answers": [{ + "answers": [ + { "value": true, "label": "Yes" }, @@ -2280,16 +2420,20 @@ ], "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ] } }, "incompatibleWith": [ @@ -2309,7 +2453,8 @@ "name": "Between Care Visit", "allowedIf": "programLocation !== intendedVisitLocationUuid && !isFirstAMPATHHIVVisit", "message": "Patient has to be in a different location from location he was enrolled into HIV care and treatment program and must have a prior clinical encounter", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -2354,37 +2499,39 @@ { "uuid": "0bcccab0-59ce-4a25-a158-cc722427ff3f", "name": "Treatment Supporter visit", - "encounterTypes": [{ - "uuid": "693559d3-4e44-4d33-83f9-bc70ca56fe34", - "display": "TXSUPPORTERMEDREFILL" - }, - { - "uuid": "987009c6-6f24-43f7-9640-c285d6553c63", - "display": "DRUGPICKUP" - }, - { - "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", - "display": "COVIDSCREENING" - }, - { - "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", - "display": "COVIDCASEREPORTING" - }, - { - "uuid": "a393699f-8e99-4727-81c3-873873022dd8", - "display": "MOBILITYSCREENING" - }, - { - "uuid": "5b1ef308-ed8f-4a86-88a0-c29a30246740", - "display": "HIVCLINICALREFERRAL" - } + "encounterTypes": [ + { + "uuid": "693559d3-4e44-4d33-83f9-bc70ca56fe34", + "display": "TXSUPPORTERMEDREFILL" + }, + { + "uuid": "987009c6-6f24-43f7-9640-c285d6553c63", + "display": "DRUGPICKUP" + }, + { + "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", + "display": "COVIDSCREENING" + }, + { + "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", + "display": "COVIDCASEREPORTING" + }, + { + "uuid": "a393699f-8e99-4727-81c3-873873022dd8", + "display": "MOBILITYSCREENING" + }, + { + "uuid": "5b1ef308-ed8f-4a86-88a0-c29a30246740", + "display": "HIVCLINICALREFERRAL" + } ] }, { "uuid": "0d608b80-1cb5-4c85-835a-29072683ca27", "name": "Community Visit for Differentiated Care", "groupVisit": true, - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "0e9e0b44-5650-4d07-8ccc-77c3dca9cbbf", "display": "DIFFERENTIATEDCARECOMMUNITY" }, @@ -2452,7 +2599,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -2524,7 +2672,8 @@ { "uuid": "7bb2d036-d25e-4c00-b732-6b597f0a1d12", "name": "Phone Follow Up Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", "display": "TELECARE" }, @@ -2544,37 +2693,44 @@ "hivLastTenClinicalEncounters" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Patient HIV status", - "enrollIf": "positive", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Patient HIV status", + "enrollIf": "positive", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ { - "value": "negative", - "label": "Negative" - }, + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ { - "value": "exposed", - "label": "Exposed" + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true } ] - }], - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] } }, "incompatibleWith": [ @@ -2587,10 +2743,12 @@ "0904172d-0b6a-40df-b8a2-b3653d16dc45", "a8e7c30d-6d2f-401c-bb52-d4433689a36b" ], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "52e67f49-4ec3-41b2-bfe2-93144ea03eb2", "name": "Transit Care Visit ", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -2628,7 +2786,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -2649,7 +2808,8 @@ { "uuid": "40353c46-cd54-4629-a5d1-0a1f1108b19f", "name": "Inpatient peer visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", "display": "INPATIENTPEER" } @@ -2659,63 +2819,59 @@ }, "43b42170-b3ce-4e03-9390-6bd78384ac06": { "name": "GYN-ONCOLOGY TREATMENT PROGRAM", - "dataDependencies": [ - "patient" - ], + "dataDependencies": ["patient"], "enrollmentOptions": { "enrollIf": "gender === 'F'" }, "incompatibleWith": [], - "visitTypes": [{ - "uuid": "b12cb85e-0c1e-4372-92ed-3bedcec1b105", - "name": "Cervical Cancer Treatment ", - "encounterTypes": [{ - "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", - "display": "HematOncologyTriage" - }, - { - "uuid": "c87c5b9a-9bb6-4afe-88c6-2deb7fb49320", - "display": "GYNONCOLOGYINITIAL " - }, - { - "uuid": "57bd19b1-d64c-4cde-b436-0167f1276d9a", - "display": "GYNONCOLOGYOVARIAN" - }, - { - "uuid": "d84854b0-e9a9-4953-8888-3dbc701771f0", - "display": "GYNONCOLOGYCERVICAL" - }, - { - "uuid": "9b763f62-7d2b-4fde-9de6-e6162422b17d", - "display": "GYNONCOLOGYCERVICALSURGICAL" - }, - { - "uuid": "df55584c-1350-11df-a1f1-0026b9348838", - "display": "DEATHREPORT" - }, - { - "uuid": "2cd62224-5507-48ee-a7b3-55f66162b148", - "display": "ONCOLOGYLABENTRY" - }, - { - "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", - "display": "COVIDSCREENING" - }, - { - "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", - "display": "COVIDCASEREPORTING" - } - - ] - }] + "visitTypes": [ + { + "uuid": "b12cb85e-0c1e-4372-92ed-3bedcec1b105", + "name": "Cervical Cancer Treatment ", + "encounterTypes": [ + { + "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", + "display": "HematOncologyTriage" + }, + { + "uuid": "c87c5b9a-9bb6-4afe-88c6-2deb7fb49320", + "display": "GYNONCOLOGYINITIAL " + }, + { + "uuid": "57bd19b1-d64c-4cde-b436-0167f1276d9a", + "display": "GYNONCOLOGYOVARIAN" + }, + { + "uuid": "d84854b0-e9a9-4953-8888-3dbc701771f0", + "display": "GYNONCOLOGYCERVICAL" + }, + { + "uuid": "9b763f62-7d2b-4fde-9de6-e6162422b17d", + "display": "GYNONCOLOGYCERVICALSURGICAL" + }, + { + "uuid": "df55584c-1350-11df-a1f1-0026b9348838", + "display": "DEATHREPORT" + }, + { + "uuid": "2cd62224-5507-48ee-a7b3-55f66162b148", + "display": "ONCOLOGYLABENTRY" + }, + { + "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", + "display": "COVIDSCREENING" + }, + { + "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", + "display": "COVIDCASEREPORTING" + } + ] + } + ] }, "88566621-828f-4569-9af5-c54f8237750a": { "name": "BREAST CANCER TREATMENT PROGRAM", - "dataDependencies": [ - "patient", - "enrollment", - "patientEncounters" - ], + "dataDependencies": ["patient", "enrollment", "patientEncounters"], "incompatibleWith": [], "visitTypes": [ { @@ -2727,15 +2883,18 @@ { "uuid": "9ad5292c-14c3-489b-9c14-5f816e839691", "display": "BreastCancerInitial" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" } ] - }, { + }, + { "uuid": "2307390b-3464-435e-9c14-86041da9c8d8", "name": "Breast Cancer Return Visit", "message": "Patient must have a prior clinical encounter.", @@ -2744,15 +2903,18 @@ { "uuid": "e58469f1-f6be-4e53-a843-fb06f93c60ba", "display": "BreastCancerReturn" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" } ] - }, { + }, + { "uuid": "c1be5560-5efe-493c-96f9-e40f0a724142", "name": "Oncology Lab Visit", "encounterTypes": [ @@ -2760,8 +2922,9 @@ "uuid": "2cd62224-5507-48ee-a7b3-55f66162b148", "display": "ONCOLOGYLABENTRY" } - ] - }, { + ] + }, + { "uuid": "fac19544-1478-483f-8d4f-3792b1282981", "name": "Oncology Pharmacy Visit", "encounterTypes": [ @@ -2775,11 +2938,7 @@ }, "e8bc5036-1462-44fa-bcfe-ced21eae2790": { "name": "LUNG CANCER TREATMENT PROGRAM", - "dataDependencies": [ - "patient", - "enrollment", - "patientEncounters" - ], + "dataDependencies": ["patient", "enrollment", "patientEncounters"], "incompatibleWith": [], "visitTypes": [ { @@ -2791,15 +2950,18 @@ { "uuid": "be7b0971-b2ab-4f4d-88c7-e7322aa58dbb", "display": "LUNGCANCERINITIAL" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" } ] - }, { + }, + { "uuid": "7b7f4505-80f9-4762-b153-3397d14355b0", "name": "Lung Cancer Return Visit", "message": "Patient must have a prior clinical encounter.", @@ -2808,15 +2970,18 @@ { "uuid": "eca95bb1-b651-45b7-85f8-2d3ce7e8313e", "display": "LUNGCANCERRETURN" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" } ] - }, { + }, + { "uuid": "c1be5560-5efe-493c-96f9-e40f0a724142", "name": "Oncology Lab Visit", "encounterTypes": [ @@ -2825,7 +2990,8 @@ "display": "ONCOLOGYLABENTRY" } ] - }, { + }, + { "uuid": "fac19544-1478-483f-8d4f-3792b1282981", "name": "Oncology Pharmacy Visit", "encounterTypes": [ @@ -2839,11 +3005,7 @@ }, "e48b266e-4d80-41f8-a56a-a8ce5449ebc6": { "name": "SICKLE CELL PROGRAM", - "dataDependencies": [ - "patient", - "enrollment", - "patientEncounters" - ], + "dataDependencies": ["patient", "enrollment", "patientEncounters"], "incompatibleWith": [], "visitTypes": [ { @@ -2865,7 +3027,8 @@ "display": "DEATHREPORT" } ] - }, { + }, + { "uuid": "cfedf31e-95f4-4248-9b1f-42844b4e8f3b", "name": "Sickle Cell Return Visit", "message": "Patient must have a prior clinical encounter.", @@ -2874,15 +3037,18 @@ { "uuid": "3a0e7e4e-426e-4dc7-8f60-9114c43432eb", "display": "SICKLECELLRETURN" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" } ] - }, { + }, + { "uuid": "c1be5560-5efe-493c-96f9-e40f0a724142", "name": "Oncology Lab Visit", "encounterTypes": [ @@ -2890,8 +3056,9 @@ "uuid": "2cd62224-5507-48ee-a7b3-55f66162b148", "display": "ONCOLOGYLABENTRY" } - ] - }, { + ] + }, + { "uuid": "fac19544-1478-483f-8d4f-3792b1282981", "name": "Oncology Pharmacy Visit", "encounterTypes": [ @@ -2905,11 +3072,7 @@ }, "698b7153-bff3-4931-9638-d279ca47b32e": { "name": "MULTIPLE MYELOMA PROGRAM", - "dataDependencies": [ - "patient", - "enrollment", - "patientEncounters" - ], + "dataDependencies": ["patient", "enrollment", "patientEncounters"], "incompatibleWith": [], "visitTypes": [ { @@ -2921,15 +3084,18 @@ { "uuid": "bf762b3e-b60a-436a-a40b-f874c59869ec", "display": "MULTIPLEMYELOMAINITIAL" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" } ] - }, { + }, + { "uuid": "a6b65bf3-2577-414a-becf-18fe530353ea", "name": "Multiple Myeloma Return Visit", "message": "Patient must have a prior clinical encounter.", @@ -2938,15 +3104,18 @@ { "uuid": "50f307c4-b92e-4a41-bbbb-5cee1bd1c561", "display": "MULTIPLEMYELOMARETURN" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" } ] - }, { + }, + { "uuid": "c1be5560-5efe-493c-96f9-e40f0a724142", "name": "Oncology Lab Visit", "encounterTypes": [ @@ -2954,8 +3123,9 @@ "uuid": "2cd62224-5507-48ee-a7b3-55f66162b148", "display": "ONCOLOGYLABENTRY" } - ] - }, { + ] + }, + { "uuid": "fac19544-1478-483f-8d4f-3792b1282981", "name": "Oncology Pharmacy Visit", "encounterTypes": [ @@ -2969,11 +3139,7 @@ }, "a3610ba4-9811-46b3-9628-83ec9310be13": { "name": "HEMOPHILIA PROGRAM", - "dataDependencies": [ - "patient", - "enrollment", - "patientEncounters" - ], + "dataDependencies": ["patient", "enrollment", "patientEncounters"], "incompatibleWith": [], "visitTypes": [ { @@ -2985,15 +3151,18 @@ { "uuid": "3945005a-c24f-478b-90ec-4af84ffcdf6b", "display": "HEMOPHILIAINITIAL" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" } - ] - }, { + ] + }, + { "uuid": "1d644de3-b206-414d-a2a9-e1cefd554dd3", "name": "Hemophilia Return Visit", "message": "Patient must have a prior clinical encounter.", @@ -3002,15 +3171,18 @@ { "uuid": "36927b3c-db32-4063-90df-e45640e9aabc", "display": "HEMOPHILIARETURN" - }, { + }, + { "uuid": "5fa823ce-7592-482f-a0aa-361abf326ade", "display": "HematOncologyTriage" - }, { + }, + { "uuid": "df55584c-1350-11df-a1f1-0026b9348838", "display": "DEATHREPORT" } ] - }, { + }, + { "uuid": "c1be5560-5efe-493c-96f9-e40f0a724142", "name": "Oncology Lab Visit", "encounterTypes": [ @@ -3018,8 +3190,9 @@ "uuid": "2cd62224-5507-48ee-a7b3-55f66162b148", "display": "ONCOLOGYLABENTRY" } - ] - }, { + ] + }, + { "uuid": "fac19544-1478-483f-8d4f-3792b1282981", "name": "Oncology Pharmacy Visit", "encounterTypes": [ @@ -3033,11 +3206,7 @@ }, "418fe011-a903-4862-93d4-5e7c84d9c253": { "name": "ANTICOAGULATION TREATMENT PROGRAM", - "dataDependencies": [ - "patient", - "enrollment", - "patientEncounters" - ], + "dataDependencies": ["patient", "enrollment", "patientEncounters"], "incompatibleWith": [], "visitTypes": [ { @@ -3094,10 +3263,7 @@ }, "40677054-c402-4c56-a0e4-5dd7d799b52f": { "name": "LYMPHOMA TREATMENT PROGRAM", - "dataDependencies": [ - "patient", - "enrollment" - ], + "dataDependencies": ["patient", "enrollment"], "incompatibleWith": [], "visitTypes": [ { @@ -3131,37 +3297,44 @@ "781d8880-1359-11df-a1f1-0026b9348838": { "name": "EXPRESS CARE PROGRAM", "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Patient HIV status", - "enrollIf": "positive", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Patient HIV status", + "enrollIf": "positive", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ { - "value": "negative", - "label": "Negative" - }, + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ { - "value": "exposed", - "label": "Exposed" + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true } ] - }], - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] } }, "dataDependencies": [ @@ -3178,12 +3351,14 @@ "96ba279b-b23b-4e78-aba9-dcbd46a96b7b", "a8e7c30d-6d2f-401c-bb52-d4433689a36b" ], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "0883d972-4122-454d-a746-9d28ecb23b66", "name": "Express Care Program Referral Visit", "allowedIf": "inCareUuid === '72443cac-4822-4dce-8460-794af7af8167'", "message": "Patient must be `in care` state", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", "display": "TRANSFERENCOUNTER" }, @@ -3208,7 +3383,8 @@ { "uuid": "e2c37c46-3ee9-4cff-9af6-aa5c41fb30da", "name": "Express Care Visit ", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -3246,7 +3422,8 @@ { "uuid": "9cbec0ea-9091-4a1d-9d2d-a3bbc295a04f", "name": "Phone Follow Up Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", "display": "TELECARE" }, @@ -3266,44 +3443,53 @@ "hivLastTenClinicalEncounters" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Patient HIV status", - "enrollIf": "positive", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Patient HIV status", + "enrollIf": "positive", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ { - "value": "negative", - "label": "Negative" - }, + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ { - "value": "exposed", - "label": "Exposed" + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true } ] - }], - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] } }, "incompatibleWith": [], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "260c2535-f946-44ea-a038-34cc4f8174be", "name": "Outreach Visit ", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "df5547bc-1350-11df-a1f1-0026b9348838", "display": "OUTREACHFIELDFU" }, @@ -3336,7 +3522,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -3357,7 +3544,8 @@ { "uuid": "40353c46-cd54-4629-a5d1-0a1f1108b19f", "name": "Inpatient peer visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", "display": "INPATIENTPEER" }, @@ -3381,54 +3569,63 @@ "hivLastTenClinicalEncounters" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Patient HIV status", - "enrollIf": "positive", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, - { - "value": "negative", - "label": "Negative" - }, - { - "value": "exposed", - "label": "Exposed" - } - ] - }], - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] - } - }, - "incompatibleWith": [ - "781d897a-1359-11df-a1f1-0026b9348838", - "96047aaf-7ab3-45e9-be6a-b61810fe617d", - "c19aec66-1a40-4588-9b03-b6be55a8dd1d", - "334c9e98-173f-4454-a8ce-f80b20b7fdf0", - "96ba279b-b23b-4e78-aba9-dcbd46a96b7b", - "781d8880-1359-11df-a1f1-0026b9348838", - "781d85b0-1359-11df-a1f1-0026b9348838", - "c6bf3625-de80-4a88-a913-38273e300a55", - "a8e7c30d-6d2f-401c-bb52-d4433689a36b" + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Patient HIV status", + "enrollIf": "positive", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ] + } + }, + "incompatibleWith": [ + "781d897a-1359-11df-a1f1-0026b9348838", + "96047aaf-7ab3-45e9-be6a-b61810fe617d", + "c19aec66-1a40-4588-9b03-b6be55a8dd1d", + "334c9e98-173f-4454-a8ce-f80b20b7fdf0", + "96ba279b-b23b-4e78-aba9-dcbd46a96b7b", + "781d8880-1359-11df-a1f1-0026b9348838", + "781d85b0-1359-11df-a1f1-0026b9348838", + "c6bf3625-de80-4a88-a913-38273e300a55", + "a8e7c30d-6d2f-401c-bb52-d4433689a36b" ], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "b8516e6e-17c6-4f28-bc3d-ec58d591e455", "name": "ACTG Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -3453,7 +3650,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -3474,7 +3672,8 @@ { "uuid": "40353c46-cd54-4629-a5d1-0a1f1108b19f", "name": "Inpatient peer visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", "display": "INPATIENTPEER" }, @@ -3496,7 +3695,8 @@ "allowMultipleEnrollment": false, "requiredProgramEnrollment": [] }, - "stateChangeForms": [{ + "stateChangeForms": [ + { "type": "inCare", "uuid": "72443cac-4822-4dce-8460-794af7af8167", "forms": [] @@ -3514,18 +3714,22 @@ { "type": "referred", "uuid": "0c5565c5-45cf-40ab-aa6d-5694aeabae18", - "forms": [{ - "uuid": "1469e5fe-ad76-4041-9aa7-650e6afbe3a1", - "required": true - }] + "forms": [ + { + "uuid": "1469e5fe-ad76-4041-9aa7-650e6afbe3a1", + "required": true + } + ] }, { "type": "referredBack", "uuid": "15977097-13b7-4186-80a7-a78535f27866", - "forms": [{ - "uuid": "a70681eb-2238-48c6-b135-4ac9d9afea51", - "required": true - }] + "forms": [ + { + "uuid": "a70681eb-2238-48c6-b135-4ac9d9afea51", + "required": true + } + ] }, { "type": "pendingTransfer", @@ -3535,18 +3739,22 @@ { "type": "transferOut", "uuid": "5520f234-258e-49f0-97ab-701b98fab608", - "forms": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "required": true - }] + "forms": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "required": true + } + ] }, { "type": "referOut", "uuid": "24a2769a-296b-44bc-b50c-70089e0958db", - "forms": [{ - "uuid": "1469e5fe-ad76-4041-9aa7-650e6afbe3a1", - "required": true - }] + "forms": [ + { + "uuid": "1469e5fe-ad76-4041-9aa7-650e6afbe3a1", + "required": true + } + ] } ], "dataDependencies": [ @@ -3554,28 +3762,33 @@ "enrollment", "hivLastTenClinicalEncounters" ], - "visitTypes": [{ - "uuid": "567e4bde-cc1f-45d7-9c5c-93d0b04d8ced", - "name": "Dermatology Encounter Visit", - "encounterTypes": [{ - "uuid": "4587a5ab-0aad-4312-9eaa-b57151599729", - "display": "DERMATOLOGY" - }, - { - "uuid": "9150f9e5-d284-45e0-9702-faf8d2bcd1f9", - "display": "DERMRETURN" - }, - { - "uuid": "fa49ec8b-1f19-41b2-ade2-e31ae291196b", - "display": "DERMINITIAL" - } - - ] - }] + "visitTypes": [ + { + "uuid": "567e4bde-cc1f-45d7-9c5c-93d0b04d8ced", + "name": "Dermatology Encounter Visit", + "encounterTypes": [ + { + "uuid": "4587a5ab-0aad-4312-9eaa-b57151599729", + "display": "DERMATOLOGY" + }, + { + "uuid": "9150f9e5-d284-45e0-9702-faf8d2bcd1f9", + "display": "DERMRETURN" + }, + { + "uuid": "fa49ec8b-1f19-41b2-ade2-e31ae291196b", + "display": "DERMINITIAL" + } + ] + } + ] }, "c4246ff0-b081-460c-bcc5-b0678012659e": { "name": "VIREMIA PROGRAM", - "incompatibleWith": ["781d85b0-1359-11df-a1f1-0026b9348838", "334c9e98-173f-4454-a8ce-f80b20b7fdf0"], + "incompatibleWith": [ + "781d85b0-1359-11df-a1f1-0026b9348838", + "334c9e98-173f-4454-a8ce-f80b20b7fdf0" + ], "dataDependencies": [ "patient", "enrollment", @@ -3583,44 +3796,53 @@ "patientEnrollment" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Patient HIV status", - "enrollIf": "positive", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Patient HIV status", + "enrollIf": "positive", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ { - "value": "negative", - "label": "Negative" - }, + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ { - "value": "exposed", - "label": "Exposed" + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true } ] - }], - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] } }, - "visitTypes": [{ + "visitTypes": [ + { "uuid": "6c5d74f4-943f-489a-b1c4-b2accfae92fb", "name": "Viremia Visit", "allowedIf": "!isEnrolledInViremiaPMTCT", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -3674,7 +3896,8 @@ "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", "allowedIf": "!isEnrolledInViremiaPMTCT", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -3695,7 +3918,8 @@ { "uuid": "0b26e1ca-8b32-40e9-af4d-aa1c2cc68a58", "name": "Phone Follow Up Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", "display": "TELECARE" }, @@ -3708,30 +3932,31 @@ { "uuid": "52fddd42-f9ea-4946-8733-f0e584360780", "name": "Treatment Supporter visit", - "encounterTypes": [{ - "uuid": "693559d3-4e44-4d33-83f9-bc70ca56fe34", - "display": "TXSUPPORTERMEDREFILL" - }, - { - "uuid": "987009c6-6f24-43f7-9640-c285d6553c63", - "display": "DRUGPICKUP" - }, - { - "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", - "display": "COVIDSCREENING" - }, - { - "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", - "display": "COVIDCASEREPORTING" - }, - { - "uuid": "a393699f-8e99-4727-81c3-873873022dd8", - "display": "MOBILITYSCREENING" - }, - { - "uuid": "5b1ef308-ed8f-4a86-88a0-c29a30246740", - "display": "HIVCLINICALREFERRAL" - } + "encounterTypes": [ + { + "uuid": "693559d3-4e44-4d33-83f9-bc70ca56fe34", + "display": "TXSUPPORTERMEDREFILL" + }, + { + "uuid": "987009c6-6f24-43f7-9640-c285d6553c63", + "display": "DRUGPICKUP" + }, + { + "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", + "display": "COVIDSCREENING" + }, + { + "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", + "display": "COVIDCASEREPORTING" + }, + { + "uuid": "a393699f-8e99-4727-81c3-873873022dd8", + "display": "MOBILITYSCREENING" + }, + { + "uuid": "5b1ef308-ed8f-4a86-88a0-c29a30246740", + "display": "HIVCLINICALREFERRAL" + } ] }, { @@ -3739,7 +3964,8 @@ "name": "Between Care Visit", "allowedIf": "programLocation !== intendedVisitLocationUuid && !isFirstAMPATHHIVVisit", "message": "Patient has to be in a different location from location he was enrolled into HIV care and treatment program and must have a prior clinical encounter", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", "display": "HIVTRIAGE" }, @@ -3785,53 +4011,61 @@ "enrollmentOptions": { "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ] } }, "incompatibleWith": [], - "visitTypes": [{ - "uuid": "62b3d72c-a00b-46a8-af7b-e8f0c3186664", - "name": "DTG Pharmaco-vigilance visit", - "encounterTypes": [{ - "uuid": "85523cbc-6b8c-4b9d-91a6-a9e6ae012e7f", - "display": "PHARMACOVIGILANCECLINICAL" - }, - { - "uuid": "655c3451-172e-4c85-960a-392e4284ef92", - "display": "PHARMACOVIGILANCEPEER" - }, - { - "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", - "display": "COVIDSCREENING" - }, - { - "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", - "display": "COVIDCASEREPORTING" - } - ] - }, - { - "uuid": "2b9be1a5-0686-4d55-8383-d7c107f3aea3", - "name": "Phone Follow Up Visit", - "encounterTypes": [{ - "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", - "display": "TELECARE" - }, - { - "uuid": "5a58f6f5-f5a6-47eb-a644-626abd83f83b", - "display": "CALLCONSENT" - } - ] - }] + "visitTypes": [ + { + "uuid": "62b3d72c-a00b-46a8-af7b-e8f0c3186664", + "name": "DTG Pharmaco-vigilance visit", + "encounterTypes": [ + { + "uuid": "85523cbc-6b8c-4b9d-91a6-a9e6ae012e7f", + "display": "PHARMACOVIGILANCECLINICAL" + }, + { + "uuid": "655c3451-172e-4c85-960a-392e4284ef92", + "display": "PHARMACOVIGILANCEPEER" + }, + { + "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", + "display": "COVIDSCREENING" + }, + { + "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", + "display": "COVIDCASEREPORTING" + } + ] + }, + { + "uuid": "2b9be1a5-0686-4d55-8383-d7c107f3aea3", + "name": "Phone Follow Up Visit", + "encounterTypes": [ + { + "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", + "display": "TELECARE" + }, + { + "uuid": "5a58f6f5-f5a6-47eb-a644-626abd83f83b", + "display": "CALLCONSENT" + } + ] + } + ] }, "a8e7c30d-6d2f-401c-bb52-d4433689a36b": { "name": "HEI PROGRAM", @@ -3841,37 +4075,44 @@ "hivLastTenClinicalEncounters" ], "enrollmentOptions": { - "requiredProgramQuestions": [{ - "qtype": "hivStatus", - "name": "Mother's HIV status", - "enrollIf": "positive", - "value": null, - "answers": [{ - "value": "positive", - "label": "Positive" - }, + "requiredProgramQuestions": [ + { + "qtype": "hivStatus", + "name": "Mother's HIV status", + "enrollIf": "positive", + "value": null, + "answers": [ + { + "value": "positive", + "label": "Positive" + }, + { + "value": "negative", + "label": "Negative" + }, + { + "value": "exposed", + "label": "Exposed" + } + ] + } + ], + "stateChangeEncounterTypes": { + "enrollment": [], + "transfer": [ { - "value": "negative", - "label": "Negative" - }, + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ { - "value": "exposed", - "label": "Exposed" + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true } ] - }], - "stateChangeEncounterTypes": { - "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] } }, "incompatibleWith": [ @@ -3884,39 +4125,46 @@ "781d8880-1359-11df-a1f1-0026b9348838", "0904172d-0b6a-40df-b8a2-b3653d16dc45" ], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "097e4a13-f874-4ecc-b5c9-122ade250f99", "name": "HEI Visit", - "encounterTypes": [{ - "uuid": "5e019c94-0f80-49b7-8593-28100eb4f787", - "display": "HEIFOLLOWUP" - }, { - "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", - "display": "HIVTRIAGE" - }, { - "uuid": "df55584c-1350-11df-a1f1-0026b9348838", - "display": "DEATHREPORT" - }, { - "uuid": "df5547bc-1350-11df-a1f1-0026b9348838", - "display": "OUTREACHFIELDFU" - }, - { - "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", - "display": "COVIDSCREENING" - }, - { - "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", - "display": "COVIDCASEREPORTING" - }, - { - "uuid": "824ca90d-c313-4d7e-bc99-119871d927cb", - "display": "OVCNONENROLLMENT" - }] + "encounterTypes": [ + { + "uuid": "5e019c94-0f80-49b7-8593-28100eb4f787", + "display": "HEIFOLLOWUP" + }, + { + "uuid": "a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7", + "display": "HIVTRIAGE" + }, + { + "uuid": "df55584c-1350-11df-a1f1-0026b9348838", + "display": "DEATHREPORT" + }, + { + "uuid": "df5547bc-1350-11df-a1f1-0026b9348838", + "display": "OUTREACHFIELDFU" + }, + { + "uuid": "466d6707-8429-4e61-b5a0-d63444f5ad35", + "display": "COVIDSCREENING" + }, + { + "uuid": "afabceae-61d4-42b6-8f6a-fff48a7797ea", + "display": "COVIDCASEREPORTING" + }, + { + "uuid": "824ca90d-c313-4d7e-bc99-119871d927cb", + "display": "OVCNONENROLLMENT" + } + ] }, { "uuid": "015af4d4-67cb-45a3-9929-8dbd53b1e47c", "name": "Treatment Supporter Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "693559d3-4e44-4d33-83f9-bc70ca56fe34", "display": "TXSUPPORTERMEDREFILL" }, @@ -3937,7 +4185,8 @@ { "uuid": "06eca2a8-1da9-4ac4-95c6-15afedd4de21", "name": "HIV Lab Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "5ef97eed-18f5-40f6-9fbf-a11b1f06484a", "display": "LABORDERENCOUNTER" }, @@ -3958,7 +4207,8 @@ { "uuid": "40353c46-cd54-4629-a5d1-0a1f1108b19f", "name": "Inpatient peer visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "10a86a62-b771-44d1-b1ad-3b8496c7bc47", "display": "INPATIENTPEER" }, @@ -3975,7 +4225,8 @@ { "uuid": "8ec3bb23-6d7d-4638-9b2a-16b070760e34", "name": "HEI Phone Follow Up Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", "display": "TELECARE" }, @@ -3986,7 +4237,6 @@ ] } ] - }, "03552f68-8233-4793-8353-3db1847bb617": { "name": "NUTRITION PROGRAM", @@ -3999,27 +4249,34 @@ "enrollmentOptions": { "stateChangeEncounterTypes": { "enrollment": [], - "transfer": [{ - "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", - "name": "AMPATH POC Transfer Out Form v0.01", - "required": true - }], - "discharge": [{ - "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", - "name": "AMPATH POC HIV Exit Care Form v1.1", - "required": true - }] + "transfer": [ + { + "uuid": "cbe2d31d-2201-44ce-b52e-fbd5dc7cff33", + "name": "AMPATH POC Transfer Out Form v0.01", + "required": true + } + ], + "discharge": [ + { + "uuid": "9765992c-6279-46cc-915b-452a73e7dab5", + "name": "AMPATH POC HIV Exit Care Form v1.1", + "required": true + } + ] } }, - "visitTypes": [{ - "uuid": "540444dc-5dc1-436b-90f0-0dceb7c7df89", - "name": "Nutrition Visit", - "encounterTypes": [{ - "uuid": "3cd9dd0a-a5d1-4482-9f45-a0fea4f5e556", - "display": "NUTRITIONENCOUNTER" - }] - }] - + "visitTypes": [ + { + "uuid": "540444dc-5dc1-436b-90f0-0dceb7c7df89", + "name": "Nutrition Visit", + "encounterTypes": [ + { + "uuid": "3cd9dd0a-a5d1-4482-9f45-a0fea4f5e556", + "display": "NUTRITIONENCOUNTER" + } + ] + } + ] }, "da0c184e-751c-4b7e-a761-a60dc2d3f798": { "name": "INTEGRATED SCREENING PROGRAM", @@ -4029,49 +4286,50 @@ "hivLastTenClinicalEncounters" ], "incompatibleWith": [], - "visitTypes": [{ - "uuid": "c7fd1d31-da42-4a5b-ba76-80c1439b1865", - "name": "Integrated Screening Visit", - "encounterTypes": [{ - "uuid": "344719af-b526-46d3-b7f1-64e9ae618619", - "display": "HTNDMSCREENING" - }, - { - "uuid": "a8ab57df-a539-4a37-9eba-8f9ebd96809e", - "display": "FPSCREENING" - }, - { - "uuid": "30787193-3a03-443e-b025-f55c126793eb", - "display": "MENTALHEALTHSCREENING" - } - ] - }, - { - "uuid": "cc50bea5-9ca2-4505-876c-90400c3347cd", - "name": "CDM Confirmatory Screening Visit", - "encounterTypes": [ - { - "uuid": "3339810c-4980-4325-9825-0f0ed0c2da4a", - "display": "CDMSCREENINGCONFIRMATORY" - } - ] - - }, - { - "uuid": "9cbec0ea-9091-4a1d-9d2d-a3bbc295a04f", - "name": "Phone Follow Up Visit", - "encounterTypes": [{ - "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", - "display": "TELECARE" - }, - { - "uuid": "5a58f6f5-f5a6-47eb-a644-626abd83f83b", - "display": "CALLCONSENT" - } - ] - } - ] - + "visitTypes": [ + { + "uuid": "c7fd1d31-da42-4a5b-ba76-80c1439b1865", + "name": "Integrated Screening Visit", + "encounterTypes": [ + { + "uuid": "344719af-b526-46d3-b7f1-64e9ae618619", + "display": "HTNDMSCREENING" + }, + { + "uuid": "a8ab57df-a539-4a37-9eba-8f9ebd96809e", + "display": "FPSCREENING" + }, + { + "uuid": "30787193-3a03-443e-b025-f55c126793eb", + "display": "MENTALHEALTHSCREENING" + } + ] + }, + { + "uuid": "cc50bea5-9ca2-4505-876c-90400c3347cd", + "name": "CDM Confirmatory Screening Visit", + "encounterTypes": [ + { + "uuid": "3339810c-4980-4325-9825-0f0ed0c2da4a", + "display": "CDMSCREENINGCONFIRMATORY" + } + ] + }, + { + "uuid": "9cbec0ea-9091-4a1d-9d2d-a3bbc295a04f", + "name": "Phone Follow Up Visit", + "encounterTypes": [ + { + "uuid": "cac3b8e5-d8f8-4d4f-b791-8c43b4cc674b", + "display": "TELECARE" + }, + { + "uuid": "5a58f6f5-f5a6-47eb-a644-626abd83f83b", + "display": "CALLCONSENT" + } + ] + } + ] }, "f5cbf61f-eadc-4fe6-999c-2dfe9556df95": { "name": "BIGPIC PROGRAM", @@ -4081,35 +4339,36 @@ "hivLastTenClinicalEncounters" ], "incompatibleWith": [], - "visitTypes": [{ - "uuid": "f13f49ca-36b3-4abb-a24e-1776803ca69b", - "name": "GROUP CARE VISIT", - "encounterTypes": [{ - "uuid": "d54ce118-ce48-4e94-9315-ffe81df085fb", - "display": "BIGPICADULTRETURN" - }, - { - "uuid": "9bc0fa73-474e-45ab-bdac-7282e95d856f", - "display": "ONCOLOGYDYSPLASIA" - }, - { - "uuid": "238625fc-8a25-44b2-aa5a-8bf48fa0e18d", - "display": "ONCOLOGYVIA" - } - - ] - }, - { - "uuid": "f7cadb7e-b8be-4ea4-a6ad-4578aa7d18c9", - "name": "BIGPIC PHONE FOLLOW UP VISIT", - "encounterTypes": [ - { - "uuid": "0e5b24d2-b642-4c9d-b236-595dab3323cb", - "display": "BIGPICTELECARE" - } - ] - }] - + "visitTypes": [ + { + "uuid": "f13f49ca-36b3-4abb-a24e-1776803ca69b", + "name": "GROUP CARE VISIT", + "encounterTypes": [ + { + "uuid": "d54ce118-ce48-4e94-9315-ffe81df085fb", + "display": "BIGPICADULTRETURN" + }, + { + "uuid": "9bc0fa73-474e-45ab-bdac-7282e95d856f", + "display": "ONCOLOGYDYSPLASIA" + }, + { + "uuid": "238625fc-8a25-44b2-aa5a-8bf48fa0e18d", + "display": "ONCOLOGYVIA" + } + ] + }, + { + "uuid": "f7cadb7e-b8be-4ea4-a6ad-4578aa7d18c9", + "name": "BIGPIC PHONE FOLLOW UP VISIT", + "encounterTypes": [ + { + "uuid": "0e5b24d2-b642-4c9d-b236-595dab3323cb", + "display": "BIGPICTELECARE" + } + ] + } + ] }, "62741bb8-949e-4acc-9e38-50d9d874c1fb": { "name": "BI KUZA AFYA PROGRAM", @@ -4119,10 +4378,12 @@ "hivLastTenClinicalEncounters" ], "incompatibleWith": [], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "6deaadcf-a347-4af9-9b08-5ddba646d64e", "name": "Primary Care Level Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "f5381269-c889-4c5a-b384-d017441eedae", "display": "CDMTRIAGE" }, @@ -4139,7 +4400,8 @@ { "uuid": "031044cf-441f-48f7-9374-629852b403d2", "name": "Secondary Care Level Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "f5381269-c889-4c5a-b384-d017441eedae", "display": "CDMTRIAGE" }, @@ -4160,7 +4422,8 @@ { "uuid": "4a68cc05-11b4-4c4d-9808-b924db52cd04", "name": "Tertiary Care Level Visit ", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "f5381269-c889-4c5a-b384-d017441eedae", "display": "CDMTRIAGE" }, @@ -4182,34 +4445,34 @@ }, "a15a58a4-0daa-4195-bf29-b4bccd5df01e": { "name": "REFERRAL PEER NAVIGATOR PROGRAM", - "dataDependencies": [ - ], + "dataDependencies": [], "incompatibleWith": [], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "0af25783-0446-48ac-9690-d4277793183d", "name": "Referral Peer Navigator Visit", "encounterTypes": [ - { - "uuid": "02e75e2d-a809-4458-a77e-c1883e897c36", - "display": "PEERNAVIGATORFOLLOWUP" - } + { + "uuid": "02e75e2d-a809-4458-a77e-c1883e897c36", + "display": "PEERNAVIGATORFOLLOWUP" + } ] } ] }, "37ff4124-91fd-49e6-8261-057ccfb4fcd0": { "name": "ONCOLOGY SCREENING AND DIAGNOSIS PROGRAM", - "dataDependencies": [ - "patient" - ], + "dataDependencies": ["patient"], "incompatibleWith": [], - "enrollmentOptions": { + "enrollmentOptions": { "stateChangeEncounterTypes": { - "referral": [{ - "uuid": "ff13c7ad-9552-4d94-881b-dbad1116f7f7", - "name": "Oncology POC Screening Referral Form V1.0", - "required": true - }] + "referral": [ + { + "uuid": "ff13c7ad-9552-4d94-881b-dbad1116f7f7", + "name": "Oncology POC Screening Referral Form V1.0", + "required": true + } + ] } }, "visitTypes": [ @@ -4248,11 +4511,13 @@ "requiredProgramQuestions": [], "allowMultipleEnrollment": false, "stateChangeEncounterTypes": { - "referral": [{ - "uuid": "ff13c7ad-9552-4d94-881b-dbad1116f7f7", - "name": "Oncology POC Screening Referral Form V1.0", - "required": true - }] + "referral": [ + { + "uuid": "ff13c7ad-9552-4d94-881b-dbad1116f7f7", + "name": "Oncology POC Screening Referral Form V1.0", + "required": true + } + ] } }, "encounterTypes": [ @@ -4318,65 +4583,73 @@ }, "ff446cb9-0cf4-4b39-8288-16a43ffcca25": { "name": "CDM DEFAULTER TRACING PROGRAM", - "dataDependencies": [ - ], + "dataDependencies": [], "incompatibleWith": [], - "visitTypes": [{ + "visitTypes": [ + { "uuid": "35fc940e-ca50-4d28-bc47-81a383c04a44", "name": "CDM Defaulter Tracing Visit", - "encounterTypes": [{ + "encounterTypes": [ + { "uuid": "61ff98fb-0d6f-4789-a4c8-d2d2bfe287ab", "display": "CDMDEFAULTERTRACING" - }] - } - ] -}, -"d2090d0b-990a-4b82-98a8-32f987329f63": { - "name": "HOME GLUCOSE MONITORING PROGRAM", - "dataDependencies": [ - ], - "incompatibleWith": [], - "visitTypes": [ - { - "uuid": "50249f5b-cf2f-47c4-bd79-400b8865753f", - "name": "HGM Adult Visit", - "encounterTypes": [{ - "uuid": "25314148-71b3-485a-a77c-bd767866ee5c", - "display": "HOMEGLUCOSEMONITORINGADULT" - }] + } + ] + } + ] }, - { - "uuid": "eb348297-20d5-4d52-8f67-4623528f77e5", - "name": "HGM Pediatric Visit", - "encounterTypes": [{ - "uuid": "07542bc4-77a4-44ff-986b-2f5985a74cd9", - "display": "HOMEGLUCOSEMONITORINGPEDS" - }] - } -] -}, -"6976b7eb-6d66-4aba-bcc0-cd8be80041cd": { - "name": "MENTAL HEALTH PROGRAM", - "dataDependencies": [ - ], - "incompatibleWith": [], - "visitTypes": [ - { - "uuid": "6960d9c7-f54b-4dd5-abb6-9b710a2716df", - "name": "Mental Health Initial Visit", - "encounterTypes": [{ - "uuid": "c9c2aa71-bd29-444e-b77b-31eead82fdaf", - "display": "CDMMENTALHEALTHINITIAL" - }] + "d2090d0b-990a-4b82-98a8-32f987329f63": { + "name": "HOME GLUCOSE MONITORING PROGRAM", + "dataDependencies": [], + "incompatibleWith": [], + "visitTypes": [ + { + "uuid": "50249f5b-cf2f-47c4-bd79-400b8865753f", + "name": "HGM Adult Visit", + "encounterTypes": [ + { + "uuid": "25314148-71b3-485a-a77c-bd767866ee5c", + "display": "HOMEGLUCOSEMONITORINGADULT" + } + ] + }, + { + "uuid": "eb348297-20d5-4d52-8f67-4623528f77e5", + "name": "HGM Pediatric Visit", + "encounterTypes": [ + { + "uuid": "07542bc4-77a4-44ff-986b-2f5985a74cd9", + "display": "HOMEGLUCOSEMONITORINGPEDS" + } + ] + } + ] }, - { - "uuid": "3a7c6dc0-ce13-4332-99d6-c0ebf2d3d472", - "name": "Mental Health Return Visit", - "encounterTypes": [{ - "uuid": "c2d4a901-8007-4e36-8f50-5b19eb293451", - "display": "CDMMENTALHEALTHRETURN" - }] + "6976b7eb-6d66-4aba-bcc0-cd8be80041cd": { + "name": "MENTAL HEALTH PROGRAM", + "dataDependencies": [], + "incompatibleWith": [], + "visitTypes": [ + { + "uuid": "6960d9c7-f54b-4dd5-abb6-9b710a2716df", + "name": "Mental Health Initial Visit", + "encounterTypes": [ + { + "uuid": "c9c2aa71-bd29-444e-b77b-31eead82fdaf", + "display": "CDMMENTALHEALTHINITIAL" + } + ] + }, + { + "uuid": "3a7c6dc0-ce13-4332-99d6-c0ebf2d3d472", + "name": "Mental Health Return Visit", + "encounterTypes": [ + { + "uuid": "c2d4a901-8007-4e36-8f50-5b19eb293451", + "display": "CDMMENTALHEALTHRETURN" + } + ] + } + ] } -] -} } diff --git a/programs/program-enrollment.service.js b/programs/program-enrollment.service.js index f912b37eb..4a0786959 100755 --- a/programs/program-enrollment.service.js +++ b/programs/program-enrollment.service.js @@ -1,7 +1,7 @@ -var Promise = require("bluebird"); -var async = require('async'); -var scopeBuilder = require("./scope-builder.service"); -var dataResolver = require("./patient-data-resolver.service"); +var Promise = require('bluebird'); +var async = require('async'); +var scopeBuilder = require('./scope-builder.service'); +var dataResolver = require('./patient-data-resolver.service'); var expressionRunner = require('../expression-runner/expression-runner'); var _ = require('underscore'); _ = require('lodash'); @@ -12,65 +12,61 @@ var def = { module.exports = def; -function isEnrollmentAllowed (scope, enrollmentOptions) { +function isEnrollmentAllowed(scope, enrollmentOptions) { if (!enrollmentOptions.enrollIf) { return true; } return expressionRunner.run(enrollmentOptions.enrollIf, scope); } -function updateProgramConfig (patientUuid, program, callback,res) { +function updateProgramConfig(patientUuid, program, callback, res) { if (program.enrollmentOptions) { - var scopeObj = scopeBuilder.buildScope(res); - program.enrollmentAllowed = isEnrollmentAllowed(scopeObj, program.enrollmentOptions); - callback(); - + var scopeObj = scopeBuilder.buildScope(res); + program.enrollmentAllowed = isEnrollmentAllowed( + scopeObj, + program.enrollmentOptions + ); + callback(); } else { callback(); } } -function validateEnrollmentOptions (patientUuid, allProgramsConfig) { +function validateEnrollmentOptions(patientUuid, allProgramsConfig) { return new Promise(function (resolve, reject) { - var dataObject = getDependanciesKeysAndData(allProgramsConfig, patientUuid); - + var dataObject = getDependanciesKeysAndData(allProgramsConfig, patientUuid); - - async.each(allProgramsConfig, function (program, callback) { + async.each( + allProgramsConfig, + function (program, callback) { dataObject.then(function (res) { - updateProgramConfig(patientUuid, program, callback, res); - - + updateProgramConfig(patientUuid, program, callback, res); }); - - }, function (err) { - if (!err) { - resolve(allProgramsConfig); - } else { - reject(err); + }, + function (err) { + if (!err) { + resolve(allProgramsConfig); + } else { + reject(err); + } } - }); + ); }); } function getDependanciesKeysAndData(allProgramsConfig, patientUuid) { - return new Promise(function (resolve, reject) { - var dep = []; - _.each(allProgramsConfig, function (prog) { - - dep.push(prog.dataDependencies); - - }); - dataResolver.getAllDataDependencies(dep[0] || [], patientUuid, {}) - .then(function (dataObject) { - resolve(dataObject); - - }).catch((error) => { - reject(error) - - }); + return new Promise(function (resolve, reject) { + var dep = []; + _.each(allProgramsConfig, function (prog) { + dep.push(prog.dataDependencies); }); - + dataResolver + .getAllDataDependencies(dep[0] || [], patientUuid, {}) + .then(function (dataObject) { + resolve(dataObject); + }) + .catch((error) => { + reject(error); + }); + }); } - - diff --git a/programs/program-type.service.js b/programs/program-type.service.js index 4d2364c53..8457f1641 100755 --- a/programs/program-type.service.js +++ b/programs/program-type.service.js @@ -1,4 +1,4 @@ -var Promise = require("bluebird"); +var Promise = require('bluebird'); var programTypeDao = require('../dao/program-type/program-type-dao'); const _ = require('lodash'); var programTypes = []; @@ -6,101 +6,80 @@ var programUuidIdMap = new Map(); const programsConfig = require('./patient-program-config'); var def = { - getAllprogramTypes: getAllprogramTypes, - mapprogramUuidToId: mapprogramUuidToId, - loadAndMapProgramUuidToId : loadAndMapProgramUuidToId, - getprogramIdFromUuid: getprogramIdFromUuid + getAllprogramTypes: getAllprogramTypes, + mapprogramUuidToId: mapprogramUuidToId, + loadAndMapProgramUuidToId: loadAndMapProgramUuidToId, + getprogramIdFromUuid: getprogramIdFromUuid }; module.exports = def; - -function getAllprogramTypes(){ - - /* +function getAllprogramTypes() { + /* returns a list of all program-types with their id and uuid */ return new Promise(function (resolve, reject) { - - if(programTypes.length > 0){ - - // console.log('program Type length > 0'); - - resolve(programTypes); - - }else{ - - // console.log('program Type length < 0'); - - programTypeDao.getProgramTypes().then(function (result) { - if(result){ - programTypes = result; - resolve(programTypes); - }else{ - reject('error'); - } - }) - .catch(function (error) { - reject('error'); - }); - - - } - - - - }); - - - + if (programTypes.length > 0) { + // console.log('program Type length > 0'); + + resolve(programTypes); + } else { + // console.log('program Type length < 0'); + + programTypeDao + .getProgramTypes() + .then(function (result) { + if (result) { + programTypes = result; + resolve(programTypes); + } else { + reject('error'); + } + }) + .catch(function (error) { + reject('error'); + }); + } + }); } -function mapprogramUuidToId(programTypes){ - // console.log('Got programTypes', programTypes); +function mapprogramUuidToId(programTypes) { + // console.log('Got programTypes', programTypes); - _.each(programTypes,(programType, index) => { - // console.log('Specific program Type', programType) - programUuidIdMap.set( programType.uuid ,programType.program_id); - }); - - return programUuidIdMap; + _.each(programTypes, (programType, index) => { + // console.log('Specific program Type', programType) + programUuidIdMap.set(programType.uuid, programType.program_id); + }); + return programUuidIdMap; } -function getprogramIdFromUuid(programUuid){ - - var programObj = programUuidIdMap.get(programUuid); - - if(typeof programObj === 'undefined'){ - return -1; - }else{ - return programObj; - } +function getprogramIdFromUuid(programUuid) { + var programObj = programUuidIdMap.get(programUuid); + if (typeof programObj === 'undefined') { + return -1; + } else { + return programObj; + } } -function loadAndMapProgramUuidToId(){ - - return new Promise(function (resolve, reject) { - - getAllprogramTypes() - .then((result) => { - if(result){ - programUuidIdMap = mapprogramUuidToId(result); - resolve(programUuidIdMap); - } - }) - .catch(((error) =>{ - reject('Error'); - })); - - }); - +function loadAndMapProgramUuidToId() { + return new Promise(function (resolve, reject) { + getAllprogramTypes() + .then((result) => { + if (result) { + programUuidIdMap = mapprogramUuidToId(result); + resolve(programUuidIdMap); + } + }) + .catch((error) => { + reject('Error'); + }); + }); } //get all visit types and encounters under a certain program - - diff --git a/programs/program-visit-types.service.js b/programs/program-visit-types.service.js index 9a77cbaf7..c4673ad75 100755 --- a/programs/program-visit-types.service.js +++ b/programs/program-visit-types.service.js @@ -1,6 +1,6 @@ -const Promise = require("bluebird"); -const scopeBuilder = require("./scope-builder.service"); -const dataResolver = require("./patient-data-resolver.service"); +const Promise = require('bluebird'); +const scopeBuilder = require('./scope-builder.service'); +const dataResolver = require('./patient-data-resolver.service'); const expressionRunner = require('../expression-runner/expression-runner'); const def = { @@ -36,8 +36,13 @@ function separateAllowedDisallowedVisitTypes(scope, visitTypes) { return separated; } -function getPatientVisitTypes(patientUuid, programUuid, programEnrollmentUuid, - intendedVisitLocationUuid, allProgramsConfig) { +function getPatientVisitTypes( + patientUuid, + programUuid, + programEnrollmentUuid, + intendedVisitLocationUuid, + allProgramsConfig +) { return new Promise((success, error) => { const program = allProgramsConfig[programUuid]; if (!program) { @@ -46,16 +51,14 @@ function getPatientVisitTypes(patientUuid, programUuid, programEnrollmentUuid, } // resolve data dependencies - dataResolver.getAllDataDependencies( - program.dataDependencies || [], - patientUuid, - { + dataResolver + .getAllDataDependencies(program.dataDependencies || [], patientUuid, { programUuid: programUuid, programEnrollmentUuid: programEnrollmentUuid, intendedVisitLocationUuid: intendedVisitLocationUuid }) .then((dataObject) => { - // add missing properties + // add missing properties dataObject.programUuid = programUuid; dataObject.intendedVisitLocationUuid = intendedVisitLocationUuid; @@ -63,7 +66,10 @@ function getPatientVisitTypes(patientUuid, programUuid, programEnrollmentUuid, const scopeObj = scopeBuilder.buildScope(dataObject); const visits = program.visitTypes; - program.visitTypes = separateAllowedDisallowedVisitTypes(scopeObj, visits); + program.visitTypes = separateAllowedDisallowedVisitTypes( + scopeObj, + visits + ); success(program); }) @@ -72,6 +78,6 @@ function getPatientVisitTypes(patientUuid, programUuid, programEnrollmentUuid, error({ message: 'Error resolving data dependencies' }); - }) + }); }); } diff --git a/programs/scope-builder.service.js b/programs/scope-builder.service.js index ef9ff21e3..f22b87b9f 100755 --- a/programs/scope-builder.service.js +++ b/programs/scope-builder.service.js @@ -9,7 +9,7 @@ module.exports = def; function buildScope(dataDictionary) { const scope = {}; - + if (dataDictionary.patient) { buildPatientScopeMembers(scope, dataDictionary.patient); } @@ -19,15 +19,17 @@ function buildScope(dataDictionary) { } if (dataDictionary.patientEnrollment) { - const activeEnrollments = _.filter(dataDictionary.patientEnrollment, { dateCompleted: null}); + const activeEnrollments = _.filter(dataDictionary.patientEnrollment, { + dateCompleted: null + }); let isEnrolledInPMTCT = false; let isEnrolledInViremia = false; - + activeEnrollments.forEach((item) => { if (item.program.uuid === 'c4246ff0-b081-460c-bcc5-b0678012659e') { isEnrolledInViremia = true; } - + if (item.program.uuid === '781d897a-1359-11df-a1f1-0026b9348838') { isEnrolledInPMTCT = true; } @@ -41,8 +43,11 @@ function buildScope(dataDictionary) { } if (dataDictionary.hivLastTenClinicalEncounters) { - buildHivScopeMembers(scope, dataDictionary.hivLastTenClinicalEncounters, - dataDictionary.intendedVisitLocationUuid); + buildHivScopeMembers( + scope, + dataDictionary.hivLastTenClinicalEncounters, + dataDictionary.intendedVisitLocationUuid + ); } if (dataDictionary.hivLastEncounter) { @@ -56,12 +61,16 @@ function buildScope(dataDictionary) { if (dataDictionary.intendedVisitLocationUuid) { scope.intendedVisitLocationUuid = dataDictionary.intendedVisitLocationUuid; } - + if (dataDictionary.patientEncounters) { scope.patientEncounters = dataDictionary.patientEncounters; scope.programUuid = dataDictionary.programUuid; buildHivScopeMembers(scope, dataDictionary.patientEncounters); - buildOncologyScopeMembers(scope, dataDictionary.patientEncounters, dataDictionary.programUuid); + buildOncologyScopeMembers( + scope, + dataDictionary.patientEncounters, + dataDictionary.programUuid + ); } // add other methods to build the scope objects @@ -74,7 +83,11 @@ function buildPatientScopeMembers(scope, patient) { } function isIntraTransfer(lastTenHivSummary, intendedVisitLocationUuid) { - if (intendedVisitLocationUuid && Array.isArray(lastTenHivSummary) && lastTenHivSummary.length > 0) { + if ( + intendedVisitLocationUuid && + Array.isArray(lastTenHivSummary) && + lastTenHivSummary.length > 0 + ) { return intendedVisitLocationUuid !== lastTenHivSummary[0].location_uuid; } else { return false; @@ -103,29 +116,30 @@ function isInitialPepVisit(patientEncounters) { let orderedPEPEncounters = []; let duration = 0; - - if(initialPEPEncounters.length > 0){ - // order pep initial from the latest pep encounter - orderedPEPEncounters = initialPEPEncounters.sort((a,b) => { - var dateA = new Date(a.encounterDatetime); - var dateB = new Date(b.encounterDatetime); - return dateB - dateA; - }); + + if (initialPEPEncounters.length > 0) { + // order pep initial from the latest pep encounter + orderedPEPEncounters = initialPEPEncounters.sort((a, b) => { + var dateA = new Date(a.encounterDatetime); + var dateB = new Date(b.encounterDatetime); + return dateB - dateA; + }); const today = Moment(new Date()); let latestPEPEncounter = orderedPEPEncounters[0]; - let latestPEPEncounterDate = Moment(latestPEPEncounter.encounterDatetime).format(); - duration = today.diff(latestPEPEncounterDate,'days'); + let latestPEPEncounterDate = Moment( + latestPEPEncounter.encounterDatetime + ).format(); + duration = today.diff(latestPEPEncounterDate, 'days'); // if its more than 60 days since their last PEP Initial then they should see a pep initial visit - if(duration > 120){ - isInitialPEPVisit = true; - }else{ - isInitialPEPVisit = false; + if (duration > 120) { + isInitialPEPVisit = true; + } else { + isInitialPEPVisit = false; } - } - + return isInitialPEPVisit; } @@ -176,26 +190,34 @@ function isInitialOncologyVisit(encounters, programUuid) { ]; let initialOncologyEncounters = []; - let initialEncounterType = oncologyProgramEncounterTypeMap.find(e => e.programUuid === programUuid); - + let initialEncounterType = oncologyProgramEncounterTypeMap.find( + (e) => e.programUuid === programUuid + ); + if (initialEncounterType) { - initialOncologyEncounters = _.filter(encounters, encounter => { - return initialEncounterType.initialEncounterUuid === encounter.encounterType.uuid + initialOncologyEncounters = _.filter(encounters, (encounter) => { + return ( + initialEncounterType.initialEncounterUuid === + encounter.encounterType.uuid + ); }); } return initialOncologyEncounters.length === 0; } function buildProgramScopeMembers(scope, programEnrollment) { - if (programEnrollment && programEnrollment.location && - programEnrollment.location.uuid) { + if ( + programEnrollment && + programEnrollment.location && + programEnrollment.location.uuid + ) { scope.programLocation = programEnrollment.location.uuid; } - + if (programEnrollment && programEnrollment.states) { const states = programEnrollment.states; - const currentState = states.filter(state => state.endDate === null); - + const currentState = states.filter((state) => state.endDate === null); + if (currentState.length > 0) { const state = currentState[0].state; scope.inCareUuid = state.concept.uuid; @@ -203,13 +225,20 @@ function buildProgramScopeMembers(scope, programEnrollment) { } } -function buildHivScopeMembers(scope, lastTenHivSummary, intendedVisitLocationUuid) { +function buildHivScopeMembers( + scope, + lastTenHivSummary, + intendedVisitLocationUuid +) { if (Array.isArray(lastTenHivSummary) && lastTenHivSummary.length > 0) { scope.isFirstAMPATHHIVVisit = false; scope.previousHIVClinicallocation = lastTenHivSummary[0].location_uuid; } else { // its first AMPATH visit if its not an intra transfer - scope.isFirstAMPATHHIVVisit = !isIntraTransfer(lastTenHivSummary, intendedVisitLocationUuid); + scope.isFirstAMPATHHIVVisit = !isIntraTransfer( + lastTenHivSummary, + intendedVisitLocationUuid + ); scope.previousHIVClinicallocation = null; } @@ -219,5 +248,8 @@ function buildHivScopeMembers(scope, lastTenHivSummary, intendedVisitLocationUui } function buildOncologyScopeMembers(scope, patientEncounters, programUuid) { - scope.isFirstOncologyVisit = isInitialOncologyVisit(scope.patientEncounters, programUuid); + scope.isFirstOncologyVisit = isInitialOncologyVisit( + scope.patientEncounters, + programUuid + ); } diff --git a/report-post-processors/clinic-comparator-processor.js b/report-post-processors/clinic-comparator-processor.js index c98400fd3..be51dc328 100755 --- a/report-post-processors/clinic-comparator-processor.js +++ b/report-post-processors/clinic-comparator-processor.js @@ -2,79 +2,64 @@ var _ = require('underscore'); var moment = require('moment'); var moduleExport = { - groupResultsByMonth: groupResultsByMonth - + groupResultsByMonth: groupResultsByMonth }; module.exports = moduleExport; - -function getListOfLocationIdsFromResult(results){ - var locations =[]; - var unique = {}; - for( var i in results ){ - if( typeof(unique[results[i].location_id]) == "undefined"){ - locations.push(results[i].location_id); - } - unique[results[i].location_id] = 0; +function getListOfLocationIdsFromResult(results) { + var locations = []; + var unique = {}; + for (var i in results) { + if (typeof unique[results[i].location_id] == 'undefined') { + locations.push(results[i].location_id); } - return locations; + unique[results[i].location_id] = 0; + } + return locations; } -function getListOfDistinctMonthFromResult(results){ - var months =[]; - var unique = {}; - for( var i in results ){ - if( typeof(unique[results[i].reporting_month]) == "undefined"){ - months.push(results[i].reporting_month); - - } - unique[results[i].reporting_month] = 0; +function getListOfDistinctMonthFromResult(results) { + var months = []; + var unique = {}; + for (var i in results) { + if (typeof unique[results[i].reporting_month] == 'undefined') { + months.push(results[i].reporting_month); } - return months; - + unique[results[i].reporting_month] = 0; + } + return months; } -function groupResultsByMonth(results, indicator){ - //stringify - results=JSON.stringify(results); - results= JSON.parse(results); - var finalReport=[]; - var locationIds=getListOfLocationIdsFromResult(results); - var distinctMonth=getListOfDistinctMonthFromResult(results); - //construct month - _.each(distinctMonth, function(month){ - var row={}; - var data = []; - _.each(results, function(result){ - - if(month===result.reporting_month) { - row['month']=result.reporting_month; - row[result.location]=result[indicator]; - _.each(locationIds, function (locationId) { - if (locationId === result.location_id) { - - data.push({ - location_uuid: result.location_uuid, - location_id: result.location_id, - indicator:result[indicator], - location:result.location - }); - } - }); - } +function groupResultsByMonth(results, indicator) { + //stringify + results = JSON.stringify(results); + results = JSON.parse(results); + var finalReport = []; + var locationIds = getListOfLocationIdsFromResult(results); + var distinctMonth = getListOfDistinctMonthFromResult(results); + //construct month + _.each(distinctMonth, function (month) { + var row = {}; + var data = []; + _.each(results, function (result) { + if (month === result.reporting_month) { + row['month'] = result.reporting_month; + row[result.location] = result[indicator]; + _.each(locationIds, function (locationId) { + if (locationId === result.location_id) { + data.push({ + location_uuid: result.location_uuid, + location_id: result.location_id, + indicator: result[indicator], + location: result.location + }); + } }); - row['data']=data; - finalReport.push(row) + } }); + row['data'] = data; + finalReport.push(row); + }); - return finalReport; + return finalReport; } - - - - - - - - - diff --git a/report-post-processors/patient-flow-processor.js b/report-post-processors/patient-flow-processor.js index aedeb211b..60901b46f 100755 --- a/report-post-processors/patient-flow-processor.js +++ b/report-post-processors/patient-flow-processor.js @@ -2,417 +2,482 @@ var _ = require('underscore'); var moment = require('moment'); var moduleExport = { - groupResultsByVisitId: groupResultsByVisitId, - //aggregates - calculateAverageWaitingTime: calculateAverageWaitingTime, - getIncompleteVisitsCount: getIncompleteVisitsCount, - getCompleteVisitsCount: getCompleteVisitsCount, - getTotalVisitsCount: getTotalVisitsCount, - calculateMedianWaitingTime: calculateMedianWaitingTime, - //helpers - _handleTimeToBeSeenByClinician: _handleTimeToBeSeenByClinician, - _getTimeSpanInMinutes: _getTimeSpanInMinutes, - _handleTimeToCompleteVisit: _handleTimeToCompleteVisit, - splitResultsByLocation: splitResultsByLocation, - calculateStatisticsByLocation: calculateStatisticsByLocation, - calculateHourlyStatistics: calculateHourlyStatistics + groupResultsByVisitId: groupResultsByVisitId, + //aggregates + calculateAverageWaitingTime: calculateAverageWaitingTime, + getIncompleteVisitsCount: getIncompleteVisitsCount, + getCompleteVisitsCount: getCompleteVisitsCount, + getTotalVisitsCount: getTotalVisitsCount, + calculateMedianWaitingTime: calculateMedianWaitingTime, + //helpers + _handleTimeToBeSeenByClinician: _handleTimeToBeSeenByClinician, + _getTimeSpanInMinutes: _getTimeSpanInMinutes, + _handleTimeToCompleteVisit: _handleTimeToCompleteVisit, + splitResultsByLocation: splitResultsByLocation, + calculateStatisticsByLocation: calculateStatisticsByLocation, + calculateHourlyStatistics: calculateHourlyStatistics }; module.exports = moduleExport; function groupResultsByVisitId(arrayOfResults) { - var grouped = {}; - - _.each(arrayOfResults, function (result) { - if (_.isEmpty(grouped[result.visit_id])) { - grouped[result.visit_id] = { - patient_id: result.patient_id, - patient_uuid: result.patient_uuid, - names: (result.given_name && result.given_name != null ? result.given_name : '') + - (result.middle_name && result.middle_name != null ? ' ' + result.middle_name : '') + - (result.family_name && result.family_name != null ? ' ' + result.family_name : ''), - identifiers: result.identifiers, - visit_person_Name: (result.visit_start_given_name && result.visit_start_given_name != null ? result.visit_start_given_name : '') + - (result.visit_start_middle_name && result.visit_start_middle_name != null ? ' ' + result.visit_start_middle_name : '') + - (result.visit_start_family_name && result.visit_start_family_name != null ? ' ' + result.visit_start_family_name : ''), - - location: result.location, - locationId: result.location_id, - visit_person_id: result.visit_person_id, - visit_id: result.visit_id, - registered: typeof result.triaged === 'string' ? result.visit_start : new Date(result.visit_start).toISOString(), - visit_end: result.visit_end, - encounters: [] - }; - } - var visit = grouped[result.visit_id]; - _handleTriaged(result, visit); - _handleSeenByClinician(result, visit); - _handleCompletedVisit(result, visit); - _handleEncouters(result, visit); - }); - var results = []; - for (var e in grouped) { - - //calculate time periods first - _handleTimeToBeSeenByClinician(grouped[e]); - _handleTimeToCompleteVisit(grouped[e]); - - results.push(grouped[e]); + var grouped = {}; + + _.each(arrayOfResults, function (result) { + if (_.isEmpty(grouped[result.visit_id])) { + grouped[result.visit_id] = { + patient_id: result.patient_id, + patient_uuid: result.patient_uuid, + names: + (result.given_name && result.given_name != null + ? result.given_name + : '') + + (result.middle_name && result.middle_name != null + ? ' ' + result.middle_name + : '') + + (result.family_name && result.family_name != null + ? ' ' + result.family_name + : ''), + identifiers: result.identifiers, + visit_person_Name: + (result.visit_start_given_name && + result.visit_start_given_name != null + ? result.visit_start_given_name + : '') + + (result.visit_start_middle_name && + result.visit_start_middle_name != null + ? ' ' + result.visit_start_middle_name + : '') + + (result.visit_start_family_name && + result.visit_start_family_name != null + ? ' ' + result.visit_start_family_name + : ''), + + location: result.location, + locationId: result.location_id, + visit_person_id: result.visit_person_id, + visit_id: result.visit_id, + registered: + typeof result.triaged === 'string' + ? result.visit_start + : new Date(result.visit_start).toISOString(), + visit_end: result.visit_end, + encounters: [] + }; } - - return results; + var visit = grouped[result.visit_id]; + _handleTriaged(result, visit); + _handleSeenByClinician(result, visit); + _handleCompletedVisit(result, visit); + _handleEncouters(result, visit); + }); + var results = []; + for (var e in grouped) { + //calculate time periods first + _handleTimeToBeSeenByClinician(grouped[e]); + _handleTimeToCompleteVisit(grouped[e]); + + results.push(grouped[e]); + } + + return results; } function _handleTriaged(result, visit) { - //triaged - //necessary check to ensure the first triage encounter is used - if (_.isEmpty(visit.triaged)) { - visit.triaged = null; - if (result.triaged !== null && result.triaged !== undefined) - visit.triaged = typeof result.triaged === 'string' ? result.triaged : new Date(result.triaged).toISOString(); - - visit.time_to_be_triaged = result.time_to_be_triaged; - } + //triaged + //necessary check to ensure the first triage encounter is used + if (_.isEmpty(visit.triaged)) { + visit.triaged = null; + if (result.triaged !== null && result.triaged !== undefined) + visit.triaged = + typeof result.triaged === 'string' + ? result.triaged + : new Date(result.triaged).toISOString(); + + visit.time_to_be_triaged = result.time_to_be_triaged; + } } function _handleSeenByClinician(result, visit) { - //clinical encounter - //necessary check to ensure the first clinical encounter is used - if (_.isEmpty(visit.seen_by_clinician)) { - visit.seen_by_clinician = null; - if (result.seen_by_clinician !== null && result.seen_by_clinician !== undefined) - visit.seen_by_clinician = typeof result.seen_by_clinician === 'string' ? result.seen_by_clinician : new Date(result.seen_by_clinician).toISOString(); - } + //clinical encounter + //necessary check to ensure the first clinical encounter is used + if (_.isEmpty(visit.seen_by_clinician)) { + visit.seen_by_clinician = null; + if ( + result.seen_by_clinician !== null && + result.seen_by_clinician !== undefined + ) + visit.seen_by_clinician = + typeof result.seen_by_clinician === 'string' + ? result.seen_by_clinician + : new Date(result.seen_by_clinician).toISOString(); + } } function _handleEncouters(result, visit) { + if (!_.isNull(result.encounter_type)) { + var encounter = { + encounter_type: result.encounter_type, + encounter_start: result.encounter_start, + encounter_end: result.encounter_end, + encounter_type_name: result.encounter_type_name, + location: result.location, + + person_name: + (result.provider_given_name && result.provider_given_name != null + ? result.provider_given_name + : '') + + (result.provider_middle_name && result.provider_middle_name != null + ? ' ' + result.provider_middle_name + : '') + + (result.provider_family_name && result.provider_family_name != null + ? ' ' + result.provider_family_name + : ''), + person_id: result.person_id + }; - if (!_.isNull(result.encounter_type)) { - var encounter = { - encounter_type: result.encounter_type, - encounter_start: result.encounter_start, - encounter_end: result.encounter_end, - encounter_type_name: result.encounter_type_name, - location: result.location, - - person_name: (result.provider_given_name && result.provider_given_name != null ? result.provider_given_name : '') + - (result.provider_middle_name && result.provider_middle_name != null ? ' ' + result.provider_middle_name : '') + - (result.provider_family_name && result.provider_family_name != null ? ' ' + result.provider_family_name : ''), - person_id: result.person_id - }; - - - visit.encounters.push(encounter); - } - + visit.encounters.push(encounter); + } } function _handleCompletedVisit(result, visit) { - visit.completed_visit = null; - - if (result.encounter_end !== null && result.encounter_end !== undefined) - visit.completed_visit = typeof result.encounter_end === 'string' ? result.encounter_end : new Date(result.encounter_end).toISOString(); + visit.completed_visit = null; + if (result.encounter_end !== null && result.encounter_end !== undefined) + visit.completed_visit = + typeof result.encounter_end === 'string' + ? result.encounter_end + : new Date(result.encounter_end).toISOString(); } function _handleTimeToBeSeenByClinician(visit) { - visit.time_to_be_seen_by_clinician = null; - - if (!_.isEmpty(visit.triaged)) { - if (!_.isEmpty(visit.seen_by_clinician)) - visit.time_to_be_seen_by_clinician = - _getTimeSpanInMinutes(visit.triaged, visit.seen_by_clinician); - } else { - if (!_.isEmpty(visit.seen_by_clinician) && !_.isEmpty(visit.registered)) - visit.time_to_be_seen_by_clinician = - _getTimeSpanInMinutes(visit.registered, visit.seen_by_clinician); - } + visit.time_to_be_seen_by_clinician = null; + + if (!_.isEmpty(visit.triaged)) { + if (!_.isEmpty(visit.seen_by_clinician)) + visit.time_to_be_seen_by_clinician = _getTimeSpanInMinutes( + visit.triaged, + visit.seen_by_clinician + ); + } else { + if (!_.isEmpty(visit.seen_by_clinician) && !_.isEmpty(visit.registered)) + visit.time_to_be_seen_by_clinician = _getTimeSpanInMinutes( + visit.registered, + visit.seen_by_clinician + ); + } } function _handleTimeToCompleteVisit(visit) { - visit.time_to_complete_visit = null; - if (_.isEmpty(visit.seen_by_clinician)) return; - - if (!_.isEmpty(visit.registered) && !_.isEmpty(visit.completed_visit)) { - visit.time_to_complete_visit = - _getTimeSpanInMinutes(visit.registered, visit.completed_visit); - } + visit.time_to_complete_visit = null; + if (_.isEmpty(visit.seen_by_clinician)) return; + + if (!_.isEmpty(visit.registered) && !_.isEmpty(visit.completed_visit)) { + visit.time_to_complete_visit = _getTimeSpanInMinutes( + visit.registered, + visit.completed_visit + ); + } } function _getTimeSpanInMinutes(timeA, timeB) { - var a = moment(timeA); - var b = moment(timeB); - return Math.round((b.diff(a) / (1000 * 60))); + var a = moment(timeA); + var b = moment(timeB); + return Math.round(b.diff(a) / (1000 * 60)); } function calculateAverageWaitingTime(patientFlowArray) { - var results = { - averageWaitingTime: '0', - averageVisitCompletionTime: '0', - averageTriageWaitingTime: '0', - averageClinicianWaitingTime: '0' - }; - - var triageSum = 0; - var triageCount = 0; - var clinicianSum = 0; - var clinicianCount = 0; - var completionSum = 0; - var completionCount = 0; - for (var i = 0; i < patientFlowArray.length; i++) { - var patientFlow = patientFlowArray[i]; - if (patientFlow.time_to_be_triaged !== null && - patientFlow.time_to_be_triaged !== undefined) { - triageSum = triageSum + patientFlow.time_to_be_triaged; - triageCount++; - } - - if (patientFlow.time_to_be_seen_by_clinician !== null && - patientFlow.time_to_be_seen_by_clinician !== undefined) { - clinicianSum = clinicianSum + patientFlow.time_to_be_seen_by_clinician; - clinicianCount++; - } - - if (patientFlow.time_to_complete_visit !== null && - patientFlow.time_to_complete_visit !== undefined) { - completionSum = completionSum + patientFlow.time_to_complete_visit; - completionCount++; - } - } - - if (triageSum != 0) { - results.averageTriageWaitingTime = (triageSum / triageCount).toFixed(1); + var results = { + averageWaitingTime: '0', + averageVisitCompletionTime: '0', + averageTriageWaitingTime: '0', + averageClinicianWaitingTime: '0' + }; + + var triageSum = 0; + var triageCount = 0; + var clinicianSum = 0; + var clinicianCount = 0; + var completionSum = 0; + var completionCount = 0; + for (var i = 0; i < patientFlowArray.length; i++) { + var patientFlow = patientFlowArray[i]; + if ( + patientFlow.time_to_be_triaged !== null && + patientFlow.time_to_be_triaged !== undefined + ) { + triageSum = triageSum + patientFlow.time_to_be_triaged; + triageCount++; } - if (clinicianSum != 0) { - results.averageClinicianWaitingTime = (clinicianSum / clinicianCount).toFixed(1); + if ( + patientFlow.time_to_be_seen_by_clinician !== null && + patientFlow.time_to_be_seen_by_clinician !== undefined + ) { + clinicianSum = clinicianSum + patientFlow.time_to_be_seen_by_clinician; + clinicianCount++; } - if (completionSum != 0) { - results.averageVisitCompletionTime = (completionSum / completionCount).toFixed(1); + if ( + patientFlow.time_to_complete_visit !== null && + patientFlow.time_to_complete_visit !== undefined + ) { + completionSum = completionSum + patientFlow.time_to_complete_visit; + completionCount++; } - - results.averageWaitingTime = - ((new Number(results.averageTriageWaitingTime) + new Number(results.averageClinicianWaitingTime)) / 2).toFixed(1); - - return results; + } + + if (triageSum != 0) { + results.averageTriageWaitingTime = (triageSum / triageCount).toFixed(1); + } + + if (clinicianSum != 0) { + results.averageClinicianWaitingTime = ( + clinicianSum / clinicianCount + ).toFixed(1); + } + + if (completionSum != 0) { + results.averageVisitCompletionTime = ( + completionSum / completionCount + ).toFixed(1); + } + + results.averageWaitingTime = ( + (new Number(results.averageTriageWaitingTime) + + new Number(results.averageClinicianWaitingTime)) / + 2 + ).toFixed(1); + + return results; } function getIncompleteVisitsCount(patientFlowArray) { + var count = 0; - var count = 0; - - for (var i = 0; i < patientFlowArray.length; i++) { - var patientFlow = patientFlowArray[i]; - if (_.isEmpty(patientFlow.seen_by_clinician)) { - count++; - } + for (var i = 0; i < patientFlowArray.length; i++) { + var patientFlow = patientFlowArray[i]; + if (_.isEmpty(patientFlow.seen_by_clinician)) { + count++; } + } - return count; + return count; } function getCompleteVisitsCount(patientFlowArray) { + var count = 0; - var count = 0; - - for (var i = 0; i < patientFlowArray.length; i++) { - var patientFlow = patientFlowArray[i]; - if (!_.isEmpty(patientFlow.seen_by_clinician)) { - count++; - } + for (var i = 0; i < patientFlowArray.length; i++) { + var patientFlow = patientFlowArray[i]; + if (!_.isEmpty(patientFlow.seen_by_clinician)) { + count++; } + } - return count; + return count; } - function calculateMedianWaitingTime(patientFlowArray) { - - var waitingTime = _extractWaitingTime(patientFlowArray); - - var medianWaitingTime = { - medianWaitingTime: '0', - medianVisitCompletionTime: '0', - medianTriageWaitingTime: '0', - medianClinicianWaitingTime: '0' - }; - - if (waitingTime.allWaitingTimes.length > 0) - medianWaitingTime.medianWaitingTime = _getMedian(waitingTime.allWaitingTimes).toFixed(1); - - if (waitingTime.triageWaitingTimes.length > 0) - medianWaitingTime.medianTriageWaitingTime = _getMedian(waitingTime.triageWaitingTimes).toFixed(1); - - if (waitingTime.clinicianWaitingTimes.length > 0) - medianWaitingTime.medianClinicianWaitingTime = _getMedian(waitingTime.clinicianWaitingTimes).toFixed(1); - - if (waitingTime.visitCompletionTimes.length > 0) - medianWaitingTime.medianVisitCompletionTime = _getMedian(waitingTime.visitCompletionTimes).toFixed(1); - - return medianWaitingTime; - + var waitingTime = _extractWaitingTime(patientFlowArray); + + var medianWaitingTime = { + medianWaitingTime: '0', + medianVisitCompletionTime: '0', + medianTriageWaitingTime: '0', + medianClinicianWaitingTime: '0' + }; + + if (waitingTime.allWaitingTimes.length > 0) + medianWaitingTime.medianWaitingTime = _getMedian( + waitingTime.allWaitingTimes + ).toFixed(1); + + if (waitingTime.triageWaitingTimes.length > 0) + medianWaitingTime.medianTriageWaitingTime = _getMedian( + waitingTime.triageWaitingTimes + ).toFixed(1); + + if (waitingTime.clinicianWaitingTimes.length > 0) + medianWaitingTime.medianClinicianWaitingTime = _getMedian( + waitingTime.clinicianWaitingTimes + ).toFixed(1); + + if (waitingTime.visitCompletionTimes.length > 0) + medianWaitingTime.medianVisitCompletionTime = _getMedian( + waitingTime.visitCompletionTimes + ).toFixed(1); + + return medianWaitingTime; } function _extractWaitingTime(patientFlowArray) { - var allWaitingTimes = []; - var triageWaitingTimes = []; - var clinicianWaitingTimes = []; - var visitCompletionTimes = []; - - for (var i = 0; i < patientFlowArray.length; i++) { - var patientFlow = patientFlowArray[i]; - if (patientFlow.time_to_be_seen_by_clinician !== null && - patientFlow.time_to_be_seen_by_clinician !== undefined) { - clinicianWaitingTimes.push(patientFlow.time_to_be_seen_by_clinician); - allWaitingTimes.push(patientFlow.time_to_be_seen_by_clinician); - } - if (patientFlow.time_to_be_triaged !== null && - patientFlow.time_to_be_triaged !== undefined) { - triageWaitingTimes.push(patientFlow.time_to_be_triaged); - allWaitingTimes.push(patientFlow.time_to_be_triaged); - } - if (patientFlow.time_to_complete_visit !== null && - patientFlow.time_to_complete_visit !== undefined) { - visitCompletionTimes.push(patientFlow.time_to_complete_visit); - } + var allWaitingTimes = []; + var triageWaitingTimes = []; + var clinicianWaitingTimes = []; + var visitCompletionTimes = []; + + for (var i = 0; i < patientFlowArray.length; i++) { + var patientFlow = patientFlowArray[i]; + if ( + patientFlow.time_to_be_seen_by_clinician !== null && + patientFlow.time_to_be_seen_by_clinician !== undefined + ) { + clinicianWaitingTimes.push(patientFlow.time_to_be_seen_by_clinician); + allWaitingTimes.push(patientFlow.time_to_be_seen_by_clinician); } - return { - allWaitingTimes: allWaitingTimes, - triageWaitingTimes: triageWaitingTimes, - clinicianWaitingTimes: clinicianWaitingTimes, - visitCompletionTimes: visitCompletionTimes - }; + if ( + patientFlow.time_to_be_triaged !== null && + patientFlow.time_to_be_triaged !== undefined + ) { + triageWaitingTimes.push(patientFlow.time_to_be_triaged); + allWaitingTimes.push(patientFlow.time_to_be_triaged); + } + if ( + patientFlow.time_to_complete_visit !== null && + patientFlow.time_to_complete_visit !== undefined + ) { + visitCompletionTimes.push(patientFlow.time_to_complete_visit); + } + } + return { + allWaitingTimes: allWaitingTimes, + triageWaitingTimes: triageWaitingTimes, + clinicianWaitingTimes: clinicianWaitingTimes, + visitCompletionTimes: visitCompletionTimes + }; } function _getMedian(data) { - // extract the .values field and sort the resulting array - var m = data.sort(function (a, b) { - return a - b; - }); - - var middle = Math.floor((m.length - 1) / 2); // NB: operator precedence - if (m.length % 2) { - return m[middle]; - } else { - return (m[middle] + m[middle + 1]) / 2.0; - } + // extract the .values field and sort the resulting array + var m = data.sort(function (a, b) { + return a - b; + }); + + var middle = Math.floor((m.length - 1) / 2); // NB: operator precedence + if (m.length % 2) { + return m[middle]; + } else { + return (m[middle] + m[middle + 1]) / 2.0; + } } - function splitResultsByLocation(patientFlowItemsArray) { - var locations = []; - var finalResultsByLocation = []; - for (var i = 0; i < patientFlowItemsArray.length; i++) { - var res = _.filter(patientFlowItemsArray, function (o) { - return o.locationId === patientFlowItemsArray[i].locationId; - }); - - var locationSplitResults = { - locationName: patientFlowItemsArray[i].location, - locationId: patientFlowItemsArray[i].locationId, - results: res - }; - - locations.push(locationSplitResults); - } - - locations.forEach(function (item) { - var unique = true; - finalResultsByLocation.forEach(function (item2) { - if (_.isEqual(item, item2)) unique = false; - }); - if (unique) finalResultsByLocation.push(item); + var locations = []; + var finalResultsByLocation = []; + for (var i = 0; i < patientFlowItemsArray.length; i++) { + var res = _.filter(patientFlowItemsArray, function (o) { + return o.locationId === patientFlowItemsArray[i].locationId; }); - return finalResultsByLocation; -} + var locationSplitResults = { + locationName: patientFlowItemsArray[i].location, + locationId: patientFlowItemsArray[i].locationId, + results: res + }; -function calculateStatisticsByLocation(resultsSplitByLocationArray) { - var locationsStats = []; - var stats = {}; - _.each(resultsSplitByLocationArray, function (loc) { - stats = _calculateStatsForSingleLocation(loc); - locationsStats.push(stats); + locations.push(locationSplitResults); + } + locations.forEach(function (item) { + var unique = true; + finalResultsByLocation.forEach(function (item2) { + if (_.isEqual(item, item2)) unique = false; }); + if (unique) finalResultsByLocation.push(item); + }); - return locationsStats; + return finalResultsByLocation; } -function calculateHourlyStatistics(resultsSplitByLocationArray) { - var triageCountResults = []; - var registeredCountResults = []; - var seenCountResults = []; - var countPeriod = []; - var combinedCount = []; - - _.each(resultsSplitByLocationArray, function (loc) { - - var triagedHour = loc.triaged ? moment(loc.triaged).format('H') : null; - var registeredHour = loc.registered ? moment(loc.registered).format('H') : null; - var seenHour = loc.seen_by_clinician ? moment(loc.seen_by_clinician).format('H') : null; - - //count hourly entries for triage,seen or registered - countStatByHour(triagedHour, triageCountResults); - countStatByHour(registeredHour, registeredCountResults); - countStatByHour(seenHour, seenCountResults); - - //track time period for either triage,seen or registered - countPeriod[triagedHour] = triagedHour; - countPeriod[registeredHour] = registeredHour; - countPeriod[seenHour] = seenHour; - - }); - - for (var i = 0; i < countPeriod.length; i++) { - var hour = countPeriod[i]; - if (hour) { - combinedCount.push({ - time: hour, - triaged: triageCountResults[hour] ? triageCountResults[hour].count : null, - registered: registeredCountResults[hour] ? registeredCountResults[hour].count : null, - seen: seenCountResults[hour] ? seenCountResults[hour].count : null - }) - } +function calculateStatisticsByLocation(resultsSplitByLocationArray) { + var locationsStats = []; + var stats = {}; + _.each(resultsSplitByLocationArray, function (loc) { + stats = _calculateStatsForSingleLocation(loc); + locationsStats.push(stats); + }); + + return locationsStats; +} +function calculateHourlyStatistics(resultsSplitByLocationArray) { + var triageCountResults = []; + var registeredCountResults = []; + var seenCountResults = []; + var countPeriod = []; + var combinedCount = []; + + _.each(resultsSplitByLocationArray, function (loc) { + var triagedHour = loc.triaged ? moment(loc.triaged).format('H') : null; + var registeredHour = loc.registered + ? moment(loc.registered).format('H') + : null; + var seenHour = loc.seen_by_clinician + ? moment(loc.seen_by_clinician).format('H') + : null; + + //count hourly entries for triage,seen or registered + countStatByHour(triagedHour, triageCountResults); + countStatByHour(registeredHour, registeredCountResults); + countStatByHour(seenHour, seenCountResults); + + //track time period for either triage,seen or registered + countPeriod[triagedHour] = triagedHour; + countPeriod[registeredHour] = registeredHour; + countPeriod[seenHour] = seenHour; + }); + + for (var i = 0; i < countPeriod.length; i++) { + var hour = countPeriod[i]; + if (hour) { + combinedCount.push({ + time: hour, + triaged: triageCountResults[hour] + ? triageCountResults[hour].count + : null, + registered: registeredCountResults[hour] + ? registeredCountResults[hour].count + : null, + seen: seenCountResults[hour] ? seenCountResults[hour].count : null + }); } - return combinedCount; + } + return combinedCount; } function countStatByHour(hour, countResults) { - if (hour) { - if (countResults[hour]) { - countResults[hour] = { count: countResults[hour].count + 1 }; - } else { - countResults[hour] = { count: 1 }; - } + if (hour) { + if (countResults[hour]) { + countResults[hour] = { count: countResults[hour].count + 1 }; + } else { + countResults[hour] = { count: 1 }; } + } } function _calculateStatsForSingleLocation(resultsSplitByLocation) { - var stats = { - locationId: resultsSplitByLocation.locationId, - location: resultsSplitByLocation.locationName, - - }; - - stats.medianWaitingTime = - calculateMedianWaitingTime(resultsSplitByLocation.results); - stats.incompleteVisitsCount = - getIncompleteVisitsCount(resultsSplitByLocation.results); - stats.completeVisitsCount = - getCompleteVisitsCount(resultsSplitByLocation.results); - stats.totalVisitsCount = - getTotalVisitsCount(resultsSplitByLocation.results); - return stats; + var stats = { + locationId: resultsSplitByLocation.locationId, + location: resultsSplitByLocation.locationName + }; + + stats.medianWaitingTime = calculateMedianWaitingTime( + resultsSplitByLocation.results + ); + stats.incompleteVisitsCount = getIncompleteVisitsCount( + resultsSplitByLocation.results + ); + stats.completeVisitsCount = getCompleteVisitsCount( + resultsSplitByLocation.results + ); + stats.totalVisitsCount = getTotalVisitsCount(resultsSplitByLocation.results); + return stats; } function getTotalVisitsCount(patientFlowArray) { + var inCompleteVists = getIncompleteVisitsCount(patientFlowArray); + var completeVists = getCompleteVisitsCount(patientFlowArray); - var inCompleteVists = getIncompleteVisitsCount(patientFlowArray); - var completeVists = getCompleteVisitsCount(patientFlowArray); - - return completeVists + inCompleteVists; + return completeVists + inCompleteVists; } diff --git a/report-post-processors/patient-referral-processor.js b/report-post-processors/patient-referral-processor.js index 48fdbdf33..7efd34217 100755 --- a/report-post-processors/patient-referral-processor.js +++ b/report-post-processors/patient-referral-processor.js @@ -2,150 +2,130 @@ var _ = require('lodash'); var moment = require('moment'); var moduleExport = { - UngroupResults: UngroupResults, - groupResultsByLocation: groupResultsByLocation, - getListOfDistinctStatesFromResult: getListOfDistinctStatesFromResult - + UngroupResults: UngroupResults, + groupResultsByLocation: groupResultsByLocation, + getListOfDistinctStatesFromResult: getListOfDistinctStatesFromResult }; var res; module.exports = moduleExport; - function getListOfLocationIdsFromResult(results) { - var locations = []; - var unique = {}; - for (var i in results) { - if (typeof(unique[results[i].location_id]) == "undefined") { - locations.push(results[i].location_id); - } - unique[results[i].location_id] = 0; + var locations = []; + var unique = {}; + for (var i in results) { + if (typeof unique[results[i].location_id] == 'undefined') { + locations.push(results[i].location_id); } - return locations; + unique[results[i].location_id] = 0; + } + return locations; } function getListOfDistinctStatesFromResult(results) { - var states = []; - var unique = {}; - for (var i in res) { - if (typeof(unique[res[i].state_name]) == "undefined") { - states.push({ - name: res[i].state_name.split(' ').join('_'), - - }); - - } - unique[res[i].state_name.split(' ').join('_')] = 0; + var states = []; + var unique = {}; + for (var i in res) { + if (typeof unique[res[i].state_name] == 'undefined') { + states.push({ + name: res[i].state_name.split(' ').join('_') + }); } + unique[res[i].state_name.split(' ').join('_')] = 0; + } - return states; - + return states; } function getListOfDStatesFromResult(results) { - var st = []; - var unique = {}; - for (var i in results) { - if (typeof(unique[results[i].program_id]) == "undefined") { - st.push(results[i].program_id); - - } - unique[results[i].program_id] = 0; + var st = []; + var unique = {}; + for (var i in results) { + if (typeof unique[results[i].program_id] == 'undefined') { + st.push(results[i].program_id); } - return st; - + unique[results[i].program_id] = 0; + } + return st; } function UngroupResults(results) { - return results; + return results; } function groupResultsByLocation(arrayOfResults) { - var grouped = {}; - _.each(arrayOfResults, (result) => { - grouped[result.location_id] = { - location: result.location, - locationId: result.location_id, - locationUuids: result.locationUuids, - programs: [] - } - }); - - _.each(arrayOfResults, (result) => { - const prog = { - counts: result.counts, - location: result.location, - location_id: result.locationId, - locationUuids: result.locationUuids, - program: result.program, - programUuids: result.programUuids - } - grouped[result.location_id].programs.push(prog); - }); - - var results = []; - for (var e in grouped) { - results.push(grouped[e]); - } - return results; + var grouped = {}; + _.each(arrayOfResults, (result) => { + grouped[result.location_id] = { + location: result.location, + locationId: result.location_id, + locationUuids: result.locationUuids, + programs: [] + }; + }); + + _.each(arrayOfResults, (result) => { + const prog = { + counts: result.counts, + location: result.location, + location_id: result.locationId, + locationUuids: result.locationUuids, + program: result.program, + programUuids: result.programUuids + }; + grouped[result.location_id].programs.push(prog); + }); + + var results = []; + for (var e in grouped) { + results.push(grouped[e]); + } + return results; } - function groupResultsByLocation2(arrayOfResults) { - res = arrayOfResults; - var grouped = {}; - _.each(arrayOfResults, function (result) { - if (_.isEmpty(grouped[result.location_id])) { - grouped[result.location_id] = { - locationUuids: result.locationUuids, - location: result.location, - locationId: result.location_id, - programs: [] - }; - } - var loc = grouped[result.location_id]; - _handlePrograms(result, loc); - }); - var results = []; - for (var e in grouped) { - - results.push(grouped[e]); + res = arrayOfResults; + var grouped = {}; + _.each(arrayOfResults, function (result) { + if (_.isEmpty(grouped[result.location_id])) { + grouped[result.location_id] = { + locationUuids: result.locationUuids, + location: result.location, + locationId: result.location_id, + programs: [] + }; } - - return results; - + var loc = grouped[result.location_id]; + _handlePrograms(result, loc); + }); + var results = []; + for (var e in grouped) { + results.push(grouped[e]); + } + + return results; } function _handlePrograms(result, loc) { - if (!_.isNull(result.program_id)) { - var program = { - locationUuids: result.locationUuids, - location: result.location, - location_id: result.location_id, - program_id: result.program_id, - program: result.program, - programUuids: result.programUuids, - counts:result.counts - }; - var existingProg = _.find(loc.programs, function (prog) { - return result.program_id === prog.program_id - }); - if(existingProg) { - _.merge(existingProg, program); - loc.programs.push( program); - } else { - loc.programs.push(program); - } - loc.programs = _.uniqBy(loc.programs, 'program_id') + if (!_.isNull(result.program_id)) { + var program = { + locationUuids: result.locationUuids, + location: result.location, + location_id: result.location_id, + program_id: result.program_id, + program: result.program, + programUuids: result.programUuids, + counts: result.counts + }; + var existingProg = _.find(loc.programs, function (prog) { + return result.program_id === prog.program_id; + }); + if (existingProg) { + _.merge(existingProg, program); + loc.programs.push(program); + } else { + loc.programs.push(program); } - + loc.programs = _.uniqBy(loc.programs, 'program_id'); + } } - - - - - - - - - diff --git a/reports/DQA/dqa-chart-abstraction-report-dao.js b/reports/DQA/dqa-chart-abstraction-report-dao.js index 997fd76c0..b24ce2836 100644 --- a/reports/DQA/dqa-chart-abstraction-report-dao.js +++ b/reports/DQA/dqa-chart-abstraction-report-dao.js @@ -1,12 +1,12 @@ import QueryService from '../../app/database-access/query.service'; export class DQAChartAbstractionDAO { + constructor() {} - constructor() { } - - getDQAChartAbstractionReport(locations, limit, offset) { - let runner = this.getSqlRunner(); - let sqlQuery = ` + getDQAChartAbstractionReport(locations, limit, offset) { + let runner = this.getSqlRunner(); + let sqlQuery = + ` SELECT uuid, person_id, @@ -72,7 +72,9 @@ export class DQAChartAbstractionDAO { is_clinical_encounter = 1 AND encounter_datetime < NOW() AND encounter_datetime > '2018-01-01' - AND h.location_id IN (` + locations + `) + AND h.location_id IN (` + + locations + + `) ORDER BY encounter_datetime DESC LIMIT 10000000) clinical GROUP BY person_id @@ -90,7 +92,9 @@ export class DQAChartAbstractionDAO { FROM etl.flat_vitals WHERE - location_id IN (` + locations + `) + location_id IN (` + + locations + + `) AND encounter_datetime <= NOW() AND encounter_datetime > '2018-01-01' AND (height IS NOT NULL OR weight IS NOT NULL) @@ -98,22 +102,26 @@ export class DQAChartAbstractionDAO { LIMIT 10000000) vitals GROUP BY v_person_id ORDER BY v_person_id DESC) AS vitals ON (hiv.person_id = vitals.v_person_id) - ORDER BY encounter_datetime desc limit ` + limit + ` offset ` + offset + `; `; - return new Promise((resolve, reject) => { - runner.executeQuery(sqlQuery) - .then((results) => { - resolve({ - results: results - }); - }) - .catch((error) => { - reject(error) - }); + ORDER BY encounter_datetime desc limit ` + + limit + + ` offset ` + + offset + + `; `; + return new Promise((resolve, reject) => { + runner + .executeQuery(sqlQuery) + .then((results) => { + resolve({ + results: results + }); + }) + .catch((error) => { + reject(error); }); - } - - getSqlRunner() { - return new QueryService(); - } + }); + } -} \ No newline at end of file + getSqlRunner() { + return new QueryService(); + } +} diff --git a/reports/DQA/dqa-chart-abstraction-service.js b/reports/DQA/dqa-chart-abstraction-service.js index 1de8305e8..e7bdd16b2 100644 --- a/reports/DQA/dqa-chart-abstraction-service.js +++ b/reports/DQA/dqa-chart-abstraction-service.js @@ -1,26 +1,25 @@ import { DQAChartAbstractionDAO } from './dqa-chart-abstraction-report-dao'; export class DQAChartAbstractionService { + constructor() {} - constructor() { } - - getDQAChartAbstractionReport(locations, limit, offset) { - let dao = this.getDaoClass(); - return new Promise((resolve, reject) => { - return dao.getDQAChartAbstractionReport(locations, limit, offset) - .then((results) => { - resolve({ - results: results - }); - }) - .catch((error) => { - reject(error) - }); + getDQAChartAbstractionReport(locations, limit, offset) { + let dao = this.getDaoClass(); + return new Promise((resolve, reject) => { + return dao + .getDQAChartAbstractionReport(locations, limit, offset) + .then((results) => { + resolve({ + results: results + }); + }) + .catch((error) => { + reject(error); }); - } - - getDaoClass() { - return new DQAChartAbstractionDAO(); - } + }); + } -} \ No newline at end of file + getDaoClass() { + return new DQAChartAbstractionDAO(); + } +} diff --git a/reports/clinic-calander-report-v2.json b/reports/clinic-calander-report-v2.json index 0a6d0afe7..b72af0a2d 100755 --- a/reports/clinic-calander-report-v2.json +++ b/reports/clinic-calander-report-v2.json @@ -1,453 +1,439 @@ [ - { - "name": "attended", - "table": { - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t1" - }, - "joins": [ - { - "joinType": "INNER JOIN", - "schema": "amrs", - "tableName": "visit", - "alias": "t2", - "joinExpression": "t1.visit_id = t2.visit_id" - }, - { - "joinType": "INNER JOIN", - "schema": "etl", - "tableName": "program_visit_map", - "alias": "t3", - "joinExpression": "t2.visit_type_id = t3.visit_type_id" - } - ], - "parameters": [ - { - "name": "groupByAttendedDate", - "defaultValue": [ - { - "label": "attended_date", - "expression": "attended_date" - } - ] - }, - { - "name": "startDate", - "defaultValue": [ - "10-10-2015" - ] - }, - { - "name": "endDate", - "defaultValue": [ - "defaultValue" - ] - }, - { - "name": "locationUuids", - "defaultValue": [] - }, - { - "name": "encounterIds", - "defaultValue": -1 - }, - { - "name": "visitTypeIds", - "defaultValue": -1 - }, - { - "name": "programTypeIds", - "defaultValue": -1 - } - ], - "filters": [ - { - "expression": "date(t1.encounter_datetime) >= ?", - "parameter": "startDate" - }, - { - "expression": "date(t1.encounter_datetime) <= ?", - "parameter": "endDate" - }, - { - "expression": "t1.location_uuid in (?) ", - "parameter": "locationUuids" - }, - { - "expression": "t1.encounter_type in ? ", - "parameter": "encounterIds" - }, - { - "expression": "t3.visit_type_id in ?", - "parameter": "visitTypeIds" - }, - { - "expression": "t3.program_type_id in ?", - "parameter": "programTypeIds" - }, - { - "expression": "coalesce(t1.death_date) is null", - "processForce": true, - "parameter": "" - }, - { - "expression": "t1.encounter_type not in (21,99999)", - "processForce": true - } - ], - "groupClause": [ - { - "parameter": "groupByAttendedDate" - }, - { - "parameter": "groupByw" - } - ], - "indicators": [], - "supplementColumns": [ - { - "label": "attended_date", - "type": "single", - "sql": "date(t1.encounter_datetime)" - }, - { - "label": "attended", - "type": "single", - "sql": "count(distinct person_id)" - } + { + "name": "attended", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "visit", + "alias": "t2", + "joinExpression": "t1.visit_id = t2.visit_id" + }, + { + "joinType": "INNER JOIN", + "schema": "etl", + "tableName": "program_visit_map", + "alias": "t3", + "joinExpression": "t2.visit_type_id = t3.visit_type_id" + } + ], + "parameters": [ + { + "name": "groupByAttendedDate", + "defaultValue": [ + { + "label": "attended_date", + "expression": "attended_date" + } ] + }, + { + "name": "startDate", + "defaultValue": ["10-10-2015"] + }, + { + "name": "endDate", + "defaultValue": ["defaultValue"] + }, + { + "name": "locationUuids", + "defaultValue": [] + }, + { + "name": "encounterIds", + "defaultValue": -1 + }, + { + "name": "visitTypeIds", + "defaultValue": -1 + }, + { + "name": "programTypeIds", + "defaultValue": -1 + } + ], + "filters": [ + { + "expression": "date(t1.encounter_datetime) >= ?", + "parameter": "startDate" + }, + { + "expression": "date(t1.encounter_datetime) <= ?", + "parameter": "endDate" + }, + { + "expression": "t1.location_uuid in (?) ", + "parameter": "locationUuids" + }, + { + "expression": "t1.encounter_type in ? ", + "parameter": "encounterIds" + }, + { + "expression": "t3.visit_type_id in ?", + "parameter": "visitTypeIds" + }, + { + "expression": "t3.program_type_id in ?", + "parameter": "programTypeIds" + }, + { + "expression": "coalesce(t1.death_date) is null", + "processForce": true, + "parameter": "" + }, + { + "expression": "t1.encounter_type not in (21,99999)", + "processForce": true + } + ], + "groupClause": [ + { + "parameter": "groupByAttendedDate" + }, + { + "parameter": "groupByw" + } + ], + "indicators": [], + "supplementColumns": [ + { + "label": "attended_date", + "type": "single", + "sql": "date(t1.encounter_datetime)" + }, + { + "label": "attended", + "type": "single", + "sql": "count(distinct person_id)" + } + ] + }, + { + "name": "has-not-returned-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" }, - { - "name": "has-not-returned-report", - "table": { - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t1" - }, - "joins": [ - { - "joinType": "INNER JOIN", - "schema": "", - "alias": "t7", - "joinExpression": "t1.person_id = t7.person_id", - "dynamicDataset": "has-not-returned-cohort" - }, - { - "joinType": "LEFT OUTER JOIN", - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t8", - "joinExpression": "(t1.person_id = t8.person_id AND t8.encounter_type = 116 AND t1.encounter_datetime < t8.encounter_datetime)" - }, - { - "joinType": "INNER JOIN", - "schema": "amrs", - "tableName": "visit", - "alias": "t2", - "joinExpression": "t1.visit_id = t2.visit_id" - }, - { - "joinType": "INNER JOIN", - "schema": "etl", - "tableName": "program_visit_map", - "alias": "t3", - "joinExpression": "t2.visit_type_id = t3.visit_type_id" - } - ], - "parameters": [ - { - "name": "startDate", - "defaultValue": [ - "10-10-2015" - ] - }, - { - "name": "endDate", - "defaultValue": [ - "30-10-2015" - ] - }, - { - "name": "locationUuids", - "defaultValue": [] - }, - { - "name": "encounterIds", - "defaultValue": -1 - }, - { - "name": "visitTypeIds", - "defaultValue": -1 - }, - { - "name": "programTypeIds", - "defaultValue": -1 - }, - { - "name": "groupByDate", - "defaultValue": [ - { - "label": "d", - "expression": "d" - } - ] - } - ], - "filters": [ - { - "expression": "t1.rtc_date >= ?", - "parameter": "startDate" - }, - { - "expression": "t1.rtc_date <= ?", - "parameter": "endDate" - }, - { - "expression": "t1.encounter_type in ?", - "parameter": "encounterIds" - }, - { - "expression": "t3.visit_type_id in ?", - "parameter": "visitTypeIds" - }, - { - "expression": "t3.program_type_id in ?", - "parameter": "programTypeIds" - }, - { - "expression": "t1.location_uuid in (?)", - "parameter": "locationUuids" - }, - { - "expression": "coalesce(t1.transfer_out) is null", - "processForce": true - }, - { - "expression": "coalesce(t1.death_date) is null", - "processForce": true - }, - { - "expression": "t1.next_clinical_datetime_hiv IS NULL", - "processForce": true - }, - { - "expression": "t1.encounter_type != 110", - "processForce": true - }, - { - "expression": "DATE(max_rtc_date) < DATE(NOW())", - "processForce": true - }, - { - "expression": "t1.rtc_date = max_rtc_date", - "processForce": true - } - ], - "groupClause": [ - { - "parameter": "groupByDate", - "processForce": true - } - ], - "indicators": [ - { - "label": "has_not_returned", - "expression": "has_not_returned", - "sql": "count(distinct if($expression, t1.person_id, null))" - } - ], - "supplementColumns": [ - { - "label": "d", - "type": "single", - "sql": "date_format(t1.rtc_date,'%Y-%m-%d')" - } + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "", + "alias": "t7", + "joinExpression": "t1.person_id = t7.person_id", + "dynamicDataset": "has-not-returned-cohort" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t8", + "joinExpression": "(t1.person_id = t8.person_id AND t8.encounter_type = 116 AND t1.encounter_datetime < t8.encounter_datetime)" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "visit", + "alias": "t2", + "joinExpression": "t1.visit_id = t2.visit_id" + }, + { + "joinType": "INNER JOIN", + "schema": "etl", + "tableName": "program_visit_map", + "alias": "t3", + "joinExpression": "t2.visit_type_id = t3.visit_type_id" + } + ], + "parameters": [ + { + "name": "startDate", + "defaultValue": ["10-10-2015"] + }, + { + "name": "endDate", + "defaultValue": ["30-10-2015"] + }, + { + "name": "locationUuids", + "defaultValue": [] + }, + { + "name": "encounterIds", + "defaultValue": -1 + }, + { + "name": "visitTypeIds", + "defaultValue": -1 + }, + { + "name": "programTypeIds", + "defaultValue": -1 + }, + { + "name": "groupByDate", + "defaultValue": [ + { + "label": "d", + "expression": "d" + } ] + } + ], + "filters": [ + { + "expression": "t1.rtc_date >= ?", + "parameter": "startDate" + }, + { + "expression": "t1.rtc_date <= ?", + "parameter": "endDate" + }, + { + "expression": "t1.encounter_type in ?", + "parameter": "encounterIds" + }, + { + "expression": "t3.visit_type_id in ?", + "parameter": "visitTypeIds" + }, + { + "expression": "t3.program_type_id in ?", + "parameter": "programTypeIds" + }, + { + "expression": "t1.location_uuid in (?)", + "parameter": "locationUuids" + }, + { + "expression": "coalesce(t1.transfer_out) is null", + "processForce": true + }, + { + "expression": "coalesce(t1.death_date) is null", + "processForce": true + }, + { + "expression": "t1.next_clinical_datetime_hiv IS NULL", + "processForce": true + }, + { + "expression": "t1.encounter_type != 110", + "processForce": true + }, + { + "expression": "DATE(max_rtc_date) < DATE(NOW())", + "processForce": true + }, + { + "expression": "t1.rtc_date = max_rtc_date", + "processForce": true + } + ], + "groupClause": [ + { + "parameter": "groupByDate", + "processForce": true + } + ], + "indicators": [ + { + "label": "has_not_returned", + "expression": "has_not_returned", + "sql": "count(distinct if($expression, t1.person_id, null))" + } + ], + "supplementColumns": [ + { + "label": "d", + "type": "single", + "sql": "date_format(t1.rtc_date,'%Y-%m-%d')" + } + ] + }, + { + "name": "has-not-returned-cohort", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t2" }, - { - "name": "has-not-returned-cohort", - "table": { - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t2" - }, - "joins": [], - "parameters": [ - { - "name": "startDate", - "defaultValue": [ - "10-10-2015" - ] - }, - { - "name": "locationUuids", - "defaultValue": [] - }, - { - "name": "groupByPerson", - "defaultValue": [ - { - "label": "person_id", - "expression": "person_id" - } - ] - } - ], - "filters": [ - { - "expression": "t2.rtc_date >= ?", - "parameter": "startDate" - }, - { - "expression": "t2.location_uuid in (?)", - "parameter": "locationUuids" - } - ], - "groupClause": [ - { - "parameter": "groupByPerson" - } - ], - "indicators": [], - "supplementColumns": [ - { - "label": "person_id", - "type": "single", - "sql": "person_id" - }, - { - "label": "max_rtc_date", - "type": "single", - "sql": "MAX(rtc_date)" - } + "joins": [], + "parameters": [ + { + "name": "startDate", + "defaultValue": ["10-10-2015"] + }, + { + "name": "locationUuids", + "defaultValue": [] + }, + { + "name": "groupByPerson", + "defaultValue": [ + { + "label": "person_id", + "expression": "person_id" + } ] + } + ], + "filters": [ + { + "expression": "t2.rtc_date >= ?", + "parameter": "startDate" + }, + { + "expression": "t2.location_uuid in (?)", + "parameter": "locationUuids" + } + ], + "groupClause": [ + { + "parameter": "groupByPerson" + } + ], + "indicators": [], + "supplementColumns": [ + { + "label": "person_id", + "type": "single", + "sql": "person_id" + }, + { + "label": "max_rtc_date", + "type": "single", + "sql": "MAX(rtc_date)" + } + ] + }, + { + "name": "scheduled", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" }, - { - "name": "scheduled", - "table": { - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t1" - }, - "joins": [ - { - "joinType": "INNER JOIN", - "schema": "amrs", - "tableName": "visit", - "alias": "t2", - "joinExpression": "t1.visit_id = t2.visit_id" - }, - { - "joinType": "INNER JOIN", - "schema": "etl", - "tableName": "program_visit_map", - "alias": "t3", - "joinExpression": "t2.visit_type_id = t3.visit_type_id" - } - ], - "parameters": [ - { - "name": "groupByRtcDate", - "defaultValue": [ - { - "label": "scheduled_date", - "expression": "scheduled_date" - } - ] - }, - { - "name": "startDate", - "defaultValue": [ - "10-10-2015" - ] - }, - { - "name": "endDate", - "defaultValue": [ - "30-10-2015" - ] - }, - { - "name": "locationUuids", - "defaultValue": [] - }, - { - "name": "encounterIds", - "defaultValue": -1 - }, - { - "name": "visitTypeIds", - "defaultValue": -1 - }, - { - "name": "programTypeIds", - "defaultValue": -1 - } - ], - "filters": [ - { - "expression": "date(t1.rtc_date) >= ?", - "parameter": "startDate" - }, - { - "expression": "date(t1.rtc_date) <= ?", - "parameter": "endDate" - }, - { - "expression": "t1.location_uuid in (?)", - "parameter": "locationUuids" - }, - { - "expression": "t1.encounter_type in ?", - "parameter": "encounterIds" - }, - { - "expression": "t3.visit_type_id in ?", - "parameter": "visitTypeIds" - }, - { - "expression": "t3.program_type_id in ?", - "parameter": "programTypeIds" - }, - { - "expression": "coalesce(t1.transfer_out) is null", - "processForce": true - }, - { - "expression": "coalesce(t1.death_date) is null", - "processForce": true - }, - { - "expression": "t1.encounter_type not in (99999)", - "processForce": true - } - ], - "groupClause": [ - { - "parameter": "groupByRtcDate" - }, - { - "parameter": "groupByw" - } - ], - "indicators": [], - "supplementColumns": [ - { - "label": "scheduled_date", - "type": "single", - "sql": "date_format(t1.rtc_date,'%Y-%m-%d')" - }, - { - "label": "scheduled", - "type": "single", - "sql": "count(distinct t1.person_id)" - }, - { - "label": "followed_up_by_outreach", - "type": "single", - "sql": "if(next_encounter_type_hiv =21, 1,0)" - } + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "visit", + "alias": "t2", + "joinExpression": "t1.visit_id = t2.visit_id" + }, + { + "joinType": "INNER JOIN", + "schema": "etl", + "tableName": "program_visit_map", + "alias": "t3", + "joinExpression": "t2.visit_type_id = t3.visit_type_id" + } + ], + "parameters": [ + { + "name": "groupByRtcDate", + "defaultValue": [ + { + "label": "scheduled_date", + "expression": "scheduled_date" + } ] - } -] \ No newline at end of file + }, + { + "name": "startDate", + "defaultValue": ["10-10-2015"] + }, + { + "name": "endDate", + "defaultValue": ["30-10-2015"] + }, + { + "name": "locationUuids", + "defaultValue": [] + }, + { + "name": "encounterIds", + "defaultValue": -1 + }, + { + "name": "visitTypeIds", + "defaultValue": -1 + }, + { + "name": "programTypeIds", + "defaultValue": -1 + } + ], + "filters": [ + { + "expression": "date(t1.rtc_date) >= ?", + "parameter": "startDate" + }, + { + "expression": "date(t1.rtc_date) <= ?", + "parameter": "endDate" + }, + { + "expression": "t1.location_uuid in (?)", + "parameter": "locationUuids" + }, + { + "expression": "t1.encounter_type in ?", + "parameter": "encounterIds" + }, + { + "expression": "t3.visit_type_id in ?", + "parameter": "visitTypeIds" + }, + { + "expression": "t3.program_type_id in ?", + "parameter": "programTypeIds" + }, + { + "expression": "coalesce(t1.transfer_out) is null", + "processForce": true + }, + { + "expression": "coalesce(t1.death_date) is null", + "processForce": true + }, + { + "expression": "t1.encounter_type not in (99999)", + "processForce": true + } + ], + "groupClause": [ + { + "parameter": "groupByRtcDate" + }, + { + "parameter": "groupByw" + } + ], + "indicators": [], + "supplementColumns": [ + { + "label": "scheduled_date", + "type": "single", + "sql": "date_format(t1.rtc_date,'%Y-%m-%d')" + }, + { + "label": "scheduled", + "type": "single", + "sql": "count(distinct t1.person_id)" + }, + { + "label": "followed_up_by_outreach", + "type": "single", + "sql": "if(next_encounter_type_hiv =21, 1,0)" + } + ] + } +] diff --git a/reports/clinic-calander.report.json b/reports/clinic-calander.report.json index 68873f493..565cbc1ba 100755 --- a/reports/clinic-calander.report.json +++ b/reports/clinic-calander.report.json @@ -1,242 +1,268 @@ - [{ - "name": "attended", - "table":{"schema":"","tableName":"","alias":"t1","dynamicDataset":"attended-data-table"}, - "joins":[ - ], - "parameters": [ - {"name":"groupByd", "defaultValue":[ - {"label":"d","expression":"d"} - ] - }, - {"name":"groupByw", "defaultValue":[ - {"label":"w","expression":"w"} - ] +[ + { + "name": "attended", + "table": { + "schema": "", + "tableName": "", + "alias": "t1", + "dynamicDataset": "attended-data-table" + }, + "joins": [], + "parameters": [ + { + "name": "groupByd", + "defaultValue": [{ "label": "d", "expression": "d" }] + }, + { + "name": "groupByw", + "defaultValue": [{ "label": "w", "expression": "w" }] + } + ], + "filters": [], + "groupClause": [{ "parameter": "groupByd" }, { "parameter": "groupByw" }], + "indicators": [ + { + "label": "attended", + "expression": "attended", + "sql": "count(if(attended,1,0))" + } + ], + "supplementColumns": [ + { + "label": "d", + "type": "single", + "sql": "t1.d" + }, + { + "label": "w", + "type": "single", + "sql": "t1.w" } - ], - "filters": [ - ], - "groupClause":[ - {"parameter":"groupByd"}, - {"parameter":"groupByw"} - ], - "indicators": [ - { - "label":"attended", - "expression":"attended", - "sql":"count(if(attended,1,0))" - } - ], - "supplementColumns":[ - { - "label":"d", - "type":"single", - "sql":"t1.d" - }, - { - "label":"w", - "type":"single", - "sql":"t1.w" - } - ] - }, - { - "name": "attended-data-table", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"etl","tableName":"derived_encounter","alias":"t2","joinExpression":"t1.encounter_id = t2.encounter_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"groupByPerson", "defaultValue":[ - {"label":"person_id","expression":"t1.person_id"} - ]}, - {"name":"groupByEncounter", "defaultValue":[ - {"label":"encounter_date","expression":"date(t1.encounter_datetime)"} - ]} - ], - "filters": [ - {"expression":"t1.encounter_datetime >= ?", "parameter":"startDate"}, - {"expression":"t1.encounter_datetime <= ?", "parameter":"endDate"}, - {"expression":"t1.location_uuid = (?)", "parameter":"locationUuids"} - ], - "groupClause":[ - {"parameter":"groupByPerson"}, - {"parameter":"groupByEncounter"} - ], - "indicators": [ - ], - "supplementColumns":[ - { - "label":"encounter_id", - "type":"single", - "sql":"t1.encounter_id" - }, - { - "label":"d", - "type":"single", - "sql":"date(encounter_datetime)" - }, - { - "label":"w", - "type":"single", - "sql":"date_format(encounter_datetime,'%W')" - }, - { - "label":"attended", - "type":"single", - "sql":"1" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, + ] + }, + { + "name": "attended-data-table", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "etl", + "tableName": "derived_encounter", + "alias": "t2", + "joinExpression": "t1.encounter_id = t2.encounter_id" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locationUuids", "defaultValue": [] }, + { + "name": "groupByPerson", + "defaultValue": [{ "label": "person_id", "expression": "t1.person_id" }] + }, + { + "name": "groupByEncounter", + "defaultValue": [ { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" + "label": "encounter_date", + "expression": "date(t1.encounter_datetime)" } - ] - }, - { - "name": "appointments", - "table":{"schema":"","tableName":"","alias":"t1","dynamicDataset":"appointments-data-table"}, - "joins":[ - ], - "parameters": [ - {"name":"groupByd", "defaultValue":[ - {"label":"d","expression":"d"} - ] - }, - {"name":"groupByw", "defaultValue":[ - {"label":"w","expression":"w"} - ] + ] + } + ], + "filters": [ + { "expression": "t1.encounter_datetime >= ?", "parameter": "startDate" }, + { "expression": "t1.encounter_datetime <= ?", "parameter": "endDate" }, + { "expression": "t1.location_uuid = (?)", "parameter": "locationUuids" } + ], + "groupClause": [ + { "parameter": "groupByPerson" }, + { "parameter": "groupByEncounter" } + ], + "indicators": [], + "supplementColumns": [ + { + "label": "encounter_id", + "type": "single", + "sql": "t1.encounter_id" + }, + { + "label": "d", + "type": "single", + "sql": "date(encounter_datetime)" + }, + { + "label": "w", + "type": "single", + "sql": "date_format(encounter_datetime,'%W')" + }, + { + "label": "attended", + "type": "single", + "sql": "1" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" } - ], - "filters": [ - ], - "groupClause":[ - {"parameter":"groupByd"}, - {"parameter":"groupByw"} - ], - "indicators": [ - { - "label":"scheduled", - "expression":"scheduled", - "sql":"count(scheduled)" + ] + }, + { + "name": "appointments", + "table": { + "schema": "", + "tableName": "", + "alias": "t1", + "dynamicDataset": "appointments-data-table" }, - { - "label":"defaulted", - "expression":"defaulted", - "sql":"count(defaulted)" + "joins": [], + "parameters": [ + { + "name": "groupByd", + "defaultValue": [{ "label": "d", "expression": "d" }] + }, + { + "name": "groupByw", + "defaultValue": [{ "label": "w", "expression": "w" }] + } + ], + "filters": [], + "groupClause": [{ "parameter": "groupByd" }, { "parameter": "groupByw" }], + "indicators": [ + { + "label": "scheduled", + "expression": "scheduled", + "sql": "count(scheduled)" + }, + { + "label": "defaulted", + "expression": "defaulted", + "sql": "count(defaulted)" + }, + { + "label": "has_not_returned", + "expression": "has_not_returned", + "sql": "count(has_not_returned)" + } + ], + "supplementColumns": [ + { + "label": "d", + "type": "single", + "sql": "t1.d" + }, + { + "label": "w", + "type": "single", + "sql": "t1.w" + } + ] + }, + { + "name": "appointments-data-table", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" }, - { - "label":"has_not_returned", - "expression":"has_not_returned", - "sql":"count(has_not_returned)" - } - ], - "supplementColumns":[ - { - "label":"d", - "type":"single", - "sql":"t1.d" - }, - { - "label":"w", - "type":"single", - "sql":"t1.w" - } - ] - } - , - { - "name": "appointments-data-table", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"etl","tableName":"derived_encounter","alias":"t2","joinExpression":"t1.encounter_id = t2.encounter_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"groupByPerson", "defaultValue":[ - {"label":"person_id","expression":"t1.person_id"} - ]}, - {"name":"groupByRtc", "defaultValue":[ - {"label":"rtc_date","expression":"t1.rtc_date"} - ]} - ], - "filters": [ - {"expression":"t1.rtc_date >= ?", "parameter":"startDate"}, - {"expression":"t1.rtc_date <= ?", "parameter":"endDate"}, - {"expression":"t1.location_uuid = ?", "parameter":"locationUuids"} - ], - "groupClause":[ -{"parameter":"groupByPerson"}, -{"parameter":"groupByRtc"} - ], - "indicators": [ - ], - "supplementColumns":[ - { - "label":"encounter_id", - "type":"single", - "sql":"t1.encounter_id" - }, - { - "label":"d", - "type":"single", - "sql":"date(rtc_date)" - }, - { - "label":"w", - "type":"single", - "sql":"date_format(rtc_date,'%W')" - }, - { - "label":"scheduled", - "type":"single", - "sql":"1" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"patient_id", - "type":"single", - "sql":"t1.person_id" - }, - { - "label":"scheduled_and_attended", - "type":"single", - "sql":"if(timestampdiff(day,rtc_date,next_clinic_datetime) between -7 and 7,1,null)" - }, - { - "label":"defaulted", - "type":"single", - "sql":"if(death_date is null and transfer_out is null and timestampdiff(day,rtc_date,if(next_encounter_datetime,next_encounter_datetime,'')) > 90,1,null) " - }, - { - "label":"has_not_returned", - "type":"single", - "sql":"if(death_date is null and transfer_out is null and next_clinic_datetime is null,1,null)" - }, - { - "label":"followed_up_by_outreach", - "type":"single", - "sql":"if(next_encounter_type =21, 1,0)" - } - ] - } - - ] + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "etl", + "tableName": "derived_encounter", + "alias": "t2", + "joinExpression": "t1.encounter_id = t2.encounter_id" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locationUuids", "defaultValue": [] }, + { + "name": "groupByPerson", + "defaultValue": [{ "label": "person_id", "expression": "t1.person_id" }] + }, + { + "name": "groupByRtc", + "defaultValue": [{ "label": "rtc_date", "expression": "t1.rtc_date" }] + } + ], + "filters": [ + { "expression": "t1.rtc_date >= ?", "parameter": "startDate" }, + { "expression": "t1.rtc_date <= ?", "parameter": "endDate" }, + { "expression": "t1.location_uuid = ?", "parameter": "locationUuids" } + ], + "groupClause": [ + { "parameter": "groupByPerson" }, + { "parameter": "groupByRtc" } + ], + "indicators": [], + "supplementColumns": [ + { + "label": "encounter_id", + "type": "single", + "sql": "t1.encounter_id" + }, + { + "label": "d", + "type": "single", + "sql": "date(rtc_date)" + }, + { + "label": "w", + "type": "single", + "sql": "date_format(rtc_date,'%W')" + }, + { + "label": "scheduled", + "type": "single", + "sql": "1" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "patient_id", + "type": "single", + "sql": "t1.person_id" + }, + { + "label": "scheduled_and_attended", + "type": "single", + "sql": "if(timestampdiff(day,rtc_date,next_clinic_datetime) between -7 and 7,1,null)" + }, + { + "label": "defaulted", + "type": "single", + "sql": "if(death_date is null and transfer_out is null and timestampdiff(day,rtc_date,if(next_encounter_datetime,next_encounter_datetime,'')) > 90,1,null) " + }, + { + "label": "has_not_returned", + "type": "single", + "sql": "if(death_date is null and transfer_out is null and next_clinic_datetime is null,1,null)" + }, + { + "label": "followed_up_by_outreach", + "type": "single", + "sql": "if(next_encounter_type =21, 1,0)" + } + ] + } +] diff --git a/reports/clinic-comparator-report.json b/reports/clinic-comparator-report.json index a34fbc0dc..9981fe3e6 100755 --- a/reports/clinic-comparator-report.json +++ b/reports/clinic-comparator-report.json @@ -1,295 +1,319 @@ [ - { - "name": "clinic-comparator-report", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t3", - "joinExpression":"t1.location_uuid = t3.uuid"}, - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t4","joinExpression":"t1.person_id = t4.person_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["01-01-1980"]}, - {"name":"endDate", "defaultValue":["Now()"]}, - {"name":"startAge", "defaultValue":[]}, - {"name":"endAge", "defaultValue":[]}, - {"name":"gender", "defaultValue":[]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"location"} - ] - }, - {"name":"groupByYear", "defaultValue":[ - {"label":"encounter_datetime","expression":"YEAR(encounter_datetime)"} - ] - }, - {"name":"groupByMonth", "defaultValue":[ - {"label":"encounter_datetime","expression":"MONTH(encounter_datetime)"} - ] - } - ], - "filters": [ - {"expression":"t1.encounter_datetime >= ?", "parameter":"startDate"}, - {"expression":"t1.encounter_datetime <= ?", "parameter":"endDate"}, - {"expression":"t1.location_uuid in ?", "parameter":"locationUuids"}, - {"expression":"round(datediff(t1.encounter_datetime,t4.birthdate)/365) >= ?", "parameter":"startAge"}, - {"expression":"round(datediff(t1.encounter_datetime,t4.birthdate)/365) <= ?", "parameter":"endAge"}, - {"expression":"t4.gender in ?", "parameter":"gender"}, - {"expression":"t1.is_clinical_encounter = 1", "processForce":true}, - {"expression":"coalesce(t1.death_date, out_of_care) is null", "processForce":true}, - {"expression":"(t1.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= ?)","parameter":"startDate"} - - - ], - "groupClause":[ - {"parameter":"groupByYear"}, - {"parameter":"groupByMonth"}, - {"parameter":"groupByLocation"} - ], - "indicators": [ - { - "label":"patients", - "expression":"patients", - "sql":"count(distinct t1.person_id)" - }, - { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"on_arvs_first_line", - "expression":"on_arvs_first_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_second_line", - "expression":"on_arvs_second_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_third_line", - "expression":"on_arvs_third_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_past_year", - "expression":"vl_done_past_year", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"no_vl_done_past_year", - "expression":"no_vl_done_past_year", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_second_line_not_suppressed", - "expression":"on_second_line_not_suppressed", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"not_on_arvs_cd4_lte_500", - "expression":"not_on_arvs_cd4_lte_500", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_past_year_lte_1000", - "expression":"vl_done_past_year_lte_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_past_year_gt_1000", - "expression":"vl_done_past_year_gt_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_this_encounter", - "expression":"vl_done_this_encounter", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_this_encounter_lte_1000", - "expression":"vl_done_this_encounter_lte_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_this_encounter_gt_1000", - "expression":"vl_done_this_encounter_gt_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_ordered", - "expression":"vl_ordered", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pending_vl_order", - "expression":"pending_vl_order", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pending_vl_order_no_result_after_4_weeks", - "expression":"pending_vl_order_no_result_after_4_weeks", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_26_weeks", - "expression":"on_arvs_lte_26_weeks", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_52_weeks", - "expression":"on_arvs_lte_52_weeks", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_52_weeks_and_have_vl", - "expression":"on_arvs_lte_52_weeks_and_have_vl", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expression":"on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pregnant", - "expression":"pregnant", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pregnant_and_on_arvs", - "expression":"pregnant_and_on_arvs", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"newly_enrolled", - "expression":"newly_enrolled", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"enrolled_in_care_total", - "expression":"enrolled_in_care_total", - "sql": "count(distinct if($expression,t1.person_id,0))" - - }, - { - "label":"virally_suppressed", - "expression":"virally_suppressed", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"virally_suppressed_in_past_year", - "expression":"virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,t1.person_id,0))" - - }, - { - "label":"viral_load_resulted_in_past_year", - "expression":"viral_load_resulted_in_past_year", - "sql": "count(distinct if($expression,t1.person_id,0))" - - }, - { - "label":"not_virally_suppressed_in_past_year", - "expression":"not_virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,t1.person_id,0))" - - }, - { - "label":"perc_virally_suppressed_in_past_year", - "expression":"perc_virally_suppressed_in_past_year", - "sql":"[virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" - }, - { - "label":"perc_not_virally_suppressed_in_past_year", - "expression":"perc_not_virally_suppressed_in_past_year", - "sql":"[not_virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" - }, - { - "label":"perc_on_arvs", - "expression":"perc_on_arvs", - "sql":"[on_arvs]/[patients]" - }, - { - "label":"perc_on_arv_first_line", - "expression":"perc_on_arv_first_line", - "sql":"[on_arvs_first_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_second_line", - "expression":"perc_on_arv_second_line", - "sql":"[on_arvs_second_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_third_line", - "expression":"perc_on_arv_third_line", - "sql":"[on_arvs_third_line]/[on_arvs]" - }, - { - "label":"perc_with_pending_viral_load", - "expression":"perc_with_pending_viral_load", - "sql":"[pending_vl_order]/[on_arvs]" - }, - { - "label":"perc_on_arvs_lte_6_months", - "expression":"perc_on_arvs_lte_6_months", - "sql":"[on_arvs_lte_26_weeks]/[on_arvs]" - }, - { - "label":"on_arvs_gt_26_weeks", - "expression":"on_arvs_gt_26_weeks", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"perc_on_arvs_gt_6_months", - "expression":"perc_on_arvs_gt_6_months", - "sql":"[on_arvs_gt_26_weeks]/[patients]" - } - - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t3.name" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"encounter_datetime", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"month", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"reporting_month", - "type":"single", - "sql":"date_format(t1.encounter_datetime, '%m/%Y')" - } - - ], - "indicatorHandlers": [ - { - "processor": "processClinicalComparator", - "indicators": [] - - - - - } + { + "name": "clinic-comparator-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t3", + "joinExpression": "t1.location_uuid = t3.uuid" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t4", + "joinExpression": "t1.person_id = t4.person_id" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["01-01-1980"] }, + { "name": "endDate", "defaultValue": ["Now()"] }, + { "name": "startAge", "defaultValue": [] }, + { "name": "endAge", "defaultValue": [] }, + { "name": "gender", "defaultValue": [] }, + { "name": "locationUuids", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [{ "label": "location", "expression": "location" }] + }, + { + "name": "groupByYear", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "YEAR(encounter_datetime)" + } ] - } + }, + { + "name": "groupByMonth", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "MONTH(encounter_datetime)" + } + ] + } + ], + "filters": [ + { "expression": "t1.encounter_datetime >= ?", "parameter": "startDate" }, + { "expression": "t1.encounter_datetime <= ?", "parameter": "endDate" }, + { "expression": "t1.location_uuid in ?", "parameter": "locationUuids" }, + { + "expression": "round(datediff(t1.encounter_datetime,t4.birthdate)/365) >= ?", + "parameter": "startAge" + }, + { + "expression": "round(datediff(t1.encounter_datetime,t4.birthdate)/365) <= ?", + "parameter": "endAge" + }, + { "expression": "t4.gender in ?", "parameter": "gender" }, + { "expression": "t1.is_clinical_encounter = 1", "processForce": true }, + { + "expression": "coalesce(t1.death_date, out_of_care) is null", + "processForce": true + }, + { + "expression": "(t1.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= ?)", + "parameter": "startDate" + } + ], + "groupClause": [ + { "parameter": "groupByYear" }, + { "parameter": "groupByMonth" }, + { "parameter": "groupByLocation" } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct t1.person_id)" + }, + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_first_line", + "expression": "on_arvs_first_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_second_line", + "expression": "on_arvs_second_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_third_line", + "expression": "on_arvs_third_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year", + "expression": "vl_done_past_year", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "no_vl_done_past_year", + "expression": "no_vl_done_past_year", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_second_line_not_suppressed", + "expression": "on_second_line_not_suppressed", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "not_on_arvs_cd4_lte_500", + "expression": "not_on_arvs_cd4_lte_500", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year_lte_1000", + "expression": "vl_done_past_year_lte_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year_gt_1000", + "expression": "vl_done_past_year_gt_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_this_encounter", + "expression": "vl_done_this_encounter", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_this_encounter_lte_1000", + "expression": "vl_done_this_encounter_lte_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_this_encounter_gt_1000", + "expression": "vl_done_this_encounter_gt_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_ordered", + "expression": "vl_ordered", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pending_vl_order", + "expression": "pending_vl_order", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pending_vl_order_no_result_after_4_weeks", + "expression": "pending_vl_order_no_result_after_4_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_52_weeks", + "expression": "on_arvs_lte_52_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_52_weeks_and_have_vl", + "expression": "on_arvs_lte_52_weeks_and_have_vl", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expression": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pregnant", + "expression": "pregnant", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pregnant_and_on_arvs", + "expression": "pregnant_and_on_arvs", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "newly_enrolled", + "expression": "newly_enrolled", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "enrolled_in_care_total", + "expression": "enrolled_in_care_total", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "virally_suppressed", + "expression": "virally_suppressed", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "virally_suppressed_in_past_year", + "expression": "virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "viral_load_resulted_in_past_year", + "expression": "viral_load_resulted_in_past_year", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "not_virally_suppressed_in_past_year", + "expression": "not_virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "perc_virally_suppressed_in_past_year", + "expression": "perc_virally_suppressed_in_past_year", + "sql": "[virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" + }, + { + "label": "perc_not_virally_suppressed_in_past_year", + "expression": "perc_not_virally_suppressed_in_past_year", + "sql": "[not_virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" + }, + { + "label": "perc_on_arvs", + "expression": "perc_on_arvs", + "sql": "[on_arvs]/[patients]" + }, + { + "label": "perc_on_arv_first_line", + "expression": "perc_on_arv_first_line", + "sql": "[on_arvs_first_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_second_line", + "expression": "perc_on_arv_second_line", + "sql": "[on_arvs_second_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_third_line", + "expression": "perc_on_arv_third_line", + "sql": "[on_arvs_third_line]/[on_arvs]" + }, + { + "label": "perc_with_pending_viral_load", + "expression": "perc_with_pending_viral_load", + "sql": "[pending_vl_order]/[on_arvs]" + }, + { + "label": "perc_on_arvs_lte_6_months", + "expression": "perc_on_arvs_lte_6_months", + "sql": "[on_arvs_lte_26_weeks]/[on_arvs]" + }, + { + "label": "on_arvs_gt_26_weeks", + "expression": "on_arvs_gt_26_weeks", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "perc_on_arvs_gt_6_months", + "expression": "perc_on_arvs_gt_6_months", + "sql": "[on_arvs_gt_26_weeks]/[patients]" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t3.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_datetime", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "month", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "reporting_month", + "type": "single", + "sql": "date_format(t1.encounter_datetime, '%m/%Y')" + } + ], + "indicatorHandlers": [ + { + "processor": "processClinicalComparator", + "indicators": [] + } + ] + } ] diff --git a/reports/clinic-lab-orders-report.json b/reports/clinic-lab-orders-report.json index f45f4e0bd..d9e49e86b 100755 --- a/reports/clinic-lab-orders-report.json +++ b/reports/clinic-lab-orders-report.json @@ -124,12 +124,10 @@ "parameters": [ { "name": "dateActivated", - "defaultValue": [ - "10-10-2015" - ] + "defaultValue": ["10-10-2015"] }, - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, { "name": "locations" }, @@ -151,7 +149,7 @@ } ] }, - {"name": "patientUuid"} + { "name": "patientUuid" } ], "filters": [ { @@ -159,12 +157,12 @@ "parameter": "dateActivated" }, { - "expression":"date(t1.date_activated) >= ?", - "parameter":"startDate" + "expression": "date(t1.date_activated) >= ?", + "parameter": "startDate" }, { - "expression":"date(t1.date_activated) <= ?", - "parameter":"endDate" + "expression": "date(t1.date_activated) <= ?", + "parameter": "endDate" }, { "expression": "t2.location_id in ?", @@ -187,9 +185,7 @@ "parameter": "groupByOrderId" } ], - "orderBy": [ - - ], + "orderBy": [], "indicators": [], "supplementColumns": [ { @@ -268,9 +264,9 @@ "sql": "concat(COALESCE(t3.given_name,''),' ',COALESCE(t3.middle_name,''),' ',COALESCE(t3.family_name,''))" }, { - "label":"location_name", - "type":"single", - "sql":"t5.name" + "label": "location_name", + "type": "single", + "sql": "t5.name" }, { "label": "gender", @@ -283,14 +279,14 @@ "sql": "extract(year from (from_days(datediff(now(),t6.birthdate))))" }, { - "label":"locationUuid", - "type":"single", - "sql":"t5.uuid" + "label": "locationUuid", + "type": "single", + "sql": "t5.uuid" }, { - "label":"location_id", - "type":"single", - "sql":"t5.location_id" + "label": "location_id", + "type": "single", + "sql": "t5.location_id" }, { "label": "patient_uuid", @@ -338,22 +334,20 @@ "sql": "fhs.cur_arv_meds" }, { - "type": "simple_column", - "alias": "previous_vl", - "column": "fhs.vl_2" + "type": "simple_column", + "alias": "previous_vl", + "column": "fhs.vl_2" }, { - "type": "simple_column", - "alias": "previous_vl_date", - "column": "date_format(fhs.vl_2_date, '%Y-%m-%d')" + "type": "simple_column", + "alias": "previous_vl_date", + "column": "date_format(fhs.vl_2_date, '%Y-%m-%d')" }, { - "type": "simple_column", - "alias": "nearest_center", - "column": "pa.address3" + "type": "simple_column", + "alias": "nearest_center", + "column": "pa.address3" } - ] - } -] \ No newline at end of file +] diff --git a/reports/clinical-overview-visualization-report.json b/reports/clinical-overview-visualization-report.json index 375454798..fc558fae3 100755 --- a/reports/clinical-overview-visualization-report.json +++ b/reports/clinical-overview-visualization-report.json @@ -1,431 +1,415 @@ [ - { - "name": "clinical-hiv-comparative-overview-report", - "table": { - "schema": "etl", - "tableName": "dates", - "alias": "t2" - }, - "joins": [ - { - "joinType": "JOIN", - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t1", - "indexExpression": "FORCE INDEX (loc_id_enc_date_next_clinic)", - "joinExpression": "date(t1.encounter_datetime) <= date(t2.endDate)" - }, - { - "joinType": "LEFT OUTER JOIN", - "schema": "amrs", - "tableName": "orders", - "alias": "orders", - "joinExpression": "orders.voided=0 and t1.encounter_id=orders.encounter_id" - }, - { - "joinType": "INNER JOIN", - "schema": "amrs", - "tableName": "person", - "alias": "t3", - "joinExpression": "t1.person_id = t3.person_id" - } - ], - "parameters": [ - { - "name": "startDate", - "defaultValue": [ - "01-01-1980" - ] - }, - { - "name": "endDate", - "defaultValue": [ - "Now()" - ] - }, - {"name":"locations","defaultValue":[]}, - { - "name": "groupByEndDate", - "defaultValue": [ - { - "label": "endDate", - "expression": "endDate" - } - ] - } - ], - "filters": [ - { - "expression": "t2.endDate >= date(?)", - "parameter": "startDate" - }, - { - "expression": "t2.endDate <= date(?)", - "parameter": "endDate" - }, - { - "expression": "t1.location_id in ?", - "parameter": "locations" - }, - { - "expression": "t1.is_clinical_encounter=1", - "processForce": true - }, - { - "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then false when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 end", - "processForce": true - }, - { - "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > t2.endDate)", - "processForce": true - } - ], - "groupClause": [ - { - "parameter": "groupByEndDate" - } - ], - "indicators": [ - { - "label": "currently_in_care_total", - "expression": "currently_in_care_total", - "sql": "count(distinct if($expression, t1.person_id,null))", - "canBeDisaggregated": true - }, - { - "label": "on_art_total", - "expression": "on_art_total", - "sql": "count(distinct if($expression, t1.person_id,null))", - "canBeDisaggregated": true - }, - { - "label": "not_on_art_total", - "expression": "not_on_art_total", - "sql": "count(distinct if($expression, t1.person_id,null))", - "canBeDisaggregated": true - }, - { - "label": "patients_requiring_vl", - "expression": "patients_requiring_vl", - "sql": "count(distinct if($expression, t1.person_id,null))", - "canBeDisaggregated": true - }, - { - "label": "tested_appropriately", - "expression": "tested_appropriately", - "sql": "count(distinct if($expression, t1.person_id,null))", - "canBeDisaggregated": true - }, - { - "label": "not_tested_appropriately", - "expression": "not_tested_appropriately", - "sql": "count(distinct if($expression, t1.person_id,null))", - "canBeDisaggregated": true - }, - { - "label": "due_for_annual_vl", - "expression": "due_for_annual_vl", - "sql": "count(distinct if($expression, t1.person_id,null))", - "canBeDisaggregated": true - }, - { - "label": "pending_vl_orders", - "expression": "pending_vl_orders", - "sql": "count(distinct if($expression, t1.person_id,null))", - "canBeDisaggregated": true - }, - { - "label": "missing_vl_order", - "expression": "missing_vl_order", - "sql": "count(distinct if($expression, t1.person_id,null))", - "canBeDisaggregated": true - }, - { - "label": "perc_tested_appropriately", - "expression": "perc_tested_appropriately", - "sql": "if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100)" - }, - { - "label": "virally_suppressed", - "expression": "virally_suppressed", - "sql": "count(distinct if($expression, t1.person_id,null))" - }, - { - "label": "not_virally_suppressed", - "expression": "not_virally_suppressed", - "sql": "count(distinct if($expression, t1.person_id,null))" - }, - { - "label": "perc_virally_suppressed", - "expression": "perc_virally_suppressed", - "sql": "if([virally_suppressed]=0, 0,([virally_suppressed]/[tested_appropriately])*100)" - } - ], - "supplementColumns": [ - { - "label": "reporting_date", - "type": "single", - "sql": "t2.endDate" - }, - { - "label": "location_uuid", - "type": "single", - "sql": "t1.location_uuid" - }, - { - "label": "location_id", - "type": "single", - "sql": "t1.location_id" - }, - { - "label": "reporting_month", - "type": "single", - "sql": "date_format(t2.endDate, '%Y/%m')" - } + { + "name": "clinical-hiv-comparative-overview-report", + "table": { + "schema": "etl", + "tableName": "dates", + "alias": "t2" + }, + "joins": [ + { + "joinType": "JOIN", + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1", + "indexExpression": "FORCE INDEX (loc_id_enc_date_next_clinic)", + "joinExpression": "date(t1.encounter_datetime) <= date(t2.endDate)" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "amrs", + "tableName": "orders", + "alias": "orders", + "joinExpression": "orders.voided=0 and t1.encounter_id=orders.encounter_id" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t3", + "joinExpression": "t1.person_id = t3.person_id" + } + ], + "parameters": [ + { + "name": "startDate", + "defaultValue": ["01-01-1980"] + }, + { + "name": "endDate", + "defaultValue": ["Now()"] + }, + { "name": "locations", "defaultValue": [] }, + { + "name": "groupByEndDate", + "defaultValue": [ + { + "label": "endDate", + "expression": "endDate" + } ] + } + ], + "filters": [ + { + "expression": "t2.endDate >= date(?)", + "parameter": "startDate" + }, + { + "expression": "t2.endDate <= date(?)", + "parameter": "endDate" + }, + { + "expression": "t1.location_id in ?", + "parameter": "locations" + }, + { + "expression": "t1.is_clinical_encounter=1", + "processForce": true + }, + { + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then false when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 end", + "processForce": true + }, + { + "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > t2.endDate)", + "processForce": true + } + ], + "groupClause": [ + { + "parameter": "groupByEndDate" + } + ], + "indicators": [ + { + "label": "currently_in_care_total", + "expression": "currently_in_care_total", + "sql": "count(distinct if($expression, t1.person_id,null))", + "canBeDisaggregated": true + }, + { + "label": "on_art_total", + "expression": "on_art_total", + "sql": "count(distinct if($expression, t1.person_id,null))", + "canBeDisaggregated": true + }, + { + "label": "not_on_art_total", + "expression": "not_on_art_total", + "sql": "count(distinct if($expression, t1.person_id,null))", + "canBeDisaggregated": true + }, + { + "label": "patients_requiring_vl", + "expression": "patients_requiring_vl", + "sql": "count(distinct if($expression, t1.person_id,null))", + "canBeDisaggregated": true + }, + { + "label": "tested_appropriately", + "expression": "tested_appropriately", + "sql": "count(distinct if($expression, t1.person_id,null))", + "canBeDisaggregated": true + }, + { + "label": "not_tested_appropriately", + "expression": "not_tested_appropriately", + "sql": "count(distinct if($expression, t1.person_id,null))", + "canBeDisaggregated": true + }, + { + "label": "due_for_annual_vl", + "expression": "due_for_annual_vl", + "sql": "count(distinct if($expression, t1.person_id,null))", + "canBeDisaggregated": true + }, + { + "label": "pending_vl_orders", + "expression": "pending_vl_orders", + "sql": "count(distinct if($expression, t1.person_id,null))", + "canBeDisaggregated": true + }, + { + "label": "missing_vl_order", + "expression": "missing_vl_order", + "sql": "count(distinct if($expression, t1.person_id,null))", + "canBeDisaggregated": true + }, + { + "label": "perc_tested_appropriately", + "expression": "perc_tested_appropriately", + "sql": "if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100)" + }, + { + "label": "virally_suppressed", + "expression": "virally_suppressed", + "sql": "count(distinct if($expression, t1.person_id,null))" + }, + { + "label": "not_virally_suppressed", + "expression": "not_virally_suppressed", + "sql": "count(distinct if($expression, t1.person_id,null))" + }, + { + "label": "perc_virally_suppressed", + "expression": "perc_virally_suppressed", + "sql": "if([virally_suppressed]=0, 0,([virally_suppressed]/[tested_appropriately])*100)" + } + ], + "supplementColumns": [ + { + "label": "reporting_date", + "type": "single", + "sql": "t2.endDate" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "reporting_month", + "type": "single", + "sql": "date_format(t2.endDate, '%Y/%m')" + } + ] + }, + { + "name": "clinical-art-overview-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" }, - { - "name": "clinical-art-overview-report", - "table": { - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t1" - }, - "joins": [], - "parameters": [ - { - "name": "startDate", - "defaultValue": [ - "01-01-1980" - ] - }, - { - "name": "endDate", - "defaultValue": [ - "Now()" - ] - }, - { - "name": "locationUuids", - "defaultValue": [ - 1 - ] - }, - { - "name": "groupByLocation", - "defaultValue": [ - { - "label": "location_id", - "expression": "location_id" - } - ] - } - ], - "filters": [ - { - "expression": "t1.encounter_datetime >= ?", - "parameter": "startDate" - }, - { - "expression": "t1.encounter_datetime <= ?", - "parameter": "endDate" - }, - { - "expression": "t1.location_uuid in (?)", - "parameter": "locationUuids" - }, - { - "expression": "t1.is_clinical_encounter = 1", - "processForce": true - }, - { - "expression": "(t1.next_encounter_datetime_hiv is null or t1.next_encounter_datetime_hiv > ?)", - "parameter": "endDate" - } - ], - "groupClause": [ - { - "parameter": "groupByLocation" - } - ], - "indicators": [ - { - "label": "patients", - "expression": "patients", - "sql": "count(distinct if(true, person_id,null))" - }, - { - "label": "on_nevirapine", - "expression": "on_nevirapine", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "on_lopinavir", - "expression": "on_lopinavir", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "on_efavirenz", - "expression": "on_efavirenz", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "on_atazanavir", - "expression": "on_atazanavir", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "on_raltegravir", - "expression": "on_raltegravir", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "on_other_arv_drugs", - "expression": "on_other_arv_drugs", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "not_on_arv", - "expression": "not_on_arv", - "sql": "count(distinct if($expression, person_id,null))" - } - ], - "supplementColumns": [ - { - "label": "location_uuid", - "type": "single", - "sql": "t1.location_uuid" - }, - { - "label": "location_id", - "type": "single", - "sql": "t1.location_id" - } + "joins": [], + "parameters": [ + { + "name": "startDate", + "defaultValue": ["01-01-1980"] + }, + { + "name": "endDate", + "defaultValue": ["Now()"] + }, + { + "name": "locationUuids", + "defaultValue": [1] + }, + { + "name": "groupByLocation", + "defaultValue": [ + { + "label": "location_id", + "expression": "location_id" + } ] + } + ], + "filters": [ + { + "expression": "t1.encounter_datetime >= ?", + "parameter": "startDate" + }, + { + "expression": "t1.encounter_datetime <= ?", + "parameter": "endDate" + }, + { + "expression": "t1.location_uuid in (?)", + "parameter": "locationUuids" + }, + { + "expression": "t1.is_clinical_encounter = 1", + "processForce": true + }, + { + "expression": "(t1.next_encounter_datetime_hiv is null or t1.next_encounter_datetime_hiv > ?)", + "parameter": "endDate" + } + ], + "groupClause": [ + { + "parameter": "groupByLocation" + } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct if(true, person_id,null))" + }, + { + "label": "on_nevirapine", + "expression": "on_nevirapine", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "on_lopinavir", + "expression": "on_lopinavir", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "on_efavirenz", + "expression": "on_efavirenz", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "on_atazanavir", + "expression": "on_atazanavir", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "on_raltegravir", + "expression": "on_raltegravir", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "on_other_arv_drugs", + "expression": "on_other_arv_drugs", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "not_on_arv", + "expression": "not_on_arv", + "sql": "count(distinct if($expression, person_id,null))" + } + ], + "supplementColumns": [ + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + } + ] + }, + { + "name": "clinical-patient-care-status-overview-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" }, - { - "name": "clinical-patient-care-status-overview-report", - "table": { - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t1" - }, - "joins": [], - "parameters": [ - { - "name": "startDate", - "defaultValue": [ - "01-01-1980" - ] - }, - { - "name": "endDate", - "defaultValue": [ - "Now()" - ] - }, - { - "name": "locationUuids", - "defaultValue": [ - 1 - ] - }, - { - "name": "groupByLocation", - "defaultValue": [ - { - "label": "location_id", - "expression": "location_id" - } - ] - } - ], - "filters": [ - { - "expression": "t1.encounter_datetime >= ?", - "parameter": "startDate" - }, - { - "expression": "t1.encounter_datetime <= ?", - "parameter": "endDate" - }, - { - "expression": "t1.location_uuid in (?)", - "parameter": "locationUuids" - }, - { - "expression": "(t1.next_encounter_datetime_hiv is null or t1.next_encounter_datetime_hiv > ?)", - "parameter": "endDate" - } - ], - "groupClause": [ - { - "parameter": "groupByLocation" - } - ], - "indicators": [ - { - "label": "patients", - "expression": "patients", - "sql": "count(distinct if(true, person_id,null))" - }, - { - "label": "deceased_patients", - "expression": "deceased_patients", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "untraceable_patients", - "expression": "untraceable_patients", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "transferred_out_patients", - "expression": "transferred_out_patients", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "hiv_negative_patients", - "expression": "hiv_negative_patients", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "patients_continuing_care", - "expression": "patients_continuing_care", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "self_disengaged_from_care", - "expression": "self_disengaged_from_care", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "defaulters", - "expression": "defaulters", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "transfer_to_MNCH", - "expression": "transfer_to_MNCH", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "other_patient_care_status", - "expression": "other_patient_care_status", - "sql": "count(distinct if($expression, person_id,null))" - } - ], - "supplementColumns": [ - { - "label": "location_uuid", - "type": "single", - "sql": "t1.location_uuid" - }, - { - "label": "location_id", - "type": "single", - "sql": "t1.location_id" - } + "joins": [], + "parameters": [ + { + "name": "startDate", + "defaultValue": ["01-01-1980"] + }, + { + "name": "endDate", + "defaultValue": ["Now()"] + }, + { + "name": "locationUuids", + "defaultValue": [1] + }, + { + "name": "groupByLocation", + "defaultValue": [ + { + "label": "location_id", + "expression": "location_id" + } ] - } + } + ], + "filters": [ + { + "expression": "t1.encounter_datetime >= ?", + "parameter": "startDate" + }, + { + "expression": "t1.encounter_datetime <= ?", + "parameter": "endDate" + }, + { + "expression": "t1.location_uuid in (?)", + "parameter": "locationUuids" + }, + { + "expression": "(t1.next_encounter_datetime_hiv is null or t1.next_encounter_datetime_hiv > ?)", + "parameter": "endDate" + } + ], + "groupClause": [ + { + "parameter": "groupByLocation" + } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct if(true, person_id,null))" + }, + { + "label": "deceased_patients", + "expression": "deceased_patients", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "untraceable_patients", + "expression": "untraceable_patients", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "transferred_out_patients", + "expression": "transferred_out_patients", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "hiv_negative_patients", + "expression": "hiv_negative_patients", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "patients_continuing_care", + "expression": "patients_continuing_care", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "self_disengaged_from_care", + "expression": "self_disengaged_from_care", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "defaulters", + "expression": "defaulters", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "transfer_to_MNCH", + "expression": "transfer_to_MNCH", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "other_patient_care_status", + "expression": "other_patient_care_status", + "sql": "count(distinct if($expression, person_id,null))" + } + ], + "supplementColumns": [ + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + } + ] + } ] diff --git a/reports/clinical-reminder-report.json b/reports/clinical-reminder-report.json index 28d111775..2a763f8b8 100755 --- a/reports/clinical-reminder-report.json +++ b/reports/clinical-reminder-report.json @@ -1,202 +1,219 @@ - [ - { - "name": "clinical-reminder-report", - "table":{"schema":"etl","tableName":"flat_hiv_summary_v15b","alias":"t1", "indexExpression":"FORCE INDEX (person_uuid)"}, - "joins":[ - {"joinType":"LEFT OUTER JOIN","schema":"etl","tableName":"flat_labs_and_imaging","alias":"t2","joinExpression":"date(t1.encounter_datetime) = date(t2.test_datetime)"}, - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t5","joinExpression":"t5.person_id = t1.person_id"}, - {"joinType":"LEFT OUTER JOIN","schema":"","alias":"t3","joinExpression":"t3.person_uuid = t1.uuid", - "dynamicDataset":"labs_and_imaging_dataset"} - ], - "parameters": [ - {"name":"patientUuid", "defaultValue":[]}, - {"name":"@referenceDate", "defaultValue":["defaultValue"]} - ], - "filters": [ - {"expression":"t1.uuid = ?", "parameter":"patientUuid"}, - {"expression":"t1.encounter_datetime < ?", "parameter":"@referenceDate"} - ], - "groupClause":[ - ], - "indicators": [ - { - "label":"needs_vl_coded", - "expression":"needs_vl_coded", - "sql":"$expression" - }, - { - "label":"overdue_vl_lab_order", - "expression":"overdue_vl_lab_order", - "sql":"$expression" - }, - { - "label":"new_viral_load_present", - "expression":"new_viral_load_present", - "sql":"$expression" - }, - { - "label":"needs_cd4_count_coded", - "expression":"needs_cd4_count_coded", - "sql":"$expression" - }, - { - "label":"months_since_last_vl_date", - "expression":"months_since_last_vl_date", - "sql":"$expression" - }, - { - "label":"overdue_cd4_count_lab_order", - "expression":"overdue_cd4_count_lab_order", - "sql":"$expression" - }, - { - "label":"is_on_inh_treatment", - "expression":"is_on_inh_treatment", - "sql":"$expression" - }, - { - "label":"qualifies_differenciated_care", - "expression":"qualifies_differenciated_care", - "sql":"$expression" - }, - { - "label":"not_completed_ipt", - "expression":"not_completed_ipt", - "sql":"$expression" - } +[ + { + "name": "clinical-reminder-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary_v15b", + "alias": "t1", + "indexExpression": "FORCE INDEX (person_uuid)" + }, + "joins": [ + { + "joinType": "LEFT OUTER JOIN", + "schema": "etl", + "tableName": "flat_labs_and_imaging", + "alias": "t2", + "joinExpression": "date(t1.encounter_datetime) = date(t2.test_datetime)" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t5", + "joinExpression": "t5.person_id = t1.person_id" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "", + "alias": "t3", + "joinExpression": "t3.person_uuid = t1.uuid", + "dynamicDataset": "labs_and_imaging_dataset" + } + ], + "parameters": [ + { "name": "patientUuid", "defaultValue": [] }, + { "name": "@referenceDate", "defaultValue": ["defaultValue"] } + ], + "filters": [ + { "expression": "t1.uuid = ?", "parameter": "patientUuid" }, + { + "expression": "t1.encounter_datetime < ?", + "parameter": "@referenceDate" + } + ], + "groupClause": [], + "indicators": [ + { + "label": "needs_vl_coded", + "expression": "needs_vl_coded", + "sql": "$expression" + }, + { + "label": "overdue_vl_lab_order", + "expression": "overdue_vl_lab_order", + "sql": "$expression" + }, + { + "label": "new_viral_load_present", + "expression": "new_viral_load_present", + "sql": "$expression" + }, + { + "label": "needs_cd4_count_coded", + "expression": "needs_cd4_count_coded", + "sql": "$expression" + }, + { + "label": "months_since_last_vl_date", + "expression": "months_since_last_vl_date", + "sql": "$expression" + }, + { + "label": "overdue_cd4_count_lab_order", + "expression": "overdue_cd4_count_lab_order", + "sql": "$expression" + }, + { + "label": "is_on_inh_treatment", + "expression": "is_on_inh_treatment", + "sql": "$expression" + }, + { + "label": "qualifies_differenciated_care", + "expression": "qualifies_differenciated_care", + "sql": "$expression" + }, + { + "label": "not_completed_ipt", + "expression": "not_completed_ipt", + "sql": "$expression" + } + ], + "supplementColumns": [ + { + "label": "last_encounter_date", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "birth_date", + "type": "single", + "sql": "t5.birthdate" + }, + { + "label": "person_id", + "type": "single", + "sql": "t1.person_id" + }, + { + "label": "person_uuid", + "type": "single", + "sql": "t1.uuid" + }, + { + "label": "arv_start_date", + "type": "single", + "sql": "t1.arv_start_date" + }, + { + "label": "cur_arv_meds", + "type": "single", + "sql": "t1.cur_arv_meds" + }, + { + "label": "viral_load", + "type": "single", + "sql": "t1.vl_1" + }, + { + "label": "vl_order_date", + "type": "single", + "sql": "t1.vl_order_date" + }, + { + "label": "last_vl_date", + "type": "single", + "sql": "t1.vl_1_date" + }, + { + "label": "vl_error", + "type": "single", + "sql": "t2.vl_error" + }, + { + "label": "vl_error_date", + "type": "single", + "sql": "t2.test_datetime" + }, + { + "label": "ordered_vl_has_error", + "type": "single", + "sql": "t3.ordered_vl_has_error" + }, + { + "label": "vl_error_order_date", + "type": "single", + "sql": "t3.vl_error_order_date" + }, + { + "label": "tb_prophylaxis_end_date", + "type": "single", + "sql": "DATE_ADD(t1.tb_prophylaxis_start_date, INTERVAL 180 DAY)" + }, + { + "label": "tb_prophylaxis_start_date", + "type": "single", + "sql": "t1.tb_prophylaxis_start_date" + }, + { + "label": "inh_treatment_days_remaining", + "type": "single", + "sql": "DATEDIFF(DATE_ADD(t1.tb_prophylaxis_start_date, INTERVAL 180 DAY), now())" + } + ], + "orderBy": [ + { "column": "encounter_datetime", "order": "desc", "name": "orderByDate" } + ] + }, - - ], - "supplementColumns":[ - - { - "label":"last_encounter_date", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"birth_date", - "type":"single", - "sql":"t5.birthdate" - }, - { - "label":"person_id", - "type":"single", - "sql":"t1.person_id" - }, - { - "label":"person_uuid", - "type":"single", - "sql":"t1.uuid" - }, - { - "label":"arv_start_date", - "type":"single", - "sql":"t1.arv_start_date" - }, - { - "label":"cur_arv_meds", - "type":"single", - "sql":"t1.cur_arv_meds" - }, - { - "label":"viral_load", - "type":"single", - "sql":"t1.vl_1" - }, - { - "label":"vl_order_date", - "type":"single", - "sql":"t1.vl_order_date" - }, - { - "label":"last_vl_date", - "type":"single", - "sql":"t1.vl_1_date" - }, - { - "label":"vl_error", - "type":"single", - "sql":"t2.vl_error" - }, - { - "label":"vl_error_date", - "type":"single", - "sql":"t2.test_datetime" - }, - { - "label":"ordered_vl_has_error", - "type":"single", - "sql":"t3.ordered_vl_has_error" - }, - { - "label":"vl_error_order_date", - "type":"single", - "sql":"t3.vl_error_order_date" - }, - { - "label":"tb_prophylaxis_end_date", - "type":"single", - "sql":"DATE_ADD(t1.tb_prophylaxis_start_date, INTERVAL 180 DAY)" - }, - { - "label":"tb_prophylaxis_start_date", - "type":"single", - "sql":"t1.tb_prophylaxis_start_date" - }, - { - "label":"inh_treatment_days_remaining", - "type":"single", - "sql":"DATEDIFF(DATE_ADD(t1.tb_prophylaxis_start_date, INTERVAL 180 DAY), now())" - } - - - ], - "orderBy":[ - {"column":"encounter_datetime", "order":"desc", "name":"orderByDate"} - ] - - }, - - { - "name": "labs_and_imaging_dataset", - "table":{"schema":"etl","tableName":"flat_labs_and_imaging","alias":"t1"}, - "joins":[], - "parameters": [ - {"name":"patientUuid", "defaultValue":[]}, - {"name":"@referenceDate", "defaultValue":["defaultValue"]} - ], - "filters": [ - {"expression":"t1.uuid = ?", "parameter":"patientUuid"}, - {"expression":"t1.test_datetime < ?", "parameter":"@referenceDate"} - ], - "groupClause":[ - ], - "indicators": [ - { - "label":"ordered_vl_has_error", - "expression":"ordered_vl_has_error", - "sql":"$expression" - } - - ], - "supplementColumns":[ - { - "label":"person_uuid", - "type":"single", - "sql":"t1.uuid" - }, - { - "label":"vl_error_order_date", - "type":"single", - "sql":"t1.test_datetime" - } - - ], - "orderBy":[ - {"column":"test_datetime", "order":"desc", "name":"orderByDate"} - ] - } - - - ] + { + "name": "labs_and_imaging_dataset", + "table": { + "schema": "etl", + "tableName": "flat_labs_and_imaging", + "alias": "t1" + }, + "joins": [], + "parameters": [ + { "name": "patientUuid", "defaultValue": [] }, + { "name": "@referenceDate", "defaultValue": ["defaultValue"] } + ], + "filters": [ + { "expression": "t1.uuid = ?", "parameter": "patientUuid" }, + { "expression": "t1.test_datetime < ?", "parameter": "@referenceDate" } + ], + "groupClause": [], + "indicators": [ + { + "label": "ordered_vl_has_error", + "expression": "ordered_vl_has_error", + "sql": "$expression" + } + ], + "supplementColumns": [ + { + "label": "person_uuid", + "type": "single", + "sql": "t1.uuid" + }, + { + "label": "vl_error_order_date", + "type": "single", + "sql": "t1.test_datetime" + } + ], + "orderBy": [ + { "column": "test_datetime", "order": "desc", "name": "orderByDate" } + ] + } +] diff --git a/reports/cohort-report.json b/reports/cohort-report.json index 3242d7605..411ea15e0 100755 --- a/reports/cohort-report.json +++ b/reports/cohort-report.json @@ -77,7 +77,6 @@ "type": "single", "sql": "case when t2.role is null then 'private' else 'shared' end" } - ] - + ] } -] \ No newline at end of file +] diff --git a/reports/daily-visits-appointment.report.json b/reports/daily-visits-appointment.report.json index 227b6be9d..fbc903db8 100755 --- a/reports/daily-visits-appointment.report.json +++ b/reports/daily-visits-appointment.report.json @@ -36,7 +36,7 @@ "alias": "t5", "joinExpression": "t1.visit_id = t5.visit_id" }, - { + { "joinType": "INNER JOIN", "schema": "etl", "tableName": "program_visit_map", @@ -47,9 +47,7 @@ "parameters": [ { "name": "startDate", - "defaultValue": [ - "10-10-2015" - ] + "defaultValue": ["10-10-2015"] }, { "name": "locations", @@ -63,7 +61,7 @@ "name": "visitTypeIds", "defaultValue": [-1] }, - { + { "name": "programTypeIds", "defaultValue": [-1] }, @@ -92,8 +90,8 @@ "parameter": "" }, { - "expression": "coalesce(t1.transfer_out) is null", - "processForce": true + "expression": "coalesce(t1.transfer_out) is null", + "processForce": true }, { "expression": "t1.encounter_type in ?", @@ -209,7 +207,7 @@ "alias": "t5", "joinExpression": "t1.visit_id = t5.visit_id" }, - { + { "joinType": "INNER JOIN", "schema": "etl", "tableName": "program_visit_map", @@ -220,9 +218,7 @@ "parameters": [ { "name": "startDate", - "defaultValue": [ - "10-10-2015" - ] + "defaultValue": ["10-10-2015"] }, { "name": "locations", @@ -232,11 +228,11 @@ "name": "encounterIds", "defaultValue": [-1] }, - { + { "name": "visitTypeIds", "defaultValue": [-1] }, - { + { "name": "programTypeIds", "defaultValue": [-1] }, @@ -259,7 +255,7 @@ "expression": "t1.location_id in (?)", "parameter": "locations" }, - { + { "expression": "encounter_type in ?", "parameter": "encounterIds" }, @@ -347,9 +343,7 @@ "parameters": [ { "name": "startDate", - "defaultValue": [ - "10-10-2015" - ] + "defaultValue": ["10-10-2015"] }, { "name": "locations", @@ -410,7 +404,7 @@ "alias": "t3", "joinExpression": "t1.person_id = t3.person_id and (t3.voided is null || t3.voided = 0)" }, - { + { "joinType": "INNER JOIN", "schema": "amrs", "tableName": "encounter_type", @@ -459,7 +453,7 @@ "alias": "t10", "joinExpression": "t1.visit_id = t10.visit_id" }, - { + { "joinType": "INNER JOIN", "schema": "etl", "tableName": "program_visit_map", @@ -470,9 +464,7 @@ "parameters": [ { "name": "startDate", - "defaultValue": [ - "10-10-2015" - ] + "defaultValue": ["10-10-2015"] }, { "name": "locations", @@ -482,11 +474,11 @@ "name": "encounterIds", "defaultValue": [-1] }, - { + { "name": "visitTypeIds", "defaultValue": [-1] }, - { + { "name": "programTypeIds", "defaultValue": [-1] }, @@ -631,4 +623,4 @@ } ] } -] \ No newline at end of file +] diff --git a/reports/dataentry-statistics.json b/reports/dataentry-statistics.json index ac16cea38..7f26bd498 100755 --- a/reports/dataentry-statistics.json +++ b/reports/dataentry-statistics.json @@ -1,690 +1,1021 @@ [ - { - "name": "by-date-by-encounter-type", - "table":{"schema":"amrs","tableName":"encounter_provider","alias":"t1"}, - "joins":[ - {"joinType":"JOIN","schema":"amrs","tableName":"encounter","alias":"t2","joinExpression":"t1.encounter_id = t2.encounter_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"encounter_type","alias":"t3","joinExpression":"t3.encounter_type_id = t2.encounter_type"}, - {"joinType":"JOIN","schema":"amrs","tableName":"provider","alias":"t4","joinExpression":"t4.provider_id = t1.provider_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"location","alias":"t5","joinExpression":"t2.location_id = t5.location_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit","alias":"t6","joinExpression":"t6.visit_id = t2.visit_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit_type","alias":"t7","joinExpression":"t7.visit_type_id = t6.visit_type_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["01-01-1980"]}, - {"name":"endDate", "defaultValue":["Now()"]}, - {"name":"locations","defaultValue":[1]}, - {"name":"providerUuid","defaultValue":[1]}, - {"name":"formIds","defaultValue":[1]}, - {"name":"encounterTypeIds","defaultValue":[1]}, - {"name":"visitTypeIds","defaultValue":[1]}, - {"name":"groupByDate", "defaultValue":[ - {"label":"date","expression":"date"} - ] - }, - {"name":"groupByEncounterTypeId", "defaultValue":[ - {"label":"encounter_type_id","expression":"encounter_type_id"} - ] - }, - {"name":"groupByLocationId", "defaultValue":[ - {"label":"locations","expression":"locations"} - ] - } - ], - "filters": [ - {"expression":"date(t2.encounter_datetime) >= ?", "parameter":"startDate"}, - {"expression":"date(t2.encounter_datetime) <= ?", "parameter":"endDate"}, - {"expression":"t2.location_id in ?", "parameter":"locations"}, - {"expression":"t4.uuid = ?", "parameter":"providerUuid"}, - {"expression":"t2.form_id in ?", "parameter":"formIds"}, - {"expression":"t2.encounter_type in ?", "parameter":"encounterTypeIds"}, - {"expression":"t7.visit_type_id in ?", "parameter":"visitTypeIds"} - ], - "groupClause":[ - {"parameter":"groupByLocationId"}, - {"parameter":"groupByDate"}, - {"parameter":"groupByEncounterTypeId"} - - ], - "indicators": [ - { - "label":"encounters_count", - "expression":"encounters_count", - "sql":"count(*)" - } - ], - "supplementColumns":[ - { - "label":"date", - "type":"single", - "sql":"date(t2.encounter_datetime)" - }, - { - "label":"encounter_type_id", - "type":"single", - "sql":"t2.encounter_type" - }, - { - "label":"encounter_type", - "type":"single", - "sql":"t3.name" - }, - { - "label":"encounter_type_uuid", - "type":"single", - "sql":"t3.uuid" - }, - { - "label":"locations", - "type":"single", - "sql":"t2.location_id" - }, - { - "label":"location", - "type":"single", - "sql":"t5.name" - }, - { - "label":"locationUuid", - "type":"single", - "sql":"t5.uuid" - } - ], - "orderBy":[ - {"column":"location", "order":"asc"} + { + "name": "by-date-by-encounter-type", + "table": { + "schema": "amrs", + "tableName": "encounter_provider", + "alias": "t1" + }, + "joins": [ + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter", + "alias": "t2", + "joinExpression": "t1.encounter_id = t2.encounter_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter_type", + "alias": "t3", + "joinExpression": "t3.encounter_type_id = t2.encounter_type" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "provider", + "alias": "t4", + "joinExpression": "t4.provider_id = t1.provider_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t5", + "joinExpression": "t2.location_id = t5.location_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit", + "alias": "t6", + "joinExpression": "t6.visit_id = t2.visit_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit_type", + "alias": "t7", + "joinExpression": "t7.visit_type_id = t6.visit_type_id" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["01-01-1980"] }, + { "name": "endDate", "defaultValue": ["Now()"] }, + { "name": "locations", "defaultValue": [1] }, + { "name": "providerUuid", "defaultValue": [1] }, + { "name": "formIds", "defaultValue": [1] }, + { "name": "encounterTypeIds", "defaultValue": [1] }, + { "name": "visitTypeIds", "defaultValue": [1] }, + { + "name": "groupByDate", + "defaultValue": [{ "label": "date", "expression": "date" }] + }, + { + "name": "groupByEncounterTypeId", + "defaultValue": [ + { "label": "encounter_type_id", "expression": "encounter_type_id" } ] - }, - { - "name": "by-month-by-encounter-type", - "table":{"schema":"amrs","tableName":"encounter_provider","alias":"t1"}, - "joins":[ - {"joinType":"JOIN","schema":"amrs","tableName":"encounter","alias":"t2","joinExpression":"t1.encounter_id = t2.encounter_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"encounter_type","alias":"t3","joinExpression":"t3.encounter_type_id = t2.encounter_type"}, - {"joinType":"JOIN","schema":"amrs","tableName":"provider","alias":"t4","joinExpression":"t4.provider_id = t1.provider_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"location","alias":"t5","joinExpression":"t2.location_id = t5.location_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit","alias":"t6","joinExpression":"t6.visit_id = t2.visit_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit_type","alias":"t7","joinExpression":"t7.visit_type_id = t6.visit_type_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["01-01-1980"]}, - {"name":"endDate", "defaultValue":["Now()"]}, - {"name":"locations","defaultValue":[1]}, - {"name":"providerUuid","defaultValue":[1]}, - {"name":"formIds","defaultValue":[1]}, - {"name":"encounterTypeIds","defaultValue":[1]}, - {"name":"visitTypeIds","defaultValue":[1]}, - {"name":"groupByMonth", "defaultValue":[ - {"label":"month","expression":"month"} - ] - }, - {"name":"groupByEncounterTypeId", "defaultValue":[ - {"label":"encounter_type_id","expression":"encounter_type_id"} - ] - }, - {"name":"groupByLocationId", "defaultValue":[ - {"label":"locations","expression":"locations"} - ] - } - ], - "filters": [ - {"expression":"date(t2.encounter_datetime) >= ?", "parameter":"startDate"}, - {"expression":"date(t2.encounter_datetime) <= ?", "parameter":"endDate"}, - {"expression":"t2.location_id in ?", "parameter":"locations"}, - {"expression":"t4.uuid = ?", "parameter":"providerUuid"}, - {"expression":"t2.form_id in ?", "parameter":"formIds"}, - {"expression":"t2.encounter_type in ?", "parameter":"encounterTypeIds"}, - {"expression":"t7.visit_type_id in ?", "parameter":"visitTypeIds"} - ], - "groupClause":[ - {"parameter":"groupByLocationId"}, - {"parameter":"groupByMonth"}, - {"parameter":"groupByEncounterTypeId"} - ], - "indicators": [ - { - "label":"encounters_count", - "expression":"encounters_count", - "sql":"count(*)" + }, + { + "name": "groupByLocationId", + "defaultValue": [{ "label": "locations", "expression": "locations" }] + } + ], + "filters": [ + { + "expression": "date(t2.encounter_datetime) >= ?", + "parameter": "startDate" + }, + { + "expression": "date(t2.encounter_datetime) <= ?", + "parameter": "endDate" + }, + { "expression": "t2.location_id in ?", "parameter": "locations" }, + { "expression": "t4.uuid = ?", "parameter": "providerUuid" }, + { "expression": "t2.form_id in ?", "parameter": "formIds" }, + { + "expression": "t2.encounter_type in ?", + "parameter": "encounterTypeIds" + }, + { "expression": "t7.visit_type_id in ?", "parameter": "visitTypeIds" } + ], + "groupClause": [ + { "parameter": "groupByLocationId" }, + { "parameter": "groupByDate" }, + { "parameter": "groupByEncounterTypeId" } + ], + "indicators": [ + { + "label": "encounters_count", + "expression": "encounters_count", + "sql": "count(*)" + } + ], + "supplementColumns": [ + { + "label": "date", + "type": "single", + "sql": "date(t2.encounter_datetime)" + }, + { + "label": "encounter_type_id", + "type": "single", + "sql": "t2.encounter_type" + }, + { + "label": "encounter_type", + "type": "single", + "sql": "t3.name" + }, + { + "label": "encounter_type_uuid", + "type": "single", + "sql": "t3.uuid" + }, + { + "label": "locations", + "type": "single", + "sql": "t2.location_id" + }, + { + "label": "location", + "type": "single", + "sql": "t5.name" + }, + { + "label": "locationUuid", + "type": "single", + "sql": "t5.uuid" } - ], - "supplementColumns":[ - { - "label":"year", - "type":"single", - "sql":"year(t2.encounter_datetime)" - }, - { - "label":"month_number", - "type":"single", - "sql":"month(t2.encounter_datetime)" - }, - { - "label":"month", - "type":"single", - "sql":"DATE_FORMAT(t2.encounter_datetime, '%M, %Y')" - }, - { - "label":" encounter_type_id", - "type":"single", - "sql":"t2.encounter_type" - }, - { - "label":"encounter_type", - "type":"single", - "sql":"t3.name" - }, - { - "label":"encounter_type_uuid", - "type":"single", - "sql":"t3.uuid" - }, - { - "label":"locations", - "type":"single", - "sql":"t2.location_id" - }, - { - "label":"location", - "type":"single", - "sql":"t5.name" - }, - { - "label":"locationUuid", - "type":"single", - "sql":"t5.uuid" - } - ], - "orderBy":[ - {"column":"year", "order":"asc"}, - {"column":"month_number", "order":"asc"}, - {"column":"location", "order":"asc"} - ] -}, -{ - "name": "by-provider-by-encounter-type", - "table":{"schema":"amrs","tableName":"encounter_provider","alias":"t1"}, - "joins":[ - {"joinType":"JOIN","schema":"amrs","tableName":"encounter","alias":"t2","joinExpression":"t1.encounter_id = t2.encounter_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"encounter_type","alias":"t3","joinExpression":"t3.encounter_type_id = t2.encounter_type"}, - {"joinType":"JOIN","schema":"amrs","tableName":"provider","alias":"t4","joinExpression":"t4.provider_id = t1.provider_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"person_name","alias":"t5","joinExpression":"t4.person_id = t5.person_id"}, - {"joinType":"JOIN","schema":"etl","tableName":"clinical_encounter_type_map","alias":"t6","joinExpression":"t6.encounter_type = t2.encounter_type"}, - {"joinType":"JOIN","schema":"amrs","tableName":"location","alias":"t7","joinExpression":"t2.location_id = t7.location_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit","alias":"t8","joinExpression":"t8.visit_id = t2.visit_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit_type","alias":"t9","joinExpression":"t9.visit_type_id = t8.visit_type_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["01-01-1980"]}, - {"name":"endDate", "defaultValue":["Now()"]}, - {"name":"locations","defaultValue":[1]}, - {"name":"providerUuid","defaultValue":[1]}, - {"name":"formIds","defaultValue":[1]}, - {"name":"encounterTypeIds","defaultValue":[1]}, - {"name":"visitTypeIds","defaultValue":[1]}, - {"name":"groupByProviderId", "defaultValue":[ - {"label":"provider_id","expression":"provider_id"} - ] + ], + "orderBy": [{ "column": "location", "order": "asc" }] + }, + { + "name": "by-month-by-encounter-type", + "table": { + "schema": "amrs", + "tableName": "encounter_provider", + "alias": "t1" }, - {"name":"groupByEncounterTypeId", "defaultValue":[ - {"label":"encounter_type_id","expression":"encounter_type_id"} + "joins": [ + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter", + "alias": "t2", + "joinExpression": "t1.encounter_id = t2.encounter_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter_type", + "alias": "t3", + "joinExpression": "t3.encounter_type_id = t2.encounter_type" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "provider", + "alias": "t4", + "joinExpression": "t4.provider_id = t1.provider_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t5", + "joinExpression": "t2.location_id = t5.location_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit", + "alias": "t6", + "joinExpression": "t6.visit_id = t2.visit_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit_type", + "alias": "t7", + "joinExpression": "t7.visit_type_id = t6.visit_type_id" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["01-01-1980"] }, + { "name": "endDate", "defaultValue": ["Now()"] }, + { "name": "locations", "defaultValue": [1] }, + { "name": "providerUuid", "defaultValue": [1] }, + { "name": "formIds", "defaultValue": [1] }, + { "name": "encounterTypeIds", "defaultValue": [1] }, + { "name": "visitTypeIds", "defaultValue": [1] }, + { + "name": "groupByMonth", + "defaultValue": [{ "label": "month", "expression": "month" }] + }, + { + "name": "groupByEncounterTypeId", + "defaultValue": [ + { "label": "encounter_type_id", "expression": "encounter_type_id" } + ] + }, + { + "name": "groupByLocationId", + "defaultValue": [{ "label": "locations", "expression": "locations" }] + } + ], + "filters": [ + { + "expression": "date(t2.encounter_datetime) >= ?", + "parameter": "startDate" + }, + { + "expression": "date(t2.encounter_datetime) <= ?", + "parameter": "endDate" + }, + { "expression": "t2.location_id in ?", "parameter": "locations" }, + { "expression": "t4.uuid = ?", "parameter": "providerUuid" }, + { "expression": "t2.form_id in ?", "parameter": "formIds" }, + { + "expression": "t2.encounter_type in ?", + "parameter": "encounterTypeIds" + }, + { "expression": "t7.visit_type_id in ?", "parameter": "visitTypeIds" } + ], + "groupClause": [ + { "parameter": "groupByLocationId" }, + { "parameter": "groupByMonth" }, + { "parameter": "groupByEncounterTypeId" } + ], + "indicators": [ + { + "label": "encounters_count", + "expression": "encounters_count", + "sql": "count(*)" + } + ], + "supplementColumns": [ + { + "label": "year", + "type": "single", + "sql": "year(t2.encounter_datetime)" + }, + { + "label": "month_number", + "type": "single", + "sql": "month(t2.encounter_datetime)" + }, + { + "label": "month", + "type": "single", + "sql": "DATE_FORMAT(t2.encounter_datetime, '%M, %Y')" + }, + { + "label": " encounter_type_id", + "type": "single", + "sql": "t2.encounter_type" + }, + { + "label": "encounter_type", + "type": "single", + "sql": "t3.name" + }, + { + "label": "encounter_type_uuid", + "type": "single", + "sql": "t3.uuid" + }, + { + "label": "locations", + "type": "single", + "sql": "t2.location_id" + }, + { + "label": "location", + "type": "single", + "sql": "t5.name" + }, + { + "label": "locationUuid", + "type": "single", + "sql": "t5.uuid" + } + ], + "orderBy": [ + { "column": "year", "order": "asc" }, + { "column": "month_number", "order": "asc" }, + { "column": "location", "order": "asc" } ] + }, + { + "name": "by-provider-by-encounter-type", + "table": { + "schema": "amrs", + "tableName": "encounter_provider", + "alias": "t1" }, - {"name":"groupByLocationId", "defaultValue":[ - {"label":"locations","expression":"locations"} - ] - } - ], - "filters": [ - {"expression":"date(t2.encounter_datetime) >= ?", "parameter":"startDate"}, - {"expression":"date(t2.encounter_datetime) <= ?", "parameter":"endDate"}, - {"expression":"t2.location_id in ?", "parameter":"locations"}, - {"expression":"t4.uuid = ?", "parameter":"providerUuid"}, - {"expression":"t2.form_id in ?", "parameter":"formIds"}, - {"expression":"t2.encounter_type in ?", "parameter":"encounterTypeIds"}, - {"expression":"t9.visit_type_id in ?", "parameter":"visitTypeIds"} - ], - "groupClause":[ - {"parameter":"groupByLocationId"}, - {"parameter":"groupByProviderId"}, - {"parameter":"groupByEncounterTypeId"} - ], - "indicators": [ - { - "label":"encounters_count", - "expression":"encounters_count", - "sql":"count(*)" - } - ], - "supplementColumns":[ - { - "label":"provider_id", - "type":"single", - "sql":"t4.provider_id" - }, - { - "label":"provider_uuid", - "type":"single", - "sql":"t4.uuid" - }, - { - "label":"encounter_type_id", - "type":"single", - "sql":"t2.encounter_type" - }, - { - "label":"encounter_type", - "type":"single", - "sql":"t3.name" - }, - { - "label":"encounter_type_uuid", - "type":"single", - "sql":"t3.uuid" - }, - { - "label":"provider_name", - "type":"single", - "sql":"CONCAT(COALESCE(t5.given_name, ''),' ', COALESCE(t5.middle_name, ''),' ', COALESCE(t5.family_name, ''))" - }, - { - "label":"is_clinical_encounter", - "type":"single", - "sql":"t6.is_clinical" - }, - { - "label":"locations", - "type":"single", - "sql":"t2.location_id" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t7.uuid" - }, - { - "label":"location", - "type":"single", - "sql":"t7.name" - } + "joins": [ + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter", + "alias": "t2", + "joinExpression": "t1.encounter_id = t2.encounter_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter_type", + "alias": "t3", + "joinExpression": "t3.encounter_type_id = t2.encounter_type" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "provider", + "alias": "t4", + "joinExpression": "t4.provider_id = t1.provider_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "person_name", + "alias": "t5", + "joinExpression": "t4.person_id = t5.person_id" + }, + { + "joinType": "JOIN", + "schema": "etl", + "tableName": "clinical_encounter_type_map", + "alias": "t6", + "joinExpression": "t6.encounter_type = t2.encounter_type" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t7", + "joinExpression": "t2.location_id = t7.location_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit", + "alias": "t8", + "joinExpression": "t8.visit_id = t2.visit_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit_type", + "alias": "t9", + "joinExpression": "t9.visit_type_id = t8.visit_type_id" + } ], - "orderBy":[ - {"column":"location", "order":"asc"} - ] + "parameters": [ + { "name": "startDate", "defaultValue": ["01-01-1980"] }, + { "name": "endDate", "defaultValue": ["Now()"] }, + { "name": "locations", "defaultValue": [1] }, + { "name": "providerUuid", "defaultValue": [1] }, + { "name": "formIds", "defaultValue": [1] }, + { "name": "encounterTypeIds", "defaultValue": [1] }, + { "name": "visitTypeIds", "defaultValue": [1] }, + { + "name": "groupByProviderId", + "defaultValue": [ + { "label": "provider_id", "expression": "provider_id" } + ] + }, + { + "name": "groupByEncounterTypeId", + "defaultValue": [ + { "label": "encounter_type_id", "expression": "encounter_type_id" } + ] + }, + { + "name": "groupByLocationId", + "defaultValue": [{ "label": "locations", "expression": "locations" }] + } + ], + "filters": [ + { + "expression": "date(t2.encounter_datetime) >= ?", + "parameter": "startDate" + }, + { + "expression": "date(t2.encounter_datetime) <= ?", + "parameter": "endDate" + }, + { "expression": "t2.location_id in ?", "parameter": "locations" }, + { "expression": "t4.uuid = ?", "parameter": "providerUuid" }, + { "expression": "t2.form_id in ?", "parameter": "formIds" }, + { + "expression": "t2.encounter_type in ?", + "parameter": "encounterTypeIds" + }, + { "expression": "t9.visit_type_id in ?", "parameter": "visitTypeIds" } + ], + "groupClause": [ + { "parameter": "groupByLocationId" }, + { "parameter": "groupByProviderId" }, + { "parameter": "groupByEncounterTypeId" } + ], + "indicators": [ + { + "label": "encounters_count", + "expression": "encounters_count", + "sql": "count(*)" + } + ], + "supplementColumns": [ + { + "label": "provider_id", + "type": "single", + "sql": "t4.provider_id" + }, + { + "label": "provider_uuid", + "type": "single", + "sql": "t4.uuid" + }, + { + "label": "encounter_type_id", + "type": "single", + "sql": "t2.encounter_type" + }, + { + "label": "encounter_type", + "type": "single", + "sql": "t3.name" + }, + { + "label": "encounter_type_uuid", + "type": "single", + "sql": "t3.uuid" + }, + { + "label": "provider_name", + "type": "single", + "sql": "CONCAT(COALESCE(t5.given_name, ''),' ', COALESCE(t5.middle_name, ''),' ', COALESCE(t5.family_name, ''))" + }, + { + "label": "is_clinical_encounter", + "type": "single", + "sql": "t6.is_clinical" + }, + { + "label": "locations", + "type": "single", + "sql": "t2.location_id" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t7.uuid" + }, + { + "label": "location", + "type": "single", + "sql": "t7.name" + } + ], + "orderBy": [{ "column": "location", "order": "asc" }] }, -{ - "name": "by-creator-by-encounter-type", - "table":{"schema":"amrs","tableName":"encounter_provider","alias":"t1"}, - "joins":[ - {"joinType":"JOIN","schema":"amrs","tableName":"encounter","alias":"t2","joinExpression":"t1.encounter_id = t2.encounter_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"encounter_type","alias":"t3","joinExpression":"t3.encounter_type_id = t2.encounter_type"}, - {"joinType":"JOIN","schema":"amrs","tableName":"provider","alias":"t4","joinExpression":"t4.provider_id = t1.provider_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"users","alias":"t5","joinExpression":"t2.creator = t5.user_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"person_name","alias":"t6","joinExpression":"t4.person_id = t6.person_id"}, - {"joinType":"LEFT OUTER JOIN","schema":"amrs","tableName":"provider","alias":"t9","joinExpression":"t5.person_id = t9.person_id"}, - {"joinType":"JOIN","schema":"etl","tableName":"clinical_encounter_type_map","alias":"t7","joinExpression":"t7.encounter_type = t2.encounter_type"}, - {"joinType":"JOIN","schema":"amrs","tableName":"location","alias":"t8","joinExpression":"t2.location_id = t8.location_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit","alias":"t10","joinExpression":"t10.visit_id = t2.visit_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit_type","alias":"t11","joinExpression":"t11.visit_type_id = t10.visit_type_id"} - - ], - "parameters": [ - {"name":"startDate", "defaultValue":["01-01-1980"]}, - {"name":"endDate", "defaultValue":["Now()"]}, - {"name":"locations","defaultValue":[1]}, - {"name":"providerUuid","defaultValue":[1]}, - {"name":"formIds","defaultValue":[1]}, - {"name":"encounterTypeIds","defaultValue":[1]}, - {"name":"visitTypeIds","defaultValue":[1]}, - {"name":"creatorUuid","defaultValue":[1]}, - {"name":"groupByCreatorId", "defaultValue":[ - {"label":"creator_id","expression":"creator_id"} - ] + { + "name": "by-creator-by-encounter-type", + "table": { + "schema": "amrs", + "tableName": "encounter_provider", + "alias": "t1" }, - {"name":"groupByEncounterTypeId", "defaultValue":[ - {"label":"encounter_type_id","expression":"encounter_type_id"} - ] + "joins": [ + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter", + "alias": "t2", + "joinExpression": "t1.encounter_id = t2.encounter_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter_type", + "alias": "t3", + "joinExpression": "t3.encounter_type_id = t2.encounter_type" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "provider", + "alias": "t4", + "joinExpression": "t4.provider_id = t1.provider_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "users", + "alias": "t5", + "joinExpression": "t2.creator = t5.user_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "person_name", + "alias": "t6", + "joinExpression": "t4.person_id = t6.person_id" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "amrs", + "tableName": "provider", + "alias": "t9", + "joinExpression": "t5.person_id = t9.person_id" + }, + { + "joinType": "JOIN", + "schema": "etl", + "tableName": "clinical_encounter_type_map", + "alias": "t7", + "joinExpression": "t7.encounter_type = t2.encounter_type" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t8", + "joinExpression": "t2.location_id = t8.location_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit", + "alias": "t10", + "joinExpression": "t10.visit_id = t2.visit_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit_type", + "alias": "t11", + "joinExpression": "t11.visit_type_id = t10.visit_type_id" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["01-01-1980"] }, + { "name": "endDate", "defaultValue": ["Now()"] }, + { "name": "locations", "defaultValue": [1] }, + { "name": "providerUuid", "defaultValue": [1] }, + { "name": "formIds", "defaultValue": [1] }, + { "name": "encounterTypeIds", "defaultValue": [1] }, + { "name": "visitTypeIds", "defaultValue": [1] }, + { "name": "creatorUuid", "defaultValue": [1] }, + { + "name": "groupByCreatorId", + "defaultValue": [{ "label": "creator_id", "expression": "creator_id" }] + }, + { + "name": "groupByEncounterTypeId", + "defaultValue": [ + { "label": "encounter_type_id", "expression": "encounter_type_id" } + ] + }, + { + "name": "groupByLocationId", + "defaultValue": [{ "label": "locations", "expression": "locations" }] + } + ], + "filters": [ + { + "expression": "date(t2.encounter_datetime) >= ?", + "parameter": "startDate" + }, + { + "expression": "date(t2.encounter_datetime) <= ?", + "parameter": "endDate" + }, + { "expression": "t2.location_id in ?", "parameter": "locations" }, + { "expression": "t4.uuid = ?", "parameter": "providerUuid" }, + { "expression": "t2.form_id in ?", "parameter": "formIds" }, + { + "expression": "t2.encounter_type in ?", + "parameter": "encounterTypeIds" + }, + { "expression": "t5.uuid in ?", "parameter": "creatorUuid" }, + { "expression": "t11.visit_type_id in ?", "parameter": "visitTypeIds" } + ], + "groupClause": [ + { "parameter": "groupByLocationId" }, + { "parameter": "groupByCreatorId" }, + { "parameter": "groupByEncounterTypeId" } + ], + "indicators": [ + { + "label": "encounters_count", + "expression": "encounters_count", + "sql": "count(*)" + } + ], + "supplementColumns": [ + { + "label": "creator_id", + "type": "single", + "sql": "t5.user_id" + }, + { + "label": "is_provider", + "type": "single", + "sql": "IF(t9.provider_id IS NOT NULL, 'YES', 'NO')" + }, + { + "label": "user_uuid", + "type": "single", + "sql": "t5.uuid" + }, + { + "label": "encounter_type_id", + "type": "single", + "sql": "t2.encounter_type" + }, + { + "label": "encounter_type", + "type": "single", + "sql": "t3.name" + }, + { + "label": "encounter_type_uuid", + "type": "single", + "sql": "t3.uuid" + }, + { + "label": "creator_name", + "type": "single", + "sql": "CONCAT(COALESCE(t6.given_name, ''),' ', COALESCE(t6.middle_name, ''),' ', COALESCE(t6.family_name, ''))" + }, + { + "label": "is_clinical_encounter", + "type": "single", + "sql": "t7.is_clinical" + }, + { + "label": "locations", + "type": "single", + "sql": "t2.location_id" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t8.uuid" + }, + { + "label": "location", + "type": "single", + "sql": "t8.name" + } + ], + "orderBy": [{ "column": "location", "order": "asc" }] + }, + { + "name": "patientList-encounter", + "table": { + "schema": "amrs", + "tableName": "encounter_provider", + "alias": "t1" }, - {"name":"groupByLocationId", "defaultValue":[ - {"label":"locations","expression":"locations"} - ] - } - ], - "filters": [ - {"expression":"date(t2.encounter_datetime) >= ?", "parameter":"startDate"}, - {"expression":"date(t2.encounter_datetime) <= ?", "parameter":"endDate"}, - {"expression":"t2.location_id in ?", "parameter":"locations"}, - {"expression":"t4.uuid = ?", "parameter":"providerUuid"}, - {"expression":"t2.form_id in ?", "parameter":"formIds"}, - {"expression":"t2.encounter_type in ?", "parameter":"encounterTypeIds"}, - {"expression":"t5.uuid in ?", "parameter":"creatorUuid"}, - {"expression":"t11.visit_type_id in ?", "parameter":"visitTypeIds"} - ], - "groupClause":[ - {"parameter":"groupByLocationId"}, - {"parameter":"groupByCreatorId"}, - {"parameter":"groupByEncounterTypeId"} - ], - "indicators": [ - { - "label":"encounters_count", - "expression":"encounters_count", - "sql":"count(*)" - } - ], - "supplementColumns":[ - { - "label":"creator_id", - "type":"single", - "sql":"t5.user_id" - }, - { - "label":"is_provider", - "type":"single", - "sql":"IF(t9.provider_id IS NOT NULL, 'YES', 'NO')" - }, - { - "label":"user_uuid", - "type":"single", - "sql":"t5.uuid" - }, - { - "label":"encounter_type_id", - "type":"single", - "sql":"t2.encounter_type" - }, - { - "label":"encounter_type", - "type":"single", - "sql":"t3.name" - }, - { - "label":"encounter_type_uuid", - "type":"single", - "sql":"t3.uuid" - }, - { - "label":"creator_name", - "type":"single", - "sql":"CONCAT(COALESCE(t6.given_name, ''),' ', COALESCE(t6.middle_name, ''),' ', COALESCE(t6.family_name, ''))" - }, - { - "label":"is_clinical_encounter", - "type":"single", - "sql":"t7.is_clinical" - }, - { - "label":"locations", - "type":"single", - "sql":"t2.location_id" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t8.uuid" - }, - { - "label":"location", - "type":"single", - "sql":"t8.name" - } + "joins": [ + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter", + "alias": "t2", + "joinExpression": "t1.encounter_id = t2.encounter_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "encounter_type", + "alias": "t3", + "joinExpression": "t3.encounter_type_id = t2.encounter_type" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "provider", + "alias": "t4", + "joinExpression": "t4.provider_id = t1.provider_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "users", + "alias": "t5", + "joinExpression": "t2.creator = t5.user_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit", + "alias": "t6", + "joinExpression": "t6.visit_id = t2.visit_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "visit_type", + "alias": "t7", + "joinExpression": "t7.visit_type_id = t6.visit_type_id" + } ], - "orderBy":[ - {"column":"location", "order":"asc"} - ] -}, -{ - "name": "patientList-encounter", - "table":{"schema":"amrs","tableName":"encounter_provider","alias":"t1"}, - "joins":[ - {"joinType":"JOIN","schema":"amrs","tableName":"encounter","alias":"t2","joinExpression":"t1.encounter_id = t2.encounter_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"encounter_type","alias":"t3","joinExpression":"t3.encounter_type_id = t2.encounter_type"}, - {"joinType":"JOIN","schema":"amrs","tableName":"provider","alias":"t4","joinExpression":"t4.provider_id = t1.provider_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"users","alias":"t5","joinExpression":"t2.creator = t5.user_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit","alias":"t6","joinExpression":"t6.visit_id = t2.visit_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"visit_type","alias":"t7","joinExpression":"t7.visit_type_id = t6.visit_type_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["01-01-1980"]}, - {"name":"endDate", "defaultValue":["Now()"]}, - {"name":"locations","defaultValue":[1]}, - {"name":"providerUuid","defaultValue":[1]}, - {"name":"formIds","defaultValue":[1]}, - {"name":"encounterTypeIds","defaultValue":[1]}, - {"name":"visitTypeIds","defaultValue":[1]}, - {"name":"creatorUuid","defaultValue":[1]} - ], - "filters": [ - {"expression":"date(t2.encounter_datetime) >= ?", "parameter":"startDate"}, - {"expression":"date(t2.encounter_datetime) <= ?", "parameter":"endDate"}, - {"expression":"t2.location_id in ?", "parameter":"locations"}, - {"expression":"t4.uuid = ?", "parameter":"providerUuid"}, - {"expression":"t2.form_id in ?", "parameter":"formIds"}, - {"expression":"t2.encounter_type in ?", "parameter":"encounterTypeIds"}, - {"expression":"t5.uuid = ?", "parameter":"creatorUuid"}, - {"expression":"t7.visit_type_id in ?", "parameter":"visitTypeIds"} - ], - "groupClause":[], - "indicators": [], - "supplementColumns":[ - { - "label":"patient_id", - "type":"single", - "sql":"DISTINCT t2.patient_id" - }, - { - "label":"creator_id", - "type":"single", - "sql":"t5.user_id" - }, - { - "label":"user_uuid", - "type":"single", - "sql":"t5.uuid" - }, - { - "label":"encounter_type_id", - "type":"single", - "sql":"t2.encounter_type" - }, - { - "label":"encounter_type", - "type":"single", - "sql":"t3.name" - }, - { - "label":"provider_id", - "type":"single", - "sql":"t4.provider_id" - }, - { - "label":"provider_uuid", - "type":"single", - "sql":"t4.uuid" - }, - { - "label":"year", - "type":"single", - "sql":"year(t2.encounter_datetime)" - }, - { - "label":"month_number", - "type":"single", - "sql":"month(t2.encounter_datetime)" - }, - { - "label":"month", - "type":"single", - "sql":"DATE_FORMAT(t2.encounter_datetime, '%M, %Y')" - }, - { - "label":"date", - "type":"single", - "sql":"date(t2.encounter_datetime)" - }, - { - "label":"location_id", - "type":"single", - "sql":"t2.location_id" - }, - { - "label":"form_id", - "type":"single", - "sql":"t2.form_id" - } + "parameters": [ + { "name": "startDate", "defaultValue": ["01-01-1980"] }, + { "name": "endDate", "defaultValue": ["Now()"] }, + { "name": "locations", "defaultValue": [1] }, + { "name": "providerUuid", "defaultValue": [1] }, + { "name": "formIds", "defaultValue": [1] }, + { "name": "encounterTypeIds", "defaultValue": [1] }, + { "name": "visitTypeIds", "defaultValue": [1] }, + { "name": "creatorUuid", "defaultValue": [1] } + ], + "filters": [ + { + "expression": "date(t2.encounter_datetime) >= ?", + "parameter": "startDate" + }, + { + "expression": "date(t2.encounter_datetime) <= ?", + "parameter": "endDate" + }, + { "expression": "t2.location_id in ?", "parameter": "locations" }, + { "expression": "t4.uuid = ?", "parameter": "providerUuid" }, + { "expression": "t2.form_id in ?", "parameter": "formIds" }, + { + "expression": "t2.encounter_type in ?", + "parameter": "encounterTypeIds" + }, + { "expression": "t5.uuid = ?", "parameter": "creatorUuid" }, + { "expression": "t7.visit_type_id in ?", "parameter": "visitTypeIds" } + ], + "groupClause": [], + "indicators": [], + "supplementColumns": [ + { + "label": "patient_id", + "type": "single", + "sql": "DISTINCT t2.patient_id" + }, + { + "label": "creator_id", + "type": "single", + "sql": "t5.user_id" + }, + { + "label": "user_uuid", + "type": "single", + "sql": "t5.uuid" + }, + { + "label": "encounter_type_id", + "type": "single", + "sql": "t2.encounter_type" + }, + { + "label": "encounter_type", + "type": "single", + "sql": "t3.name" + }, + { + "label": "provider_id", + "type": "single", + "sql": "t4.provider_id" + }, + { + "label": "provider_uuid", + "type": "single", + "sql": "t4.uuid" + }, + { + "label": "year", + "type": "single", + "sql": "year(t2.encounter_datetime)" + }, + { + "label": "month_number", + "type": "single", + "sql": "month(t2.encounter_datetime)" + }, + { + "label": "month", + "type": "single", + "sql": "DATE_FORMAT(t2.encounter_datetime, '%M, %Y')" + }, + { + "label": "date", + "type": "single", + "sql": "date(t2.encounter_datetime)" + }, + { + "label": "location_id", + "type": "single", + "sql": "t2.location_id" + }, + { + "label": "form_id", + "type": "single", + "sql": "t2.form_id" + } ] -}, -{ - "name": "patientList", - "table":{"schema":"amrs","tableName":"person_name","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","alias":"t2","joinExpression":"t2.patient_id = t1.person_id and (t1.voided is null || t1.voided = 0)", - "dynamicDataset":"patientList-encounter"}, - {"joinType":"JOIN","schema":"amrs","tableName":"person","alias":"t3","joinExpression":"t3.person_id = t2.patient_id"}, - {"joinType":"JOIN","schema":"amrs","tableName":"location","alias":"t5","joinExpression":"t2.location_id = t5.location_id"}, - {"joinType":"LEFT OUTER JOIN","schema":"amrs","tableName":"patient_identifier","alias":"t4","joinExpression":"t4.patient_id = t2.patient_id"}, - {"joinType":"LEFT OUTER JOIN","schema":"amrs","tableName":"person_attribute","alias":"contacts","joinExpression":"t3.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)"}, - {"joinType":"LEFT OUTER JOIN","schema":"etl","tableName":"flat_hiv_summary_v15b","alias":"fh","joinExpression":"t3.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) "}, - {"joinType":"LEFT OUTER JOIN","schema":"amrs","tableName":"encounter_type","alias":"et","joinExpression":"fh.encounter_type = et.encounter_type_id"}, - {"joinType":"LEFT OUTER JOIN","schema":"amrs","tableName":"person_address","alias":"pa","joinExpression":"t3.person_id = pa.person_id"} - ], - "parameters": [ - {"name":"groupByPatientId", "defaultValue":[ - {"label":"patient_id","expression":"patient_id"} - ] }, - {"name":"groupByLocationId", "defaultValue":[ - {"label":"location_id","expression":"location_id"} - ] - } - ], - "filters": [], - "groupClause":[ - {"parameter":"groupByLocationId"}, - {"parameter":"groupByPatientId"} - ], - "indicators": [], - "supplementColumns":[ - { - "label":"patient_id", - "type":"single", - "sql":"t2.patient_id" - }, - { - "label":"patient_uuid", - "type":"single", - "sql":"t3.uuid" - }, - { - "label":"person_name", - "type":"single", - "sql":"concat_ws(' ',t1.given_name,t1.middle_name,t1.family_name)" - }, - { - "label":"identifiers", - "type":"single", - "sql":"group_concat(distinct t4.identifier separator ', ')" - }, - { - "label":"provider_id", - "type":"single", - "sql":"t2.provider_id" - }, - { - "label":"provider_uuid", - "type":"single", - "sql":"t2.provider_uuid" - }, - { - "label":"gender", - "type":"single", - "sql":"t3.gender" - }, - { - "label": "age", - "type": "single", - "sql": "extract(year from (from_days(datediff(now(),t3.birthdate))))" - }, - { - "label":"birthdate", - "type":"single", - "sql":"t3.birthdate" - }, - { - "label":"month", - "type":"single", - "sql":"DATE_FORMAT(t2.date, '%M, %Y')" - }, - { - "label":"date", - "type":"single", - "sql":"date(t2.date)" - }, - { - "label":"location_id", - "type":"single", - "sql":"t2.location_id" - }, - { - "label":"location_name", - "type":"single", - "sql":"t5.name" - }, - { - "label":"form_id", - "type":"single", - "sql":"t2.form_id" - }, - { - "label":"creator_id", - "type":"single", - "sql":"t2.creator_id" - }, - { - "label":"phone_number", - "type":"single", - "sql":"GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" - }, - { - "label":"latest_rtc_date", - "type":"single", - "sql":"date_format(fh.rtc_date, '%Y-%m-%d')" - }, - { - "label":"latest_vl", - "type":"single", - "sql":"fh.vl_1" - }, - { - "label":"latest_vl_date", - "type":"single", - "sql":"date_format(fh.vl_1_date, '%Y-%m-%d')" - }, - { - "label":"last_appointment", - "type":"single", - "sql":"CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" - }, - { - "label":"cur_meds", - "type":"single", - "sql":"fh.cur_arv_meds" - }, - { - "type": "single", - "label": "previous_vl", - "sql": "fh.vl_2" - }, - { - "type": "single", - "label": "previous_vl_date", - "sql": "date_format(fh.vl_2_date, '%Y-%m-%d')" - }, - { - "type": "single", - "label": "nearest_center", - "sql": "pa.address3" - } + { + "name": "patientList", + "table": { "schema": "amrs", "tableName": "person_name", "alias": "t1" }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "alias": "t2", + "joinExpression": "t2.patient_id = t1.person_id and (t1.voided is null || t1.voided = 0)", + "dynamicDataset": "patientList-encounter" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t3", + "joinExpression": "t3.person_id = t2.patient_id" + }, + { + "joinType": "JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t5", + "joinExpression": "t2.location_id = t5.location_id" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "amrs", + "tableName": "patient_identifier", + "alias": "t4", + "joinExpression": "t4.patient_id = t2.patient_id" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "amrs", + "tableName": "person_attribute", + "alias": "contacts", + "joinExpression": "t3.person_id = contacts.person_id AND (contacts.voided IS NULL || contacts.voided = 0) AND contacts.person_attribute_type_id in (10, 48)" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "etl", + "tableName": "flat_hiv_summary_v15b", + "alias": "fh", + "joinExpression": "t3.person_id = fh.person_id AND fh.next_clinical_location_id IS NULL AND fh.encounter_type NOT IN (99999) " + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "amrs", + "tableName": "encounter_type", + "alias": "et", + "joinExpression": "fh.encounter_type = et.encounter_type_id" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "amrs", + "tableName": "person_address", + "alias": "pa", + "joinExpression": "t3.person_id = pa.person_id" + } + ], + "parameters": [ + { + "name": "groupByPatientId", + "defaultValue": [{ "label": "patient_id", "expression": "patient_id" }] + }, + { + "name": "groupByLocationId", + "defaultValue": [ + { "label": "location_id", "expression": "location_id" } + ] + } + ], + "filters": [], + "groupClause": [ + { "parameter": "groupByLocationId" }, + { "parameter": "groupByPatientId" } + ], + "indicators": [], + "supplementColumns": [ + { + "label": "patient_id", + "type": "single", + "sql": "t2.patient_id" + }, + { + "label": "patient_uuid", + "type": "single", + "sql": "t3.uuid" + }, + { + "label": "person_name", + "type": "single", + "sql": "concat_ws(' ',t1.given_name,t1.middle_name,t1.family_name)" + }, + { + "label": "identifiers", + "type": "single", + "sql": "group_concat(distinct t4.identifier separator ', ')" + }, + { + "label": "provider_id", + "type": "single", + "sql": "t2.provider_id" + }, + { + "label": "provider_uuid", + "type": "single", + "sql": "t2.provider_uuid" + }, + { + "label": "gender", + "type": "single", + "sql": "t3.gender" + }, + { + "label": "age", + "type": "single", + "sql": "extract(year from (from_days(datediff(now(),t3.birthdate))))" + }, + { + "label": "birthdate", + "type": "single", + "sql": "t3.birthdate" + }, + { + "label": "month", + "type": "single", + "sql": "DATE_FORMAT(t2.date, '%M, %Y')" + }, + { + "label": "date", + "type": "single", + "sql": "date(t2.date)" + }, + { + "label": "location_id", + "type": "single", + "sql": "t2.location_id" + }, + { + "label": "location_name", + "type": "single", + "sql": "t5.name" + }, + { + "label": "form_id", + "type": "single", + "sql": "t2.form_id" + }, + { + "label": "creator_id", + "type": "single", + "sql": "t2.creator_id" + }, + { + "label": "phone_number", + "type": "single", + "sql": "GROUP_CONCAT(DISTINCT contacts.value SEPARATOR ', ')" + }, + { + "label": "latest_rtc_date", + "type": "single", + "sql": "date_format(fh.rtc_date, '%Y-%m-%d')" + }, + { + "label": "latest_vl", + "type": "single", + "sql": "fh.vl_1" + }, + { + "label": "latest_vl_date", + "type": "single", + "sql": "date_format(fh.vl_1_date, '%Y-%m-%d')" + }, + { + "label": "last_appointment", + "type": "single", + "sql": "CONCAT(COALESCE(DATE_FORMAT(fh.encounter_datetime, '%Y-%m-%d'),''),' ',COALESCE(et.name, ''))" + }, + { + "label": "cur_meds", + "type": "single", + "sql": "fh.cur_arv_meds" + }, + { + "type": "single", + "label": "previous_vl", + "sql": "fh.vl_2" + }, + { + "type": "single", + "label": "previous_vl_date", + "sql": "date_format(fh.vl_2_date, '%Y-%m-%d')" + }, + { + "type": "single", + "label": "nearest_center", + "sql": "pa.address3" + } ] -} - + } ] diff --git a/reports/datasets/pep-dataset-report.json b/reports/datasets/pep-dataset-report.json index 5329bd3b6..e6e9f6f60 100755 --- a/reports/datasets/pep-dataset-report.json +++ b/reports/datasets/pep-dataset-report.json @@ -1,5 +1,4 @@ [ - { "name": "PEP-encounters-within-reporting-period-dataset", "table": { diff --git a/reports/hiv-care-continuum-report.json b/reports/hiv-care-continuum-report.json index a67910313..fcc1937f7 100755 --- a/reports/hiv-care-continuum-report.json +++ b/reports/hiv-care-continuum-report.json @@ -1,646 +1,735 @@ -[{ - "name": "hiv-care-continuum", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t2","joinExpression":"t1.location_uuid = t2.uuid"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locations","defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"location"} - ] - }, - {"name":"groupByYear", "defaultValue":[ - {"label":"encounter_datetime","expression":"YEAR(encounter_datetime)"} - ] - }, - {"name":"groupByMonth", "defaultValue":[ - {"label":"encounter_datetime","expression":"MONTH(encounter_datetime)"} - ] - } - ], - "filters": [ - {"expression":"t1.encounter_datetime >= ?", "parameter":"startDate"}, - {"expression":"t1.encounter_datetime <= ?", "parameter":"endDate"}, - {"expression":"t1.location_id in ?", "parameter":"locations"} - ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByYear"}, - {"parameter":"groupByMonth"} - ], - "indicators": [ - { - "label":"patients", - "expression":"patients", - "sql":"count(distinct person_id)" - }, - { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(distinct if($expression,person_id,0))" - - }, - { - "label":"enrolled_in_care_total", - "expression":"enrolled_in_care_total", - "sql": "count(distinct if($expression,person_id,0))" - - }, - { - "label":"virally_suppressed_in_past_year", - "expression":"virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,person_id,0))" - - }, - { - "label":"not_virally_suppressed_in_past_year", - "expression":"not_virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,person_id,0))" - - }, - { - "label":"perc_on_arvs", - "expression":"perc_on_arvs", - "sql":"[on_arvs]/[patients]" - }, - { - "label":"perc_in_care", - "expression":"perc_in_care", - "sql":"[enrolled_in_care_total]/[patients]" - }, - { - "label":"perc_virally_suppressed_in_past_year", - "expression":"perc_virally_suppressed_in_past_year", - "sql":"[virally_suppressed_in_past_year]/[patients]" - }, - { - "label":"perc_not_virally_suppressed_in_past_year", - "expression":"perc_virally_suppressed_in_past_year", - "sql":"[not_virally_suppressed_in_past_year]/[patients]" - }, - { - "label":"perc_on_arv_first_line", - "expression":"perc_on_arv_first_line", - "sql":"[on_arvs_first_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_second_line", - "expression":"perc_on_arv_second_line", - "sql":"[on_arvs_second_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_third_line", - "expression":"perc_on_arv_third_line", - "sql":"[on_arvs_third_line]/[on_arvs]" - }, - { - "label":"perc_with_pending_viral_load", - "expression":"perc_with_pending_viral_load", - "sql":"[pending_vl_order]/[on_arvs]" - }, - { - "label":"pending_vl_order", - "expression":"pending_vl_order", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"perc_on_arvs_lte_6_months", - "expression":"perc_on_arvs_lte_6_months", - "sql":"[on_arvs_lte_26_weeks]/[on_arvs]" - }, - { - "label":"on_arvs_third_line", - "expression":"on_arvs_third_line", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_lte_26_weeks", - "expression":"on_arvs_lte_26_weeks", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_gt_26_weeks", - "expression":"on_arvs_gt_26_weeks", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_second_line", - "expression":"on_arvs_second_line", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_first_line", - "expression":"on_arvs_first_line", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_lte_26_weeks", - "expression":"on_arvs_lte_26_weeks", - "sql": "count(distinct if($expression,person_id,0))" - } - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t2.name" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"encounter_datetime", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"month", - "type":"single", - "sql":"t1.encounter_datetime" - } +[ + { + "name": "hiv-care-continuum", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locations", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [{ "label": "location", "expression": "location" }] + }, + { + "name": "groupByYear", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "YEAR(encounter_datetime)" + } + ] + }, + { + "name": "groupByMonth", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "MONTH(encounter_datetime)" + } + ] + } + ], + "filters": [ + { "expression": "t1.encounter_datetime >= ?", "parameter": "startDate" }, + { "expression": "t1.encounter_datetime <= ?", "parameter": "endDate" }, + { "expression": "t1.location_id in ?", "parameter": "locations" } + ], + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByYear" }, + { "parameter": "groupByMonth" } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct person_id)" + }, + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "enrolled_in_care_total", + "expression": "enrolled_in_care_total", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "virally_suppressed_in_past_year", + "expression": "virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "not_virally_suppressed_in_past_year", + "expression": "not_virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "perc_on_arvs", + "expression": "perc_on_arvs", + "sql": "[on_arvs]/[patients]" + }, + { + "label": "perc_in_care", + "expression": "perc_in_care", + "sql": "[enrolled_in_care_total]/[patients]" + }, + { + "label": "perc_virally_suppressed_in_past_year", + "expression": "perc_virally_suppressed_in_past_year", + "sql": "[virally_suppressed_in_past_year]/[patients]" + }, + { + "label": "perc_not_virally_suppressed_in_past_year", + "expression": "perc_virally_suppressed_in_past_year", + "sql": "[not_virally_suppressed_in_past_year]/[patients]" + }, + { + "label": "perc_on_arv_first_line", + "expression": "perc_on_arv_first_line", + "sql": "[on_arvs_first_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_second_line", + "expression": "perc_on_arv_second_line", + "sql": "[on_arvs_second_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_third_line", + "expression": "perc_on_arv_third_line", + "sql": "[on_arvs_third_line]/[on_arvs]" + }, + { + "label": "perc_with_pending_viral_load", + "expression": "perc_with_pending_viral_load", + "sql": "[pending_vl_order]/[on_arvs]" + }, + { + "label": "pending_vl_order", + "expression": "pending_vl_order", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "perc_on_arvs_lte_6_months", + "expression": "perc_on_arvs_lte_6_months", + "sql": "[on_arvs_lte_26_weeks]/[on_arvs]" + }, + { + "label": "on_arvs_third_line", + "expression": "on_arvs_third_line", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_gt_26_weeks", + "expression": "on_arvs_gt_26_weeks", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_second_line", + "expression": "on_arvs_second_line", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_first_line", + "expression": "on_arvs_first_line", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "count(distinct if($expression,person_id,0))" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t2.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_datetime", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "month", + "type": "single", + "sql": "t1.encounter_datetime" + } ] -}, -{ - "name": "hiv-care-continuum-enrolled", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t2","joinExpression":"t1.location_uuid = t2.uuid"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locations","defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"location"} - ] - }, - {"name":"groupByYear", "defaultValue":[ - {"label":"encounter_datetime","expression":"YEAR(encounter_datetime)"} - ] - }, - {"name":"groupByMonth", "defaultValue":[ - {"label":"encounter_datetime","expression":"MONTH(encounter_datetime)"} - ] - } - ], - "filters": [ - {"expression":"t1.enrollment_date >= ?", "parameter":"startDate"}, - {"expression":"t1.enrollment_date <= ?", "parameter":"endDate"}, - {"expression":"t1.location_id in ?", "parameter":"locations"} - ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByYear"}, - {"parameter":"groupByMonth"} - ], - "indicators": [ - { - "label":"patients", - "expression":"patients", - "sql":"count(distinct person_id)" - }, - { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(distinct if($expression,person_id,0))" - - }, - { - "label":"enrolled_in_care_total", - "expression":"enrolled_in_care_total", - "sql": "count(distinct if($expression,person_id,0))" - - }, - { - "label":"virally_suppressed_in_past_year", - "expression":"virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,person_id,0))" - - }, - { - "label":"perc_on_arvs", - "expression":"perc_on_arvs", - "sql":"[on_arvs]/[patients]" - }, - { - "label":"perc_in_care", - "expression":"perc_in_care", - "sql":"[enrolled_in_care_total]/[patients]" - }, - { - "label":"perc_virally_suppressed_in_past_year", - "expression":"perc_virally_suppressed_in_past_year", - "sql":"[virally_suppressed_in_past_year]/[patients]" - } - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t2.name" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"encounter_datetime", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"month", - "type":"single", - "sql":"t1.encounter_datetime" - } + }, + { + "name": "hiv-care-continuum-enrolled", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locations", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [{ "label": "location", "expression": "location" }] + }, + { + "name": "groupByYear", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "YEAR(encounter_datetime)" + } + ] + }, + { + "name": "groupByMonth", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "MONTH(encounter_datetime)" + } + ] + } + ], + "filters": [ + { "expression": "t1.enrollment_date >= ?", "parameter": "startDate" }, + { "expression": "t1.enrollment_date <= ?", "parameter": "endDate" }, + { "expression": "t1.location_id in ?", "parameter": "locations" } + ], + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByYear" }, + { "parameter": "groupByMonth" } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct person_id)" + }, + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "enrolled_in_care_total", + "expression": "enrolled_in_care_total", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "virally_suppressed_in_past_year", + "expression": "virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "perc_on_arvs", + "expression": "perc_on_arvs", + "sql": "[on_arvs]/[patients]" + }, + { + "label": "perc_in_care", + "expression": "perc_in_care", + "sql": "[enrolled_in_care_total]/[patients]" + }, + { + "label": "perc_virally_suppressed_in_past_year", + "expression": "perc_virally_suppressed_in_past_year", + "sql": "[virally_suppressed_in_past_year]/[patients]" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t2.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_datetime", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "month", + "type": "single", + "sql": "t1.encounter_datetime" + } ] -} -, -{ - "name": "hiv-care-continuum-on-arv-past-6-months", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t2","joinExpression":"t1.location_uuid = t2.uuid"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locations","defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"location"} - ] - }, - {"name":"groupByYear", "defaultValue":[ - {"label":"encounter_datetime","expression":"YEAR(encounter_datetime)"} - ] - }, - {"name":"groupByMonth", "defaultValue":[ - {"label":"encounter_datetime","expression":"MONTH(encounter_datetime)"} - ] - } - ], - "filters": [ - {"expression":"timestampdiff(month,?,t1.arv_start_date) > 6", "parameter":"startDate"}, - {"expression":"t1.location_id in ?", "parameter":"locations"} - ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByYear"}, - {"parameter":"groupByMonth"} - ], - "indicators": [ - { - "label":"patients", - "expression":"patients", - "sql":"count(distinct person_id)" - }, - { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(distinct if($expression,person_id,0))" - - }, - { - "label":"enrolled_in_care_total", - "expression":"enrolled_in_care_total", - "sql": "count(distinct if($expression,person_id,0))" - - }, - { - "label":"virally_suppressed_in_past_year", - "expression":"virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,person_id,0))" - - }, - { - "label":"not_virally_suppressed_in_past_year", - "expression":"not_virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,person_id,0))" - - }, - { - "label":"perc_in_care", - "expression":"perc_in_care", - "sql":"[enrolled_in_care_total]/[patients]" - }, - { - "label":"perc_virally_suppressed_in_past_year", - "expression":"perc_virally_suppressed_in_past_year", - "sql":"[virally_suppressed_in_past_year]/[on_arvs]" - }, - { - "label":"perc_not_virally_suppressed_in_past_year", - "expression":"perc_not_virally_suppressed_in_past_year", - "sql":"[not_virally_suppressed_in_past_year]/[on_arvs]" - } - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t2.name" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"encounter_datetime", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"month", - "type":"single", - "sql":"t1.encounter_datetime" - } + }, + { + "name": "hiv-care-continuum-on-arv-past-6-months", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locations", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [{ "label": "location", "expression": "location" }] + }, + { + "name": "groupByYear", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "YEAR(encounter_datetime)" + } + ] + }, + { + "name": "groupByMonth", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "MONTH(encounter_datetime)" + } + ] + } + ], + "filters": [ + { + "expression": "timestampdiff(month,?,t1.arv_start_date) > 6", + "parameter": "startDate" + }, + { "expression": "t1.location_id in ?", "parameter": "locations" } + ], + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByYear" }, + { "parameter": "groupByMonth" } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct person_id)" + }, + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "enrolled_in_care_total", + "expression": "enrolled_in_care_total", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "virally_suppressed_in_past_year", + "expression": "virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "not_virally_suppressed_in_past_year", + "expression": "not_virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "perc_in_care", + "expression": "perc_in_care", + "sql": "[enrolled_in_care_total]/[patients]" + }, + { + "label": "perc_virally_suppressed_in_past_year", + "expression": "perc_virally_suppressed_in_past_year", + "sql": "[virally_suppressed_in_past_year]/[on_arvs]" + }, + { + "label": "perc_not_virally_suppressed_in_past_year", + "expression": "perc_not_virally_suppressed_in_past_year", + "sql": "[not_virally_suppressed_in_past_year]/[on_arvs]" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t2.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_datetime", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "month", + "type": "single", + "sql": "t1.encounter_datetime" + } ] -}, + }, -{ - "name": "hiv-care-continuum-virally-suppressed", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t2","joinExpression":"t1.location_uuid = t2.uuid"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locations","defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"location"} - ] - }, - {"name":"groupByYear", "defaultValue":[ - {"label":"encounter_datetime","expression":"YEAR(encounter_datetime)"} - ] - }, - {"name":"groupByMonth", "defaultValue":[ - {"label":"encounter_datetime","expression":"MONTH(encounter_datetime)"} - ] - } - ], - "filters": [ - {"expression":"t1.encounter_datetime >= ?", "parameter":"startDate"}, - {"expression":"t1.encounter_datetime <= ?", "parameter":"endDate"}, - {"expression":"t1.location_id in ?", "parameter":"locations"} - ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByYear"}, - {"parameter":"groupByMonth"} - ], - "indicators": [ - { - "label":"patients", - "expression":"patients", - "sql":"count(distinct person_id)" - }, - { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(distinct if($expression,person_id,0))" - - } , - { - "label":"on_arvs_lte_26_weeks", - "expression":"on_arvs_lte_26_weeks", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_gt_26_weeks", - "expression":"on_arvs_gt_26_weeks", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_second_line", - "expression":"on_arvs_second_line", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_first_line", - "expression":"on_arvs_first_line", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_lte_26_weeks", - "expression":"on_arvs_lte_26_weeks", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_third_line", - "expression":"on_arvs_third_line", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"perc_on_arv_first_line", - "expression":"perc_on_arv_first_line", - "sql":"[on_arvs_first_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_second_line", - "expression":"perc_on_arv_second_line", - "sql":"[on_arvs_second_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_third_line", - "expression":"perc_on_arv_third_line", - "sql":"[on_arvs_third_line]/[on_arvs]" - }, - { - "label":"perc_on_arvs_lte_6_months", - "expression":"perc_on_arvs_lte_6_months", - "sql":"[on_arvs_lte_26_weeks]/[on_arvs]" - } - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t2.name" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"encounter_datetime", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"month", - "type":"single", - "sql":"t1.encounter_datetime" - } + { + "name": "hiv-care-continuum-virally-suppressed", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locations", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [{ "label": "location", "expression": "location" }] + }, + { + "name": "groupByYear", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "YEAR(encounter_datetime)" + } + ] + }, + { + "name": "groupByMonth", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "MONTH(encounter_datetime)" + } + ] + } + ], + "filters": [ + { "expression": "t1.encounter_datetime >= ?", "parameter": "startDate" }, + { "expression": "t1.encounter_datetime <= ?", "parameter": "endDate" }, + { "expression": "t1.location_id in ?", "parameter": "locations" } + ], + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByYear" }, + { "parameter": "groupByMonth" } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct person_id)" + }, + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_gt_26_weeks", + "expression": "on_arvs_gt_26_weeks", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_second_line", + "expression": "on_arvs_second_line", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_first_line", + "expression": "on_arvs_first_line", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_third_line", + "expression": "on_arvs_third_line", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "perc_on_arv_first_line", + "expression": "perc_on_arv_first_line", + "sql": "[on_arvs_first_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_second_line", + "expression": "perc_on_arv_second_line", + "sql": "[on_arvs_second_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_third_line", + "expression": "perc_on_arv_third_line", + "sql": "[on_arvs_third_line]/[on_arvs]" + }, + { + "label": "perc_on_arvs_lte_6_months", + "expression": "perc_on_arvs_lte_6_months", + "sql": "[on_arvs_lte_26_weeks]/[on_arvs]" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t2.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_datetime", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "month", + "type": "single", + "sql": "t1.encounter_datetime" + } ] -}, -{ - "name": "hiv-care-continuum-not-virally-suppressed", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t2","joinExpression":"t1.location_uuid = t2.uuid"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locations","defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"location"} - ] - }, - {"name":"groupByYear", "defaultValue":[ - {"label":"encounter_datetime","expression":"YEAR(encounter_datetime)"} - ] - }, - {"name":"groupByMonth", "defaultValue":[ - {"label":"encounter_datetime","expression":"MONTH(encounter_datetime)"} - ] - } - ], - "filters": [ - {"expression":"t1.encounter_datetime >= ?", "parameter":"startDate"}, - {"expression":"t1.encounter_datetime <= ?", "parameter":"endDate"}, - {"expression":"t1.location_id in ?", "parameter":"locations"} - ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByYear"}, - {"parameter":"groupByMonth"} - ], - "indicators": [ - { - "label":"patients", - "expression":"patients", - "sql":"count(distinct person_id)" - }, - { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(distinct if($expression,person_id,0))" - - } , - { - "label":"on_arvs_lte_26_weeks", - "expression":"on_arvs_lte_26_weeks", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_gt_26_weeks", - "expression":"on_arvs_gt_26_weeks", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_second_line", - "expression":"on_arvs_second_line", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_first_line", - "expression":"on_arvs_first_line", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_lte_26_weeks", - "expression":"on_arvs_lte_26_weeks", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"on_arvs_third_line", - "expression":"on_arvs_third_line", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"pending_vl_order", - "expression":"pending_vl_order", - "sql": "count(distinct if($expression,person_id,0))" - }, - { - "label":"perc_on_arv_first_line", - "expression":"perc_on_arv_first_line", - "sql":"[on_arvs_first_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_second_line", - "expression":"perc_on_arv_second_line", - "sql":"[on_arvs_second_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_third_line", - "expression":"perc_on_arv_third_line", - "sql":"[on_arvs_third_line]/[on_arvs]" - }, - { - "label":"perc_on_arvs_lte_6_months", - "expression":"perc_on_arvs_lte_6_months", - "sql":"[on_arvs_lte_26_weeks]/[patients]" - }, - { - "label":"perc_with_pending_viral_load", - "expression":"perc_with_pending_viral_load", - "sql":"[pending_vl_order]/[on_arvs]" - }, - { - "label":"perc_on_arvs_gt_6_months", - "expression":"perc_on_arvs_gt_6_months", - "sql":"[on_arvs_gt_26_weeks]/[patients]" - } - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t2.name" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"encounter_datetime", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"month", - "type":"single", - "sql":"t1.encounter_datetime" - } + }, + { + "name": "hiv-care-continuum-not-virally-suppressed", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locations", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [{ "label": "location", "expression": "location" }] + }, + { + "name": "groupByYear", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "YEAR(encounter_datetime)" + } + ] + }, + { + "name": "groupByMonth", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "MONTH(encounter_datetime)" + } + ] + } + ], + "filters": [ + { "expression": "t1.encounter_datetime >= ?", "parameter": "startDate" }, + { "expression": "t1.encounter_datetime <= ?", "parameter": "endDate" }, + { "expression": "t1.location_id in ?", "parameter": "locations" } + ], + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByYear" }, + { "parameter": "groupByMonth" } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct person_id)" + }, + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_gt_26_weeks", + "expression": "on_arvs_gt_26_weeks", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_second_line", + "expression": "on_arvs_second_line", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_first_line", + "expression": "on_arvs_first_line", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "on_arvs_third_line", + "expression": "on_arvs_third_line", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "pending_vl_order", + "expression": "pending_vl_order", + "sql": "count(distinct if($expression,person_id,0))" + }, + { + "label": "perc_on_arv_first_line", + "expression": "perc_on_arv_first_line", + "sql": "[on_arvs_first_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_second_line", + "expression": "perc_on_arv_second_line", + "sql": "[on_arvs_second_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_third_line", + "expression": "perc_on_arv_third_line", + "sql": "[on_arvs_third_line]/[on_arvs]" + }, + { + "label": "perc_on_arvs_lte_6_months", + "expression": "perc_on_arvs_lte_6_months", + "sql": "[on_arvs_lte_26_weeks]/[patients]" + }, + { + "label": "perc_with_pending_viral_load", + "expression": "perc_with_pending_viral_load", + "sql": "[pending_vl_order]/[on_arvs]" + }, + { + "label": "perc_on_arvs_gt_6_months", + "expression": "perc_on_arvs_gt_6_months", + "sql": "[on_arvs_gt_26_weeks]/[patients]" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t2.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_datetime", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "month", + "type": "single", + "sql": "t1.encounter_datetime" + } ] -} - + } ] diff --git a/reports/hiv-summary-monthly-report.json b/reports/hiv-summary-monthly-report.json index 4065a7805..013b92275 100755 --- a/reports/hiv-summary-monthly-report.json +++ b/reports/hiv-summary-monthly-report.json @@ -1,515 +1,546 @@ [ - { - "name": "hiv-summary-monthly-report", - "table":{"schema":"etl","tableName":"dates","alias":"t2"}, - "joins":[ - {"joinType":"JOIN","schema":"etl","tableName":"flat_hiv_summary","alias":"t1", - "joinExpression":"is_clinical_encounter=1 and encounter_datetime <= t2.endDate and coalesce(t1.death_date, out_of_care) is null"}, - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t3", - "joinExpression":"t1.location_uuid = t3.uuid"}, - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t4","joinExpression":"t1.person_id = t4.person_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["01-01-1980"]}, - {"name":"endDate", "defaultValue":["Now()"]}, - {"name":"startAge", "defaultValue":[]}, - {"name":"endAge", "defaultValue":[]}, - {"name":"gender", "defaultValue":[]}, - {"name":"locationUuids","defaultValue":[1]}, - {"name":"groupByYear", "defaultValue":[ - {"label":"encounter_datetime","expression":"YEAR(encounter_datetime)"} - ] - }, - {"name":"groupByMonth", "defaultValue":[ - {"label":"encounter_datetime","expression":"MONTH(encounter_datetime)"} - ] - } - ], - "filters": [ - {"expression":"t1.encounter_datetime >= ?", "parameter":"startDate"}, - {"expression":"t1.encounter_datetime <= ?", "parameter":"endDate"}, - {"expression":"t1.location_uuid in ?", "parameter":"locationUuids"}, - {"expression":"round(datediff(t1.encounter_datetime,t4.birthdate)/365) >= ?", "parameter":"startAge"}, - {"expression":"round(datediff(t1.encounter_datetime,t4.birthdate)/365) <= ?", "parameter":"endAge"}, - {"expression":"t4.gender in ?", "parameter":"gender"}, - {"expression":"t1.is_clinical_encounter = 1", "processForce":true}, - {"expression":"coalesce(t1.death_date, out_of_care) is null", "processForce":true}, - {"expression":"(t1.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= t2.endDate)", "processForce":true} - - - ], - "groupClause":[ - {"parameter":"groupByYear"}, - {"parameter":"groupByMonth"} - ], - "indicators": [ - { - "label":"patients", - "expression":"patients", - "sql":"count(distinct t1.person_id)" - }, - { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"on_arvs_first_line", - "expression":"on_arvs_first_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_second_line", - "expression":"on_arvs_second_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"newly_on_second_line", - "expression":"newly_on_second_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_third_line", - "expression":"on_arvs_third_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_past_year", - "expression":"vl_done_past_year", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label": "vl_done_past_year_relative_to_end_date", - "expression": "vl_done_past_year_relative_to_end_date", - "sql": "count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"no_vl_done_past_year", - "expression":"no_vl_done_past_year", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_second_line_not_suppressed", - "expression":"on_second_line_not_suppressed", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"not_on_arvs_cd4_lte_500", - "expression":"not_on_arvs_cd4_lte_500", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_past_year_lte_1000", - "expression":"vl_done_past_year_lte_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_past_year_gt_1000", - "expression":"vl_done_past_year_gt_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_this_encounter", - "expression":"vl_done_this_encounter", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_this_encounter_lte_1000", - "expression":"vl_done_this_encounter_lte_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_this_encounter_gt_1000", - "expression":"vl_done_this_encounter_gt_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_ordered", - "expression":"vl_ordered", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pending_vl_order", - "expression":"pending_vl_order", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pending_vl_order_no_result_after_4_weeks", - "expression":"pending_vl_order_no_result_after_4_weeks", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_26_weeks", - "expression":"on_arvs_lte_26_weeks", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_52_weeks", - "expression":"on_arvs_lte_52_weeks", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_52_weeks_and_have_vl", - "expression":"on_arvs_lte_52_weeks_and_have_vl", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expression":"on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pregnant", - "expression":"pregnant", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pregnant_and_on_arvs", - "expression":"pregnant_and_on_arvs", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"virally_suppressed", - "expression":"virally_suppressed", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"virally_suppressed_in_past_year", - "expression":"virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,t1.person_id,0))" - - }, - { - "label":"viral_load_resulted_in_past_year", - "expression":"viral_load_resulted_in_past_year", - "sql": "count(distinct if($expression,t1.person_id,0))" - - }, - { - "label":"not_virally_suppressed_in_past_year", - "expression":"not_virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,t1.person_id,0))" - - }, - { - "label":"perc_virally_suppressed_in_past_year", - "expression":"perc_virally_suppressed_in_past_year", - "sql":"[virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" - }, - { - "label":"perc_not_virally_suppressed_in_past_year", - "expression":"perc_not_virally_suppressed_in_past_year", - "sql":"[not_virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" - }, - { - "label":"perc_on_arvs", - "expression":"perc_on_arvs", - "sql":"[on_arvs]/[patients]" - }, - { - "label":"perc_on_arv_first_line", - "expression":"perc_on_arv_first_line", - "sql":"[on_arvs_first_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_second_line", - "expression":"perc_on_arv_second_line", - "sql":"[on_arvs_second_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_third_line", - "expression":"perc_on_arv_third_line", - "sql":"[on_arvs_third_line]/[on_arvs]" - }, - { - "label":"perc_with_pending_viral_load", - "expression":"perc_with_pending_viral_load", - "sql":"[pending_vl_order]/[on_arvs]" - }, - { - "label":"perc_on_arvs_lte_6_months", - "expression":"perc_on_arvs_lte_6_months", - "sql":"[on_arvs_lte_26_weeks]/[on_arvs]" - }, - { - "label":"on_arvs_gt_26_weeks", - "expression":"on_arvs_gt_26_weeks", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"perc_on_arvs_gt_6_months", - "expression":"perc_on_arvs_gt_6_months", - "sql":"[on_arvs_gt_26_weeks]/[patients]" - }, - { - "label":"perc_ART_pats_screened_for_TB_receiving_TB_medication", - "expression":"perc_ART_pats_screened_for_TB_receiving_TB_medication", - "sql":"[num_ART_pats_screened_for_tb_started_TB]/[num_ART_pats_screened_for_tb]" - }, - - { - "label":"num_new_ART_pats_screened_for_tb_started_TB_this_period", - "expression":"num_new_ART_pats_screened_for_tb_started_TB_this_period", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_previous_ART_pats_screened_for_tb_started_TB", - "expression":"num_previous_ART_pats_screened_for_tb_started_TB", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_ART_pats_screened_for_tb_started_TB", - "expression":"num_ART_pats_screened_for_tb_started_TB", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_ART_pats_screened_for_tb_started_TB_female_below_15", - "expression":"num_ART_pats_screened_for_tb_started_TB_female_below_15", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_pats_screened_for_tb_started_TB", - "filters": ["female", "age_below_15"] - } - }, - { - "label":"num_ART_pats_screened_for_tb_started_TB_female_above_15", - "expression":"num_ART_pats_screened_for_tb_started_TB_female_above_15", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_pats_screened_for_tb_started_TB", - "filters": ["female","age_15_and_older"] - } - }, - { - "label":"num_ART_pats_screened_for_tb_started_TB_male_below_15", - "expression":"num_ART_pats_screened_for_tb_started_TB_male_below_15", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_pats_screened_for_tb_started_TB", - "filters": ["male", "age_below_15"] - } - }, - { - "label":"num_ART_pats_screened_for_tb_started_TB_male_above_15", - "expression":"num_ART_pats_screened_for_tb_started_TB_male_above_15", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_pats_screened_for_tb_started_TB", - "filters": ["male","age_15_and_older"] - } - }, - { - "label":"num_ART_pats_screened_for_tb", - "expression":"num_ART_pats_screened_for_tb", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_ART_pats_screened_for_tb_female_below_15", - "expression":"num_ART_pats_screened_for_tb_female_below_15", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_pats_screened_for_tb", - "filters": ["female", "age_below_15"] - } - }, - { - "label":"num_ART_pats_screened_for_tb_female_above_15", - "expression":"num_ART_pats_screened_for_tb_female_above_15", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_pats_screened_for_tb", - "filters": ["female","age_15_and_older"] - } - }, - { - "label":"num_ART_pats_screened_for_tb_male_below_15", - "expression":"num_ART_pats_screened_for_tb_male_below_15", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_pats_screened_for_tb", - "filters": ["male", "age_below_15"] - } - }, - { - "label":"num_ART_pats_screened_for_tb_male_above_15", - "expression":"num_ART_pats_screened_for_tb_male_above_15", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_pats_screened_for_tb", - "filters": ["male","age_15_and_older"] - } - }, - { - "label":"perc_ART_pats_completed_6mths_IPT", - "expression":"perc_ART_pats_completed_6mths_IPT", - "sql": "[num_ART_patients_completed_6mths_IPT]/[num_ART_patients_newly_started_IPT_less_6mths]" - }, - { - "label":"num_ART_patients_completed_6mths_IPT", - "expression":"num_ART_patients_completed_6mths_IPT", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_ART_patients_completed_6mths_IPT_females_below_15_yrs", - "expression":"num_ART_patients_completed_6mths_IPT_females_below_15_yrs", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_patients_completed_6mths_IPT", - "filters": ["female", "age_below_15"] - } - }, - { - "label":"num_ART_patients_completed_6mths_IPT_females_above_15_yrs", - "expression":"num_ART_patients_completed_6mths_IPT_females_above_15_yrs", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_patients_completed_6mths_IPT", - "filters": ["female","age_15_and_older"] - } - }, - { - "label":"num_ART_patients_completed_6mths_IPT_males_below_15_yrs", - "expression":"num_ART_patients_completed_6mths_IPT_males_below_15_yrs", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_patients_completed_6mths_IPT", - "filters": ["male", "age_below_15"] - } - }, - { - "label":"num_ART_patients_completed_6mths_IPT_males_above_15_yrs", - "expression":"num_ART_patients_completed_6mths_IPT_males_above_15_yrs", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_patients_completed_6mths_IPT", - "filters": ["male","age_15_and_older"] - } - }, - { - "label":"num_ART_patients_newly_started_IPT_less_6mths", - "expression":"num_ART_patients_newly_started_IPT_less_6mths", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_ART_patients_newly_started_IPT_less_6mths_females_below_15yrs", - "expression":"num_ART_patients_newly_started_IPT_less_6mths_females_below_15yrs", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_patients_newly_started_IPT_less_6mths", - "filters": ["male","age_15_and_older"] - } - }, - { - "label":"num_ART_patients_newly_started_IPT_less_6mths_females_above_15yrs", - "expression":"num_ART_patients_newly_started_IPT_less_6mths_females_above_15yrs", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_patients_newly_started_IPT_less_6mths", - "filters": ["female", "age_below_15"] - } - }, - { - "label":"num_ART_patients_newly_started_IPT_less_6mths_males_below_15yrs", - "expression":"num_ART_patients_newly_started_IPT_less_6mths_males_below_15yrs", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_patients_newly_started_IPT_less_6mths", - "filters": ["male", "age_below_15"] - } - }, - { - "label":"num_ART_patients_newly_started_IPT_less_6mths_males_above_15yrs", - "expression":"num_ART_patients_newly_started_IPT_less_6mths_males_above_15yrs", - "sql": "count(distinct if($expression,t1.person_id,0))", - "disaggregation": { - "indicator":"num_ART_patients_newly_started_IPT_less_6mths", - "filters": ["male","age_15_and_older"] - } - }, - { - "label":"num_ART_patients_newly_started_IPT_this_period_less_6mths", - "expression":"num_ART_patients_newly_started_IPT_this_period_less_6mths", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_ART_patients_newly_started_IPT_previous_period_less_6mths", - "expression":"num_ART_patients_newly_started_IPT_previous_period_less_6mths", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_patients_currently_on_IPT", - "expression":"num_patients_currently_on_IPT", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"ever_started_on_IPT", - "expression":"ever_started_on_IPT", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"newly_started_IPT", - "expression":"newly_started_IPT", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_patients_newly_enrolled_newly_started_on_IPT", - "expression":"num_patients_newly_enrolled_newly_started_on_IPT", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"num_patients_stopped_on_IPT", - "expression":"num_patients_stopped_on_IPT", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"transfer_in_from_non_Ampath_site", - "expression":"transfer_in_from_non_Ampath_site", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"transfer_in_from_Ampath_site", - "expression":"transfer_in_from_Ampath_site", - "sql": "count(distinct if($expression,t1.person_id,0))" - }, - { - "label":"transfer_in", - "expression":"transfer_in", - "sql": "count(distinct if($expression,t1.person_id,0))" - } - - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t3.name" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"encounter_datetime", - "type":"single", - "sql":"t2.endDate" - }, - { - "label":"month", - "type":"single", - "sql":"t2.endDate" - }, - { - "label":"reporting_month", - "type":"single", - "sql":"date_format(t2.endDate, '%m/%Y')" - } + { + "name": "hiv-summary-monthly-report", + "table": { "schema": "etl", "tableName": "dates", "alias": "t2" }, + "joins": [ + { + "joinType": "JOIN", + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1", + "joinExpression": "is_clinical_encounter=1 and encounter_datetime <= t2.endDate and coalesce(t1.death_date, out_of_care) is null" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t3", + "joinExpression": "t1.location_uuid = t3.uuid" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t4", + "joinExpression": "t1.person_id = t4.person_id" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["01-01-1980"] }, + { "name": "endDate", "defaultValue": ["Now()"] }, + { "name": "startAge", "defaultValue": [] }, + { "name": "endAge", "defaultValue": [] }, + { "name": "gender", "defaultValue": [] }, + { "name": "locationUuids", "defaultValue": [1] }, + { + "name": "groupByYear", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "YEAR(encounter_datetime)" + } ] - } + }, + { + "name": "groupByMonth", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "MONTH(encounter_datetime)" + } + ] + } + ], + "filters": [ + { "expression": "t1.encounter_datetime >= ?", "parameter": "startDate" }, + { "expression": "t1.encounter_datetime <= ?", "parameter": "endDate" }, + { "expression": "t1.location_uuid in ?", "parameter": "locationUuids" }, + { + "expression": "round(datediff(t1.encounter_datetime,t4.birthdate)/365) >= ?", + "parameter": "startAge" + }, + { + "expression": "round(datediff(t1.encounter_datetime,t4.birthdate)/365) <= ?", + "parameter": "endAge" + }, + { "expression": "t4.gender in ?", "parameter": "gender" }, + { "expression": "t1.is_clinical_encounter = 1", "processForce": true }, + { + "expression": "coalesce(t1.death_date, out_of_care) is null", + "processForce": true + }, + { + "expression": "(t1.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= t2.endDate)", + "processForce": true + } + ], + "groupClause": [ + { "parameter": "groupByYear" }, + { "parameter": "groupByMonth" } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct t1.person_id)" + }, + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_first_line", + "expression": "on_arvs_first_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_second_line", + "expression": "on_arvs_second_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "newly_on_second_line", + "expression": "newly_on_second_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_third_line", + "expression": "on_arvs_third_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year", + "expression": "vl_done_past_year", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year_relative_to_end_date", + "expression": "vl_done_past_year_relative_to_end_date", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "no_vl_done_past_year", + "expression": "no_vl_done_past_year", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_second_line_not_suppressed", + "expression": "on_second_line_not_suppressed", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "not_on_arvs_cd4_lte_500", + "expression": "not_on_arvs_cd4_lte_500", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year_lte_1000", + "expression": "vl_done_past_year_lte_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year_gt_1000", + "expression": "vl_done_past_year_gt_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_this_encounter", + "expression": "vl_done_this_encounter", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_this_encounter_lte_1000", + "expression": "vl_done_this_encounter_lte_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_this_encounter_gt_1000", + "expression": "vl_done_this_encounter_gt_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_ordered", + "expression": "vl_ordered", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pending_vl_order", + "expression": "pending_vl_order", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pending_vl_order_no_result_after_4_weeks", + "expression": "pending_vl_order_no_result_after_4_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_52_weeks", + "expression": "on_arvs_lte_52_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_52_weeks_and_have_vl", + "expression": "on_arvs_lte_52_weeks_and_have_vl", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expression": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pregnant", + "expression": "pregnant", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pregnant_and_on_arvs", + "expression": "pregnant_and_on_arvs", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "virally_suppressed", + "expression": "virally_suppressed", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "virally_suppressed_in_past_year", + "expression": "virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "viral_load_resulted_in_past_year", + "expression": "viral_load_resulted_in_past_year", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "not_virally_suppressed_in_past_year", + "expression": "not_virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "perc_virally_suppressed_in_past_year", + "expression": "perc_virally_suppressed_in_past_year", + "sql": "[virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" + }, + { + "label": "perc_not_virally_suppressed_in_past_year", + "expression": "perc_not_virally_suppressed_in_past_year", + "sql": "[not_virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" + }, + { + "label": "perc_on_arvs", + "expression": "perc_on_arvs", + "sql": "[on_arvs]/[patients]" + }, + { + "label": "perc_on_arv_first_line", + "expression": "perc_on_arv_first_line", + "sql": "[on_arvs_first_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_second_line", + "expression": "perc_on_arv_second_line", + "sql": "[on_arvs_second_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_third_line", + "expression": "perc_on_arv_third_line", + "sql": "[on_arvs_third_line]/[on_arvs]" + }, + { + "label": "perc_with_pending_viral_load", + "expression": "perc_with_pending_viral_load", + "sql": "[pending_vl_order]/[on_arvs]" + }, + { + "label": "perc_on_arvs_lte_6_months", + "expression": "perc_on_arvs_lte_6_months", + "sql": "[on_arvs_lte_26_weeks]/[on_arvs]" + }, + { + "label": "on_arvs_gt_26_weeks", + "expression": "on_arvs_gt_26_weeks", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "perc_on_arvs_gt_6_months", + "expression": "perc_on_arvs_gt_6_months", + "sql": "[on_arvs_gt_26_weeks]/[patients]" + }, + { + "label": "perc_ART_pats_screened_for_TB_receiving_TB_medication", + "expression": "perc_ART_pats_screened_for_TB_receiving_TB_medication", + "sql": "[num_ART_pats_screened_for_tb_started_TB]/[num_ART_pats_screened_for_tb]" + }, + + { + "label": "num_new_ART_pats_screened_for_tb_started_TB_this_period", + "expression": "num_new_ART_pats_screened_for_tb_started_TB_this_period", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_previous_ART_pats_screened_for_tb_started_TB", + "expression": "num_previous_ART_pats_screened_for_tb_started_TB", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_ART_pats_screened_for_tb_started_TB", + "expression": "num_ART_pats_screened_for_tb_started_TB", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_ART_pats_screened_for_tb_started_TB_female_below_15", + "expression": "num_ART_pats_screened_for_tb_started_TB_female_below_15", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_pats_screened_for_tb_started_TB", + "filters": ["female", "age_below_15"] + } + }, + { + "label": "num_ART_pats_screened_for_tb_started_TB_female_above_15", + "expression": "num_ART_pats_screened_for_tb_started_TB_female_above_15", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_pats_screened_for_tb_started_TB", + "filters": ["female", "age_15_and_older"] + } + }, + { + "label": "num_ART_pats_screened_for_tb_started_TB_male_below_15", + "expression": "num_ART_pats_screened_for_tb_started_TB_male_below_15", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_pats_screened_for_tb_started_TB", + "filters": ["male", "age_below_15"] + } + }, + { + "label": "num_ART_pats_screened_for_tb_started_TB_male_above_15", + "expression": "num_ART_pats_screened_for_tb_started_TB_male_above_15", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_pats_screened_for_tb_started_TB", + "filters": ["male", "age_15_and_older"] + } + }, + { + "label": "num_ART_pats_screened_for_tb", + "expression": "num_ART_pats_screened_for_tb", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_ART_pats_screened_for_tb_female_below_15", + "expression": "num_ART_pats_screened_for_tb_female_below_15", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_pats_screened_for_tb", + "filters": ["female", "age_below_15"] + } + }, + { + "label": "num_ART_pats_screened_for_tb_female_above_15", + "expression": "num_ART_pats_screened_for_tb_female_above_15", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_pats_screened_for_tb", + "filters": ["female", "age_15_and_older"] + } + }, + { + "label": "num_ART_pats_screened_for_tb_male_below_15", + "expression": "num_ART_pats_screened_for_tb_male_below_15", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_pats_screened_for_tb", + "filters": ["male", "age_below_15"] + } + }, + { + "label": "num_ART_pats_screened_for_tb_male_above_15", + "expression": "num_ART_pats_screened_for_tb_male_above_15", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_pats_screened_for_tb", + "filters": ["male", "age_15_and_older"] + } + }, + { + "label": "perc_ART_pats_completed_6mths_IPT", + "expression": "perc_ART_pats_completed_6mths_IPT", + "sql": "[num_ART_patients_completed_6mths_IPT]/[num_ART_patients_newly_started_IPT_less_6mths]" + }, + { + "label": "num_ART_patients_completed_6mths_IPT", + "expression": "num_ART_patients_completed_6mths_IPT", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_ART_patients_completed_6mths_IPT_females_below_15_yrs", + "expression": "num_ART_patients_completed_6mths_IPT_females_below_15_yrs", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_patients_completed_6mths_IPT", + "filters": ["female", "age_below_15"] + } + }, + { + "label": "num_ART_patients_completed_6mths_IPT_females_above_15_yrs", + "expression": "num_ART_patients_completed_6mths_IPT_females_above_15_yrs", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_patients_completed_6mths_IPT", + "filters": ["female", "age_15_and_older"] + } + }, + { + "label": "num_ART_patients_completed_6mths_IPT_males_below_15_yrs", + "expression": "num_ART_patients_completed_6mths_IPT_males_below_15_yrs", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_patients_completed_6mths_IPT", + "filters": ["male", "age_below_15"] + } + }, + { + "label": "num_ART_patients_completed_6mths_IPT_males_above_15_yrs", + "expression": "num_ART_patients_completed_6mths_IPT_males_above_15_yrs", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_patients_completed_6mths_IPT", + "filters": ["male", "age_15_and_older"] + } + }, + { + "label": "num_ART_patients_newly_started_IPT_less_6mths", + "expression": "num_ART_patients_newly_started_IPT_less_6mths", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_ART_patients_newly_started_IPT_less_6mths_females_below_15yrs", + "expression": "num_ART_patients_newly_started_IPT_less_6mths_females_below_15yrs", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_patients_newly_started_IPT_less_6mths", + "filters": ["male", "age_15_and_older"] + } + }, + { + "label": "num_ART_patients_newly_started_IPT_less_6mths_females_above_15yrs", + "expression": "num_ART_patients_newly_started_IPT_less_6mths_females_above_15yrs", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_patients_newly_started_IPT_less_6mths", + "filters": ["female", "age_below_15"] + } + }, + { + "label": "num_ART_patients_newly_started_IPT_less_6mths_males_below_15yrs", + "expression": "num_ART_patients_newly_started_IPT_less_6mths_males_below_15yrs", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_patients_newly_started_IPT_less_6mths", + "filters": ["male", "age_below_15"] + } + }, + { + "label": "num_ART_patients_newly_started_IPT_less_6mths_males_above_15yrs", + "expression": "num_ART_patients_newly_started_IPT_less_6mths_males_above_15yrs", + "sql": "count(distinct if($expression,t1.person_id,0))", + "disaggregation": { + "indicator": "num_ART_patients_newly_started_IPT_less_6mths", + "filters": ["male", "age_15_and_older"] + } + }, + { + "label": "num_ART_patients_newly_started_IPT_this_period_less_6mths", + "expression": "num_ART_patients_newly_started_IPT_this_period_less_6mths", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_ART_patients_newly_started_IPT_previous_period_less_6mths", + "expression": "num_ART_patients_newly_started_IPT_previous_period_less_6mths", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_patients_currently_on_IPT", + "expression": "num_patients_currently_on_IPT", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "ever_started_on_IPT", + "expression": "ever_started_on_IPT", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "newly_started_IPT", + "expression": "newly_started_IPT", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_patients_newly_enrolled_newly_started_on_IPT", + "expression": "num_patients_newly_enrolled_newly_started_on_IPT", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "num_patients_stopped_on_IPT", + "expression": "num_patients_stopped_on_IPT", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "transfer_in_from_non_Ampath_site", + "expression": "transfer_in_from_non_Ampath_site", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "transfer_in_from_Ampath_site", + "expression": "transfer_in_from_Ampath_site", + "sql": "count(distinct if($expression,t1.person_id,0))" + }, + { + "label": "transfer_in", + "expression": "transfer_in", + "sql": "count(distinct if($expression,t1.person_id,0))" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t3.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_datetime", + "type": "single", + "sql": "t2.endDate" + }, + { + "label": "month", + "type": "single", + "sql": "t2.endDate" + }, + { + "label": "reporting_month", + "type": "single", + "sql": "date_format(t2.endDate, '%m/%Y')" + } + ] + } ] diff --git a/reports/hiv-summary-report.json b/reports/hiv-summary-report.json index 114fa6b04..49d45bc9b 100755 --- a/reports/hiv-summary-report.json +++ b/reports/hiv-summary-report.json @@ -1,407 +1,423 @@ - [ - { - "name": "hiv-summary-report", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t2","joinExpression":"t1.location_uuid = t2.uuid"}, - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t3","joinExpression":"t1.person_id = t3.person_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"startAge", "defaultValue":[]}, - {"name":"endAge", "defaultValue":[]}, - {"name":"gender", "defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"location"} - ] - }, - {"name":"groupByYear", "defaultValue":[ - {"label":"encounter_datetime","expression":"YEAR(encounter_datetime)"} - ] - }, - {"name":"groupByMonth", "defaultValue":[ - {"label":"encounter_datetime","expression":"MONTH(encounter_datetime)"} - ] - } - ], - "filters": [ - { - "expression":"t1.encounter_datetime >= ?", - "parameter":"startDate" - }, - { - "expression":"t1.encounter_datetime <= ?", - "parameter":"endDate" - }, - { - "expression":"t1.location_uuid in ?", - "parameter":"locationUuids" - }, - { - "expression":"round(datediff(t1.encounter_datetime,t3.birthdate)/365) >= ?", - "parameter":"startAge" - }, - { - "expression":"round(datediff(t1.encounter_datetime,t3.birthdate)/365) <= ?", - "parameter":"endAge" - }, - { - "expression":"t3.gender in ?", - "parameter":"gender" - }, - { - "expression":"t1.is_clinical_encounter = 1", - "processForce":true - }, - { - "expression":"coalesce(t1.death_date, out_of_care) is null", - "processForce":true - }, - { - "expression":"(t1.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= ?)", - "parameter":"endDate" - } - - ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByYear"}, - {"parameter":"groupByMonth"} - ], - "indicators": [ - { - "label":"patients", - "expression":"patients", - "sql":"count(distinct t1.person_id)" - }, - { - "label":"on_tdf_3tc_dtg", - "expression":"on_tdf_3tc_dtg", - "sql":"1" - }, - { - "label":"on_tdf_3tc_efv_400", - "expression":"on_tdf_3tc_efv_400", - "sql":"1" - }, - { - "label":"on_tdf_3tc_efv_600", - "expression":"on_tdf_3tc_efv_600", - "sql":"1" - }, - { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"on_arvs_first_line", - "expression":"on_arvs_first_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_second_line", - "expression":"on_arvs_second_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"newly_on_second_line", - "expression":"newly_on_second_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_third_line", - "expression":"on_arvs_third_line", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_past_year", - "expression":"vl_done_past_year", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label": "vl_done_past_year_relative_to_end_date", - "expression": "vl_done_past_year_relative_to_end_date", - "sql": "count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"no_vl_done_past_year", - "expression":"no_vl_done_past_year", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_past_year_lte_1000", - "expression":"vl_done_past_year_lte_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_second_line_not_suppressed", - "expression":"on_second_line_not_suppressed", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"not_on_arvs_cd4_lte_500", - "expression":"not_on_arvs_cd4_lte_500", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_past_year_gt_1000", - "expression":"vl_done_past_year_gt_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_this_encounter", - "expression":"vl_done_this_encounter", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_this_encounter_lte_1000", - "expression":"vl_done_this_encounter_lte_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_done_this_encounter_gt_1000", - "expression":"vl_done_this_encounter_gt_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"vl_ordered", - "expression":"vl_ordered", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pending_vl_order", - "expression":"pending_vl_order", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pending_vl_order_no_result_after_4_weeks", - "expression":"pending_vl_order_no_result_after_4_weeks", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_26_weeks", - "expression":"on_arvs_lte_26_weeks", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_52_weeks", - "expression":"on_arvs_lte_52_weeks", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_52_weeks_and_have_vl", - "expression":"on_arvs_lte_52_weeks_and_have_vl", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expression":"on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_modern_contraception", - "expression":"on_modern_contraception", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_short_term_modern_contraception", - "expression":"on_short_term_modern_contraception", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_long_term_modern_contraception", - "expression":"on_long_term_modern_contraception", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"not_on_modern_contraception", - "expression":"not_on_modern_contraception", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_short_term_modern_contraception_pnc", - "expression":"on_short_term_modern_contraception_pnc", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_long_term_modern_contraception_pnc", - "expression":"on_long_term_modern_contraception_pnc", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_modern_contraception_pnc", - "expression":"on_modern_contraception_pnc", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"not_on_modern_contraception_pnc", - "expression":"not_on_modern_contraception_pnc", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"in_pnc", - "expression":"in_pnc", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"on_art_and_not_on_modern_contraception", - "expression":"on_art_and_not_on_modern_contraception", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"started_modern_contraception", - "expression":"started_modern_contraception", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pregnant", - "expression":"pregnant", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pregnant_and_on_arvs", - "expression":"pregnant_and_on_arvs", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"pregnant_and_started_art", - "expression":"pregnant_and_started_art", - "sql":"count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"viral_load_resulted_in_past_year", - "expression":"viral_load_resulted_in_past_year", - "sql": "count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"virally_suppressed_in_past_year", - "expression":"virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"not_virally_suppressed_in_past_year", - "expression":"not_virally_suppressed_in_past_year", - "sql": "count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"perc_virally_suppressed_in_past_year", - "expression":"perc_virally_suppressed_in_past_year", - "sql":"[virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" - }, - { - "label":"perc_not_virally_suppressed_in_past_year", - "expression":"perc_not_virally_suppressed_in_past_year", - "sql":"[not_virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" - }, - { - "label":"perc_on_arvs", - "expression":"perc_on_arvs", - "sql":"[on_arvs]/[patients]" - }, - { - "label":"perc_on_arv_first_line", - "expression":"perc_on_arv_first_line", - "sql":"[on_arvs_first_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_second_line", - "expression":"perc_on_arv_second_line", - "sql":"[on_arvs_second_line]/[on_arvs]" - }, - { - "label":"perc_on_arv_third_line", - "expression":"perc_on_arv_third_line", - "sql":"[on_arvs_third_line]/[on_arvs]" - }, - { - "label":"perc_with_pending_viral_load", - "expression":"perc_with_pending_viral_load", - "sql":"[pending_vl_order]/[on_arvs]" - }, - { - "label":"perc_on_arvs_lte_6_months", - "expression":"perc_on_arvs_lte_6_months", - "sql":"[on_arvs_lte_26_weeks]/[on_arvs]" - }, - { - "label":"on_arvs_gt_26_weeks", - "expression":"on_arvs_gt_26_weeks", - "sql": "count(distinct if($expression,t1.person_id,null))" - }, - { - "label":"perc_on_arvs_gt_6_months", - "expression":"perc_on_arvs_gt_6_months", - "sql":"[on_arvs_gt_26_weeks]/[patients]" - }, - { - "label":"transfer_in_patients", - "expression":"transfer_in_patients", - "sql": "count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"patients_with_vl_result", - "expression":"patients_with_vl_result", - "sql": "count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"vl_suppressed_patients", - "expression":"vl_suppressed_patients", - "sql": "count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"vl_unsuppressed_patients", - "expression":"vl_unsuppressed_patients", - "sql": "count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"early_scheduled_visits", - "expression":"early_scheduled_visits", - "sql": "count(distinct if($expression,t1.person_id,null))" - - }, - { - "label":"late_scheduled_visits", - "expression":"late_scheduled_visits", - "sql": "count(distinct if($expression,t1.person_id,null))" - } - - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t2.name" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"encounter_datetime", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"month", - "type":"single", - "sql":"t1.encounter_datetime" - } - ] - } +[ + { + "name": "hiv-summary-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t3", + "joinExpression": "t1.person_id = t3.person_id" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locationUuids", "defaultValue": [] }, + { "name": "startAge", "defaultValue": [] }, + { "name": "endAge", "defaultValue": [] }, + { "name": "gender", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [{ "label": "location", "expression": "location" }] + }, + { + "name": "groupByYear", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "YEAR(encounter_datetime)" + } + ] + }, + { + "name": "groupByMonth", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "MONTH(encounter_datetime)" + } + ] + } + ], + "filters": [ + { + "expression": "t1.encounter_datetime >= ?", + "parameter": "startDate" + }, + { + "expression": "t1.encounter_datetime <= ?", + "parameter": "endDate" + }, + { + "expression": "t1.location_uuid in ?", + "parameter": "locationUuids" + }, + { + "expression": "round(datediff(t1.encounter_datetime,t3.birthdate)/365) >= ?", + "parameter": "startAge" + }, + { + "expression": "round(datediff(t1.encounter_datetime,t3.birthdate)/365) <= ?", + "parameter": "endAge" + }, + { + "expression": "t3.gender in ?", + "parameter": "gender" + }, + { + "expression": "t1.is_clinical_encounter = 1", + "processForce": true + }, + { + "expression": "coalesce(t1.death_date, out_of_care) is null", + "processForce": true + }, + { + "expression": "(t1.next_clinical_datetime_hiv is null or next_clinical_datetime_hiv >= ?)", + "parameter": "endDate" + } + ], + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByYear" }, + { "parameter": "groupByMonth" } + ], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct t1.person_id)" + }, + { + "label": "on_tdf_3tc_dtg", + "expression": "on_tdf_3tc_dtg", + "sql": "1" + }, + { + "label": "on_tdf_3tc_efv_400", + "expression": "on_tdf_3tc_efv_400", + "sql": "1" + }, + { + "label": "on_tdf_3tc_efv_600", + "expression": "on_tdf_3tc_efv_600", + "sql": "1" + }, + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_first_line", + "expression": "on_arvs_first_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_second_line", + "expression": "on_arvs_second_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "newly_on_second_line", + "expression": "newly_on_second_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_third_line", + "expression": "on_arvs_third_line", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year", + "expression": "vl_done_past_year", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year_relative_to_end_date", + "expression": "vl_done_past_year_relative_to_end_date", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "no_vl_done_past_year", + "expression": "no_vl_done_past_year", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year_lte_1000", + "expression": "vl_done_past_year_lte_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_second_line_not_suppressed", + "expression": "on_second_line_not_suppressed", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "not_on_arvs_cd4_lte_500", + "expression": "not_on_arvs_cd4_lte_500", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_past_year_gt_1000", + "expression": "vl_done_past_year_gt_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_this_encounter", + "expression": "vl_done_this_encounter", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_this_encounter_lte_1000", + "expression": "vl_done_this_encounter_lte_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_done_this_encounter_gt_1000", + "expression": "vl_done_this_encounter_gt_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_ordered", + "expression": "vl_ordered", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pending_vl_order", + "expression": "pending_vl_order", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pending_vl_order_no_result_after_4_weeks", + "expression": "pending_vl_order_no_result_after_4_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_52_weeks", + "expression": "on_arvs_lte_52_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_52_weeks_and_have_vl", + "expression": "on_arvs_lte_52_weeks_and_have_vl", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expression": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_modern_contraception", + "expression": "on_modern_contraception", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_short_term_modern_contraception", + "expression": "on_short_term_modern_contraception", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_long_term_modern_contraception", + "expression": "on_long_term_modern_contraception", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "not_on_modern_contraception", + "expression": "not_on_modern_contraception", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_short_term_modern_contraception_pnc", + "expression": "on_short_term_modern_contraception_pnc", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_long_term_modern_contraception_pnc", + "expression": "on_long_term_modern_contraception_pnc", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_modern_contraception_pnc", + "expression": "on_modern_contraception_pnc", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "not_on_modern_contraception_pnc", + "expression": "not_on_modern_contraception_pnc", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "in_pnc", + "expression": "in_pnc", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "on_art_and_not_on_modern_contraception", + "expression": "on_art_and_not_on_modern_contraception", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "started_modern_contraception", + "expression": "started_modern_contraception", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pregnant", + "expression": "pregnant", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pregnant_and_on_arvs", + "expression": "pregnant_and_on_arvs", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "pregnant_and_started_art", + "expression": "pregnant_and_started_art", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "viral_load_resulted_in_past_year", + "expression": "viral_load_resulted_in_past_year", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "virally_suppressed_in_past_year", + "expression": "virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "not_virally_suppressed_in_past_year", + "expression": "not_virally_suppressed_in_past_year", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "perc_virally_suppressed_in_past_year", + "expression": "perc_virally_suppressed_in_past_year", + "sql": "[virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" + }, + { + "label": "perc_not_virally_suppressed_in_past_year", + "expression": "perc_not_virally_suppressed_in_past_year", + "sql": "[not_virally_suppressed_in_past_year]/[viral_load_resulted_in_past_year]" + }, + { + "label": "perc_on_arvs", + "expression": "perc_on_arvs", + "sql": "[on_arvs]/[patients]" + }, + { + "label": "perc_on_arv_first_line", + "expression": "perc_on_arv_first_line", + "sql": "[on_arvs_first_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_second_line", + "expression": "perc_on_arv_second_line", + "sql": "[on_arvs_second_line]/[on_arvs]" + }, + { + "label": "perc_on_arv_third_line", + "expression": "perc_on_arv_third_line", + "sql": "[on_arvs_third_line]/[on_arvs]" + }, + { + "label": "perc_with_pending_viral_load", + "expression": "perc_with_pending_viral_load", + "sql": "[pending_vl_order]/[on_arvs]" + }, + { + "label": "perc_on_arvs_lte_6_months", + "expression": "perc_on_arvs_lte_6_months", + "sql": "[on_arvs_lte_26_weeks]/[on_arvs]" + }, + { + "label": "on_arvs_gt_26_weeks", + "expression": "on_arvs_gt_26_weeks", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "perc_on_arvs_gt_6_months", + "expression": "perc_on_arvs_gt_6_months", + "sql": "[on_arvs_gt_26_weeks]/[patients]" + }, + { + "label": "transfer_in_patients", + "expression": "transfer_in_patients", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "patients_with_vl_result", + "expression": "patients_with_vl_result", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_suppressed_patients", + "expression": "vl_suppressed_patients", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "vl_unsuppressed_patients", + "expression": "vl_unsuppressed_patients", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "early_scheduled_visits", + "expression": "early_scheduled_visits", + "sql": "count(distinct if($expression,t1.person_id,null))" + }, + { + "label": "late_scheduled_visits", + "expression": "late_scheduled_visits", + "sql": "count(distinct if($expression,t1.person_id,null))" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t2.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_datetime", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "month", + "type": "single", + "sql": "t1.encounter_datetime" + } + ] + } ] diff --git a/reports/indicators.json b/reports/indicators.json index 51e84a479..8c46f5197 100755 --- a/reports/indicators.json +++ b/reports/indicators.json @@ -1,1366 +1,1364 @@ [ - { - "name": "encounters", - "label": "encounters", - "description": "Total # of encounters", - "expression": "true" - }, - { - "name": "patients", - "label": "patients", - "description": "Total number of patients", - "expression": "true" - }, - { - "name": "on_arvs", - "label": "on arvs", - "description": "Total # of patients who are on ARVs", - "expression": "cur_arv_line is not null" - }, - { - "name": "on_tdf_3tc_efv_400", - "label": "On TDF300/3TC300/EFV400", - "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ 400", - "expression": "true" - }, - { - "name": "on_tdf_3tc_efv_600", - "label": "On TDF300/3TC300/EFV600", - "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ 600", - "expression": "true" - }, - { - "name": "on_tdf_3tc_dtg", - "label": "On TDF300/3TC300/DTG50", - "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND DOLUTEGRAVIR", - "expression": "true" - }, - { - "name": "art_net_cohort_at_12_months", - "label": "art net cohort at 12 months", - "description": "ART Net Cohort at 12 months", - "expression": "date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(transfer_out, out_of_care) is null" - }, - { - "name": "on_arvs_first_line", - "label": "on arvs first line", - "description": "# of patient on ARVs first line", - "expression": "cur_arv_line=1" - }, - { - "name": "total_on_therapy_at_12_months", - "label": "total on therapy at 12 months", - "description": "# of patients on therapy at 12 months", - "expression": "date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(t1.death_date, coalesce(transfer_out, out_of_care)) is null and timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),@startDate) <= 90" - }, - { - "name": "on_arvs_second_line", - "label": "on arvs second line", - "description": "# of patient on ARVs second line", - "expression": "cur_arv_line=2 and coalesce(transfer_out, out_of_care) is null" - }, - { - "name": "on_arvs_third_line", - "label": "on arvs third line", - "description": "# of patient on ARVs third line", - "expression": "cur_arv_line>2" - }, - { - "name": "vl_done_past_year", - "label": "vl done past year", - "description": "# of patient(s) whose Viral Load have been taken in the past 1 year", - "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, - { - "name": "vl_done_past_year_relative_to_end_date", - "label": "vl done past year relative to end date", - "description": "# of patient(s) whose Viral Load have been taken in the past 1 year", - "expression": "timestampdiff(week,vl_1_date,@endDate) <= 52" - }, - { - "name": "no_vl_done_past_year", - "label": "no vl done past year", - "description": "# of patient(s) whose Viral Load have not been taken in the past 1 year", - "expression": "cur_arv_line is not null and (vl_1_date is null or timestampdiff(week,vl_1_date,encounter_datetime) >= 52)" - }, - { - "name": "vl_done_past_year_lte_1000", - "label": "vl done past year lte 1000", - "description": "# of patient(s) whose Viral Load is Less Than or Equal to 1000", - "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" - }, - { - "name": "vl_done_past_year_gt_1000", - "label": "vl done past year gt 1000", - "description": "# of patient(s) whose Viral Load is Greater Than 1000", - "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 > 1000" - }, - { - "name": "vl_done_this_encounter", - "label": "vl done this encounter", - "description": "# of patient(s) whose Viral Load has been taken in this encounter", - "expression": "vl_resulted >= 0 and vl_resulted_date=date(encounter_datetime)" - }, - { - "name": "vl_done_this_encounter_lte_1000", - "label": "vl done this encounter lte 1000", - "description": "# of patient(s) whose Viral Load in this encounter is Less Than 1000", - "expression": "vl_resulted <= 1000 and vl_resulted_date = date(encounter_datetime)" - }, - { - "name": "vl_done_this_encounter_gt_1000", - "label": "vl done this encounter gt 1000", - "description": "# of patient(s) whose Viral Load in this encounter is Greater Than 1000", - "expression": "vl_resulted > 1000 and vl_resulted_date = date(encounter_datetime)" - }, - { - "name": "vl_ordered", - "label": "vl ordered", - "description": "# of patient(s) whose Viral Load has been ordered", - "expression": "date(vl_order_date)=date(encounter_datetime)" - }, - { - "name": "pending_vl_order", - "label": "pending vl order", - "description": "# of patient(s) whose Viral Load has been Ordered but awaiting result", - "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 0 and vl_1_date < vl_order_date" - }, - { - "name": "pending_vl_order_no_result_after_4_weeks", - "label": "pending vl order no result after 4 weeks", - "description": "# of patient(s) whose Pending Viral Load Result is missing even after 4 weeks", - "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 4 and vl_1_date < vl_order_date" - }, - { - "name": "on_arvs_lte_26_weeks", - "label": "on arvs lte 26 weeks", - "description": "# of patient(s) who have been on ARVs for the last 26 weeks or less", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 26" - }, - { - "name": "on_arvs_lte_52_weeks", - "label": "on arvs lte 52 weeks", - "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52" - }, - { - "name": "on_arvs_lte_52_weeks_and_have_vl", - "label": "on arvs lte 52 weeks and have vl", - "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less and have Viral Load", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, - { - "name": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "label": "on arvs lte 52 weeks and have vl lte 1000", - "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less and their Viral Load is Less Than or Equal to 1000", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" - }, - { - "name": "not_on_modern_contraception", - "label": "not on modern contraception", - "description": "# of patients not on modern contraception in a given time period", - "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277))" - }, - { - "name": "on_short_term_modern_contraception_pnc", - "label": "On short term modern contraception pnc", - "description": "# of patients on short term modern contraception in a given time period and in pnc", - "expression": "fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method is not null AND fhs.contraceptive_method not in (1107, 6700, 9510, 9511, 9734, 9735, 6701)" - }, - { - "name": "on_long_term_modern_contraception_pnc", - "label": "On long term modern contraception pnc", - "description": "# of patients on long term modern contraception in a given time period and in pnc", - "expression": "fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817)" - }, - { - "name": "on_modern_contraception_pnc", - "label": "on modern contraception pnc", - "description": "# of patients on modern contraception in a given time period", - "expression": "fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method in (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817) AND fhs.visit_type in (68, 55, 52, 18)" - }, - { - "name": "not_on_modern_contraception_pnc", - "label": "not on modern contraception pnc", - "description": "# of patients not on modern contraception in a given time period and they are in PNC", - "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method in (1107, 5277, 6219)) AND fhs.visit_type in (68, 55, 52, 18)" - }, - { - "name": "in_pnc", - "label": "in pnc", - "description": "# of patients with a pnc visit in a given time period", - "expression": "fhs.visit_type in (68, 55, 52, 18)" - }, - { - "name": "on_art_and_not_on_modern_contraception", - "label": "on art and not on modern contraception", - "description": "# of patients on art and not on modern contraception in a given time period", - "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method = 1107) and cur_arv_line is not null" - }, - { - "name": "on_modern_contraception", - "label": "on modern contraception", - "description": "# of patients on modern contraception in a given time period", - "expression": "(fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method IN (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817) )" - }, - { - "name": "on_short_term_modern_contraception", - "label": "on short term modern contraception", - "description": "# of patients on short term modern contraception in a given time period", - "expression": "fhs.contraceptive_method is not null AND fhs.contraceptive_method in (190,780,907,6218,6217,5841,6717,6718,6725,8134,5274,8300)" - }, - { - "name": "on_long_term_modern_contraception", - "label": "on long term modern contraception", - "description": "# of patients on long term modern contraception in a given time period", - "expression": "fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817)" - }, - { - "name": "started_modern_contraception", - "label": "started modern contraception", - "description": "# of patients who started modern contraception in a given time period", - "expression": "date(fhs.modern_contraceptive_method_start_date) between @startDate and @endDate" - }, - { - "name": "pregnant", - "label": "pregnant", - "description": "# of pregnant patients in a given time period", - "expression": "edd > encounter_datetime" - }, - { - "name": "pregnant_and_on_arvs", - "label": "pregnant and on arvs", - "description": "# of pregnant patients and are on ARVs in a given time period", - "expression": "edd > encounter_datetime and cur_arv_line is not null" - }, - { - "name": "pregnant_and_started_art", - "label": "pregnant and started art", - "description": "# of pregnant patients and started ART in a given time period", - "expression": "edd > encounter_datetime and date(fhs.arv_first_regimen_start_date) between @startDate and @endDate" - }, - { - "name": "on_pcp_prophylaxis", - "label": "on pcp prophylaxis", - "description": "on PCP prophylaxis", - "expression": "encounter_datetime >= pcp_prophylaxis_start_date and coalesce(t1.death_date, out_of_care) is null" - }, - { - "name": "hiv_exposed_infants_below_2_months", - "label": "hiv exposed infants 2 months and below", - "description": "Total # of infants below 2 months who are exposed to hiv", - "expression": "hiv_rapid_test_resulted is not null and DATEDIFF(birthdate, @endDate) <= 60 and coalesce(t1.death_date, out_of_care) is null" - }, - { - "name": "hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below", - "label": "hiv exposed infants on pcp prophylaxis 2 months and below", - "description": "Total # of hiv exposed infants 2 months and below who are on PCP prophylaxis", - "expression": "hiv_rapid_test_resulted is not null and encounter_datetime >= pcp_prophylaxis_start_date and DATEDIFF(birthdate, @endDate) <= 60 and coalesce(t1.death_date, out_of_care) is null" - }, - { - "name": "enrolled_in_care_total", - "label": "enrolled in care total", - "description": "Total # of patients enrolled in care", - "expression": "(date(prev_clinical_datetime_hiv) between @startDate and @endDate or prev_clinical_datetime_hiv is null) and date(enrollment_date) between @startDate and @endDate" - }, - { - "name": "currently_in_care_total", - "label": "currently in care total", - "description": "A patient is in care if it has been less than 90 days from the return to clinic date within the given reporting period. For example, if at the last clinical encounter, the patient was given an RTC date of February 1, she is active in care in February, March and April. If she does not come back to clinic, she will be first out of care in May. Note, we are using the last RTC date given by a clinician for this definition.", - "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 end" - }, - { - "name": "pre_art_total", - "label": "starting art total", - "description": "Total # of patients starting ART", - "expression": "arv_first_regimen_start_date is null" - }, - { - "name": "starting_art_total", - "label": "starting art total", - "description": "Total # of patients starting ART", - "expression": "arv_first_regimen_start_date is not null and date(encounter_datetime) = date(arv_first_regimen_start_date) and (date(arv_first_regimen_start_date) between @startDate and @endDate) and cur_arv_meds is not null and prev_arv_meds is null" - }, - { - "name": "starting_art_and_has_tb", - "label": "starting_art_and_has_tb", - "description": "Starting ART and has TB", - "expression": "(tb_tx_start_date is not null and timestampdiff(year,tb_tx_start_date,@startDate) <= 1) and (date(encounter_datetime) = date(arv_first_regimen_start_date) and (date(arv_first_regimen_start_date) between @startDate and @endDate) and cur_arv_meds is not null and prev_arv_meds is null)" - }, - { - "name": "revisits_on_art_total", - "label": "revisits on art total", - "description": "Total # of patient revisits on ART", - "expression": "encounter_datetime > arv_start_date and (coalesce(t1.death_date, out_of_care) is null)" - }, - { - "name": "on_art_total", - "label": "on art total", - "description": "A patient is on ART if they are in care and was prescribed ART at their last clinical encounter.", - "expression": "encounter_datetime >= arv_start_date" - }, - { - "name": "not_on_art_total", - "label": "not on art total", - "description": "Total # of patients not on ART", - "expression": "(encounter_datetime < arv_start_date or arv_start_date is null)" - }, - { - "name": "on_original_first_line", - "label": "on original first line", - "description": "Total # of patients on original ART regimen", - "expression": "cur_arv_meds = arv_first_regimen and cur_arv_line = 1 and date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(transfer_out, out_of_care) is null and timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),@endDate) <= 90 " - }, - { - "name": "on_alternative_first_line", - "label": "on alternative first line", - "description": "Total # of patients on original ART regimen", - "expression": "cur_arv_meds != arv_first_regimen and cur_arv_line = 1 and date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(transfer_out, out_of_care) is null and timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),@endDate) <= 90" - }, - { - "name": "on_second_line_or_higher", - "label": "on second line or higher", - "description": "Total # of patients on original ART regimen", - "expression": "cur_arv_meds != arv_first_regimen and cur_arv_line >= 2 and date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(transfer_out, out_of_care) is null and timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),@endDate) <= 90" - }, - { - "name": "screened_for_tb", - "label": "screened for tb", - "description": "Total # of patients screened for TB", - "expression": "screened_for_tb and encounter_datetime between @startDate and @endDate" - }, - { - "name": "is_on_inh_treatment", - "label": "is_on_inh_treatment", - "description": "patient is on INH treatment", - "expression": "tb_prophylaxis_start_date is not null" - }, - { - "name": "using_modern_contracept_method", - "label": "using modern contracept method", - "description": " # of patients using modern contraceptive methods (IUD, injectables, OCP, e.t.c)", - "expression": "using_modern_contraceptive_method = 1 and encounter_datetime between @startDate and @endDate" - }, - { - "name": "condoms_provided", - "label": "condoms provided", - "description": " # of patients provided with condoms", - "expression": "condoms_provided = 1 and encounter_datetime between @startDate and @endDate" - }, - { - "name": "female_gte_18yo_visits", - "label": "female gte 18yo visits", - "description": " female patients >= 18", - "expression": "gender='F' and timestampdiff(year,birthdate,@endDate) >= 18 and encounter_datetime between @startDate and @endDate" - }, - { - "name": "scheduled_visits", - "label": "scheduled visits", - "description": "Scheduled visit", - "expression": "(date(encounter_datetime) = date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " - }, - { - "name": "unscheduled_visits", - "label": "unscheduled visits", - "description": "Unscheduled visit", - "expression": "(date(encounter_datetime) != date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate" - }, - { - "name": "early_scheduled_visits", - "label": "early scheduled visits", - "description": "Early Scheduled visit", - "expression": "(date(encounter_datetime) < date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " - }, - { - "name": "late_scheduled_visits", - "label": " late scheduled visits", - "description": "Late scheduled visit", - "expression": "(date(encounter_datetime) > date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " - }, - { - "name": "total_visits", - "label": "total visits", - "description": "Total # of Hiv Care Visits", - "expression": "" - }, - { - "name": "on_art", - "label": "on art", - "description": "Total # patient on ART", - "expression": "encounter_datetime >= arv_start_date and (coalesce(t1.death_date, out_of_care) is null)" - }, - { - "name": "ever_on_art", - "label": "ever on art", - "description": "Total # patient ever on ART", - "expression": "arv_first_regimen_start_date is not null" - }, - { - "name": "attended", - "label": "attended", - "description": "attended", - "expression": "" - }, - { - "name": "scheduled", - "label": "scheduled", - "description": "scheduled", - "expression": "" - }, - { - "name": "defaulted", - "label": "defaulted", - "description": "defaulted", - "expression": "" - }, - { - "name": "not_attended", - "label": "not attended", - "description": "not attended", - "expression": "date(t1.rtc_date)<>date(next_clinical_datetime_hiv)" - }, - { - "name": "has_not_returned", - "label": "has not returned", - "description": "has not returned", - "expression": "date(t1.rtc_date) < DATE(NOW()) and t1.rtc_date = max_rtc_date AND COALESCE(t1.death_date) IS NULL AND t1.transfer_out IS NULL AND t1.next_clinical_datetime_hiv IS NULL AND t8.person_id is null" - }, - { - "name": "virally_suppressed_in_past_year", - "label": "virally suppressed in past year", - "description": "# of patient(s) who are virally suppressed in the past one year", - "expression": "vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, - { - "name": "viral_load_resulted_in_past_year", - "label": "viral load resulted in past year", - "description": "patient(s) whose viral load has resulted in the past one year", - "expression": "vl_1 is not null and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, - { - "name": "virally_suppressed", - "label": "virally suppressed", - "description": "# of patient(s) who are virally suppressed", - "expression": "timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and timestampdiff(day, date(vl_1_date), date(t2.endDate)) <= 365 and vl_1 < 1000" - }, - { - "name": "not_virally_suppressed", - "label": "not virally suppressed", - "description": "# of patient(s) who are not virally suppressed", - "expression": "timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and timestampdiff(day, date(vl_1_date), date(t2.endDate)) <= 365 and vl_1 >= 1000" - }, - { - "name": "perc_virally_suppressed", - "label": "perc virally suppressed", - "description": "The denominator includes those patients who are active in care, on ART, required a viral load and got a viral load. The numerator includes those patients who required a viral load and the result was less than 1000", - "expression": "" - }, - { - "name": "not_virally_suppressed_in_past_year", - "label": "not virally suppressed in past year", - "description": "# of patient(s) who are not virally suppressed in the past one year", - "expression": "vl_1> 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" - }, - { - "name": "cd4_order_date", - "label": "cd4 order date", - "description": "cd4_order_date", - "expression": "DATE_FORMAT(cd4_order_date,'%m-%d-%Y')" - }, - { - "name": "perc_virally_suppressed_in_past_year", - "label": "perc virally suppressed in past year", - "description": "% of patient(s) who are virally suppressed in the past one year", - "expression": "" - }, - { - "name": "perc_not_virally_suppressed_in_past_year", - "label": "perc not virally suppressed in past year", - "description": "% of patient(s) who are not virally suppressed in the past one year", - "expression": "" - }, - { - "name": "perc_on_arvs", - "label": "perc on arvs", - "description": "% of patients who are on ARVs", - "expression": "" - }, - { - "name": "perc_in_care", - "label": "perc in care", - "description": "% of patients who are in Care", - "expression": "" - }, - { - "name": "perc_on_arvs_lte_6_months", - "label": "perc on arvs lte 6 months", - "description": "% of patients who have been on ARVs for less than 6 months", - "expression": "" - }, - { - "name": "perc_on_arvs_gt_6_months", - "label": "perc on arvs gt 6 months", - "description": "% of patients who have been on ARVs for more than 6 months", - "expression": "" - }, - { - "name": "perc_on_arv_first_line", - "label": "perc on arv first line", - "description": "% of patients on ARVs first line", - "expression": "" - }, - { - "name": "perc_on_arv_second_line", - "label": "perc on arv second line", - "description": "% of patients on ARVs second line", - "expression": "" - }, - { - "name": "perc_on_arv_gt_third_line", - "label": "perc on arv gt third line", - "description": "% of patients on ARVs third line or more", - "expression": "" - }, - { - "name": "perc_with_pending_viral_load", - "label": "perc with pending viral load", - "description": "% of patients with pending viral load", - "expression": "" - }, - { - "name": "on_arvs_gt_26_weeks", - "label": "on arvs gt 26 weeks", - "description": "# of patient(s) who have been on ARVs 26 weeks or more", - "expression": "timestampdiff(week,arv_start_date,encounter_datetime) > 26" - }, - { - "name": "needs_vl_coded", - "label": "needs vl coded", - "description": "Patient level coded indicator that determines whether patient requires a Viral load", - "expression": "case when (cur_arv_meds is null) then 0 when (timestampdiff(month,vl_1_date, date(@referenceDate)) > 3) and vl_1 > 1000 and arv_start_date < vl_1_date then 1 when (timestampdiff(month,arv_start_date,date(@referenceDate)) between 6 and 12) and (vl_1_date is null or vl_1_date < arv_start_date ) then 2 when (timestampdiff(month,arv_start_date,@referenceDate) > 12) and (vl_1_date is null or timestampdiff(month,vl_1_date,@referenceDate) > 12) then 3 else 0 end" - }, - { - "name": "qualifies_differenciated_care", - "label": "qualifies for differentiated care", - "description": "# A patient who is above 18 yrs and qualifies and with a viral load of less than 1000 and has been on TB prophylaxis for at least six months.", - "expression": "case when vl_1 < 1000 and (timestampdiff(year,birthdate, date(@referenceDate)) > 18) and (timestampdiff(month,tb_prophylaxis_start_date,if(tb_prophylaxis_end_date,tb_prophylaxis_end_date,@referenceDate)) >= 6 ) and (timestampdiff(month,vl_1_date,now()) <= 11 ) then 1 else 0 end" - - }, - { - "name": "needs_vl_in_period", - "label": "needs vl in period", - "description": "Patient level coded indicator that determines whether patient requires a Viral load", - "expression": "case when (cur_arv_meds is not null and vl_1 > 1000) and (timestampdiff(day,vl_1_date, @endDate) >= 90) then true when (timestampdiff(month,arv_start_date, @endDate) <= 12) and (vl_1_date is null or timestampdiff(month,vl_1_date, @endDate) >= 6) and (timestampdiff(month,arv_start_date, @endDate)>=6) then true when (timestampdiff(month,arv_start_date, @endDate) >= 12) and (vl_1_date is null or timestampdiff(month,vl_1_date, @endDate) >= 12) then true else false end" - }, - { - "name": "months_since_last_vl_date", - "label": "months since last vl date", - "description": "Number of months since last vl date", - "expression": "timestampdiff(month,vl_1_date, @referenceDate)" - }, - { - "name": "overdue_vl_lab_order", - "label": "overdue vl lab order", - "description": "Patient level coded indicator that determines whether patient Viral load order is overdue", - "expression": "case when (timestampdiff(day,vl_order_date, @referenceDate) >= 14) and (vl_1_date is null or vl_order_date > vl_1_date) and vl_error <> 1 then timestampdiff(day,vl_order_date, @referenceDate) else 0 end " - }, - { - "name": "ordered_vl_has_error", - "label": "latest ordered vl has error", - "description": "Patient level coded indicator that determines whether patient Viral load order is overdue", - "expression": "case when vl_error= 1 then 1 else 0 end " - }, - { - "name": "needs_cd4_count_coded", - "label": "needs cd4 count coded", - "description": "Patient level coded indicator that determines whether patient requires a Viral load", - "expression": "case when cur_arv_meds is not null and vl_1 > 1000 and timestampdiff(day,cd4_1_date, @referenceDate) >= 90 then 1 when timestampdiff(month,arv_start_date, @referenceDate) <= 12 and (cd4_1_date is null or timestampdiff(month,cd4_1_date, @referenceDate) > 6) then 2 when timestampdiff(month,arv_start_date, @referenceDate) > 12 and (cd4_1_date is null or timestampdiff(month,cd4_1_date, @referenceDate) > 12) then 3 else 0 end" - }, - { - "name": "overdue_cd4_count_lab_order", - "label": "overdue cd4 count lab order", - "description": "Patient level coded indicator that determines whether patient Viral load order is overdue", - "expression": "case when timestampdiff(day,cd4_order_date, @referenceDate) > 30 and cd4_1_date is null or cd4_order_date > cd4_1_date then timestampdiff(day,cd4_order_date, @referenceDate) else 0 end " - }, - { - "name": "encounters_count", - "label": "encounters_count", - "description": "", - "expression": "" - }, - { - "name": "patients_requiring_vl", - "label": "patients requiring vl", - "description": "patients requiring vl", - "expression": "timestampdiff(month,arv_start_date,encounter_datetime) >= 6" - }, - { - "name": "tested_appropriately", - "label": "tested appropriately", - "description": "Patients who are under ART and are missing Viral Load in past year", - "expression": "timestampdiff(month, arv_start_date, encounter_datetime) >= 6 and timestampdiff(day, date(vl_1_date), date(t2.endDate)) <= 365" - }, - { - "name": "not_tested_appropriately", - "label": "not tested appropriately", - "description": "Patients who are under ART and are missing Viral Load in past year", - "expression": "timestampdiff(month, arv_start_date, encounter_datetime) >= 6 and (timestampdiff(day,vl_1_date, date(t2.endDate)) > 365 or vl_1_date is null)" - }, - { - "name": "due_for_annual_vl", - "label": "due for annual vl", - "description": "In a specific month, these are patients who need new Annual Viral Load but none was ordered in that month. For example, If a patient had an annual VL on 10/2015, the he/she will be due on 10/2016 and not any other month", - "expression": "timestampdiff(month, arv_start_date, encounter_datetime) >= 6 and (DATE_ADD(vl_1_date, INTERVAL 1 YEAR) between DATE_FORMAT(t2.endDate,'%Y-%m-01') and t2.endDate) and (orders.date_created is null or orders.concept_id!=856)" - }, - { - "name": "pending_vl_orders", - "label": "pending vl orders", - "description": "In a specific month, these are patients with pending Viral Load Orders that have not resulted.", - "expression": "orders.concept_id=856 and (date(orders.date_created) between DATE_FORMAT(t2.endDate,'%Y-%m-01') and t2.endDate) and date(vl_1_date) != date(orders.date_created) and date(vl_1_date) < DATE_FORMAT(t2.endDate,'%Y-%m-01')" - }, - { - "name": "missing_vl_order", - "label": "missing vl and vl order", - "description": " From reporting start-date to a specific month, these are patients on ART, with no Viral Load and no Viral Load Test Order (Patients whose Viral Load Test Order not placed)", - "expression": "timestampdiff(month, arv_start_date, encounter_datetime) >= 6 and (timestampdiff(day,vl_1_date, date(t2.endDate)) > 365 or vl_1_date is null) and (orders.date_created is null or orders.concept_id!=856)" - }, - { - "name": "perc_tested_appropriately", - "label": "perc tested appropriately", - "description": " For this indicator the denominator includes patients who are active in care, on ART and require a viral load. A patient requires a viral load if they have been on ART more than 6 months. The numerator are those patients who are active in care, on ART, required a viral load and got a viral load", - "expression": "" - }, - { - "name": "deceased_patients", - "label": "Deceased Patients", - "description": "This indicator includes all patients with patient care status of 'DECEASED'", - "expression": "patient_care_status=159" - }, - { - "name": "untraceable_patients", - "label": "untraceable patients", - "description": "This indicator includes all patients with patient care status of 'UNTRACEABLE'", - "expression": "patient_care_status=9079" - }, - { - "name": "transferred_out_patients", - "label": "transferred out patients", - "description": "A patient is considered to be transferred out if a provider declares the patient as NON-AMPATH", - "expression": "patient_care_status=1287" - }, - { - "name": "hiv_negative_patients", - "label": "hiv negative patients", - "description": "This indicator includes all patients with patient care status of 'HIV NEGATIVE, NO LONGER AT RISK'", - "expression": "patient_care_status=9036" - }, - { - "name": "patients_continuing_care", - "label": "patients continuing care", - "description": "This indicator includes all patients with patient care status of 'CONTINUE'", - "expression": "(patient_care_status=6101 and timestampdiff(day,rtc_date, @endDate) < 90 and is_clinical_encounter=1 ) or (patient_care_status=6101 and is_clinical_encounter=0 and @endDate > DATE_ADD(prev_clinical_rtc_date_hiv, INTERVAL 90 DAY))" - }, - { - "name": "self_disengaged_from_care", - "label": "self disengaged from care", - "description": "This indicator includes all patients with patient care status of 'SELF DISENGAGED FROM CARE'", - "expression": "patient_care_status=9083" - }, - { - "name": "defaulters", - "label": "defaulters", - "description": "This indicator includes all patients with patient care status of 'CONTINUE' and their RTC date is greater than 90 days from the reporting date", - "expression": "(patient_care_status=6101 and timestampdiff(day,if(is_clinical_encounter=1,rtc_date,prev_clinical_rtc_date_hiv), @endDate) > 90)" - }, - { - "name": "transfer_to_MNCH", - "label": "transfer to MNCH", - "description": "transfer to MNCH", - "expression": "patient_care_status=9504" - }, - { - "name": "other_patient_care_status", - "label": "other status", - "description": "This indicator includes all patients who do not fall in either of the above categories ", - "expression": "patient_care_status not in (159,9079,1287,9036,6101,9083)" - }, - { - "name": "on_nevirapine", - "label": "patient on_nevirapine", - "description": "A patient is considered to be on \"Nevirapine\" if current ARV regimen formulation contains: NEVIRAPINE or NEVIRAPINE LAMIVUDINE AND ZIDOVUDINE or STAVUDINE LAMIVUDINE AND NEVIRAPINE", - "expression": "cur_arv_meds regexp '(631|6467|792)'" - }, - { - "name": "on_lopinavir", - "label": "patient on_lopinavir", - "description": "A patient is considered to be on \"Lopinavir\" if current ARV regimen formulation contains: Lopinavir or LOPINAVIR AND RITONAVIR.", - "expression": "cur_arv_meds regexp '(9026|794)'" - }, - { - "name": "on_efavirenz", - "label": "patient on_efavirenz", - "description": "A patient is considered to be on \"Efavirenz\" if current ARV regimen formulation contains: TDF AND 3TC AND EFV or Efavirenz.", - "expression": "cur_arv_meds regexp '(633|6964)'" - }, - { - "name": "on_atazanavir", - "label": "patient on_atazanavir", - "description": "A patient is considered to be using \"Atazanavir\" if current ARV regimen formulation contains: ATAZANAVIR or ATAZANAVIR AND RITONAVIR.", - "expression": "cur_arv_meds regexp '(6159|6160)'" - }, - { - "name": "on_raltegravir", - "label": "patient on_raltegravir", - "description": "A patient is considered to be on \"Raltegravir\" if current ARV regimen formulation contains: Raltegravir.", - "expression": "cur_arv_meds regexp '(6156)'" - }, - { - "name": "on_other_arv_drugs", - "label": "patient on_other_arv_drugs", - "description": "A patient is considered to be on \"others\" if current ARV regimen formulation neither contains: Raltegravir or Atazanavir or ATAZANAVIR AND RITONAVIR or Efavirenz or TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ or LOPINAVIR or LOPINAVIR AND RITONAVIR or NEVIRAPINE or NEVIRAPINE LAMIVUDINE AND ZIDOVUDINE or STAVUDINE LAMIVUDINE AND NEVIRAPINE.", - "expression": "not (cur_arv_meds regexp '(6156|6159|6160|633|6964|9026|794|631|6467|792)')" - }, - { - "name": "not_on_arv", - "label": "patient not_on_arv", - "description": "A patient is considered to be on \"Not on any ARV Drugs\" if he/she is not on any ARV drugs.", - "expression": "cur_arv_meds is null" - }, - { - "name": "on_second_line_not_suppressed", - "label": "on second line not suppressed", - "description": "patient on second line not suppressed", - "expression": "vl_1 > 1000 and cur_arv_line =2" - }, - { - "name": "newly_on_second_line", - "label": "newly on second line", - "description": "patient newly on second line within a given period", - "expression": "cur_arv_line =2 and (arv_start_date between @startDate and @endDate)" - }, - { - "name": "newly_enrolled", - "label": "newly enrolled", - "description": "patients who are newly enrolled", - "expression": "is_clinical_encounter=1 and prev_clinical_datetime_hiv is null" - }, - { - "name": "new_viral_load_present", - "label": "new viral load present", - "description": "patient has a new viral load result", - "expression": "DATE_ADD(vl_1_date, INTERVAL 90 DAY) > NOW()" - }, - { - "name": "not_on_arvs_cd4_lte_500", - "label": "not on arvs cd4 lte 500", - "description": "patients who qualify for ART but are not on therapy", - "expression": "arv_start_date is null and cd4_1 < 500" - }, - { - "name": "total_with_vl", - "label": "total with vl", - "description": "The number of patients who have at least one viral load resulted within 366 days of the end_date (can be more than 1 year", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 AND TIMESTAMPDIFF(DAY, vl_2_date, @endDate) <= 366" - }, - { - "name": "num_with_two_vls_past_year", - "label": "num with two vls past year", - "description": "The number of patients who have two viral load results within 366 days of end_date", - "expression": "timestampdiff(day,t1.vl_1_date,@endDate) <= 366 and timestampdiff(day,t1.vl_2_date,@endDate) <= 366" - }, - { - "name": "num_with_only_one_vl_past_year", - "label": "num with only one vl past year", - "description": "the number of patients who have only one viral in the past year and no other viral load in past year", - "expression": "timestampdiff(day,t1.vl_1_date,@endDate) <= 366 and timestampdiff(day,t1.vl_2_date,@endDate) <= 366" - }, - { - "name": "num_with_at_least_one_vl_past_year", - "label": "num with at least one vl past year", - "description": "the number of patients with at least one viral in the past year and no other viral load in past year", - "expression": "timestampdiff(day,t1.vl_1_date,@endDate) <= 366" - }, - { - "name": "second_vl_gt_one_yo", - "label": "second vl gt one year", - "description": "The number of patients who only have a single viral load resulted within 366 days of end_date and another viral load older than one year from year from end_date", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and timestampdiff(day,vl_2_date,@endDate) > 366" - }, - { - "name": "last_vl_undetected", - "label": "last vl undetected", - "description": "Total # of patients with last vl undetected", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 = 0" - }, - { - "name": "last_vl_unsuppressed", - "label": "last vl unsuppressed", - "description": "Total # of patients which have a VL in past year which was unsuppressed.", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 >= 1000" - }, - { - "name": "last_vl_suppressed", - "label": "last vl suppressed", - "description": "Total # of patients which have a VL in past year which was unsuppressed", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 < 1000" - }, - { - "name": "perc_unsuppressed", - "label": "perc unsuppressed", - "description": "The number of patients with a unsuppressed viral load within 1 year from end date divided by the number of patients with a viral load within 1 year of end date", - "expression": "" - }, - { - "name": "one_vl_unsuppressed", - "label": "one vl unsuppressed", - "description": "The number of patients with a single vl within one year of end_date and that vl >= 1000", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 is null or timestampdiff(day,vl_2_date,@endDate) > 366) and vl_1 >= 1000" - }, - { - "name": "one_vl_suppressed", - "label": "one vl suppressed", - "description": "The number of patients with a single vl within one year of end_date and that VL < 1000", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 is null or timestampdiff(day,vl_2_date,@endDate) > 366) and vl_1 < 1000" - }, - { - "name": "num_requiring_followup_vl", - "label": "num requiring followup vl", - "description": "The number of patients with viral load in the past year in which the VL >= 1000 and it’s been more than 90 days between that VL and end_date.", - "expression": "timestampdiff(day,vl_2_date,@endDate) <= 366 AND vl_2 >1000 || (timestampdiff(day,vl_1_date,@endDate) <= 366 AND vl_1 > 1000 AND timestampdiff(day,vl_1_date,@endDate) > 90 AND (vl_2 is null or vl_2_date > 1 ))" - }, - { - "name": "getting_followup_vl", - "label": "getting followup vl", - "description": "Number of patients who got a follow-up viral load who needed one", - "expression": "TIMESTAMPDIFF(DAY, vl_2_date,@endDate) <= 366 AND vl_2 > 1000" - }, - { - "name": "getting_followup_vl_180_days", - "label": "getting followup vl", - "description": "Number of patients who got a follow-up viral load who needed one and the follow up is within 180 days", - "expression": "TIMESTAMPDIFF(DAY, vl_2_date,@endDate) <= 366 AND vl_2 > 1000 AND TIMESTAMPDIFF(DAY, vl_1_date,@endDate) <= 180" - }, - { - "name": "perc_getting_followup_vl", - "label": "perc getting followup vl", - "description": "The numerator is number of patients who got a follow-up viral load who needed one. The denominator is the number of patients who required a follow-up (num_requiring_followup_vl)", - "expression": "" - }, - { - "name": "perc_getting_followup_vl_180_days", - "label": "perc getting followup vl 180 days", - "description": "The numerator is number of patients who got a follow-up viral load within 180 days who needed one. The denominator is the number of patients who required a follow-up (num_requiring_followup_vl)", - "expression": "" - }, - { - "name": "one_vl_unsuppressed_gt_90_days", - "label": "one vl unsuppressed gt 90 days", - "description": "The number of patients who have a single viral load in the past year which is >= 1000 and the difference between end_date and the vl date is > 90 days", - "expression": "TIMESTAMPDIFF(DAY, vl_1_date, @endDate) <= 366 AND (vl_2 IS NULL OR TIMESTAMPDIFF(DAY, vl_2_date, @endDate > 366) AND vl_1 >= 1000 AND TIMESTAMPDIFF(DAY, vl_1_date, @endDate > 90" - }, - { - "name": "one_vl_unsuppressed_gt_180_days", - "label": "one vl unsuppressed gt 180 days", - "description": "The number of patients who have a single viral load in the past year which is >= 1000 and the difference between end_date and the vl date is > 180 days", - "expression": "TIMESTAMPDIFF(DAY, vl_1_date, @endDate) <= 366 AND (vl_2 IS NULL OR TIMESTAMPDIFF(DAY, vl_2_date, @endDate > 366) AND vl_1 >= 1000 AND TIMESTAMPDIFF(DAY, vl_1_date, @endDate > 180" - }, - { - "name": "avg_time_since_last_unsuppressed_vl_one_vl", - "label": "avg time since last unsuppressed vl one vl", - "description": "Avg time since last unsuppressed vl one vl", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 > 1000 and (vl_2 is null or timestampdiff(day,vl_2_date,@endDate) > 366)" - }, - { - "name": "total_with_two_vls", - "label": "total with two vls", - "description": "Total # of patients with two vls within one year of end_date.", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" - }, - { - "name": "init_vl_unsuppressed_follow_up_unsuppressed", - "label": "init vl unsuppressed follow up unsuppressed", - "description": "Total # of patients with an initial viral load >= 1000 with a follow-up viral load >= 1000 where both viral loads are within one year of end_date", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 >= 1000 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" - }, - { - "name": "follow_up_suppressed", - "label": "follow up suppressed", - "description": "Total # of patients with an initial viral load >= 1000 with a follow-up viral load < 1000 where both viral loads are within one year of end_date", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 >= 1000 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 < 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" - }, - { - "name": "perc_fu_suppressed", - "label": "perc fu suppressed", - "description": "Of the cohort of patients with a VL >= 1000, what percentage have a follow-up that is suppressed. The denominator is all the patients with a VL >= 1000 within one year of end_date AND have a follow-up viral load within 1 year of end date", - "expression": "" - }, - { - "name": "avg_length_btwn_vls_first_unsuppressed", - "label": "avg length btwn vls first unsuppressed", - "description": "For patients with an initial VL >= 1000 within 1 year of end_date, the average number of days until a follow-up viral load was ordered.", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" - }, - { - "name": "days_since_last_vl_first_unsuppressed", - "label": "days since last vl first unsuppressed", - "description": "avg days since last vl first unsuppressed", - "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" - }, - { - "name": "no_switch_after_unsuppressed", - "label": "no switch after unsuppressed", - "description": "# The number of patients switched to new regiment after the previous vl vl >= 1000", - "expression": "arv_start_date < vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366" - }, - { - "name": "switch_after_unsuppressed", - "label": "switch after unsuppressed", - "description": "# of patients with switch after unsuppressed", - "expression": "arv_start_date > vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366" - }, - { - "name": "no_switch_after_unsuppressed_x1", - "label": "no switch after unsuppressed x1", - "description": "# The number of patients remaining on same regimen after the previous vl >= 1000", - "expression": "arv_start_date < vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 < 1000 or timestampdiff(day,vl_2_date,@endDate) <= 366)" - }, - { - "name": "switch_after_unsuppressed_x1", - "label": "switch after unsuppressed x1", - "description": "# of patients switched to new regimen after a single, unsuppressed VL in past year", - "expression": "arv_start_date > vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 < 1000 or timestampdiff(day,vl_2_date,@endDate) <= 366)" - }, - { - "name": "no_switch_after_unsuppressed_x_2", - "label": "no switch after unsuppressed x2", - "description": "# of patients not switched to new regimen after two unsuppressed VLs in past year", - "expression": "arv_start_date < vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,@endDate) <= 366" - }, - { - "name": "switch_after_unsuppressed_x_2", - "label": "switch after unsuppressed x 2", - "description": "# of patients switched to new regimen after two unsuppressed VLs in past year", - "expression": "arv_start_date > vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 < 1000 or timestampdiff(day,vl_2_date,@endDate) <= 366)" - }, - { - "name": "avg_time_to_switch_after_unsuppressed", - "label": "avg time to switch after unsuppressed", - "description": "Average time to switch a patient to a new regimen after an unsuppressed viral load", - "expression": "arv_start_date > vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366" - }, - { - "name": "avg_time_to_switch_after_unsuppressed_x2", - "label": "avg time to switch after unsuppressed x2", - "description": "Average time to switch a patient to a new regimen after two two unsuppressed viral loads", - "expression": "arv_start_date > vl_1_date AND vl_1 >= 1000 AND TIMESTAMPDIFF(DAY, vl_1_date, NOW()) <= 366 AND vl_2 > 1000 AND TIMESTAMPDIFF(DAY, vl_2_date, NOW()) <= 366, TIMESTAMPDIFF(DAY,vl_1_date, arv_start_date)" - }, - { - "name": "avg_days_to_switch_after_unsuppressed", - "label": "avg days to switch after unsuppressed", - "description": "avg time to switch after unsuppressed", - "expression": "arv_start_date > vl_1_date and vl_1 >= 1000" - }, - { - "name": "num_with_vl_after_switch", - "label": "num with vl after switch", - "description": "# of patients with vl after switch", - "expression": "arv_start_date > vl_2_date and arv_start_date < vl_1_date" - }, - { - "name": "num_with_vl_after_switch_suppressed", - "label": "num with vl after switch suppressed", - "description": "# of patients with suppressed follow-up viral load after a regiment switch", - "expression": "arv_start_date > vl_2_date and arv_start_date < vl_1_date and vl_1 < 1000" - }, - { - "name": "num_with_vl_after_switch_unsuppressed", - "label": "num with vl after switch unsuppressed", - "description": "# of patients with unsuppressed follow-up viral load after a regimen switch", - "expression": "arv_start_date > vl_2_date and arv_start_date < vl_1_date and vl_1 >= 1000" - }, - { - "name": "perc_switched_with_suppressed_fu", - "label": "perc switched with suppressed fu", - "description": "% of patients switched with suppressed f/u VL", - "expression": "" - }, - { - "name": "perc_ART_pats_screened_for_TB_receiving_TB_medication", - "label": "perc ART pats screened for TB receiving TB medication", - "description": "percentage of ART pats who are screened for TB and receiving TB medication", - "expression": "" - }, - { - "name": "num_ART_pats_screened_for_tb_started_TB", - "label": "# ART pats screened for tb started TB", - "description": "# of ART patients who are screened for tb and are started on TB medication", - "expression": "screened_for_tb is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(t1.death_date, out_of_care) is null" - }, - { - "name": "num_new_ART_pats_screened_for_tb_started_TB_this_period", - "label": "# newly started on ART pats screened for tb started TB this reporting period", - "description": "# of newly started on ART patients who are screened for tb and are started on TB medication this reporting period", - "expression": "screened_for_tb is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(t1.death_date, out_of_care) is null and arv_start_date>= @startDate and arv_start_date<= @endDate" - }, - { - "name": "num_previous_ART_pats_screened_for_tb_started_TB", - "label": "# previously started on ART pats screened for tb started TB", - "description": "# of previously started on ART patients who are screened for tb and are started on TB medication", - "expression": "screened_for_tb is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(t1.death_date, out_of_care) is null and arv_start_date< @startDate" - }, - { - "name": "num_ART_pats_screened_for_tb", - "label": "# ART pats screened for tb", - "description": "# of ART patients who are screened for tb", - "expression": "screened_for_tb is not null and cur_arv_line is not null and coalesce(t1.death_date, out_of_care) is null" - }, - { - "name": "perc_ART_pats_completed_6mths_IPT", - "label": "perc ART pats completed 6mths IPT", - "description": "percentage of ART pats who have completed 6 months of IPT therapy", - "expression": "" - }, - { - "name": "num_ART_patients_completed_6mths_IPT", - "label": "# of ART patients who have completed 6mths IPT", - "description": "# of ART patients who have completed 6mths of IPT patients", - "expression": "round(datediff(encounter_datetime,tb_prophylaxis_start_date)/30.5) >= 6 or round(datediff(tb_prophylaxis_end_date,tb_prophylaxis_start_date)/30.5) >= 6 and (coalesce(t1.death_date, out_of_care) is null)" - }, - { - "name": "num_ART_patients_newly_started_IPT_less_6mths", - "label": "# ART patients newly started IPT less 6mths", - "description": "# ART patients newly started IPT and have completed less than 6mths on therapy", - "expression": "tb_prophylaxis_start_date is not null or tb_prophylaxis_end_date is not null and tb_prophylaxis_start_date >= DATE_ADD(@startDate, INTERVAL -6 month) and (coalesce(t1.death_date, out_of_care) is null) " - }, - { - "name": "num_ART_patients_newly_started_IPT_this_period_less_6mths", - "label": "# ART patients newly started IPT this period less 6mths", - "description": "# of ART patients newly started IPT in this reporting period and have completed less than 6mths on therapy", - "expression": "tb_prophylaxis_start_date is not null or tb_prophylaxis_end_date is not null and tb_prophylaxis_start_date >= @startDate" - }, - { - "name": "num_ART_patients_newly_started_IPT_previous_period_less_6mths", - "label": "# ART patients newly started IPT in the previous period less 6mths", - "description": "# of ART patients newly started IPT in the previous reporting period and have completed less than 6mths on therapy", - "expression": "tb_prophylaxis_start_date is not null or tb_prophylaxis_end_date is not null and tb_prophylaxis_start_date < @startDate" - }, - { - "name": "num_ART_patients_newly_started_IPT_previous_period_less_6mths", - "label": "# ART patients newly started IPT in the previous period less 6mths", - "description": "# of ART patients newly started IPT in the previous reporting period and have completed less than 6mths on therapy", - "expression": "tb_prophylaxis_start_date is not null or tb_prophylaxis_end_date is not null and tb_prophylaxis_start_date < @startDate" - }, - { - "name": "num_patients_currently_on_IPT", - "label": "# patients currently on IPT", - "description": "number of patients currently on IPT", - "expression": "coalesce(t1.death_date, out_of_care) is null and tb_prophylaxis_start_date is not null and tb_prophylaxis_end_date is null" - }, - { - "name": "num_patients_newly_enrolled_newly_started_on_IPT", - "label": "# patients newly enrolled newly started on IPT", - "description": "number of patients newly enrolled and newly started on IPT", - "expression": "coalesce(t1.death_date, out_of_care) is null and tb_prophylaxis_start_date is not null and @startDate<=enrollment_date and enrollment_date<=@endDate" - }, - { - "name": "num_patients_stopped_on_IPT", - "label": "# patients stopped on IPT", - "description": "number of patients stopped on IPT", - "expression": "coalesce(t1.death_date, out_of_care) is null and t1.tb_prophylaxis_end_date is not null and @startDate<=tb_prophylaxis_end_date<=@endDate" - }, - { - "name": "newly_started_IPT", - "label": "# patients newly started IPT", - "description": "# eligible patients newly started IPT within the reporting period", - "expression": "date(tb_prophylaxis_start_date) between @startDate and @endDate" - }, - { - "name": "ever_started_on_IPT", - "label": "# patients ever started on IPT", - "description": "# eligible patients ever started on IPT within the reporting period", - "expression": " tb_prophylaxis_start_date is not null" - }, - { - "name": "completed_12_months_IPT", - "label": "# patients completed 12 months IPT within reporting period", - "description": "# completed 12 months IPT within the reporting period", - "expression": "date(tb_prophylaxis_end_date) between @startDate and @endDate and (timestampdiff(month,tb_prophylaxis_start_date, tb_prophylaxis_end_date) >= 12) " - }, - { - "name": "started_TB_treatment_within_reporting_period", - "label": "# patients started_TB_treatment_within_reporting_period", - "description": "Total clients who are started treatment within reporting period", - "expression": "tb_tx_start_date is not null and date(tb_tx_start_date) between @startDate and @endDate" - }, - { - "name": "HIV_patients_newly_enrolled_into_TB_treatment", - "label": "# patients who were hiv positive before initiating TB treatment within reporting period", - "description": "Total clients who were hiv positive before initiating TB treatment within reporting period", - "expression": "date(hiv_start_date) < date(tb_tx_start_date) and date(tb_tx_start_date) between @startDate and @endDate" - }, - { - "name": "TB_patients_newly_enrolled_into_HIV_care", - "label": "# TB patients who are being enrolled in ART", - "description": "TB clients who are enrolled into HIV care within reporting period", - "expression": "date(tb_tx_start_date) < date(hiv_start_date) and date(hiv_start_date) between @startDate and @endDate" - }, - { - "name": "newly_identified_HIV_positive_patient_on_TB_treatment", - "label": "newly_identified_HIV_positive_patient_on_TB_treatment within reporting period", - "description": "[HIV_patients_newly_enrolled_into_TB_treatment]+[TB_patients_newly_enrolled_into_HIV_care]", - "expression": "" - }, - { - "name": "patients_on_ARV_starting_TB_treatment", - "label": "patients_on_ARV_starting_TB_treatment", - "description": "TB clients who were on ARVs before starting TB treatment within reporting period", - "expression": " date(arv_first_regimen_start_date) < date(tb_tx_start_date) and date(tb_tx_start_date) between @startDate and @endDate" - }, - { - "name": "TB_patients_starting_ARV_medication", - "label": "# TB_patients_starting_ARV_medication", - "description": "TB clients who are starting ARV medication within reporting period", - "expression": "date(tb_tx_start_date) < date(arv_first_regimen_start_date) and date(arv_first_regimen_start_date) between @startDate and @endDate" - }, - { - "name": "newly_identified_TB_patients_on_ARVs", - "label": "newly_identified_TB_patients_on_ARVs within reporting period", - "description": "[TB_patients_starting_ARV_medication]+[patients_on_ARV_starting_TB_treatment]", - "expression": "" - }, - { - "name": "total_hiv_exposed", - "label": "# count of all clients exposed to HIV", - "description": "all clients exposed to HIV within reporting period", - "expression": "hiv_exposed_occupational is not null" - }, - { - "name": "hiv_exposed_occupational", - "label": "# count of all clients exposed to HIV (occupational)", - "description": "occupational clients exposed to HIV within reporting period", - "expression": "hiv_exposed_occupational=1" - }, - { - "name": "hiv_exposed_non_occupational", - "label": "# count of all clients exposed to HIV (non-occupational)", - "description": "non-occupational clients exposed to HIV within reporting period", - "expression": "hiv_exposed_occupational=0" - }, - { - "name": "total_started_PEP", - "label": "# count of all clients exposed to HIV and started PEP", - "description": "all clients exposed to HIV and received PEP within reporting period", - "expression": "hiv_exposed_occupational is not null and date(pep_start_date) between @startDate and @endDate" - }, - { - "name": "started_PEP_occupational", - "label": "# count of all clients exposed to HIV (occupational) and started PEP", - "description": "occupational clients exposed to HIV and started PEP within reporting period", - "expression": "hiv_exposed_occupational=1 and date(pep_start_date) between @startDate and @endDate" - }, - { - "name": "started_PEP_non_occupational", - "label": "# count of all clients exposed to HIV (non-occupational) and started PEP", - "description": "non-occupational clients exposed to HIV and started PEP within reporting period", - "expression": "hiv_exposed_occupational=0 and date(pep_start_date) between @startDate and @endDate" - }, - { - "name": "total_patients", - "label": "total_patients", - "description": "These are all patients ever enrolled into care as of end of the reporting month", - "expression": "case when date(t1.encounter_datetime) <= t2.endDate then 1 else null end " - }, - { - "name": "new_enrollments", - "label": "new_enrollments", - "description": "These are patients enrolled into care within the reporting month", - "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when date(t1.hiv_start_date) between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate then 1 else null end" - }, - { - "name": "transfer_in_from_non_Ampath_site", - "label": "transfer_in_from_non_Ampath_site", - "description": "These are patients who transferred in form NON AMPATH facility within the reporting month", - "expression": "t1.transfer_in=1287 and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)" - }, - { - "name": "transfer_in_from_Ampath_site", - "label": "transfer_in_from_Ampath_site", - "description": "These are patients who transferred in form AMPATH facility within the reporting month", - "expression": "t1.transfer_in=1286 and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)" - }, - { - "name": "transfer_in", - "label": "transfer_in", - "description": "These are patients who transferred into the selected facility within the reporting month", - "expression": "case when date(t1.hiv_start_date) between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate then null when t1.transfer_in is not null and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 else null end " - }, - { - "name": "transfer_in_patients", - "label": "transfer in patients", - "description": "These are patients who transferred into the selected facility within the reporting period", - "expression": "t1.transfer_in is not null" - }, - { - "name": "transfer_out_patients_this_month", - "label": "transfer_out_patients_this_month", - "description": "These are patients transferred to other Ampath or NON Ampath facility within the reporting month", - "expression": "((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and ((t1.transfer_out is not null and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)) or ( (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and (outreach_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate))) and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) " - }, - { - "name": "active_in_care_to_transfer_out", - "label": "active_in_care_to_transfer_out", - "description": "These are patients who were Active in care in the previous reporting month, but changed to transferred out in this reporting month", - "expression": "((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and ((t1.transfer_out is not null and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)) or ( (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and (outreach_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate))) and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) and timestampdiff(day,t1.rtc_date, date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) <= 90" - }, - { - "name": "transfer_out_patients", - "label": "transfer_out_patients", - "description": "These are patients ever transferred to other Ampath or NON Ampath facility", - "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then 1 else null end" - }, - { - "name": "deaths", - "label": "deaths", - "description": "These are dead patients ever reported", - "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then 1 else null end " - }, - { - "name": "HIV_negative_patients", - "label": "HIV_negative_patients", - "description": "These are HIV Negative patients ever reported", - "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then 1 else null end" - }, - { - "name": "self_disengaged_patients", - "label": "self_disengaged_patients", - "description": "These are patients ever disengaged out of care by themselves", - "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then 1 else null end " - }, - { - "name": "HIV_negative_patients_this_month", - "label": "HIV_negative_patients_this_month", - "description": "These are HIV Negative patients that were reported within the reporting month", - "expression": "case when outreach_death_date_bncd or t1.death_date then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) and (outreach_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 when t1.patient_care_status in (9036) and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 else null end" - }, - { - "name": "self_disengaged_patients_this_month", - "label": "self_disengaged_patients_this_month", - "description": "These are patients that have disengaged themselves from care within the reporting month", - "expression": "case when outreach_death_date_bncd or t1.death_date then null when (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) and (outreach_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 when t1.patient_care_status in (9083) and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 else null end" - }, - { - "name": "deaths_this_month", - "label": "deaths_this_month", - "description": "These are deaths that occurred within the reporting month", - "expression": "(t1.death_date between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) or (outreach_death_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)" - }, - { - "name": "active_in_care_to_death", - "label": "active_in_care_to_death", - "description": "These are patients who were Active in care in the previous reporting month, but died within this reporting month", - "expression": "(t1.death_date between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) or (outreach_death_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) and timestampdiff(day,t1.rtc_date, date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) <= 90" - }, - { - "name": "LTFU", - "label": "LTFU", - "description": "A patient is LTFU if it has been greater than 90 days from the RTC date within the given reporting period ", - "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) > 90 then 1 else null end" - }, - { - "name": "LTFU_this_month", - "label": "LTFU_this_month", - "description": "Total # of new patients", - "expression": "((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) and t1.transfer_out is null and (outreach_patient_care_status_bncd not in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) between 91 and 121" - }, - { - "name": "LTFU_to_active_in_care", - "label": "LTFU_to_active_in_care", - "description": "These are patients who were LTFU in the previous reporting month, but changed to active in care in this reporting month", - "expression": "t1.transfer_out is null and (outreach_patient_care_status_bncd not in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and ((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and date(t1.encounter_datetime) between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) and timestampdiff(day, if(t1.prev_clinical_rtc_date_hiv, t1.prev_clinical_rtc_date_hiv, DATE_ADD(t1.prev_clinical_datetime_hiv, INTERVAL 30 DAY)), date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) > 90" - }, - { - "name": "active_in_care_to_LTFU", - "label": "active_in_care_to_LTFU", - "description": "These are patient who were Active in care on the previous reporting month, but changed to LTFU in this reporting month", - "expression": "t1.transfer_out is null and (outreach_patient_care_status_bncd not in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and ((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) and timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) > 90 and timestampdiff(day,t1.rtc_date, date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) <= 90" - }, - { - "name": "active_in_care", - "label": "active_in_care", - "description": "A patient is active in care if it has been less than 90 days from the RTC date within the given reporting period", - "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 end" - }, - { - "name": "active_return", - "label": "active_return", - "description": "These are active patients without including new enrollments and transfer ins: i.e Active Patients - (Transfer In + New Enrollment)", - "expression": "case when date(t1.hiv_start_date) between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate then null when t1.transfer_in is not null and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then null when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 else null end" - }, - { - "name": "active_in_care_prev_month", - "label": "active_in_care_prev_month", - "description": "Total # of acive patients prev reporting month", - "expression": "timestampdiff(day,t1.rtc_date, date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) <= 90" - }, - { - "name": "monthly_patient_care_status", - "label": "Monthly patient care status", - "description": "Care status of patient on a monthly basis", - "expression": "CASE WHEN TIMESTAMPDIFF(DAY, IF(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 AND t1.transfer_out IS NULL AND COALESCE(t1.death_date, t1.out_of_care) IS NULL THEN 'active' WHEN TIMESTAMPDIFF(DAY, IF(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) > 90 AND transfer_out IS NULL THEN 'ltfu' WHEN t1.transfer_out IS NOT NULL AND COALESCE(t1.death_date) IS NULL THEN 'transfered_out' END" - }, - { - "name": "patient_daily_care_status", - "label": "patient_daily_care_status", - "description": "Patient daily care status", - "expression": "CASE WHEN TIMESTAMPDIFF(DAY, IF(rtc_date, rtc_date, DATE_ADD(encounter_datetime, INTERVAL 30 DAY)),@referenceDate) <= 90 AND transfer_out IS NULL AND COALESCE(death_date, out_of_care) IS NULL THEN 'active' WHEN TIMESTAMPDIFF(DAY, IF(rtc_date, rtc_date, DATE_ADD(encounter_datetime, INTERVAL 30 DAY)), @referenceDate) > 90 THEN 'ltfu' WHEN transfer_out IS NOT NULL AND COALESCE(death_date) IS NULL THEN 'transfered_out' END" - }, - { - "name": "community_ART_dispensing", - "label": "community_ART_dispensing", - "description": "These are patients who are on ART through community dispensing program", - "expression": "t1.encounter_type = 128" - }, - { - "name": "patients_with_vl_result", - "label": "patients with vl result", - "description": "# of patients with vl", - "expression": "vl_1_date between @startDate and @endDate" - }, - { - "name": "vl_suppressed_patients", - "label": "vl suppressed patients", - "description": "# of patients with vl < 1000", - "expression": "vl_1_date between @startDate and @endDate and vl_1 < 1000" - }, - { - "name": "vl_unsuppressed_patients", - "label": "vl unsuppressed patients", - "description": "# of patients with vl >= 1000", - "expression": "vl_1_date between @startDate and @endDate and vl_1 >= 1000" - }, - { - "name": "active_and_on_art", - "label": "Active and on ART", - "description": "A patient who meets the definition for active in care and was dispensed ART at the last clinical visit", - "expression": "(case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 end) and encounter_datetime >= arv_start_date" - }, - { - "name": "has_vl_since_oct", - "label": "has VL since october", - "description": "As of the reporting month, the number of patients who have had a VL since october", - "expression": "(case when (date(t2.endDate) > date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(vl_1_date) between date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(DATE_ADD(DATE_FORMAT(t2.endDate, '%Y-09-01'), INTERVAL 1 YEAR))) then true when (date(t2.endDate) < date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(vl_1_date) between date(DATE_SUB(DATE_FORMAT(t2.endDate, '%Y-09-01'), INTERVAL 1 YEAR)) and date(DATE_FORMAT(t2.endDate, '%Y-09-01'))) then true else false end)" - }, - { - "name": "virally_suppressed_since_oct", - "label": "virally suppressed_since_oct", - "description": "# of patient(s) who are virally suppressed", - "expression": "vl_1 < 1000 and (case when (date(t2.endDate) > date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(vl_1_date) between date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(DATE_ADD(DATE_FORMAT(t2.endDate, '%Y-09-01'), INTERVAL 1 YEAR))) then true when (date(t2.endDate) < date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(vl_1_date) between date(DATE_SUB(DATE_FORMAT(t2.endDate, '%Y-09-01'), INTERVAL 1 YEAR)) and date(DATE_FORMAT(t2.endDate, '%Y-09-01'))) then true else false end)" - }, - { - "name": "perc_virally_suppressed_since_oct", - "label": "perc virally suppressed since oct", - "description": "The denominator includes those patients (both active and LTFU) who have had a VL since October 1. The numerator includes those patients (both active and LTFU) who have had a VL since October 1 and had Vl < 100", - "expression": "" - } - + { + "name": "encounters", + "label": "encounters", + "description": "Total # of encounters", + "expression": "true" + }, + { + "name": "patients", + "label": "patients", + "description": "Total number of patients", + "expression": "true" + }, + { + "name": "on_arvs", + "label": "on arvs", + "description": "Total # of patients who are on ARVs", + "expression": "cur_arv_line is not null" + }, + { + "name": "on_tdf_3tc_efv_400", + "label": "On TDF300/3TC300/EFV400", + "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ 400", + "expression": "true" + }, + { + "name": "on_tdf_3tc_efv_600", + "label": "On TDF300/3TC300/EFV600", + "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ 600", + "expression": "true" + }, + { + "name": "on_tdf_3tc_dtg", + "label": "On TDF300/3TC300/DTG50", + "description": "Total # of patients who are on TENOFOVIR AND LAMIVUDINE AND DOLUTEGRAVIR", + "expression": "true" + }, + { + "name": "art_net_cohort_at_12_months", + "label": "art net cohort at 12 months", + "description": "ART Net Cohort at 12 months", + "expression": "date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(transfer_out, out_of_care) is null" + }, + { + "name": "on_arvs_first_line", + "label": "on arvs first line", + "description": "# of patient on ARVs first line", + "expression": "cur_arv_line=1" + }, + { + "name": "total_on_therapy_at_12_months", + "label": "total on therapy at 12 months", + "description": "# of patients on therapy at 12 months", + "expression": "date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(t1.death_date, coalesce(transfer_out, out_of_care)) is null and timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),@startDate) <= 90" + }, + { + "name": "on_arvs_second_line", + "label": "on arvs second line", + "description": "# of patient on ARVs second line", + "expression": "cur_arv_line=2 and coalesce(transfer_out, out_of_care) is null" + }, + { + "name": "on_arvs_third_line", + "label": "on arvs third line", + "description": "# of patient on ARVs third line", + "expression": "cur_arv_line>2" + }, + { + "name": "vl_done_past_year", + "label": "vl done past year", + "description": "# of patient(s) whose Viral Load have been taken in the past 1 year", + "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "vl_done_past_year_relative_to_end_date", + "label": "vl done past year relative to end date", + "description": "# of patient(s) whose Viral Load have been taken in the past 1 year", + "expression": "timestampdiff(week,vl_1_date,@endDate) <= 52" + }, + { + "name": "no_vl_done_past_year", + "label": "no vl done past year", + "description": "# of patient(s) whose Viral Load have not been taken in the past 1 year", + "expression": "cur_arv_line is not null and (vl_1_date is null or timestampdiff(week,vl_1_date,encounter_datetime) >= 52)" + }, + { + "name": "vl_done_past_year_lte_1000", + "label": "vl done past year lte 1000", + "description": "# of patient(s) whose Viral Load is Less Than or Equal to 1000", + "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" + }, + { + "name": "vl_done_past_year_gt_1000", + "label": "vl done past year gt 1000", + "description": "# of patient(s) whose Viral Load is Greater Than 1000", + "expression": "timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 > 1000" + }, + { + "name": "vl_done_this_encounter", + "label": "vl done this encounter", + "description": "# of patient(s) whose Viral Load has been taken in this encounter", + "expression": "vl_resulted >= 0 and vl_resulted_date=date(encounter_datetime)" + }, + { + "name": "vl_done_this_encounter_lte_1000", + "label": "vl done this encounter lte 1000", + "description": "# of patient(s) whose Viral Load in this encounter is Less Than 1000", + "expression": "vl_resulted <= 1000 and vl_resulted_date = date(encounter_datetime)" + }, + { + "name": "vl_done_this_encounter_gt_1000", + "label": "vl done this encounter gt 1000", + "description": "# of patient(s) whose Viral Load in this encounter is Greater Than 1000", + "expression": "vl_resulted > 1000 and vl_resulted_date = date(encounter_datetime)" + }, + { + "name": "vl_ordered", + "label": "vl ordered", + "description": "# of patient(s) whose Viral Load has been ordered", + "expression": "date(vl_order_date)=date(encounter_datetime)" + }, + { + "name": "pending_vl_order", + "label": "pending vl order", + "description": "# of patient(s) whose Viral Load has been Ordered but awaiting result", + "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 0 and vl_1_date < vl_order_date" + }, + { + "name": "pending_vl_order_no_result_after_4_weeks", + "label": "pending vl order no result after 4 weeks", + "description": "# of patient(s) whose Pending Viral Load Result is missing even after 4 weeks", + "expression": "timestampdiff(week,vl_order_date,encounter_datetime) >= 4 and vl_1_date < vl_order_date" + }, + { + "name": "on_arvs_lte_26_weeks", + "label": "on arvs lte 26 weeks", + "description": "# of patient(s) who have been on ARVs for the last 26 weeks or less", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 26" + }, + { + "name": "on_arvs_lte_52_weeks", + "label": "on arvs lte 52 weeks", + "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52" + }, + { + "name": "on_arvs_lte_52_weeks_and_have_vl", + "label": "on arvs lte 52 weeks and have vl", + "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less and have Viral Load", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "label": "on arvs lte 52 weeks and have vl lte 1000", + "description": "# of patient(s) who have been on ARVs for the last 52 weeks or less and their Viral Load is Less Than or Equal to 1000", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) <= 52 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52 and vl_1 <= 1000" + }, + { + "name": "not_on_modern_contraception", + "label": "not on modern contraception", + "description": "# of patients not on modern contraception in a given time period", + "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method in (6219 , 1624, 6707, 1067, 1107, 10956, 5622, 5277))" + }, + { + "name": "on_short_term_modern_contraception_pnc", + "label": "On short term modern contraception pnc", + "description": "# of patients on short term modern contraception in a given time period and in pnc", + "expression": "fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method is not null AND fhs.contraceptive_method not in (1107, 6700, 9510, 9511, 9734, 9735, 6701)" + }, + { + "name": "on_long_term_modern_contraception_pnc", + "label": "On long term modern contraception pnc", + "description": "# of patients on long term modern contraception in a given time period and in pnc", + "expression": "fhs.visit_type in (68, 55, 52, 18) AND fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817)" + }, + { + "name": "on_modern_contraception_pnc", + "label": "on modern contraception pnc", + "description": "# of patients on modern contraception in a given time period", + "expression": "fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method in (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817) AND fhs.visit_type in (68, 55, 52, 18)" + }, + { + "name": "not_on_modern_contraception_pnc", + "label": "not on modern contraception pnc", + "description": "# of patients not on modern contraception in a given time period and they are in PNC", + "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method in (1107, 5277, 6219)) AND fhs.visit_type in (68, 55, 52, 18)" + }, + { + "name": "in_pnc", + "label": "in pnc", + "description": "# of patients with a pnc visit in a given time period", + "expression": "fhs.visit_type in (68, 55, 52, 18)" + }, + { + "name": "on_art_and_not_on_modern_contraception", + "label": "on art and not on modern contraception", + "description": "# of patients on art and not on modern contraception in a given time period", + "expression": "(fhs.contraceptive_method IS NULL OR fhs.contraceptive_method = 1107) and cur_arv_line is not null" + }, + { + "name": "on_modern_contraception", + "label": "on modern contraception", + "description": "# of patients on modern contraception in a given time period", + "expression": "(fhs.contraceptive_method IS NOT NULL AND fhs.contraceptive_method IN (190 , 780, 907, 6218, 6217, 5841, 6717, 6718, 6725, 8134, 5274, 8300, 5279 , 5278, 5275, 5276, 6220, 6700, 6701, 9510, 9511, 9734, 9735, 10817) )" + }, + { + "name": "on_short_term_modern_contraception", + "label": "on short term modern contraception", + "description": "# of patients on short term modern contraception in a given time period", + "expression": "fhs.contraceptive_method is not null AND fhs.contraceptive_method in (190,780,907,6218,6217,5841,6717,6718,6725,8134,5274,8300)" + }, + { + "name": "on_long_term_modern_contraception", + "label": "on long term modern contraception", + "description": "# of patients on long term modern contraception in a given time period", + "expression": "fhs.contraceptive_method in (5279,5278,5275,5276,6220,6700,6701,9510,9511,9734,9735,10817)" + }, + { + "name": "started_modern_contraception", + "label": "started modern contraception", + "description": "# of patients who started modern contraception in a given time period", + "expression": "date(fhs.modern_contraceptive_method_start_date) between @startDate and @endDate" + }, + { + "name": "pregnant", + "label": "pregnant", + "description": "# of pregnant patients in a given time period", + "expression": "edd > encounter_datetime" + }, + { + "name": "pregnant_and_on_arvs", + "label": "pregnant and on arvs", + "description": "# of pregnant patients and are on ARVs in a given time period", + "expression": "edd > encounter_datetime and cur_arv_line is not null" + }, + { + "name": "pregnant_and_started_art", + "label": "pregnant and started art", + "description": "# of pregnant patients and started ART in a given time period", + "expression": "edd > encounter_datetime and date(fhs.arv_first_regimen_start_date) between @startDate and @endDate" + }, + { + "name": "on_pcp_prophylaxis", + "label": "on pcp prophylaxis", + "description": "on PCP prophylaxis", + "expression": "encounter_datetime >= pcp_prophylaxis_start_date and coalesce(t1.death_date, out_of_care) is null" + }, + { + "name": "hiv_exposed_infants_below_2_months", + "label": "hiv exposed infants 2 months and below", + "description": "Total # of infants below 2 months who are exposed to hiv", + "expression": "hiv_rapid_test_resulted is not null and DATEDIFF(birthdate, @endDate) <= 60 and coalesce(t1.death_date, out_of_care) is null" + }, + { + "name": "hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below", + "label": "hiv exposed infants on pcp prophylaxis 2 months and below", + "description": "Total # of hiv exposed infants 2 months and below who are on PCP prophylaxis", + "expression": "hiv_rapid_test_resulted is not null and encounter_datetime >= pcp_prophylaxis_start_date and DATEDIFF(birthdate, @endDate) <= 60 and coalesce(t1.death_date, out_of_care) is null" + }, + { + "name": "enrolled_in_care_total", + "label": "enrolled in care total", + "description": "Total # of patients enrolled in care", + "expression": "(date(prev_clinical_datetime_hiv) between @startDate and @endDate or prev_clinical_datetime_hiv is null) and date(enrollment_date) between @startDate and @endDate" + }, + { + "name": "currently_in_care_total", + "label": "currently in care total", + "description": "A patient is in care if it has been less than 90 days from the return to clinic date within the given reporting period. For example, if at the last clinical encounter, the patient was given an RTC date of February 1, she is active in care in February, March and April. If she does not come back to clinic, she will be first out of care in May. Note, we are using the last RTC date given by a clinician for this definition.", + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 end" + }, + { + "name": "pre_art_total", + "label": "starting art total", + "description": "Total # of patients starting ART", + "expression": "arv_first_regimen_start_date is null" + }, + { + "name": "starting_art_total", + "label": "starting art total", + "description": "Total # of patients starting ART", + "expression": "arv_first_regimen_start_date is not null and date(encounter_datetime) = date(arv_first_regimen_start_date) and (date(arv_first_regimen_start_date) between @startDate and @endDate) and cur_arv_meds is not null and prev_arv_meds is null" + }, + { + "name": "starting_art_and_has_tb", + "label": "starting_art_and_has_tb", + "description": "Starting ART and has TB", + "expression": "(tb_tx_start_date is not null and timestampdiff(year,tb_tx_start_date,@startDate) <= 1) and (date(encounter_datetime) = date(arv_first_regimen_start_date) and (date(arv_first_regimen_start_date) between @startDate and @endDate) and cur_arv_meds is not null and prev_arv_meds is null)" + }, + { + "name": "revisits_on_art_total", + "label": "revisits on art total", + "description": "Total # of patient revisits on ART", + "expression": "encounter_datetime > arv_start_date and (coalesce(t1.death_date, out_of_care) is null)" + }, + { + "name": "on_art_total", + "label": "on art total", + "description": "A patient is on ART if they are in care and was prescribed ART at their last clinical encounter.", + "expression": "encounter_datetime >= arv_start_date" + }, + { + "name": "not_on_art_total", + "label": "not on art total", + "description": "Total # of patients not on ART", + "expression": "(encounter_datetime < arv_start_date or arv_start_date is null)" + }, + { + "name": "on_original_first_line", + "label": "on original first line", + "description": "Total # of patients on original ART regimen", + "expression": "cur_arv_meds = arv_first_regimen and cur_arv_line = 1 and date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(transfer_out, out_of_care) is null and timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),@endDate) <= 90 " + }, + { + "name": "on_alternative_first_line", + "label": "on alternative first line", + "description": "Total # of patients on original ART regimen", + "expression": "cur_arv_meds != arv_first_regimen and cur_arv_line = 1 and date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(transfer_out, out_of_care) is null and timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),@endDate) <= 90" + }, + { + "name": "on_second_line_or_higher", + "label": "on second line or higher", + "description": "Total # of patients on original ART regimen", + "expression": "cur_arv_meds != arv_first_regimen and cur_arv_line >= 2 and date(t1.arv_first_regimen_start_date) >= DATE_SUB(@startDate, INTERVAL 1 YEAR) and date(t1.arv_first_regimen_start_date) <= DATE_SUB(@endDate, INTERVAL 1 YEAR) and coalesce(transfer_out, out_of_care) is null and timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),@endDate) <= 90" + }, + { + "name": "screened_for_tb", + "label": "screened for tb", + "description": "Total # of patients screened for TB", + "expression": "screened_for_tb and encounter_datetime between @startDate and @endDate" + }, + { + "name": "is_on_inh_treatment", + "label": "is_on_inh_treatment", + "description": "patient is on INH treatment", + "expression": "tb_prophylaxis_start_date is not null" + }, + { + "name": "using_modern_contracept_method", + "label": "using modern contracept method", + "description": " # of patients using modern contraceptive methods (IUD, injectables, OCP, e.t.c)", + "expression": "using_modern_contraceptive_method = 1 and encounter_datetime between @startDate and @endDate" + }, + { + "name": "condoms_provided", + "label": "condoms provided", + "description": " # of patients provided with condoms", + "expression": "condoms_provided = 1 and encounter_datetime between @startDate and @endDate" + }, + { + "name": "female_gte_18yo_visits", + "label": "female gte 18yo visits", + "description": " female patients >= 18", + "expression": "gender='F' and timestampdiff(year,birthdate,@endDate) >= 18 and encounter_datetime between @startDate and @endDate" + }, + { + "name": "scheduled_visits", + "label": "scheduled visits", + "description": "Scheduled visit", + "expression": "(date(encounter_datetime) = date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " + }, + { + "name": "unscheduled_visits", + "label": "unscheduled visits", + "description": "Unscheduled visit", + "expression": "(date(encounter_datetime) != date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate" + }, + { + "name": "early_scheduled_visits", + "label": "early scheduled visits", + "description": "Early Scheduled visit", + "expression": "(date(encounter_datetime) < date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " + }, + { + "name": "late_scheduled_visits", + "label": " late scheduled visits", + "description": "Late scheduled visit", + "expression": "(date(encounter_datetime) > date(prev_rtc_date)) and encounter_datetime between @startDate and @endDate " + }, + { + "name": "total_visits", + "label": "total visits", + "description": "Total # of Hiv Care Visits", + "expression": "" + }, + { + "name": "on_art", + "label": "on art", + "description": "Total # patient on ART", + "expression": "encounter_datetime >= arv_start_date and (coalesce(t1.death_date, out_of_care) is null)" + }, + { + "name": "ever_on_art", + "label": "ever on art", + "description": "Total # patient ever on ART", + "expression": "arv_first_regimen_start_date is not null" + }, + { + "name": "attended", + "label": "attended", + "description": "attended", + "expression": "" + }, + { + "name": "scheduled", + "label": "scheduled", + "description": "scheduled", + "expression": "" + }, + { + "name": "defaulted", + "label": "defaulted", + "description": "defaulted", + "expression": "" + }, + { + "name": "not_attended", + "label": "not attended", + "description": "not attended", + "expression": "date(t1.rtc_date)<>date(next_clinical_datetime_hiv)" + }, + { + "name": "has_not_returned", + "label": "has not returned", + "description": "has not returned", + "expression": "date(t1.rtc_date) < DATE(NOW()) and t1.rtc_date = max_rtc_date AND COALESCE(t1.death_date) IS NULL AND t1.transfer_out IS NULL AND t1.next_clinical_datetime_hiv IS NULL AND t8.person_id is null" + }, + { + "name": "virally_suppressed_in_past_year", + "label": "virally suppressed in past year", + "description": "# of patient(s) who are virally suppressed in the past one year", + "expression": "vl_1 < 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "viral_load_resulted_in_past_year", + "label": "viral load resulted in past year", + "description": "patient(s) whose viral load has resulted in the past one year", + "expression": "vl_1 is not null and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "virally_suppressed", + "label": "virally suppressed", + "description": "# of patient(s) who are virally suppressed", + "expression": "timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and timestampdiff(day, date(vl_1_date), date(t2.endDate)) <= 365 and vl_1 < 1000" + }, + { + "name": "not_virally_suppressed", + "label": "not virally suppressed", + "description": "# of patient(s) who are not virally suppressed", + "expression": "timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and timestampdiff(day, date(vl_1_date), date(t2.endDate)) <= 365 and vl_1 >= 1000" + }, + { + "name": "perc_virally_suppressed", + "label": "perc virally suppressed", + "description": "The denominator includes those patients who are active in care, on ART, required a viral load and got a viral load. The numerator includes those patients who required a viral load and the result was less than 1000", + "expression": "" + }, + { + "name": "not_virally_suppressed_in_past_year", + "label": "not virally suppressed in past year", + "description": "# of patient(s) who are not virally suppressed in the past one year", + "expression": "vl_1> 1000 and timestampdiff(week,vl_1_date,encounter_datetime) <= 52" + }, + { + "name": "cd4_order_date", + "label": "cd4 order date", + "description": "cd4_order_date", + "expression": "DATE_FORMAT(cd4_order_date,'%m-%d-%Y')" + }, + { + "name": "perc_virally_suppressed_in_past_year", + "label": "perc virally suppressed in past year", + "description": "% of patient(s) who are virally suppressed in the past one year", + "expression": "" + }, + { + "name": "perc_not_virally_suppressed_in_past_year", + "label": "perc not virally suppressed in past year", + "description": "% of patient(s) who are not virally suppressed in the past one year", + "expression": "" + }, + { + "name": "perc_on_arvs", + "label": "perc on arvs", + "description": "% of patients who are on ARVs", + "expression": "" + }, + { + "name": "perc_in_care", + "label": "perc in care", + "description": "% of patients who are in Care", + "expression": "" + }, + { + "name": "perc_on_arvs_lte_6_months", + "label": "perc on arvs lte 6 months", + "description": "% of patients who have been on ARVs for less than 6 months", + "expression": "" + }, + { + "name": "perc_on_arvs_gt_6_months", + "label": "perc on arvs gt 6 months", + "description": "% of patients who have been on ARVs for more than 6 months", + "expression": "" + }, + { + "name": "perc_on_arv_first_line", + "label": "perc on arv first line", + "description": "% of patients on ARVs first line", + "expression": "" + }, + { + "name": "perc_on_arv_second_line", + "label": "perc on arv second line", + "description": "% of patients on ARVs second line", + "expression": "" + }, + { + "name": "perc_on_arv_gt_third_line", + "label": "perc on arv gt third line", + "description": "% of patients on ARVs third line or more", + "expression": "" + }, + { + "name": "perc_with_pending_viral_load", + "label": "perc with pending viral load", + "description": "% of patients with pending viral load", + "expression": "" + }, + { + "name": "on_arvs_gt_26_weeks", + "label": "on arvs gt 26 weeks", + "description": "# of patient(s) who have been on ARVs 26 weeks or more", + "expression": "timestampdiff(week,arv_start_date,encounter_datetime) > 26" + }, + { + "name": "needs_vl_coded", + "label": "needs vl coded", + "description": "Patient level coded indicator that determines whether patient requires a Viral load", + "expression": "case when (cur_arv_meds is null) then 0 when (timestampdiff(month,vl_1_date, date(@referenceDate)) > 3) and vl_1 > 1000 and arv_start_date < vl_1_date then 1 when (timestampdiff(month,arv_start_date,date(@referenceDate)) between 6 and 12) and (vl_1_date is null or vl_1_date < arv_start_date ) then 2 when (timestampdiff(month,arv_start_date,@referenceDate) > 12) and (vl_1_date is null or timestampdiff(month,vl_1_date,@referenceDate) > 12) then 3 else 0 end" + }, + { + "name": "qualifies_differenciated_care", + "label": "qualifies for differentiated care", + "description": "# A patient who is above 18 yrs and qualifies and with a viral load of less than 1000 and has been on TB prophylaxis for at least six months.", + "expression": "case when vl_1 < 1000 and (timestampdiff(year,birthdate, date(@referenceDate)) > 18) and (timestampdiff(month,tb_prophylaxis_start_date,if(tb_prophylaxis_end_date,tb_prophylaxis_end_date,@referenceDate)) >= 6 ) and (timestampdiff(month,vl_1_date,now()) <= 11 ) then 1 else 0 end" + }, + { + "name": "needs_vl_in_period", + "label": "needs vl in period", + "description": "Patient level coded indicator that determines whether patient requires a Viral load", + "expression": "case when (cur_arv_meds is not null and vl_1 > 1000) and (timestampdiff(day,vl_1_date, @endDate) >= 90) then true when (timestampdiff(month,arv_start_date, @endDate) <= 12) and (vl_1_date is null or timestampdiff(month,vl_1_date, @endDate) >= 6) and (timestampdiff(month,arv_start_date, @endDate)>=6) then true when (timestampdiff(month,arv_start_date, @endDate) >= 12) and (vl_1_date is null or timestampdiff(month,vl_1_date, @endDate) >= 12) then true else false end" + }, + { + "name": "months_since_last_vl_date", + "label": "months since last vl date", + "description": "Number of months since last vl date", + "expression": "timestampdiff(month,vl_1_date, @referenceDate)" + }, + { + "name": "overdue_vl_lab_order", + "label": "overdue vl lab order", + "description": "Patient level coded indicator that determines whether patient Viral load order is overdue", + "expression": "case when (timestampdiff(day,vl_order_date, @referenceDate) >= 14) and (vl_1_date is null or vl_order_date > vl_1_date) and vl_error <> 1 then timestampdiff(day,vl_order_date, @referenceDate) else 0 end " + }, + { + "name": "ordered_vl_has_error", + "label": "latest ordered vl has error", + "description": "Patient level coded indicator that determines whether patient Viral load order is overdue", + "expression": "case when vl_error= 1 then 1 else 0 end " + }, + { + "name": "needs_cd4_count_coded", + "label": "needs cd4 count coded", + "description": "Patient level coded indicator that determines whether patient requires a Viral load", + "expression": "case when cur_arv_meds is not null and vl_1 > 1000 and timestampdiff(day,cd4_1_date, @referenceDate) >= 90 then 1 when timestampdiff(month,arv_start_date, @referenceDate) <= 12 and (cd4_1_date is null or timestampdiff(month,cd4_1_date, @referenceDate) > 6) then 2 when timestampdiff(month,arv_start_date, @referenceDate) > 12 and (cd4_1_date is null or timestampdiff(month,cd4_1_date, @referenceDate) > 12) then 3 else 0 end" + }, + { + "name": "overdue_cd4_count_lab_order", + "label": "overdue cd4 count lab order", + "description": "Patient level coded indicator that determines whether patient Viral load order is overdue", + "expression": "case when timestampdiff(day,cd4_order_date, @referenceDate) > 30 and cd4_1_date is null or cd4_order_date > cd4_1_date then timestampdiff(day,cd4_order_date, @referenceDate) else 0 end " + }, + { + "name": "encounters_count", + "label": "encounters_count", + "description": "", + "expression": "" + }, + { + "name": "patients_requiring_vl", + "label": "patients requiring vl", + "description": "patients requiring vl", + "expression": "timestampdiff(month,arv_start_date,encounter_datetime) >= 6" + }, + { + "name": "tested_appropriately", + "label": "tested appropriately", + "description": "Patients who are under ART and are missing Viral Load in past year", + "expression": "timestampdiff(month, arv_start_date, encounter_datetime) >= 6 and timestampdiff(day, date(vl_1_date), date(t2.endDate)) <= 365" + }, + { + "name": "not_tested_appropriately", + "label": "not tested appropriately", + "description": "Patients who are under ART and are missing Viral Load in past year", + "expression": "timestampdiff(month, arv_start_date, encounter_datetime) >= 6 and (timestampdiff(day,vl_1_date, date(t2.endDate)) > 365 or vl_1_date is null)" + }, + { + "name": "due_for_annual_vl", + "label": "due for annual vl", + "description": "In a specific month, these are patients who need new Annual Viral Load but none was ordered in that month. For example, If a patient had an annual VL on 10/2015, the he/she will be due on 10/2016 and not any other month", + "expression": "timestampdiff(month, arv_start_date, encounter_datetime) >= 6 and (DATE_ADD(vl_1_date, INTERVAL 1 YEAR) between DATE_FORMAT(t2.endDate,'%Y-%m-01') and t2.endDate) and (orders.date_created is null or orders.concept_id!=856)" + }, + { + "name": "pending_vl_orders", + "label": "pending vl orders", + "description": "In a specific month, these are patients with pending Viral Load Orders that have not resulted.", + "expression": "orders.concept_id=856 and (date(orders.date_created) between DATE_FORMAT(t2.endDate,'%Y-%m-01') and t2.endDate) and date(vl_1_date) != date(orders.date_created) and date(vl_1_date) < DATE_FORMAT(t2.endDate,'%Y-%m-01')" + }, + { + "name": "missing_vl_order", + "label": "missing vl and vl order", + "description": " From reporting start-date to a specific month, these are patients on ART, with no Viral Load and no Viral Load Test Order (Patients whose Viral Load Test Order not placed)", + "expression": "timestampdiff(month, arv_start_date, encounter_datetime) >= 6 and (timestampdiff(day,vl_1_date, date(t2.endDate)) > 365 or vl_1_date is null) and (orders.date_created is null or orders.concept_id!=856)" + }, + { + "name": "perc_tested_appropriately", + "label": "perc tested appropriately", + "description": " For this indicator the denominator includes patients who are active in care, on ART and require a viral load. A patient requires a viral load if they have been on ART more than 6 months. The numerator are those patients who are active in care, on ART, required a viral load and got a viral load", + "expression": "" + }, + { + "name": "deceased_patients", + "label": "Deceased Patients", + "description": "This indicator includes all patients with patient care status of 'DECEASED'", + "expression": "patient_care_status=159" + }, + { + "name": "untraceable_patients", + "label": "untraceable patients", + "description": "This indicator includes all patients with patient care status of 'UNTRACEABLE'", + "expression": "patient_care_status=9079" + }, + { + "name": "transferred_out_patients", + "label": "transferred out patients", + "description": "A patient is considered to be transferred out if a provider declares the patient as NON-AMPATH", + "expression": "patient_care_status=1287" + }, + { + "name": "hiv_negative_patients", + "label": "hiv negative patients", + "description": "This indicator includes all patients with patient care status of 'HIV NEGATIVE, NO LONGER AT RISK'", + "expression": "patient_care_status=9036" + }, + { + "name": "patients_continuing_care", + "label": "patients continuing care", + "description": "This indicator includes all patients with patient care status of 'CONTINUE'", + "expression": "(patient_care_status=6101 and timestampdiff(day,rtc_date, @endDate) < 90 and is_clinical_encounter=1 ) or (patient_care_status=6101 and is_clinical_encounter=0 and @endDate > DATE_ADD(prev_clinical_rtc_date_hiv, INTERVAL 90 DAY))" + }, + { + "name": "self_disengaged_from_care", + "label": "self disengaged from care", + "description": "This indicator includes all patients with patient care status of 'SELF DISENGAGED FROM CARE'", + "expression": "patient_care_status=9083" + }, + { + "name": "defaulters", + "label": "defaulters", + "description": "This indicator includes all patients with patient care status of 'CONTINUE' and their RTC date is greater than 90 days from the reporting date", + "expression": "(patient_care_status=6101 and timestampdiff(day,if(is_clinical_encounter=1,rtc_date,prev_clinical_rtc_date_hiv), @endDate) > 90)" + }, + { + "name": "transfer_to_MNCH", + "label": "transfer to MNCH", + "description": "transfer to MNCH", + "expression": "patient_care_status=9504" + }, + { + "name": "other_patient_care_status", + "label": "other status", + "description": "This indicator includes all patients who do not fall in either of the above categories ", + "expression": "patient_care_status not in (159,9079,1287,9036,6101,9083)" + }, + { + "name": "on_nevirapine", + "label": "patient on_nevirapine", + "description": "A patient is considered to be on \"Nevirapine\" if current ARV regimen formulation contains: NEVIRAPINE or NEVIRAPINE LAMIVUDINE AND ZIDOVUDINE or STAVUDINE LAMIVUDINE AND NEVIRAPINE", + "expression": "cur_arv_meds regexp '(631|6467|792)'" + }, + { + "name": "on_lopinavir", + "label": "patient on_lopinavir", + "description": "A patient is considered to be on \"Lopinavir\" if current ARV regimen formulation contains: Lopinavir or LOPINAVIR AND RITONAVIR.", + "expression": "cur_arv_meds regexp '(9026|794)'" + }, + { + "name": "on_efavirenz", + "label": "patient on_efavirenz", + "description": "A patient is considered to be on \"Efavirenz\" if current ARV regimen formulation contains: TDF AND 3TC AND EFV or Efavirenz.", + "expression": "cur_arv_meds regexp '(633|6964)'" + }, + { + "name": "on_atazanavir", + "label": "patient on_atazanavir", + "description": "A patient is considered to be using \"Atazanavir\" if current ARV regimen formulation contains: ATAZANAVIR or ATAZANAVIR AND RITONAVIR.", + "expression": "cur_arv_meds regexp '(6159|6160)'" + }, + { + "name": "on_raltegravir", + "label": "patient on_raltegravir", + "description": "A patient is considered to be on \"Raltegravir\" if current ARV regimen formulation contains: Raltegravir.", + "expression": "cur_arv_meds regexp '(6156)'" + }, + { + "name": "on_other_arv_drugs", + "label": "patient on_other_arv_drugs", + "description": "A patient is considered to be on \"others\" if current ARV regimen formulation neither contains: Raltegravir or Atazanavir or ATAZANAVIR AND RITONAVIR or Efavirenz or TENOFOVIR AND LAMIVUDINE AND EFAVIRENZ or LOPINAVIR or LOPINAVIR AND RITONAVIR or NEVIRAPINE or NEVIRAPINE LAMIVUDINE AND ZIDOVUDINE or STAVUDINE LAMIVUDINE AND NEVIRAPINE.", + "expression": "not (cur_arv_meds regexp '(6156|6159|6160|633|6964|9026|794|631|6467|792)')" + }, + { + "name": "not_on_arv", + "label": "patient not_on_arv", + "description": "A patient is considered to be on \"Not on any ARV Drugs\" if he/she is not on any ARV drugs.", + "expression": "cur_arv_meds is null" + }, + { + "name": "on_second_line_not_suppressed", + "label": "on second line not suppressed", + "description": "patient on second line not suppressed", + "expression": "vl_1 > 1000 and cur_arv_line =2" + }, + { + "name": "newly_on_second_line", + "label": "newly on second line", + "description": "patient newly on second line within a given period", + "expression": "cur_arv_line =2 and (arv_start_date between @startDate and @endDate)" + }, + { + "name": "newly_enrolled", + "label": "newly enrolled", + "description": "patients who are newly enrolled", + "expression": "is_clinical_encounter=1 and prev_clinical_datetime_hiv is null" + }, + { + "name": "new_viral_load_present", + "label": "new viral load present", + "description": "patient has a new viral load result", + "expression": "DATE_ADD(vl_1_date, INTERVAL 90 DAY) > NOW()" + }, + { + "name": "not_on_arvs_cd4_lte_500", + "label": "not on arvs cd4 lte 500", + "description": "patients who qualify for ART but are not on therapy", + "expression": "arv_start_date is null and cd4_1 < 500" + }, + { + "name": "total_with_vl", + "label": "total with vl", + "description": "The number of patients who have at least one viral load resulted within 366 days of the end_date (can be more than 1 year", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 AND TIMESTAMPDIFF(DAY, vl_2_date, @endDate) <= 366" + }, + { + "name": "num_with_two_vls_past_year", + "label": "num with two vls past year", + "description": "The number of patients who have two viral load results within 366 days of end_date", + "expression": "timestampdiff(day,t1.vl_1_date,@endDate) <= 366 and timestampdiff(day,t1.vl_2_date,@endDate) <= 366" + }, + { + "name": "num_with_only_one_vl_past_year", + "label": "num with only one vl past year", + "description": "the number of patients who have only one viral in the past year and no other viral load in past year", + "expression": "timestampdiff(day,t1.vl_1_date,@endDate) <= 366 and timestampdiff(day,t1.vl_2_date,@endDate) <= 366" + }, + { + "name": "num_with_at_least_one_vl_past_year", + "label": "num with at least one vl past year", + "description": "the number of patients with at least one viral in the past year and no other viral load in past year", + "expression": "timestampdiff(day,t1.vl_1_date,@endDate) <= 366" + }, + { + "name": "second_vl_gt_one_yo", + "label": "second vl gt one year", + "description": "The number of patients who only have a single viral load resulted within 366 days of end_date and another viral load older than one year from year from end_date", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and timestampdiff(day,vl_2_date,@endDate) > 366" + }, + { + "name": "last_vl_undetected", + "label": "last vl undetected", + "description": "Total # of patients with last vl undetected", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 = 0" + }, + { + "name": "last_vl_unsuppressed", + "label": "last vl unsuppressed", + "description": "Total # of patients which have a VL in past year which was unsuppressed.", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 >= 1000" + }, + { + "name": "last_vl_suppressed", + "label": "last vl suppressed", + "description": "Total # of patients which have a VL in past year which was unsuppressed", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 < 1000" + }, + { + "name": "perc_unsuppressed", + "label": "perc unsuppressed", + "description": "The number of patients with a unsuppressed viral load within 1 year from end date divided by the number of patients with a viral load within 1 year of end date", + "expression": "" + }, + { + "name": "one_vl_unsuppressed", + "label": "one vl unsuppressed", + "description": "The number of patients with a single vl within one year of end_date and that vl >= 1000", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 is null or timestampdiff(day,vl_2_date,@endDate) > 366) and vl_1 >= 1000" + }, + { + "name": "one_vl_suppressed", + "label": "one vl suppressed", + "description": "The number of patients with a single vl within one year of end_date and that VL < 1000", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 is null or timestampdiff(day,vl_2_date,@endDate) > 366) and vl_1 < 1000" + }, + { + "name": "num_requiring_followup_vl", + "label": "num requiring followup vl", + "description": "The number of patients with viral load in the past year in which the VL >= 1000 and it’s been more than 90 days between that VL and end_date.", + "expression": "timestampdiff(day,vl_2_date,@endDate) <= 366 AND vl_2 >1000 || (timestampdiff(day,vl_1_date,@endDate) <= 366 AND vl_1 > 1000 AND timestampdiff(day,vl_1_date,@endDate) > 90 AND (vl_2 is null or vl_2_date > 1 ))" + }, + { + "name": "getting_followup_vl", + "label": "getting followup vl", + "description": "Number of patients who got a follow-up viral load who needed one", + "expression": "TIMESTAMPDIFF(DAY, vl_2_date,@endDate) <= 366 AND vl_2 > 1000" + }, + { + "name": "getting_followup_vl_180_days", + "label": "getting followup vl", + "description": "Number of patients who got a follow-up viral load who needed one and the follow up is within 180 days", + "expression": "TIMESTAMPDIFF(DAY, vl_2_date,@endDate) <= 366 AND vl_2 > 1000 AND TIMESTAMPDIFF(DAY, vl_1_date,@endDate) <= 180" + }, + { + "name": "perc_getting_followup_vl", + "label": "perc getting followup vl", + "description": "The numerator is number of patients who got a follow-up viral load who needed one. The denominator is the number of patients who required a follow-up (num_requiring_followup_vl)", + "expression": "" + }, + { + "name": "perc_getting_followup_vl_180_days", + "label": "perc getting followup vl 180 days", + "description": "The numerator is number of patients who got a follow-up viral load within 180 days who needed one. The denominator is the number of patients who required a follow-up (num_requiring_followup_vl)", + "expression": "" + }, + { + "name": "one_vl_unsuppressed_gt_90_days", + "label": "one vl unsuppressed gt 90 days", + "description": "The number of patients who have a single viral load in the past year which is >= 1000 and the difference between end_date and the vl date is > 90 days", + "expression": "TIMESTAMPDIFF(DAY, vl_1_date, @endDate) <= 366 AND (vl_2 IS NULL OR TIMESTAMPDIFF(DAY, vl_2_date, @endDate > 366) AND vl_1 >= 1000 AND TIMESTAMPDIFF(DAY, vl_1_date, @endDate > 90" + }, + { + "name": "one_vl_unsuppressed_gt_180_days", + "label": "one vl unsuppressed gt 180 days", + "description": "The number of patients who have a single viral load in the past year which is >= 1000 and the difference between end_date and the vl date is > 180 days", + "expression": "TIMESTAMPDIFF(DAY, vl_1_date, @endDate) <= 366 AND (vl_2 IS NULL OR TIMESTAMPDIFF(DAY, vl_2_date, @endDate > 366) AND vl_1 >= 1000 AND TIMESTAMPDIFF(DAY, vl_1_date, @endDate > 180" + }, + { + "name": "avg_time_since_last_unsuppressed_vl_one_vl", + "label": "avg time since last unsuppressed vl one vl", + "description": "Avg time since last unsuppressed vl one vl", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 > 1000 and (vl_2 is null or timestampdiff(day,vl_2_date,@endDate) > 366)" + }, + { + "name": "total_with_two_vls", + "label": "total with two vls", + "description": "Total # of patients with two vls within one year of end_date.", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" + }, + { + "name": "init_vl_unsuppressed_follow_up_unsuppressed", + "label": "init vl unsuppressed follow up unsuppressed", + "description": "Total # of patients with an initial viral load >= 1000 with a follow-up viral load >= 1000 where both viral loads are within one year of end_date", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 >= 1000 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" + }, + { + "name": "follow_up_suppressed", + "label": "follow up suppressed", + "description": "Total # of patients with an initial viral load >= 1000 with a follow-up viral load < 1000 where both viral loads are within one year of end_date", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_1 >= 1000 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 < 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" + }, + { + "name": "perc_fu_suppressed", + "label": "perc fu suppressed", + "description": "Of the cohort of patients with a VL >= 1000, what percentage have a follow-up that is suppressed. The denominator is all the patients with a VL >= 1000 within one year of end_date AND have a follow-up viral load within 1 year of end date", + "expression": "" + }, + { + "name": "avg_length_btwn_vls_first_unsuppressed", + "label": "avg length btwn vls first unsuppressed", + "description": "For patients with an initial VL >= 1000 within 1 year of end_date, the average number of days until a follow-up viral load was ordered.", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" + }, + { + "name": "days_since_last_vl_first_unsuppressed", + "label": "days since last vl first unsuppressed", + "description": "avg days since last vl first unsuppressed", + "expression": "timestampdiff(day,vl_1_date,@endDate) <= 366 and timestampdiff(day,vl_2_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,vl_1_date) > 60" + }, + { + "name": "no_switch_after_unsuppressed", + "label": "no switch after unsuppressed", + "description": "# The number of patients switched to new regiment after the previous vl vl >= 1000", + "expression": "arv_start_date < vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366" + }, + { + "name": "switch_after_unsuppressed", + "label": "switch after unsuppressed", + "description": "# of patients with switch after unsuppressed", + "expression": "arv_start_date > vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366" + }, + { + "name": "no_switch_after_unsuppressed_x1", + "label": "no switch after unsuppressed x1", + "description": "# The number of patients remaining on same regimen after the previous vl >= 1000", + "expression": "arv_start_date < vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 < 1000 or timestampdiff(day,vl_2_date,@endDate) <= 366)" + }, + { + "name": "switch_after_unsuppressed_x1", + "label": "switch after unsuppressed x1", + "description": "# of patients switched to new regimen after a single, unsuppressed VL in past year", + "expression": "arv_start_date > vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 < 1000 or timestampdiff(day,vl_2_date,@endDate) <= 366)" + }, + { + "name": "no_switch_after_unsuppressed_x_2", + "label": "no switch after unsuppressed x2", + "description": "# of patients not switched to new regimen after two unsuppressed VLs in past year", + "expression": "arv_start_date < vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366 and vl_2 >= 1000 and timestampdiff(day,vl_2_date,@endDate) <= 366" + }, + { + "name": "switch_after_unsuppressed_x_2", + "label": "switch after unsuppressed x 2", + "description": "# of patients switched to new regimen after two unsuppressed VLs in past year", + "expression": "arv_start_date > vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366 and (vl_2 < 1000 or timestampdiff(day,vl_2_date,@endDate) <= 366)" + }, + { + "name": "avg_time_to_switch_after_unsuppressed", + "label": "avg time to switch after unsuppressed", + "description": "Average time to switch a patient to a new regimen after an unsuppressed viral load", + "expression": "arv_start_date > vl_1_date and vl_1 >= 1000 and timestampdiff(day,vl_1_date,@endDate) <= 366" + }, + { + "name": "avg_time_to_switch_after_unsuppressed_x2", + "label": "avg time to switch after unsuppressed x2", + "description": "Average time to switch a patient to a new regimen after two two unsuppressed viral loads", + "expression": "arv_start_date > vl_1_date AND vl_1 >= 1000 AND TIMESTAMPDIFF(DAY, vl_1_date, NOW()) <= 366 AND vl_2 > 1000 AND TIMESTAMPDIFF(DAY, vl_2_date, NOW()) <= 366, TIMESTAMPDIFF(DAY,vl_1_date, arv_start_date)" + }, + { + "name": "avg_days_to_switch_after_unsuppressed", + "label": "avg days to switch after unsuppressed", + "description": "avg time to switch after unsuppressed", + "expression": "arv_start_date > vl_1_date and vl_1 >= 1000" + }, + { + "name": "num_with_vl_after_switch", + "label": "num with vl after switch", + "description": "# of patients with vl after switch", + "expression": "arv_start_date > vl_2_date and arv_start_date < vl_1_date" + }, + { + "name": "num_with_vl_after_switch_suppressed", + "label": "num with vl after switch suppressed", + "description": "# of patients with suppressed follow-up viral load after a regiment switch", + "expression": "arv_start_date > vl_2_date and arv_start_date < vl_1_date and vl_1 < 1000" + }, + { + "name": "num_with_vl_after_switch_unsuppressed", + "label": "num with vl after switch unsuppressed", + "description": "# of patients with unsuppressed follow-up viral load after a regimen switch", + "expression": "arv_start_date > vl_2_date and arv_start_date < vl_1_date and vl_1 >= 1000" + }, + { + "name": "perc_switched_with_suppressed_fu", + "label": "perc switched with suppressed fu", + "description": "% of patients switched with suppressed f/u VL", + "expression": "" + }, + { + "name": "perc_ART_pats_screened_for_TB_receiving_TB_medication", + "label": "perc ART pats screened for TB receiving TB medication", + "description": "percentage of ART pats who are screened for TB and receiving TB medication", + "expression": "" + }, + { + "name": "num_ART_pats_screened_for_tb_started_TB", + "label": "# ART pats screened for tb started TB", + "description": "# of ART patients who are screened for tb and are started on TB medication", + "expression": "screened_for_tb is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(t1.death_date, out_of_care) is null" + }, + { + "name": "num_new_ART_pats_screened_for_tb_started_TB_this_period", + "label": "# newly started on ART pats screened for tb started TB this reporting period", + "description": "# of newly started on ART patients who are screened for tb and are started on TB medication this reporting period", + "expression": "screened_for_tb is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(t1.death_date, out_of_care) is null and arv_start_date>= @startDate and arv_start_date<= @endDate" + }, + { + "name": "num_previous_ART_pats_screened_for_tb_started_TB", + "label": "# previously started on ART pats screened for tb started TB", + "description": "# of previously started on ART patients who are screened for tb and are started on TB medication", + "expression": "screened_for_tb is not null and tb_tx_start_date is not null and cur_arv_line is not null and coalesce(t1.death_date, out_of_care) is null and arv_start_date< @startDate" + }, + { + "name": "num_ART_pats_screened_for_tb", + "label": "# ART pats screened for tb", + "description": "# of ART patients who are screened for tb", + "expression": "screened_for_tb is not null and cur_arv_line is not null and coalesce(t1.death_date, out_of_care) is null" + }, + { + "name": "perc_ART_pats_completed_6mths_IPT", + "label": "perc ART pats completed 6mths IPT", + "description": "percentage of ART pats who have completed 6 months of IPT therapy", + "expression": "" + }, + { + "name": "num_ART_patients_completed_6mths_IPT", + "label": "# of ART patients who have completed 6mths IPT", + "description": "# of ART patients who have completed 6mths of IPT patients", + "expression": "round(datediff(encounter_datetime,tb_prophylaxis_start_date)/30.5) >= 6 or round(datediff(tb_prophylaxis_end_date,tb_prophylaxis_start_date)/30.5) >= 6 and (coalesce(t1.death_date, out_of_care) is null)" + }, + { + "name": "num_ART_patients_newly_started_IPT_less_6mths", + "label": "# ART patients newly started IPT less 6mths", + "description": "# ART patients newly started IPT and have completed less than 6mths on therapy", + "expression": "tb_prophylaxis_start_date is not null or tb_prophylaxis_end_date is not null and tb_prophylaxis_start_date >= DATE_ADD(@startDate, INTERVAL -6 month) and (coalesce(t1.death_date, out_of_care) is null) " + }, + { + "name": "num_ART_patients_newly_started_IPT_this_period_less_6mths", + "label": "# ART patients newly started IPT this period less 6mths", + "description": "# of ART patients newly started IPT in this reporting period and have completed less than 6mths on therapy", + "expression": "tb_prophylaxis_start_date is not null or tb_prophylaxis_end_date is not null and tb_prophylaxis_start_date >= @startDate" + }, + { + "name": "num_ART_patients_newly_started_IPT_previous_period_less_6mths", + "label": "# ART patients newly started IPT in the previous period less 6mths", + "description": "# of ART patients newly started IPT in the previous reporting period and have completed less than 6mths on therapy", + "expression": "tb_prophylaxis_start_date is not null or tb_prophylaxis_end_date is not null and tb_prophylaxis_start_date < @startDate" + }, + { + "name": "num_ART_patients_newly_started_IPT_previous_period_less_6mths", + "label": "# ART patients newly started IPT in the previous period less 6mths", + "description": "# of ART patients newly started IPT in the previous reporting period and have completed less than 6mths on therapy", + "expression": "tb_prophylaxis_start_date is not null or tb_prophylaxis_end_date is not null and tb_prophylaxis_start_date < @startDate" + }, + { + "name": "num_patients_currently_on_IPT", + "label": "# patients currently on IPT", + "description": "number of patients currently on IPT", + "expression": "coalesce(t1.death_date, out_of_care) is null and tb_prophylaxis_start_date is not null and tb_prophylaxis_end_date is null" + }, + { + "name": "num_patients_newly_enrolled_newly_started_on_IPT", + "label": "# patients newly enrolled newly started on IPT", + "description": "number of patients newly enrolled and newly started on IPT", + "expression": "coalesce(t1.death_date, out_of_care) is null and tb_prophylaxis_start_date is not null and @startDate<=enrollment_date and enrollment_date<=@endDate" + }, + { + "name": "num_patients_stopped_on_IPT", + "label": "# patients stopped on IPT", + "description": "number of patients stopped on IPT", + "expression": "coalesce(t1.death_date, out_of_care) is null and t1.tb_prophylaxis_end_date is not null and @startDate<=tb_prophylaxis_end_date<=@endDate" + }, + { + "name": "newly_started_IPT", + "label": "# patients newly started IPT", + "description": "# eligible patients newly started IPT within the reporting period", + "expression": "date(tb_prophylaxis_start_date) between @startDate and @endDate" + }, + { + "name": "ever_started_on_IPT", + "label": "# patients ever started on IPT", + "description": "# eligible patients ever started on IPT within the reporting period", + "expression": " tb_prophylaxis_start_date is not null" + }, + { + "name": "completed_12_months_IPT", + "label": "# patients completed 12 months IPT within reporting period", + "description": "# completed 12 months IPT within the reporting period", + "expression": "date(tb_prophylaxis_end_date) between @startDate and @endDate and (timestampdiff(month,tb_prophylaxis_start_date, tb_prophylaxis_end_date) >= 12) " + }, + { + "name": "started_TB_treatment_within_reporting_period", + "label": "# patients started_TB_treatment_within_reporting_period", + "description": "Total clients who are started treatment within reporting period", + "expression": "tb_tx_start_date is not null and date(tb_tx_start_date) between @startDate and @endDate" + }, + { + "name": "HIV_patients_newly_enrolled_into_TB_treatment", + "label": "# patients who were hiv positive before initiating TB treatment within reporting period", + "description": "Total clients who were hiv positive before initiating TB treatment within reporting period", + "expression": "date(hiv_start_date) < date(tb_tx_start_date) and date(tb_tx_start_date) between @startDate and @endDate" + }, + { + "name": "TB_patients_newly_enrolled_into_HIV_care", + "label": "# TB patients who are being enrolled in ART", + "description": "TB clients who are enrolled into HIV care within reporting period", + "expression": "date(tb_tx_start_date) < date(hiv_start_date) and date(hiv_start_date) between @startDate and @endDate" + }, + { + "name": "newly_identified_HIV_positive_patient_on_TB_treatment", + "label": "newly_identified_HIV_positive_patient_on_TB_treatment within reporting period", + "description": "[HIV_patients_newly_enrolled_into_TB_treatment]+[TB_patients_newly_enrolled_into_HIV_care]", + "expression": "" + }, + { + "name": "patients_on_ARV_starting_TB_treatment", + "label": "patients_on_ARV_starting_TB_treatment", + "description": "TB clients who were on ARVs before starting TB treatment within reporting period", + "expression": " date(arv_first_regimen_start_date) < date(tb_tx_start_date) and date(tb_tx_start_date) between @startDate and @endDate" + }, + { + "name": "TB_patients_starting_ARV_medication", + "label": "# TB_patients_starting_ARV_medication", + "description": "TB clients who are starting ARV medication within reporting period", + "expression": "date(tb_tx_start_date) < date(arv_first_regimen_start_date) and date(arv_first_regimen_start_date) between @startDate and @endDate" + }, + { + "name": "newly_identified_TB_patients_on_ARVs", + "label": "newly_identified_TB_patients_on_ARVs within reporting period", + "description": "[TB_patients_starting_ARV_medication]+[patients_on_ARV_starting_TB_treatment]", + "expression": "" + }, + { + "name": "total_hiv_exposed", + "label": "# count of all clients exposed to HIV", + "description": "all clients exposed to HIV within reporting period", + "expression": "hiv_exposed_occupational is not null" + }, + { + "name": "hiv_exposed_occupational", + "label": "# count of all clients exposed to HIV (occupational)", + "description": "occupational clients exposed to HIV within reporting period", + "expression": "hiv_exposed_occupational=1" + }, + { + "name": "hiv_exposed_non_occupational", + "label": "# count of all clients exposed to HIV (non-occupational)", + "description": "non-occupational clients exposed to HIV within reporting period", + "expression": "hiv_exposed_occupational=0" + }, + { + "name": "total_started_PEP", + "label": "# count of all clients exposed to HIV and started PEP", + "description": "all clients exposed to HIV and received PEP within reporting period", + "expression": "hiv_exposed_occupational is not null and date(pep_start_date) between @startDate and @endDate" + }, + { + "name": "started_PEP_occupational", + "label": "# count of all clients exposed to HIV (occupational) and started PEP", + "description": "occupational clients exposed to HIV and started PEP within reporting period", + "expression": "hiv_exposed_occupational=1 and date(pep_start_date) between @startDate and @endDate" + }, + { + "name": "started_PEP_non_occupational", + "label": "# count of all clients exposed to HIV (non-occupational) and started PEP", + "description": "non-occupational clients exposed to HIV and started PEP within reporting period", + "expression": "hiv_exposed_occupational=0 and date(pep_start_date) between @startDate and @endDate" + }, + { + "name": "total_patients", + "label": "total_patients", + "description": "These are all patients ever enrolled into care as of end of the reporting month", + "expression": "case when date(t1.encounter_datetime) <= t2.endDate then 1 else null end " + }, + { + "name": "new_enrollments", + "label": "new_enrollments", + "description": "These are patients enrolled into care within the reporting month", + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when date(t1.hiv_start_date) between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate then 1 else null end" + }, + { + "name": "transfer_in_from_non_Ampath_site", + "label": "transfer_in_from_non_Ampath_site", + "description": "These are patients who transferred in form NON AMPATH facility within the reporting month", + "expression": "t1.transfer_in=1287 and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)" + }, + { + "name": "transfer_in_from_Ampath_site", + "label": "transfer_in_from_Ampath_site", + "description": "These are patients who transferred in form AMPATH facility within the reporting month", + "expression": "t1.transfer_in=1286 and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)" + }, + { + "name": "transfer_in", + "label": "transfer_in", + "description": "These are patients who transferred into the selected facility within the reporting month", + "expression": "case when date(t1.hiv_start_date) between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate then null when t1.transfer_in is not null and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 else null end " + }, + { + "name": "transfer_in_patients", + "label": "transfer in patients", + "description": "These are patients who transferred into the selected facility within the reporting period", + "expression": "t1.transfer_in is not null" + }, + { + "name": "transfer_out_patients_this_month", + "label": "transfer_out_patients_this_month", + "description": "These are patients transferred to other Ampath or NON Ampath facility within the reporting month", + "expression": "((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and ((t1.transfer_out is not null and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)) or ( (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and (outreach_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate))) and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) " + }, + { + "name": "active_in_care_to_transfer_out", + "label": "active_in_care_to_transfer_out", + "description": "These are patients who were Active in care in the previous reporting month, but changed to transferred out in this reporting month", + "expression": "((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and ((t1.transfer_out is not null and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)) or ( (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and (outreach_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate))) and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) and timestampdiff(day,t1.rtc_date, date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) <= 90" + }, + { + "name": "transfer_out_patients", + "label": "transfer_out_patients", + "description": "These are patients ever transferred to other Ampath or NON Ampath facility", + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then 1 else null end" + }, + { + "name": "deaths", + "label": "deaths", + "description": "These are dead patients ever reported", + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then 1 else null end " + }, + { + "name": "HIV_negative_patients", + "label": "HIV_negative_patients", + "description": "These are HIV Negative patients ever reported", + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then 1 else null end" + }, + { + "name": "self_disengaged_patients", + "label": "self_disengaged_patients", + "description": "These are patients ever disengaged out of care by themselves", + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then 1 else null end " + }, + { + "name": "HIV_negative_patients_this_month", + "label": "HIV_negative_patients_this_month", + "description": "These are HIV Negative patients that were reported within the reporting month", + "expression": "case when outreach_death_date_bncd or t1.death_date then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) and (outreach_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 when t1.patient_care_status in (9036) and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 else null end" + }, + { + "name": "self_disengaged_patients_this_month", + "label": "self_disengaged_patients_this_month", + "description": "These are patients that have disengaged themselves from care within the reporting month", + "expression": "case when outreach_death_date_bncd or t1.death_date then null when (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) and (outreach_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 when t1.patient_care_status in (9083) and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then 1 else null end" + }, + { + "name": "deaths_this_month", + "label": "deaths_this_month", + "description": "These are deaths that occurred within the reporting month", + "expression": "(t1.death_date between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) or (outreach_death_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate)" + }, + { + "name": "active_in_care_to_death", + "label": "active_in_care_to_death", + "description": "These are patients who were Active in care in the previous reporting month, but died within this reporting month", + "expression": "(t1.death_date between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) or (outreach_death_date_bncd between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) and timestampdiff(day,t1.rtc_date, date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) <= 90" + }, + { + "name": "LTFU", + "label": "LTFU", + "description": "A patient is LTFU if it has been greater than 90 days from the RTC date within the given reporting period ", + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) > 90 then 1 else null end" + }, + { + "name": "LTFU_this_month", + "label": "LTFU_this_month", + "description": "Total # of new patients", + "expression": "((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) and t1.transfer_out is null and (outreach_patient_care_status_bncd not in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) between 91 and 121" + }, + { + "name": "LTFU_to_active_in_care", + "label": "LTFU_to_active_in_care", + "description": "These are patients who were LTFU in the previous reporting month, but changed to active in care in this reporting month", + "expression": "t1.transfer_out is null and (outreach_patient_care_status_bncd not in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and ((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and date(t1.encounter_datetime) between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) and timestampdiff(day, if(t1.prev_clinical_rtc_date_hiv, t1.prev_clinical_rtc_date_hiv, DATE_ADD(t1.prev_clinical_datetime_hiv, INTERVAL 30 DAY)), date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) > 90" + }, + { + "name": "active_in_care_to_LTFU", + "label": "active_in_care_to_LTFU", + "description": "These are patient who were Active in care on the previous reporting month, but changed to LTFU in this reporting month", + "expression": "t1.transfer_out is null and (outreach_patient_care_status_bncd not in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) and ((t1.death_date is null or t1.death_date > t2.endDate) and (outreach_death_date_bncd is null or outreach_death_date_bncd > t2.endDate)) and ((t1.patient_care_status is null or t1.patient_care_status not in (9036,9083)) and (outreach_patient_care_status_bncd is null or (outreach_patient_care_status_bncd not in (9036,9083) and date(outreach_date_bncd) <= t2.endDate))) and timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) > 90 and timestampdiff(day,t1.rtc_date, date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) <= 90" + }, + { + "name": "active_in_care", + "label": "active_in_care", + "description": "A patient is active in care if it has been less than 90 days from the RTC date within the given reporting period", + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 end" + }, + { + "name": "active_return", + "label": "active_return", + "description": "These are active patients without including new enrollments and transfer ins: i.e Active Patients - (Transfer In + New Enrollment)", + "expression": "case when date(t1.hiv_start_date) between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate then null when t1.transfer_in is not null and (t1.encounter_datetime between DATE_FORMAT(t2.endDate, '%Y-%m-01') and t2.endDate) then null when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 else null end" + }, + { + "name": "active_in_care_prev_month", + "label": "active_in_care_prev_month", + "description": "Total # of acive patients prev reporting month", + "expression": "timestampdiff(day,t1.rtc_date, date_sub(DATE_FORMAT(t2.endDate, '%Y-%m-01'), interval 1 day)) <= 90" + }, + { + "name": "monthly_patient_care_status", + "label": "Monthly patient care status", + "description": "Care status of patient on a monthly basis", + "expression": "CASE WHEN TIMESTAMPDIFF(DAY, IF(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 AND t1.transfer_out IS NULL AND COALESCE(t1.death_date, t1.out_of_care) IS NULL THEN 'active' WHEN TIMESTAMPDIFF(DAY, IF(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) > 90 AND transfer_out IS NULL THEN 'ltfu' WHEN t1.transfer_out IS NOT NULL AND COALESCE(t1.death_date) IS NULL THEN 'transfered_out' END" + }, + { + "name": "patient_daily_care_status", + "label": "patient_daily_care_status", + "description": "Patient daily care status", + "expression": "CASE WHEN TIMESTAMPDIFF(DAY, IF(rtc_date, rtc_date, DATE_ADD(encounter_datetime, INTERVAL 30 DAY)),@referenceDate) <= 90 AND transfer_out IS NULL AND COALESCE(death_date, out_of_care) IS NULL THEN 'active' WHEN TIMESTAMPDIFF(DAY, IF(rtc_date, rtc_date, DATE_ADD(encounter_datetime, INTERVAL 30 DAY)), @referenceDate) > 90 THEN 'ltfu' WHEN transfer_out IS NOT NULL AND COALESCE(death_date) IS NULL THEN 'transfered_out' END" + }, + { + "name": "community_ART_dispensing", + "label": "community_ART_dispensing", + "description": "These are patients who are on ART through community dispensing program", + "expression": "t1.encounter_type = 128" + }, + { + "name": "patients_with_vl_result", + "label": "patients with vl result", + "description": "# of patients with vl", + "expression": "vl_1_date between @startDate and @endDate" + }, + { + "name": "vl_suppressed_patients", + "label": "vl suppressed patients", + "description": "# of patients with vl < 1000", + "expression": "vl_1_date between @startDate and @endDate and vl_1 < 1000" + }, + { + "name": "vl_unsuppressed_patients", + "label": "vl unsuppressed patients", + "description": "# of patients with vl >= 1000", + "expression": "vl_1_date between @startDate and @endDate and vl_1 >= 1000" + }, + { + "name": "active_and_on_art", + "label": "Active and on ART", + "description": "A patient who meets the definition for active in care and was dispensed ART at the last clinical visit", + "expression": "(case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) <= 90 then 1 end) and encounter_datetime >= arv_start_date" + }, + { + "name": "has_vl_since_oct", + "label": "has VL since october", + "description": "As of the reporting month, the number of patients who have had a VL since october", + "expression": "(case when (date(t2.endDate) > date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(vl_1_date) between date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(DATE_ADD(DATE_FORMAT(t2.endDate, '%Y-09-01'), INTERVAL 1 YEAR))) then true when (date(t2.endDate) < date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(vl_1_date) between date(DATE_SUB(DATE_FORMAT(t2.endDate, '%Y-09-01'), INTERVAL 1 YEAR)) and date(DATE_FORMAT(t2.endDate, '%Y-09-01'))) then true else false end)" + }, + { + "name": "virally_suppressed_since_oct", + "label": "virally suppressed_since_oct", + "description": "# of patient(s) who are virally suppressed", + "expression": "vl_1 < 1000 and (case when (date(t2.endDate) > date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(vl_1_date) between date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(DATE_ADD(DATE_FORMAT(t2.endDate, '%Y-09-01'), INTERVAL 1 YEAR))) then true when (date(t2.endDate) < date(DATE_FORMAT(t2.endDate, '%Y-09-01')) and date(vl_1_date) between date(DATE_SUB(DATE_FORMAT(t2.endDate, '%Y-09-01'), INTERVAL 1 YEAR)) and date(DATE_FORMAT(t2.endDate, '%Y-09-01'))) then true else false end)" + }, + { + "name": "perc_virally_suppressed_since_oct", + "label": "perc virally suppressed since oct", + "description": "The denominator includes those patients (both active and LTFU) who have had a VL since October 1. The numerator includes those patients (both active and LTFU) who have had a VL since October 1 and had Vl < 100", + "expression": "" + } ] diff --git a/reports/labs-report.json b/reports/labs-report.json index 219db90ef..a3d08eca6 100755 --- a/reports/labs-report.json +++ b/reports/labs-report.json @@ -1,90 +1,119 @@ - [ - { - "name": "labs-report", - "table":{"schema":"etl","tableName":"flat_hiv_summary_v15b","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t2","joinExpression":"t1.location_uuid = t2.uuid"}, - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t3","joinExpression":"t1.person_id = t3.person_id"} - ], - "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"startAge", "defaultValue":[]}, - {"name":"endAge", "defaultValue":[]}, - {"name":"gender", "defaultValue":[]}, - {"name":"@referenceDate", "defaultValue":["defaultValue"]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"location"} - ] - }, - {"name":"groupByYear", "defaultValue":[ - {"label":"encounter_datetime","expression":"YEAR(encounter_datetime)"} - ] - }, - {"name":"groupByMonth", "defaultValue":[ - {"label":"encounter_datetime","expression":"MONTH(encounter_datetime)"} - ] - } - ], - "filters": [ - {"expression":"t1.location_uuid in ?", "parameter":"locationUuids"}, - {"expression":"coalesce(t1.death_date, out_of_care) is null", "processForce":true}, - { - "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", - "parameter":"endDate" - } - ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByYear"}, - {"parameter":"groupByMonth"} - ], - "indicators": [ - { - "label":"needs_vl_in_period", - "expression":"needs_vl_in_period", - "sql":"$expression" - } - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t2.name" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" - }, - { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" - }, - { - "label":"encounter_datetime", - "type":"single", - "sql":"t1.encounter_datetime" - }, - { - "label":"month", - "type":"single", - "sql":"t1.encounter_datetime" - } - ], - "patientListColumns": [ - "case when (timestampdiff(day,t1.vl_order_date,now()) between 0 and 14) and (t1.vl_1_date is null or t1.vl_order_date > t1.vl_1_date) then true else false end as has_pending_vl_test", - "t1.vl_1 as current_vl", - "date_format(t1.vl_1_date,'%d-%m-%Y') as current_vl_date", - "timestampdiff(day, vl_order_date, now()) as days_since_last_order", - "date_format(t1.vl_order_date,'%d-%m-%Y') as last_vl_order_date", - "date_format(t1.arv_start_date,'%d-%m-%Y') as cur_regimen_arv_start_date", - "t1.cur_arv_line", - "t1.cur_arv_meds", - "t1.arv_first_regimen", - "date_format(t1.encounter_datetime,'%d-%m-%Y') as last_clinical_encounter_datetime " - ] - } +[ + { + "name": "labs-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary_v15b", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t3", + "joinExpression": "t1.person_id = t3.person_id" + } + ], + "parameters": [ + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locationUuids", "defaultValue": [] }, + { "name": "startAge", "defaultValue": [] }, + { "name": "endAge", "defaultValue": [] }, + { "name": "gender", "defaultValue": [] }, + { "name": "@referenceDate", "defaultValue": ["defaultValue"] }, + { + "name": "groupByLocation", + "defaultValue": [{ "label": "location", "expression": "location" }] + }, + { + "name": "groupByYear", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "YEAR(encounter_datetime)" + } + ] + }, + { + "name": "groupByMonth", + "defaultValue": [ + { + "label": "encounter_datetime", + "expression": "MONTH(encounter_datetime)" + } + ] + } + ], + "filters": [ + { "expression": "t1.location_uuid in ?", "parameter": "locationUuids" }, + { + "expression": "coalesce(t1.death_date, out_of_care) is null", + "processForce": true + }, + { + "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", + "parameter": "endDate" + } + ], + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByYear" }, + { "parameter": "groupByMonth" } + ], + "indicators": [ + { + "label": "needs_vl_in_period", + "expression": "needs_vl_in_period", + "sql": "$expression" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t2.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_datetime", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "month", + "type": "single", + "sql": "t1.encounter_datetime" + } + ], + "patientListColumns": [ + "case when (timestampdiff(day,t1.vl_order_date,now()) between 0 and 14) and (t1.vl_1_date is null or t1.vl_order_date > t1.vl_1_date) then true else false end as has_pending_vl_test", + "t1.vl_1 as current_vl", + "date_format(t1.vl_1_date,'%d-%m-%Y') as current_vl_date", + "timestampdiff(day, vl_order_date, now()) as days_since_last_order", + "date_format(t1.vl_order_date,'%d-%m-%Y') as last_vl_order_date", + "date_format(t1.arv_start_date,'%d-%m-%Y') as cur_regimen_arv_start_date", + "t1.cur_arv_line", + "t1.cur_arv_meds", + "t1.arv_first_regimen", + "date_format(t1.encounter_datetime,'%d-%m-%Y') as last_clinical_encounter_datetime " + ] + } ] diff --git a/reports/medical-history-report.json b/reports/medical-history-report.json index 8d7281fab..5c9232f00 100755 --- a/reports/medical-history-report.json +++ b/reports/medical-history-report.json @@ -16,14 +16,18 @@ } ], "parameters": [ - {"name": "patientUuid"}, - {"name":"groupByCurArvMeds", "defaultValue":[ - {"label":"cur_arv_meds","expression":"t1.cur_arv_meds"} - ]}, - {"name":"groupByPrevArvMeds", "defaultValue":[ - {"label":"prev_arv_meds","expression":"t1.prev_arv_meds"} - ] - + { "name": "patientUuid" }, + { + "name": "groupByCurArvMeds", + "defaultValue": [ + { "label": "cur_arv_meds", "expression": "t1.cur_arv_meds" } + ] + }, + { + "name": "groupByPrevArvMeds", + "defaultValue": [ + { "label": "prev_arv_meds", "expression": "t1.prev_arv_meds" } + ] } ], "filters": [ @@ -32,12 +36,16 @@ "parameter": "patientUuid" } ], - "groupClause":[ - {"parameter":"groupByCurArvMeds"}, - {"parameter":"groupByPrevArvMeds"} + "groupClause": [ + { "parameter": "groupByCurArvMeds" }, + { "parameter": "groupByPrevArvMeds" } ], "orderBy": [ - {"column":"t1.encounter_datetime", "order":"desc", "name":"orderByDate"} + { + "column": "t1.encounter_datetime", + "order": "desc", + "name": "orderByDate" + } ], "indicators": [], "supplementColumns": [ @@ -67,9 +75,15 @@ "sql": "DATE_FORMAT(t1.vl_1_date,'%d-%m-%Y')" } ], - "indicatorHandlers":[ - {"processor":"findChanges","indicators":["previous_regimen","current_regimen"]}, - {"processor":"convertConceptIdToName","indicators":["previous_regimen","current_regimen"]} + "indicatorHandlers": [ + { + "processor": "findChanges", + "indicators": ["previous_regimen", "current_regimen"] + }, + { + "processor": "convertConceptIdToName", + "indicators": ["previous_regimen", "current_regimen"] + } ] } ] diff --git a/reports/moh-731-2017/moh-731-cohort-report.json b/reports/moh-731-2017/moh-731-cohort-report.json index 41b42e677..fe51488c7 100755 --- a/reports/moh-731-2017/moh-731-cohort-report.json +++ b/reports/moh-731-2017/moh-731-cohort-report.json @@ -1,3 +1 @@ -[ - -] +[] diff --git a/reports/moh-731-2017/moh-731-indicator-report.json b/reports/moh-731-2017/moh-731-indicator-report.json index a3bc2c848..5c88f729c 100755 --- a/reports/moh-731-2017/moh-731-indicator-report.json +++ b/reports/moh-731-2017/moh-731-indicator-report.json @@ -86,26 +86,22 @@ "expression": "on_art_total", "sql": "count(distinct if($expression,t1.person_id,null))" }, - { - "label": "on_art_below_1", - "expression": "on_art_below_1", - "sql": "count(distinct if($expression,t1.person_id,null))", - "disaggregation": { - "indicator": "on_art_total", - "filters": [ - "age_below_1" - ] - } - }, + { + "label": "on_art_below_1", + "expression": "on_art_below_1", + "sql": "count(distinct if($expression,t1.person_id,null))", + "disaggregation": { + "indicator": "on_art_total", + "filters": ["age_below_1"] + } + }, { "label": "on_art_1_to_9", "expression": "on_art_1_to_9", "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_art_total", - "filters": [ - "age_1_to_9" - ] + "filters": ["age_1_to_9"] } }, { @@ -114,10 +110,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_art_total", - "filters": [ - "male", - "age_10_to_14" - ] + "filters": ["male", "age_10_to_14"] } }, { @@ -126,10 +119,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_art_total", - "filters": [ - "female", - "age_10_to_14" - ] + "filters": ["female", "age_10_to_14"] } }, { @@ -138,10 +128,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_art_total", - "filters": [ - "male", - "age_15_to_19" - ] + "filters": ["male", "age_15_to_19"] } }, { @@ -150,10 +137,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_art_total", - "filters": [ - "female", - "age_15_to_19" - ] + "filters": ["female", "age_15_to_19"] } }, { @@ -162,10 +146,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_art_total", - "filters": [ - "male", - "age_20_to_24" - ] + "filters": ["male", "age_20_to_24"] } }, { @@ -174,10 +155,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_art_total", - "filters": [ - "female", - "age_20_to_24" - ] + "filters": ["female", "age_20_to_24"] } }, { @@ -186,10 +164,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_art_total", - "filters": [ - "male", - "age_25_and_older" - ] + "filters": ["male", "age_25_and_older"] } }, { @@ -198,10 +173,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_art_total", - "filters": [ - "female", - "age_25_and_older" - ] + "filters": ["female", "age_25_and_older"] } } ], @@ -301,9 +273,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "age_below_1" - ] + "filters": ["age_below_1"] } }, { @@ -312,9 +282,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "age_1_to_9" - ] + "filters": ["age_1_to_9"] } }, { @@ -323,10 +291,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "male", - "age_10_to_14" - ] + "filters": ["male", "age_10_to_14"] } }, { @@ -335,10 +300,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "female", - "age_10_to_14" - ] + "filters": ["female", "age_10_to_14"] } }, { @@ -347,10 +309,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "male", - "age_15_to_19" - ] + "filters": ["male", "age_15_to_19"] } }, { @@ -359,10 +318,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "female", - "age_15_to_19" - ] + "filters": ["female", "age_15_to_19"] } }, { @@ -371,10 +327,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "male", - "age_20_to_24" - ] + "filters": ["male", "age_20_to_24"] } }, { @@ -383,10 +336,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "female", - "age_20_to_24" - ] + "filters": ["female", "age_20_to_24"] } }, { @@ -395,10 +345,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "male", - "age_25_and_older" - ] + "filters": ["male", "age_25_and_older"] } }, { @@ -407,10 +354,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "enrolled_in_care_total", - "filters": [ - "female", - "age_25_and_older" - ] + "filters": ["female", "age_25_and_older"] } }, { @@ -424,9 +368,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "age_below_1" - ] + "filters": ["age_below_1"] } }, { @@ -435,9 +377,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "age_1_to_9" - ] + "filters": ["age_1_to_9"] } }, { @@ -446,10 +386,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "male", - "age_10_to_14" - ] + "filters": ["male", "age_10_to_14"] } }, { @@ -458,10 +395,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "female", - "age_10_to_14" - ] + "filters": ["female", "age_10_to_14"] } }, { @@ -470,10 +404,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "male", - "age_15_to_19" - ] + "filters": ["male", "age_15_to_19"] } }, { @@ -482,10 +413,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "female", - "age_15_to_19" - ] + "filters": ["female", "age_15_to_19"] } }, { @@ -494,10 +422,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "male", - "age_20_to_24" - ] + "filters": ["male", "age_20_to_24"] } }, { @@ -506,10 +431,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "female", - "age_20_to_24" - ] + "filters": ["female", "age_20_to_24"] } }, { @@ -518,10 +440,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "male", - "age_25_and_older" - ] + "filters": ["male", "age_25_and_older"] } }, { @@ -530,10 +449,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "starting_art_total", - "filters": [ - "female", - "age_25_and_older" - ] + "filters": ["female", "age_25_and_older"] } }, { @@ -552,9 +468,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_pcp_prophylaxis", - "filters": [ - "age_below_1" - ] + "filters": ["age_below_1"] } }, { @@ -563,9 +477,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_pcp_prophylaxis", - "filters": [ - "age_1_to_9" - ] + "filters": ["age_1_to_9"] } }, { @@ -574,9 +486,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_pcp_prophylaxis", - "filters": [ - "age_10_to_14" - ] + "filters": ["age_10_to_14"] } }, { @@ -585,9 +495,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_pcp_prophylaxis", - "filters": [ - "age_15_to_19" - ] + "filters": ["age_15_to_19"] } }, { @@ -596,9 +504,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_pcp_prophylaxis", - "filters": [ - "age_20_to_24" - ] + "filters": ["age_20_to_24"] } }, { @@ -607,9 +513,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "on_pcp_prophylaxis", - "filters": [ - "age_25_and_older" - ] + "filters": ["age_25_and_older"] } }, { @@ -623,9 +527,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "screened_for_tb", - "filters": [ - "age_below_1" - ] + "filters": ["age_below_1"] } }, { @@ -634,9 +536,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "screened_for_tb", - "filters": [ - "age_1_to_9" - ] + "filters": ["age_1_to_9"] } }, { @@ -645,9 +545,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "screened_for_tb", - "filters": [ - "age_10_to_14" - ] + "filters": ["age_10_to_14"] } }, { @@ -656,9 +554,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "screened_for_tb", - "filters": [ - "age_15_to_19" - ] + "filters": ["age_15_to_19"] } }, { @@ -667,9 +563,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "screened_for_tb", - "filters": [ - "age_20_to_24" - ] + "filters": ["age_20_to_24"] } }, { @@ -678,9 +572,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "screened_for_tb", - "filters": [ - "age_25_and_older" - ] + "filters": ["age_25_and_older"] } }, { @@ -694,9 +586,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "newly_started_IPT", - "filters": [ - "age_below_1" - ] + "filters": ["age_below_1"] } }, { @@ -705,9 +595,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "newly_started_IPT", - "filters": [ - "age_1_to_9" - ] + "filters": ["age_1_to_9"] } }, { @@ -716,9 +604,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "newly_started_IPT", - "filters": [ - "age_10_to_14" - ] + "filters": ["age_10_to_14"] } }, { @@ -727,9 +613,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "newly_started_IPT", - "filters": [ - "age_15_to_19" - ] + "filters": ["age_15_to_19"] } }, { @@ -738,9 +622,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "newly_started_IPT", - "filters": [ - "age_20_to_24" - ] + "filters": ["age_20_to_24"] } }, { @@ -749,9 +631,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "newly_started_IPT", - "filters": [ - "age_25_and_older" - ] + "filters": ["age_25_and_older"] } }, { @@ -810,38 +690,38 @@ "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"community_ART_dispensing_male", - "expression":"community_ART_dispensing_male", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "community_ART_dispensing_male", + "expression": "community_ART_dispensing_male", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"community_ART_dispensing", + "indicator": "community_ART_dispensing", "filters": ["male"] } }, { - "label":"community_ART_dispensing_female", - "expression":"community_ART_dispensing_female", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "community_ART_dispensing_female", + "expression": "community_ART_dispensing_female", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"community_ART_dispensing", + "indicator": "community_ART_dispensing", "filters": ["female"] } }, { - "label":"using_modern_contraceptive_method_females_15_and_older", - "expression":"using_modern_contraceptive_method_females_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "using_modern_contraceptive_method_females_15_and_older", + "expression": "using_modern_contraceptive_method_females_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"using_modern_contracept_method", - "filters": ["female","age_15_and_older"] + "indicator": "using_modern_contracept_method", + "filters": ["female", "age_15_and_older"] } } ], "supplementColumns": [ { - "label":"location", - "type":"single", - "sql":"t2.name" + "label": "location", + "type": "single", + "sql": "t2.name" }, { "label": "location_uuid", @@ -892,7 +772,10 @@ } ], "filters": [ - {"expression":"(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", "parameter":"endDate"}, + { + "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", + "parameter": "endDate" + }, { "expression": "t1.location_id in ?", "parameter": "locations" @@ -915,7 +798,6 @@ } ], "indicators": [ - { "label": "art_net_cohort_at_12_months", "expression": "art_net_cohort_at_12_months", @@ -942,41 +824,58 @@ }, { "name": "moh-731-cumulative-dataset", - "table":{ - "schema":"etl", - "tableName":"flat_hiv_summary", - "alias":"t1" - }, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t3","joinExpression":"t1.person_id = t3.person_id"} + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t3", + "joinExpression": "t1.person_id = t3.person_id" + } ], "parameters": [ - {"name":"locations","defaultValue":[]}, - {"name":"endDate", "defaultValue":["Now()"]}, - {"name":"groupByPerson", "defaultValue":[ - {"label":"person_id","expression":"t1.person_id"} - ] - }, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"t1.location_id"} - ] + { "name": "locations", "defaultValue": [] }, + { "name": "endDate", "defaultValue": ["Now()"] }, + { + "name": "groupByPerson", + "defaultValue": [{ "label": "person_id", "expression": "t1.person_id" }] + }, + { + "name": "groupByLocation", + "defaultValue": [ + { "label": "location", "expression": "t1.location_id" } + ] } ], "filters": [ - {"expression":"(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", "parameter":"endDate"}, + { + "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", + "parameter": "endDate" + }, { "expression": "timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),?) <= 90", "parameter": "endDate" }, - {"expression":"t1.is_clinical_encounter = 1", "processForce":true}, - {"expression":"t1.location_id in ?","parameter":"locations"}, - {"expression":"coalesce(t1.death_date, out_of_care) is null", "processForce":true}, - {"expression":"date(t1.encounter_datetime) <= ?", "parameter":"endDate"} + { "expression": "t1.is_clinical_encounter = 1", "processForce": true }, + { "expression": "t1.location_id in ?", "parameter": "locations" }, + { + "expression": "coalesce(t1.death_date, out_of_care) is null", + "processForce": true + }, + { + "expression": "date(t1.encounter_datetime) <= ?", + "parameter": "endDate" + } ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByPerson"}, - {"parameter":"groupByMonth"} + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByPerson" }, + { "parameter": "groupByMonth" } ], "indicators": [ { @@ -989,7 +888,7 @@ "expression": "viral_load_resulted_in_past_year", "sql": "count(distinct if($expression, t1.person_id,null))" }, - { + { "label": "pre_art_total", "expression": "pre_art_total", "sql": "count(distinct if($expression, t1.person_id,null))" @@ -1000,9 +899,7 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "pre_art_total", - "filters": [ - "age_below_15" - ] + "filters": ["age_below_15"] } }, { @@ -1011,22 +908,20 @@ "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { "indicator": "pre_art_total", - "filters": [ - "age_15_and_older" - ] + "filters": ["age_15_and_older"] } } ], - "supplementColumns":[ + "supplementColumns": [ { "label": "joining_location_id", "type": "single", "sql": "t1.location_id" }, { - "label":"joining_column", - "type":"single", - "sql":"1" + "label": "joining_column", + "type": "single", + "sql": "1" } ] } diff --git a/reports/moh-731-2017/moh-731-report.json b/reports/moh-731-2017/moh-731-report.json index ed9babdea..17bf3d2c8 100755 --- a/reports/moh-731-2017/moh-731-report.json +++ b/reports/moh-731-2017/moh-731-report.json @@ -1,45 +1,76 @@ [ { "name": "MOH-731-report-2017", - "table":{"schema":"","tableName":"","alias":"t1","dynamicDataset":"moh-731-2017-any-encounters-within-reporting-period-dataset"}, - "joins":[ - {"joinType":"LEFT OUTER JOIN","schema":"","alias":"t2","joinExpression":"t2.joining_location_id = t1.location_id", - "dynamicDataset":"moh-731-2017-monthly-dataset"}, - {"joinType":"LEFT OUTER JOIN","schema":"","alias":"t3","joinExpression":"t3.joining_location_id = t1.location_id", - "dynamicDataset":"moh-731-2017-retention-dataset"}, - {"joinType":"LEFT OUTER JOIN","schema":"","alias":"t4","joinExpression":"t4.joining_location_id = t1.location_id", - "dynamicDataset":"moh-731-cumulative-dataset"}, - {"joinType":"LEFT OUTER JOIN","schema":"","alias":"t5","joinExpression":"t5.joining_location_id = t1.location_id", - "dynamicDataset":"PEP-encounters-within-reporting-period-dataset"} - + "table": { + "schema": "", + "tableName": "", + "alias": "t1", + "dynamicDataset": "moh-731-2017-any-encounters-within-reporting-period-dataset" + }, + "joins": [ + { + "joinType": "LEFT OUTER JOIN", + "schema": "", + "alias": "t2", + "joinExpression": "t2.joining_location_id = t1.location_id", + "dynamicDataset": "moh-731-2017-monthly-dataset" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "", + "alias": "t3", + "joinExpression": "t3.joining_location_id = t1.location_id", + "dynamicDataset": "moh-731-2017-retention-dataset" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "", + "alias": "t4", + "joinExpression": "t4.joining_location_id = t1.location_id", + "dynamicDataset": "moh-731-cumulative-dataset" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "", + "alias": "t5", + "joinExpression": "t5.joining_location_id = t1.location_id", + "dynamicDataset": "PEP-encounters-within-reporting-period-dataset" + } ], "parameters": [ { - "name":"locations", - "defaultValue":[] + "name": "locations", + "defaultValue": [] }, { - "name":"groupByLocation", - "defaultValue":[{"label":"location","expression":"t1.location_id"}] + "name": "groupByLocation", + "defaultValue": [ + { "label": "location", "expression": "t1.location_id" } + ] }, { - "name":"groupByMonth", - "defaultValue":[{"expression":"date_format(encounter_datetime,'%m-%Y')", "label":"date"}] + "name": "groupByMonth", + "defaultValue": [ + { + "expression": "date_format(encounter_datetime,'%m-%Y')", + "label": "date" + } + ] } ], "filters": [ - {"expression":"t1.location_id in ?","parameter":"locations"} + { "expression": "t1.location_id in ?", "parameter": "locations" } ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByMonth"} + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByMonth" } ], "indicators": [], - "supplementColumns":[ + "supplementColumns": [ { - "label":"all", - "type":"all", - "sql":"*" + "label": "all", + "type": "all", + "sql": "*" } ] } diff --git a/reports/moh-731-legacy/moh-731-cohort-report.json b/reports/moh-731-legacy/moh-731-cohort-report.json index c6c9ed3b8..0159c626f 100755 --- a/reports/moh-731-legacy/moh-731-cohort-report.json +++ b/reports/moh-731-legacy/moh-731-cohort-report.json @@ -1,92 +1,96 @@ [ { "name": "moh-731-12month-cohort-one-row-per-encounter", - "table":{ - "schema":"etl", - "tableName":"flat_hiv_summary", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", "indexExpression": "FORCE INDEX (location_uuid_rtc_date)", - "alias":"t1" - }, - "joins":[], + "alias": "t1" + }, + "joins": [], "parameters": [ - {"name":"locationUuids","defaultValue":[]}, - {"name":"endDate", "defaultValue":"2015-10-31"}, - {"name":"startDate", "defaultValue":"2015-10-31"}, - {"name":"groupByPerson", "defaultValue":[ - {"label":"person_id","expression":"t1.person_id"} - ] + { "name": "locationUuids", "defaultValue": [] }, + { "name": "endDate", "defaultValue": "2015-10-31" }, + { "name": "startDate", "defaultValue": "2015-10-31" }, + { + "name": "groupByPerson", + "defaultValue": [{ "label": "person_id", "expression": "t1.person_id" }] } ], "filters": [ - {"expression":"t1.location_uuid in ?","parameter":"locationUuids"}, - {"expression":"date(t1.arv_first_regimen_start_date) >= DATE_SUB( ?, INTERVAL 1 YEAR)", "parameter":"startDate"}, - {"expression":"date(t1.arv_first_regimen_start_date) <= DATE_SUB( ?, INTERVAL 1 YEAR)", "parameter":"endDate"}, - {"expression":"t1.is_clinical_encounter = 1", "processForce":true} - ], - "groupClause":[ - {"parameter":"groupByPerson"} + { "expression": "t1.location_uuid in ?", "parameter": "locationUuids" }, + { + "expression": "date(t1.arv_first_regimen_start_date) >= DATE_SUB( ?, INTERVAL 1 YEAR)", + "parameter": "startDate" + }, + { + "expression": "date(t1.arv_first_regimen_start_date) <= DATE_SUB( ?, INTERVAL 1 YEAR)", + "parameter": "endDate" + }, + { "expression": "t1.is_clinical_encounter = 1", "processForce": true } ], + "groupClause": [{ "parameter": "groupByPerson" }], "indicators": [], - "supplementColumns":[ + "supplementColumns": [ { - "label":"person_id", - "type":"single", - "sql":"t1.person_id" + "label": "person_id", + "type": "single", + "sql": "t1.person_id" }, { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" }, { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" + "label": "location_id", + "type": "single", + "sql": "t1.location_id" }, { - "label":"cur_arv_line", - "type":"single", - "sql":"mid(max(concat(encounter_datetime,cur_arv_line)),20)" + "label": "cur_arv_line", + "type": "single", + "sql": "mid(max(concat(encounter_datetime,cur_arv_line)),20)" }, { - "label":"cur_arv_meds", - "type":"single", - "sql":"mid(max(concat(encounter_datetime,cur_arv_meds)),20)" + "label": "cur_arv_meds", + "type": "single", + "sql": "mid(max(concat(encounter_datetime,cur_arv_meds)),20)" }, { - "label":"arv_first_regimen", - "type":"single", - "sql":"mid(max(concat(encounter_datetime,arv_first_regimen)),20)" + "label": "arv_first_regimen", + "type": "single", + "sql": "mid(max(concat(encounter_datetime,arv_first_regimen)),20)" }, { - "label":"rtc_date", - "type":"single", - "sql":"mid(max(concat(encounter_datetime,rtc_date)),20)" + "label": "rtc_date", + "type": "single", + "sql": "mid(max(concat(encounter_datetime,rtc_date)),20)" }, { - "label":"encounter_datetime", - "type":"single", - "sql":"max(encounter_datetime)" + "label": "encounter_datetime", + "type": "single", + "sql": "max(encounter_datetime)" }, { - "label":"death_date", - "type":"single", - "sql":"max(t1.death_date)" + "label": "death_date", + "type": "single", + "sql": "max(t1.death_date)" }, { - "label":"transfer_out", - "type":"single", - "sql":"max(transfer_out)" + "label": "transfer_out", + "type": "single", + "sql": "max(transfer_out)" }, { - "label":"out_of_care", - "type":"single", - "sql":"max(out_of_care)" + "label": "out_of_care", + "type": "single", + "sql": "max(out_of_care)" }, { - "label":"arv_first_regimen_start_date", - "type":"single", - "sql":"arv_first_regimen_start_date" + "label": "arv_first_regimen_start_date", + "type": "single", + "sql": "arv_first_regimen_start_date" } ] } diff --git a/reports/moh-731-legacy/moh-731-indicator-report.json b/reports/moh-731-legacy/moh-731-indicator-report.json index e446991dc..7d8b9c6eb 100755 --- a/reports/moh-731-legacy/moh-731-indicator-report.json +++ b/reports/moh-731-legacy/moh-731-indicator-report.json @@ -15,16 +15,30 @@ "indexExpression": "FORCE INDEX (loc_id_enc_date_next_clinic)", "joinExpression": "date(t1.encounter_datetime) <= date(t2.endDate)" }, - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t2","joinExpression":"t1.location_uuid = t2.uuid"}, - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t3","joinExpression":"t1.person_id = t3.person_id"} + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t3", + "joinExpression": "t1.person_id = t3.person_id" + } ], "parameters": [ - {"name":"startDate", "defaultValue":"2015-10-01"}, - {"name":"endDate", "defaultValue":"2015-10-31"}, - {"name":"locations","defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"t1.location_id"} - ] + { "name": "startDate", "defaultValue": "2015-10-01" }, + { "name": "endDate", "defaultValue": "2015-10-31" }, + { "name": "locations", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [ + { "label": "location", "expression": "t1.location_id" } + ] } ], "filters": [ @@ -53,522 +67,535 @@ "processForce": true } ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByMonth"} + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByMonth" } ], "indicators": [ { - "label":"currently_in_care_total", - "expression":"currently_in_care_total", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "currently_in_care_total", + "expression": "currently_in_care_total", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"currently_in_care_males_lt_one", - "expression":"currently_in_care_males_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "currently_in_care_males_lt_one", + "expression": "currently_in_care_males_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"currently_in_care_total", - "filters": ["male","age_below_1"] + "indicator": "currently_in_care_total", + "filters": ["male", "age_below_1"] } }, { - "label":"currently_in_care_females_lt_one", - "expression":"currently_in_care_females_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "currently_in_care_females_lt_one", + "expression": "currently_in_care_females_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"currently_in_care_total", - "filters": ["female","age_below_1"] + "indicator": "currently_in_care_total", + "filters": ["female", "age_below_1"] } }, { - "label":"currently_in_care_males_below_15", - "expression":"currently_in_care_males_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "currently_in_care_males_below_15", + "expression": "currently_in_care_males_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"currently_in_care_total", + "indicator": "currently_in_care_total", "filters": ["male", "age_below_15"] } }, { - "label":"currently_in_care_females_below_15", - "expression":"currently_in_care_females_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "currently_in_care_females_below_15", + "expression": "currently_in_care_females_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"currently_in_care_total", + "indicator": "currently_in_care_total", "filters": ["female", "age_below_15"] } }, { - "label":"currently_in_care_males_15_and_older", - "expression":"currently_in_care_males_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "currently_in_care_males_15_and_older", + "expression": "currently_in_care_males_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"currently_in_care_total", - "filters": ["male","age_15_and_older"] + "indicator": "currently_in_care_total", + "filters": ["male", "age_15_and_older"] } }, { - "label":"currently_in_care_females_15_and_older", - "expression":"currently_in_care_females_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "currently_in_care_females_15_and_older", + "expression": "currently_in_care_females_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"currently_in_care_total", - "filters": ["female","age_15_and_older"] + "indicator": "currently_in_care_total", + "filters": ["female", "age_15_and_older"] } }, { - "label":"revisits_on_art_total", - "expression":"revisits_on_art_total", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "revisits_on_art_total", + "expression": "revisits_on_art_total", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"revisits_on_art_males_lt_one", - "expression":"revisits_on_art_males_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "revisits_on_art_males_lt_one", + "expression": "revisits_on_art_males_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"revisits_on_art_total", - "filters": ["male","age_below_1"] + "indicator": "revisits_on_art_total", + "filters": ["male", "age_below_1"] } }, { - "label":"revisits_on_art_females_lt_one", - "expression":"revisits_on_art_females_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "revisits_on_art_females_lt_one", + "expression": "revisits_on_art_females_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"revisits_on_art_total", - "filters": ["female","age_below_1"] + "indicator": "revisits_on_art_total", + "filters": ["female", "age_below_1"] } }, { - "label":"revisits_on_art_males_below_15", - "expression":"revisits_on_art_males_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "revisits_on_art_males_below_15", + "expression": "revisits_on_art_males_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"revisits_on_art_total", + "indicator": "revisits_on_art_total", "filters": ["male", "age_below_15"] } }, { - "label":"revisits_on_art_females_below_15", - "expression":"revisits_on_art_females_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "revisits_on_art_females_below_15", + "expression": "revisits_on_art_females_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"revisits_on_art_total", + "indicator": "revisits_on_art_total", "filters": ["female", "age_below_15"] } }, { - "label":"revisits_on_art_males_15_and_older", - "expression":"revisits_on_art_males_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "revisits_on_art_males_15_and_older", + "expression": "revisits_on_art_males_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"revisits_on_art_total", + "indicator": "revisits_on_art_total", "filters": ["male", "age_15_and_older"] } }, { - "label":"revisits_on_art_females_15_and_older", - "expression":"revisits_on_art_females_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "revisits_on_art_females_15_and_older", + "expression": "revisits_on_art_females_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"revisits_on_art_total", - "filters": ["female","age_15_and_older"] + "indicator": "revisits_on_art_total", + "filters": ["female", "age_15_and_older"] } }, { - "label":"on_pcp_prophylaxis", - "expression":"on_pcp_prophylaxis", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "on_pcp_prophylaxis", + "expression": "on_pcp_prophylaxis", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"on_pcp_prophylaxis_below_15", - "expression":"on_pcp_prophylaxis_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_pcp_prophylaxis_below_15", + "expression": "on_pcp_prophylaxis_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_pcp_prophylaxis", - "filters": [ "age_below_15"] + "indicator": "on_pcp_prophylaxis", + "filters": ["age_below_15"] } }, { - "label":"on_pcp_prophylaxis_15_and_above", - "expression":"on_pcp_prophylaxis_15_and_above", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_pcp_prophylaxis_15_and_above", + "expression": "on_pcp_prophylaxis_15_and_above", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_pcp_prophylaxis", + "indicator": "on_pcp_prophylaxis", "filters": ["age_15_and_older"] } }, { - "label":"on_pcp_prophylaxis_males_below_15", - "expression":"on_pcp_prophylaxis_males_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_pcp_prophylaxis_males_below_15", + "expression": "on_pcp_prophylaxis_males_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_pcp_prophylaxis", + "indicator": "on_pcp_prophylaxis", "filters": ["male", "age_below_15"] } }, { - "label":"on_pcp_prophylaxis_females_below_15", - "expression":"on_pcp_prophylaxis_females_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_pcp_prophylaxis_females_below_15", + "expression": "on_pcp_prophylaxis_females_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_pcp_prophylaxis", + "indicator": "on_pcp_prophylaxis", "filters": ["female", "age_below_15"] } }, { - "label":"on_pcp_prophylaxis_males_15_and_above", - "expression":"on_pcp_prophylaxis_males_15_and_above", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_pcp_prophylaxis_males_15_and_above", + "expression": "on_pcp_prophylaxis_males_15_and_above", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_pcp_prophylaxis", - "filters": ["male","age_15_and_older"] + "indicator": "on_pcp_prophylaxis", + "filters": ["male", "age_15_and_older"] } }, { - "label":"on_pcp_prophylaxis_females_15_and_above", - "expression":"on_pcp_prophylaxis_females_15_and_above", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_pcp_prophylaxis_females_15_and_above", + "expression": "on_pcp_prophylaxis_females_15_and_above", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_pcp_prophylaxis", - "filters": ["female","age_15_and_older"] + "indicator": "on_pcp_prophylaxis", + "filters": ["female", "age_15_and_older"] } }, - { - "label":"hiv_exposed_infants_below_2_months", - "expression":"hiv_exposed_infants_below_2_months", - "sql":"count(distinct if($expression,t1.person_id,null))" + { + "label": "hiv_exposed_infants_below_2_months", + "expression": "hiv_exposed_infants_below_2_months", + "sql": "count(distinct if($expression,t1.person_id,null))" }, - { - "label":"hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below", - "expression":"hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below", - "sql":"count(distinct if($expression,t1.person_id,null))" + { + "label": "hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below", + "expression": "hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"screened_for_tb", - "expression":"screened_for_tb", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "screened_for_tb", + "expression": "screened_for_tb", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"screened_for_tb_males_below_15", - "expression":"screened_for_tb_males_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "screened_for_tb_males_below_15", + "expression": "screened_for_tb_males_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"screened_for_tb", + "indicator": "screened_for_tb", "filters": ["male", "age_below_15"] } }, { - "label":"screened_for_tb_females_below_15", - "expression":"screened_for_tb_females_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "screened_for_tb_females_below_15", + "expression": "screened_for_tb_females_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"screened_for_tb", + "indicator": "screened_for_tb", "filters": ["female", "age_below_15"] } }, { - "label":"screened_for_tb_males_15_and_older", - "expression":"screened_for_tb_males_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "screened_for_tb_males_15_and_older", + "expression": "screened_for_tb_males_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"screened_for_tb", - "filters": ["male","age_15_and_older"] + "indicator": "screened_for_tb", + "filters": ["male", "age_15_and_older"] } }, { - "label":"screened_for_tb_females_15_and_older", - "expression":"screened_for_tb_females_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "screened_for_tb_females_15_and_older", + "expression": "screened_for_tb_females_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"screened_for_tb", - "filters": ["female","age_15_and_older"] + "indicator": "screened_for_tb", + "filters": ["female", "age_15_and_older"] } }, { - "label":"using_modern_contracept_method", - "expression":"using_modern_contracept_method", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "using_modern_contracept_method", + "expression": "using_modern_contracept_method", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"on_art", - "expression":"on_art", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "on_art", + "expression": "on_art", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"on_art_total", - "expression":"on_art_total", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "on_art_total", + "expression": "on_art_total", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"on_art_males_lt_one", - "expression":"on_art_males_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_art_males_lt_one", + "expression": "on_art_males_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_art_total", - "filters": ["male","age_below_1"] + "indicator": "on_art_total", + "filters": ["male", "age_below_1"] } }, { - "label":"on_art_females_lt_one", - "expression":"on_art_females_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_art_females_lt_one", + "expression": "on_art_females_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_art_total", - "filters": ["female","age_below_1"] + "indicator": "on_art_total", + "filters": ["female", "age_below_1"] } }, { - "label":"on_art_males_below_15", - "expression":"on_art_males_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_art_males_below_15", + "expression": "on_art_males_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_art_total", + "indicator": "on_art_total", "filters": ["male", "age_below_15"] } }, { - "label":"on_art_females_below_15", - "expression":"on_art_females_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_art_females_below_15", + "expression": "on_art_females_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_art_total", + "indicator": "on_art_total", "filters": ["female", "age_below_15"] } }, { - "label":"on_art_males_15_and_older", - "expression":"on_art_males_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_art_males_15_and_older", + "expression": "on_art_males_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_art_total", - "filters": ["male","age_15_and_older"] + "indicator": "on_art_total", + "filters": ["male", "age_15_and_older"] } }, { - "label":"on_art_females_15_and_older", - "expression":"on_art_females_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "on_art_females_15_and_older", + "expression": "on_art_females_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"on_art_total", - "filters": ["female","age_15_and_older"] + "indicator": "on_art_total", + "filters": ["female", "age_15_and_older"] } } ], - "supplementColumns":[ + "supplementColumns": [ { - "label":"location", - "type":"single", - "sql":"t2.name" + "label": "location", + "type": "single", + "sql": "t2.name" }, { - "label":"location_uuid", - "type":"single", - "sql":"t1.location_uuid" + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" }, { - "label":"location_id", - "type":"single", - "sql":"t1.location_id" + "label": "location_id", + "type": "single", + "sql": "t1.location_id" }, { - "label":"joining_column", - "type":"single", - "sql":"1" + "label": "joining_column", + "type": "single", + "sql": "1" } ] }, { "name": "moh-731-monthly-one-row-per-encounter", - "table":{ - "schema":"etl", - "tableName":"flat_hiv_summary", - "alias":"t1" - }, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t3","joinExpression":"t1.person_id = t3.person_id"} + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t3", + "joinExpression": "t1.person_id = t3.person_id" + } ], "parameters": [ - {"name":"startDate", "defaultValue":"2015-10-01"}, - {"name":"endDate", "defaultValue":"2015-10-31"}, - {"name":"locations","defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"t1.location_id"} - ] + { "name": "startDate", "defaultValue": "2015-10-01" }, + { "name": "endDate", "defaultValue": "2015-10-31" }, + { "name": "locations", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [ + { "label": "location", "expression": "t1.location_id" } + ] } ], "filters": [ - {"expression":"t1.location_id in ?","parameter":"locations"}, - {"expression":"timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),?) <= 90", "parameter":"endDate"}, - {"expression":"date(t1.encounter_datetime) <= ?", "parameter":"endDate"}, - {"expression":"t1.is_clinical_encounter = 1", "processForce":true} + { "expression": "t1.location_id in ?", "parameter": "locations" }, + { + "expression": "timestampdiff(day,date(if(t1.rtc_date, rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY))),?) <= 90", + "parameter": "endDate" + }, + { + "expression": "date(t1.encounter_datetime) <= ?", + "parameter": "endDate" + }, + { "expression": "t1.is_clinical_encounter = 1", "processForce": true } ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByMonth"} + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByMonth" } ], "indicators": [ { - "label":"enrolled_in_care_total", - "expression":"enrolled_in_care_total", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "enrolled_in_care_total", + "expression": "enrolled_in_care_total", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"enrolled_in_care_males_lt_one", - "expression":"enrolled_in_care_males_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "enrolled_in_care_males_lt_one", + "expression": "enrolled_in_care_males_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"enrolled_in_care_total", - "filters": ["male","age_below_1"] + "indicator": "enrolled_in_care_total", + "filters": ["male", "age_below_1"] } }, { - "label":"enrolled_in_care_females_lt_one", - "expression":"enrolled_in_care_females_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "enrolled_in_care_females_lt_one", + "expression": "enrolled_in_care_females_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"enrolled_in_care_total", - "filters": ["female","age_below_1"] + "indicator": "enrolled_in_care_total", + "filters": ["female", "age_below_1"] } }, { - "label":"enrolled_in_care_males_1_to_15", - "expression":"enrolled_in_care_males_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "enrolled_in_care_males_1_to_15", + "expression": "enrolled_in_care_males_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"enrolled_in_care_total", + "indicator": "enrolled_in_care_total", "filters": ["male", "age_below_15"] } }, { - "label":"enrolled_in_care_females_1_to_15", - "expression":"enrolled_in_care_females_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "enrolled_in_care_females_1_to_15", + "expression": "enrolled_in_care_females_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"enrolled_in_care_total", + "indicator": "enrolled_in_care_total", "filters": ["female", "age_below_15"] } }, { - "label":"enrolled_in_care_males_15_and_older", - "expression":"enrolled_in_care_males_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "enrolled_in_care_males_15_and_older", + "expression": "enrolled_in_care_males_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"enrolled_in_care_total", - "filters": ["male","age_15_and_older"] + "indicator": "enrolled_in_care_total", + "filters": ["male", "age_15_and_older"] } }, { - "label":"enrolled_in_care_females_15_and_older", - "expression":"enrolled_in_care_females_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "enrolled_in_care_females_15_and_older", + "expression": "enrolled_in_care_females_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"enrolled_in_care_total", - "filters": ["female","age_15_and_older"] + "indicator": "enrolled_in_care_total", + "filters": ["female", "age_15_and_older"] } }, { - "label":"condoms_provided", - "expression":"condoms_provided", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "condoms_provided", + "expression": "condoms_provided", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"female_gte_18yo_visits", - "expression":"female_gte_18yo_visits", - "sql":"count(distinct if($expression,t1.visit_id,null))" + "label": "female_gte_18yo_visits", + "expression": "female_gte_18yo_visits", + "sql": "count(distinct if($expression,t1.visit_id,null))" }, { - "label":"scheduled_visits", - "expression":"scheduled_visits", - "sql":"count(distinct if($expression,t1.visit_id,null))" + "label": "scheduled_visits", + "expression": "scheduled_visits", + "sql": "count(distinct if($expression,t1.visit_id,null))" }, { - "label":"unscheduled_visits", - "expression":"unscheduled_visits", - "sql":"count(distinct if($expression,t1.visit_id,null))" + "label": "unscheduled_visits", + "expression": "unscheduled_visits", + "sql": "count(distinct if($expression,t1.visit_id,null))" }, { - "label":"total_visits", - "expression":"total_visits", - "sql":"[scheduled_visits]+[unscheduled_visits]" + "label": "total_visits", + "expression": "total_visits", + "sql": "[scheduled_visits]+[unscheduled_visits]" }, { - "label":"starting_art_total", - "expression":"starting_art_total", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "starting_art_total", + "expression": "starting_art_total", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"starting_art_males_lt_one", - "expression":"starting_art_males_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "starting_art_males_lt_one", + "expression": "starting_art_males_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"starting_art_total", - "filters": ["male","age_below_1"] + "indicator": "starting_art_total", + "filters": ["male", "age_below_1"] } }, { - "label":"starting_art_females_lt_one", - "expression":"starting_art_females_lt_one", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "starting_art_females_lt_one", + "expression": "starting_art_females_lt_one", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"starting_art_total", - "filters": ["female","age_below_1"] + "indicator": "starting_art_total", + "filters": ["female", "age_below_1"] } }, { - "label":"starting_art_males_below_15", - "expression":"starting_art_males_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "starting_art_males_below_15", + "expression": "starting_art_males_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"starting_art_total", + "indicator": "starting_art_total", "filters": ["male", "age_below_15"] } }, { - "label":"starting_art_females_below_15", - "expression":"starting_art_females_below_15", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "starting_art_females_below_15", + "expression": "starting_art_females_below_15", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"starting_art_total", + "indicator": "starting_art_total", "filters": ["female", "age_below_15"] } }, { - "label":"starting_art_males_15_and_older", - "expression":"starting_art_males_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "starting_art_males_15_and_older", + "expression": "starting_art_males_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"starting_art_total", - "filters": ["male","age_15_and_older"] + "indicator": "starting_art_total", + "filters": ["male", "age_15_and_older"] } }, { - "label":"starting_art_females_15_and_older", - "expression":"starting_art_females_15_and_older", - "sql":"count(distinct if($expression,t1.person_id,null))", + "label": "starting_art_females_15_and_older", + "expression": "starting_art_females_15_and_older", + "sql": "count(distinct if($expression,t1.person_id,null))", "disaggregation": { - "indicator":"starting_art_total", - "filters": ["female","age_15_and_older"] + "indicator": "starting_art_total", + "filters": ["female", "age_15_and_older"] } }, { - "label":"starting_art_and_has_tb", - "expression":"starting_art_and_has_tb", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "starting_art_and_has_tb", + "expression": "starting_art_and_has_tb", + "sql": "count(distinct if($expression,t1.person_id,null))" } ], - "supplementColumns":[ - + "supplementColumns": [ { - "label":"joining_location_id", - "type":"single", - "sql":"t1.location_id" + "label": "joining_location_id", + "type": "single", + "sql": "t1.location_id" }, { - "label":"joining_column", - "type":"single", - "sql":"1" + "label": "joining_column", + "type": "single", + "sql": "1" } ] }, @@ -604,7 +631,10 @@ } ], "filters": [ - {"expression":"(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", "parameter":"endDate"}, + { + "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", + "parameter": "endDate" + }, { "expression": "t1.location_id in ?", "parameter": "locations" @@ -628,149 +658,166 @@ ], "indicators": [ { - "label":"on_alternative_first_line", - "expression":"on_alternative_first_line", - "sql":"count(distinct if($expression, t1.person_id,null))" + "label": "on_alternative_first_line", + "expression": "on_alternative_first_line", + "sql": "count(distinct if($expression, t1.person_id,null))" }, { - "label":"on_original_first_line", - "expression":"on_original_first_line", - "sql":"count(distinct if($expression, t1.person_id,null))" + "label": "on_original_first_line", + "expression": "on_original_first_line", + "sql": "count(distinct if($expression, t1.person_id,null))" }, { - "label":"art_net_cohort_at_12_months", - "expression":"art_net_cohort_at_12_months", - "sql":"count(distinct if($expression, t1.person_id,null))" + "label": "art_net_cohort_at_12_months", + "expression": "art_net_cohort_at_12_months", + "sql": "count(distinct if($expression, t1.person_id,null))" }, { - "label":"total_on_therapy_at_12_months", - "expression":"total_on_therapy_at_12_months", - "sql":"count(distinct if($expression, t1.person_id,null))" + "label": "total_on_therapy_at_12_months", + "expression": "total_on_therapy_at_12_months", + "sql": "count(distinct if($expression, t1.person_id,null))" }, { - "label":"on_second_line_or_higher", - "expression": "on_second_line_or_higher", - "sql": "count(distinct if($expression, t1.person_id,null))" + "label": "on_second_line_or_higher", + "expression": "on_second_line_or_higher", + "sql": "count(distinct if($expression, t1.person_id,null))" } ], - "supplementColumns":[ + "supplementColumns": [ { - "label":"joining_location_id", - "type":"single", - "sql":"t1.location_id" + "label": "joining_location_id", + "type": "single", + "sql": "t1.location_id" }, { - "label":"joining_column", - "type":"single", - "sql":"1" + "label": "joining_column", + "type": "single", + "sql": "1" } ] }, { "name": "moh-731-cumulative-one-row-per-patient", - "table":{ - "schema":"etl", - "tableName":"flat_hiv_summary", - "alias":"t1" - }, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t3","joinExpression":"t1.person_id = t3.person_id"} + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t3", + "joinExpression": "t1.person_id = t3.person_id" + } ], "parameters": [ - {"name":"locations","defaultValue":[]}, - {"name":"endDate", "defaultValue":["Now()"]}, - {"name":"groupByPerson", "defaultValue":[ - {"label":"person_id","expression":"t1.person_id"} - ] - }, - {"name":"groupByLocation", "defaultValue":[ - {"label":"location","expression":"t1.arv_start_location"} - ] + { "name": "locations", "defaultValue": [] }, + { "name": "endDate", "defaultValue": ["Now()"] }, + { + "name": "groupByPerson", + "defaultValue": [{ "label": "person_id", "expression": "t1.person_id" }] + }, + { + "name": "groupByLocation", + "defaultValue": [ + { "label": "location", "expression": "t1.arv_start_location" } + ] } ], "filters": [ - {"expression":"(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", "parameter":"endDate"}, - {"expression":"t1.is_clinical_encounter = 1", "processForce":true}, - {"expression":"t1.arv_start_location in ?","parameter":"locations"}, - {"expression":"coalesce(t1.death_date, out_of_care) is null", "processForce":true}, - {"expression":"date(t1.encounter_datetime) <= ?", "parameter":"endDate"} + { + "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > ?)", + "parameter": "endDate" + }, + { "expression": "t1.is_clinical_encounter = 1", "processForce": true }, + { "expression": "t1.arv_start_location in ?", "parameter": "locations" }, + { + "expression": "coalesce(t1.death_date, out_of_care) is null", + "processForce": true + }, + { + "expression": "date(t1.encounter_datetime) <= ?", + "parameter": "endDate" + } ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByPerson"}, - {"parameter":"groupByMonth"} + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByPerson" }, + { "parameter": "groupByMonth" } ], "indicators": [ { - "label":"ever_on_art", - "expression":"ever_on_art", - "sql":"count(distinct if($expression, t1.person_id,null))" + "label": "ever_on_art", + "expression": "ever_on_art", + "sql": "count(distinct if($expression, t1.person_id,null))" }, { - "label":"ever_on_art_below_15", - "expression":"ever_on_art_below_15", - "sql":"count(distinct if($expression, t1.person_id,null))", + "label": "ever_on_art_below_15", + "expression": "ever_on_art_below_15", + "sql": "count(distinct if($expression, t1.person_id,null))", "disaggregation": { - "indicator":"ever_on_art", - "filters": [ "age_below_15"] + "indicator": "ever_on_art", + "filters": ["age_below_15"] } }, { - "label":"ever_on_art_males_below_15", - "expression":"ever_on_art_males_below_15", - "sql":"count(distinct if($expression, t1.person_id,null))", + "label": "ever_on_art_males_below_15", + "expression": "ever_on_art_males_below_15", + "sql": "count(distinct if($expression, t1.person_id,null))", "disaggregation": { - "indicator":"ever_on_art", + "indicator": "ever_on_art", "filters": ["male", "age_below_15"] } }, { - "label":"ever_on_art_females_below_15", - "expression":"ever_on_art_females_below_15", - "sql":"count(distinct if($expression, t1.person_id,null))", + "label": "ever_on_art_females_below_15", + "expression": "ever_on_art_females_below_15", + "sql": "count(distinct if($expression, t1.person_id,null))", "disaggregation": { - "indicator":"ever_on_art", + "indicator": "ever_on_art", "filters": ["female", "age_below_15"] } }, { - "label":"ever_on_art_15_and_older", - "expression":"ever_on_art_15_and_older", - "sql":"count(distinct if($expression, t1.person_id,null))", + "label": "ever_on_art_15_and_older", + "expression": "ever_on_art_15_and_older", + "sql": "count(distinct if($expression, t1.person_id,null))", "disaggregation": { - "indicator":"ever_on_art", + "indicator": "ever_on_art", "filters": ["age_15_and_older"] } }, { - "label":"ever_on_art_males_15_and_older", - "expression":"ever_on_art_males_15_and_older", - "sql":"count(distinct if($expression, t1.person_id,null))", + "label": "ever_on_art_males_15_and_older", + "expression": "ever_on_art_males_15_and_older", + "sql": "count(distinct if($expression, t1.person_id,null))", "disaggregation": { - "indicator":"ever_on_art", - "filters": ["male","age_15_and_older"] + "indicator": "ever_on_art", + "filters": ["male", "age_15_and_older"] } }, { - "label":"ever_on_art_females_15_and_older", - "expression":"ever_on_art_females_15_and_older", - "sql":"count(distinct if($expression, t1.person_id,null))", + "label": "ever_on_art_females_15_and_older", + "expression": "ever_on_art_females_15_and_older", + "sql": "count(distinct if($expression, t1.person_id,null))", "disaggregation": { - "indicator":"ever_on_art", - "filters": ["female","age_15_and_older"] + "indicator": "ever_on_art", + "filters": ["female", "age_15_and_older"] } } ], - "supplementColumns":[ + "supplementColumns": [ { - "label":"joining_location_id", - "type":"single", - "sql":"t1.location_id" + "label": "joining_location_id", + "type": "single", + "sql": "t1.location_id" }, { - "label":"joining_column", - "type":"single", - "sql":"1" + "label": "joining_column", + "type": "single", + "sql": "1" } ] } diff --git a/reports/moh-731-legacy/moh-731-report.json b/reports/moh-731-legacy/moh-731-report.json index 80896cf39..fbc5d8c02 100755 --- a/reports/moh-731-legacy/moh-731-report.json +++ b/reports/moh-731-legacy/moh-731-report.json @@ -1,44 +1,76 @@ [ { "name": "MOH-731-report", - "table":{"schema":"","tableName":"","alias":"t1","dynamicDataset":"moh-731-monthly-one-row-per-patient"}, - "joins":[ - {"joinType":"LEFT OUTER JOIN","schema":"","alias":"t2","joinExpression":"t2.joining_location_id = t1.location_id", - "dynamicDataset":"moh-731-monthly-one-row-per-encounter"}, - {"joinType":"LEFT OUTER JOIN","schema":"","alias":"t3","joinExpression":"t3.joining_location_id = t1.location_id", - "dynamicDataset":"moh-731-12month-one-row-per-encounter"}, - {"joinType":"LEFT OUTER JOIN","schema":"","alias":"t4","joinExpression":"t4.joining_location_id = t1.location_id", - "dynamicDataset":"moh-731-cumulative-one-row-per-patient"}, - {"joinType":"LEFT OUTER JOIN","schema":"","alias":"t5","joinExpression":"t5.joining_location_id = t1.location_id", - "dynamicDataset":"PEP-encounters-within-reporting-period-dataset"} + "table": { + "schema": "", + "tableName": "", + "alias": "t1", + "dynamicDataset": "moh-731-monthly-one-row-per-patient" + }, + "joins": [ + { + "joinType": "LEFT OUTER JOIN", + "schema": "", + "alias": "t2", + "joinExpression": "t2.joining_location_id = t1.location_id", + "dynamicDataset": "moh-731-monthly-one-row-per-encounter" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "", + "alias": "t3", + "joinExpression": "t3.joining_location_id = t1.location_id", + "dynamicDataset": "moh-731-12month-one-row-per-encounter" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "", + "alias": "t4", + "joinExpression": "t4.joining_location_id = t1.location_id", + "dynamicDataset": "moh-731-cumulative-one-row-per-patient" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "", + "alias": "t5", + "joinExpression": "t5.joining_location_id = t1.location_id", + "dynamicDataset": "PEP-encounters-within-reporting-period-dataset" + } ], "parameters": [ { - "name":"locations", - "defaultValue":[] + "name": "locations", + "defaultValue": [] }, { - "name":"groupByLocation", - "defaultValue":[{"label":"location","expression":"t1.location_id"}] + "name": "groupByLocation", + "defaultValue": [ + { "label": "location", "expression": "t1.location_id" } + ] }, { - "name":"groupByMonth", - "defaultValue":[{"expression":"date_format(encounter_datetime,'%m-%Y')", "label":"date"}] + "name": "groupByMonth", + "defaultValue": [ + { + "expression": "date_format(encounter_datetime,'%m-%Y')", + "label": "date" + } + ] } ], "filters": [ - {"expression":"t1.location_id in ?","parameter":"locations"} + { "expression": "t1.location_id in ?", "parameter": "locations" } ], - "groupClause":[ - {"parameter":"groupByLocation"}, - {"parameter":"groupByMonth"} + "groupClause": [ + { "parameter": "groupByLocation" }, + { "parameter": "groupByMonth" } ], "indicators": [], - "supplementColumns":[ + "supplementColumns": [ { - "label":"all", - "type":"all", - "sql":"*" + "label": "all", + "type": "all", + "sql": "*" } ] } diff --git a/reports/patient-care-cascade-report.json b/reports/patient-care-cascade-report.json index 782dff440..82fcecb04 100755 --- a/reports/patient-care-cascade-report.json +++ b/reports/patient-care-cascade-report.json @@ -1,134 +1,129 @@ [ - { - "name": "patient-care-cascade-report", - "table": { - "schema": "etl", - "tableName": "dates", - "alias": "t2" - }, - "joins": [ - { - "joinType": "JOIN", - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t1", - "indexExpression": "FORCE INDEX (loc_id_enc_date_next_clinic)", - "joinExpression": "date(t1.encounter_datetime) <= date(t2.endDate)" - }, - { - "joinType": "LEFT OUTER JOIN", - "schema": "amrs", - "tableName": "orders", - "alias": "orders", - "joinExpression": "orders.voided=0 and t1.encounter_id=orders.encounter_id" - } - ], - "parameters": [ - { - "name": "startDate", - "defaultValue": [ - "01-01-1980" - ] - }, - { - "name": "endDate", - "defaultValue": [ - "Now()" - ] - }, - {"name":"locations","defaultValue":[]}, - { - "name": "groupByEndDate", - "defaultValue": [ - { - "label": "endDate", - "expression": "endDate" - } - ] - } - ], - "filters": [ - { - "expression": "t2.endDate >= date(?)", - "parameter": "startDate" - }, - { - "expression": "t2.endDate <= date(?)", - "parameter": "endDate" - }, - { - "expression": "t1.location_id in ?", - "parameter": "locations" - }, - { - "expression": "t1.is_clinical_encounter=1", - "processForce": true - }, - { - "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > t2.endDate)", - "processForce": true - } - ], - "groupClause": [ - { - "parameter": "groupByEndDate" - } - ], - "indicators": [ - { - "label": "currently_in_care_total", - "expression": "currently_in_care_total", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "active_and_on_art", - "expression": "active_and_on_art", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "LTFU", - "expression": "LTFU", - "sql": "count($expression)" - }, - { - "label": "has_vl_since_oct", - "expression": "has_vl_since_oct", - "sql": "count(distinct if($expression, person_id,null))" - }, - - { - "label": "virally_suppressed_since_oct", - "expression": "virally_suppressed_since_oct", - "sql": "count(distinct if($expression, person_id,null))" - }, - { - "label": "perc_virally_suppressed_since_oct", - "expression": "perc_virally_suppressed_since_oct", - "sql": "if([virally_suppressed_since_oct]=0, 0,([virally_suppressed_since_oct]/[has_vl_since_oct])*100)" - } - - ], - "supplementColumns": [ - { - "label": "reporting_date", - "type": "single", - "sql": "t2.endDate" - }, - { - "label": "location_uuid", - "type": "single", - "sql": "t1.location_uuid" - }, - { - "label": "location_id", - "type": "single", - "sql": "t1.location_id" - }, - { - "label": "reporting_month", - "type": "single", - "sql": "date_format(t2.endDate, '%m/%Y')" - } + { + "name": "patient-care-cascade-report", + "table": { + "schema": "etl", + "tableName": "dates", + "alias": "t2" + }, + "joins": [ + { + "joinType": "JOIN", + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1", + "indexExpression": "FORCE INDEX (loc_id_enc_date_next_clinic)", + "joinExpression": "date(t1.encounter_datetime) <= date(t2.endDate)" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "amrs", + "tableName": "orders", + "alias": "orders", + "joinExpression": "orders.voided=0 and t1.encounter_id=orders.encounter_id" + } + ], + "parameters": [ + { + "name": "startDate", + "defaultValue": ["01-01-1980"] + }, + { + "name": "endDate", + "defaultValue": ["Now()"] + }, + { "name": "locations", "defaultValue": [] }, + { + "name": "groupByEndDate", + "defaultValue": [ + { + "label": "endDate", + "expression": "endDate" + } ] - } + } + ], + "filters": [ + { + "expression": "t2.endDate >= date(?)", + "parameter": "startDate" + }, + { + "expression": "t2.endDate <= date(?)", + "parameter": "endDate" + }, + { + "expression": "t1.location_id in ?", + "parameter": "locations" + }, + { + "expression": "t1.is_clinical_encounter=1", + "processForce": true + }, + { + "expression": "(t1.next_clinical_datetime_hiv is null or date(t1.next_clinical_datetime_hiv) > t2.endDate)", + "processForce": true + } + ], + "groupClause": [ + { + "parameter": "groupByEndDate" + } + ], + "indicators": [ + { + "label": "currently_in_care_total", + "expression": "currently_in_care_total", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "active_and_on_art", + "expression": "active_and_on_art", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "LTFU", + "expression": "LTFU", + "sql": "count($expression)" + }, + { + "label": "has_vl_since_oct", + "expression": "has_vl_since_oct", + "sql": "count(distinct if($expression, person_id,null))" + }, + + { + "label": "virally_suppressed_since_oct", + "expression": "virally_suppressed_since_oct", + "sql": "count(distinct if($expression, person_id,null))" + }, + { + "label": "perc_virally_suppressed_since_oct", + "expression": "perc_virally_suppressed_since_oct", + "sql": "if([virally_suppressed_since_oct]=0, 0,([virally_suppressed_since_oct]/[has_vl_since_oct])*100)" + } + ], + "supplementColumns": [ + { + "label": "reporting_date", + "type": "single", + "sql": "t2.endDate" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "reporting_month", + "type": "single", + "sql": "date_format(t2.endDate, '%m/%Y')" + } + ] + } ] diff --git a/reports/patient-daily-care-status.json b/reports/patient-daily-care-status.json index 6fd5f6a9d..b87b605b9 100755 --- a/reports/patient-daily-care-status.json +++ b/reports/patient-daily-care-status.json @@ -1,51 +1,49 @@ [ - { - "name": "patient-daily-care-status", - "table": { - "schema": "etl", - "tableName": "flat_hiv_summary_v15b", - "alias": "t1" - }, - "joins": [], - "parameters": [ - { - "name": "referenceDate", - "defaultValue": [ - "10-10-2015" - ] - }, - { - "name": "patient_uuid", - "defaultValue": "" - } - ], - "filters": [ - { - "expression": "t1.uuid = ?", - "parameter": "patient_uuid" - }, - { - "expression": "is_clinical_encounter = 1", - "processForce": true - }, - { - "expression": "next_clinical_datetime_hiv IS NULL", - "processForce": true - } - ], - "groupClause": [ - { - "parameter": "groupByEndDate" - } - ], - "indicators": [ - { - "label": "patient_daily_care_status", - "expression": "patient_daily_care_status", - "sql": "$expression" - } - ], - "supplementColumns": [], - "indicatorHandlers": [] - } -] \ No newline at end of file + { + "name": "patient-daily-care-status", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary_v15b", + "alias": "t1" + }, + "joins": [], + "parameters": [ + { + "name": "referenceDate", + "defaultValue": ["10-10-2015"] + }, + { + "name": "patient_uuid", + "defaultValue": "" + } + ], + "filters": [ + { + "expression": "t1.uuid = ?", + "parameter": "patient_uuid" + }, + { + "expression": "is_clinical_encounter = 1", + "processForce": true + }, + { + "expression": "next_clinical_datetime_hiv IS NULL", + "processForce": true + } + ], + "groupClause": [ + { + "parameter": "groupByEndDate" + } + ], + "indicators": [ + { + "label": "patient_daily_care_status", + "expression": "patient_daily_care_status", + "sql": "$expression" + } + ], + "supplementColumns": [], + "indicatorHandlers": [] + } +] diff --git a/reports/patient-flow-report.json b/reports/patient-flow-report.json index 501c8ae79..7bdf5c15b 100755 --- a/reports/patient-flow-report.json +++ b/reports/patient-flow-report.json @@ -95,9 +95,7 @@ "parameters": [ { "name": "dateStarted", - "defaultValue": [ - "10-10-2015" - ] + "defaultValue": ["10-10-2015"] }, { "name": "locations" @@ -291,4 +289,4 @@ } ] } -] \ No newline at end of file +] diff --git a/reports/patient-level.indicators.json b/reports/patient-level.indicators.json index e80905609..f2f274b7e 100755 --- a/reports/patient-level.indicators.json +++ b/reports/patient-level.indicators.json @@ -1,219 +1,218 @@ [ - - { - "name":"encounter_type", - "label":"encounter type", - "description": "encounter_type", - "expression": "encounter_type" - }, - { - "name":"visit_num", - "label":"visit num", - "description": "visit_num", - "expression": "visit_num" - }, - { - "name":"enrollment_date", - "label":"enrollment date", - "description": "enrollment_date", - "expression": "DATE_FORMAT(enrollment_date,'%m-%d-%Y')" - }, - { - "name":"death_date", - "label":"death date", - "description": "death_date", - "expression": "DATE_FORMAT(death_date,'%m-%d-%Y')" - }, - { - "name":"scheduled_visit", - "label":"scheduled visit", - "description": "scheduled_visit", - "expression": "scheduled_visit" - }, - { - "name":"transfer_out", - "label":"transfer out", - "description": "transfer_out", - "expression": "transfer_out" - }, - { - "name":"out_of_care", - "label":"out of care", - "description": "out_of_care", - "expression": "out_of_care" - }, - { - "name":"prev_rtc_date", - "label":"prev rtc date", - "description": "prev_rtc_date", - "expression": "DATE_FORMAT(prev_rtc_date,'%m-%d-%Y')" - }, - { - "name":"rtc_date", - "label":"rtc date", - "description": "rtc_date", - "expression": "DATE_FORMAT(rtc_date,'%m-%d-%Y')" - }, - { - "name":"arv_start_date", - "label":"arv start date", - "description": "arv_start_date", - "expression": "DATE_FORMAT(arv_start_date,'%m-%d-%Y')" - }, - { - "name":"arv_first_regimen", - "label":"arv first regimen", - "description": "arv_first_regimen", - "expression": "arv_first_regimen" - }, - { - "name":"cur_arv_meds", - "label":"cur arv meds", - "description": "cur_arv_meds", - "expression": "cur_arv_meds" - }, - { - "name":"cur_arv_line", - "label":"cur arv line", - "description": "cur_arv_line", - "expression": "cur_arv_line" - }, - { - "name":"first_evidence_patient_pregnant", - "label":"first evidence patient pregnant", - "description": "first_evidence_patient_pregnant", - "expression": "DATE_FORMAT(first_evidence_patient_pregnant,'%m-%d-%Y')" - }, - { - "name":"edd", - "label":"edd", - "description": "edd", - "expression": "edd" - }, - { - "name":"tb_tx_start_date", - "label":"tb tx start date", - "description": "tb_tx_start_date", - "expression": "DATE_FORMAT(tb_tx_start_date,'%m-%d-%Y')" - }, - { - "name": "is_on_tb_medication", - "label": "is_on_tb_medication", - "description": "Is on TB medication", - "expression": "tb_tx_start_date is not null and timestampdiff(year,tb_tx_start_date,@startDate) <= 1" - }, - { - "name":"pcp_prophylaxis_start_date", - "label":"pcp prophylaxis start date", - "description": "pcp_prophylaxis_start_date", - "expression": "DATE_FORMAT(pcp_prophylaxis_start_date,'%m-%d-%Y')" - }, - { - "name":"cd4_resulted", - "label":"cd4 resulted", - "description": "cd4_resulted", - "expression": "cd4_resulted" - }, - { - "name":"cd4_resulted_date", - "label":"cd4 resulted date", - "description": "cd4_resulted_date", - "expression": "DATE_FORMAT(cd4_resulted_date,'%m-%d-%Y')" - }, - { - "name":"cd4_1", - "label":"cd4 1", - "description": "cd4 1", - "expression": "cd4_1" - }, - { - "name":"cd4_1_date", - "label":"cd4 1 date", - "description": "cd4 1 date", - "expression": "DATE_FORMAT(cd4_1_date,'%m-%d-%Y')" - }, - { - "name":"cd4_2", - "label":"cd4 2", - "description": "cd4 2", - "expression": "cd4_2" - }, - { - "name":"cd4_2_date", - "label":"cd4 2 date", - "description": "cd4 2 date", - "expression": "DATE_FORMAT(cd4_2_date,'%m-%d-%Y')" - }, - { - "name":"cd4_percent_1", - "label":"cd4 percent 1", - "description": "cd4 percent 1", - "expression": "cd4_percent_1" - }, - { - "name":"cd4_percent_1_date", - "label":"cd4 percent 1 date", - "description": "cd4 percent 1 date", - "expression": "DATE_FORMAT(cd4_percent_1_date,'%m-%d-%Y')" - }, - { - "name":"cd4_percent_2", - "label":"cd4 percent 2", - "description": "cd4 percent 2", - "expression": "cd4_percent_2" - }, - { - "name":"cd4_percent_2_date", - "label":"cd4 percent 2 date", - "description": "cd4 percent 2 date", - "expression": "DATE_FORMAT(cd4_percent_2_date,'%m-%d-%Y')" - }, - { - "name":"vl_resulted", - "label":"vl resulted", - "description": "vl resulted", - "expression": "vl_resulted" - }, - { - "name":"vl_resulted_date", - "label":"vl resulted date", - "description": "vl resulted date", - "expression": "DATE_FORMAT(vl_resulted_date,'%m-%d-%Y')" - }, - { - "name":"vl_1", - "label":"vl 1", - "description": "vl 1", - "expression": "vl_1" - }, - { - "name":"vl_1_date", - "label":"vl 1 date", - "description": "vl 1 date", - "expression": "DATE_FORMAT(vl_1_date,'%m-%d-%Y')" - }, - { - "name":"vl_2", - "label":"vl 2", - "description": "vl 2", - "expression": "vl_2" - }, - { - "name":"vl_2_date", - "label":"vl 2 date", - "description": "vl 2 date", - "expression": "DATE_FORMAT(vl_2_date,'%m-%d-%Y')" - }, - { - "name":"vl_order_date", - "label":"vl order date", - "description": "vl order date", - "expression": "DATE_FORMAT(vl_order_date,'%m-%d-%Y')" - }, - { - "name":"cd4_order_date", - "label":"cd4 order date", - "description": "cd4 order date", - "expression": "DATE_FORMAT(cd4_order_date,'%m-%d-%Y')" - } + { + "name": "encounter_type", + "label": "encounter type", + "description": "encounter_type", + "expression": "encounter_type" + }, + { + "name": "visit_num", + "label": "visit num", + "description": "visit_num", + "expression": "visit_num" + }, + { + "name": "enrollment_date", + "label": "enrollment date", + "description": "enrollment_date", + "expression": "DATE_FORMAT(enrollment_date,'%m-%d-%Y')" + }, + { + "name": "death_date", + "label": "death date", + "description": "death_date", + "expression": "DATE_FORMAT(death_date,'%m-%d-%Y')" + }, + { + "name": "scheduled_visit", + "label": "scheduled visit", + "description": "scheduled_visit", + "expression": "scheduled_visit" + }, + { + "name": "transfer_out", + "label": "transfer out", + "description": "transfer_out", + "expression": "transfer_out" + }, + { + "name": "out_of_care", + "label": "out of care", + "description": "out_of_care", + "expression": "out_of_care" + }, + { + "name": "prev_rtc_date", + "label": "prev rtc date", + "description": "prev_rtc_date", + "expression": "DATE_FORMAT(prev_rtc_date,'%m-%d-%Y')" + }, + { + "name": "rtc_date", + "label": "rtc date", + "description": "rtc_date", + "expression": "DATE_FORMAT(rtc_date,'%m-%d-%Y')" + }, + { + "name": "arv_start_date", + "label": "arv start date", + "description": "arv_start_date", + "expression": "DATE_FORMAT(arv_start_date,'%m-%d-%Y')" + }, + { + "name": "arv_first_regimen", + "label": "arv first regimen", + "description": "arv_first_regimen", + "expression": "arv_first_regimen" + }, + { + "name": "cur_arv_meds", + "label": "cur arv meds", + "description": "cur_arv_meds", + "expression": "cur_arv_meds" + }, + { + "name": "cur_arv_line", + "label": "cur arv line", + "description": "cur_arv_line", + "expression": "cur_arv_line" + }, + { + "name": "first_evidence_patient_pregnant", + "label": "first evidence patient pregnant", + "description": "first_evidence_patient_pregnant", + "expression": "DATE_FORMAT(first_evidence_patient_pregnant,'%m-%d-%Y')" + }, + { + "name": "edd", + "label": "edd", + "description": "edd", + "expression": "edd" + }, + { + "name": "tb_tx_start_date", + "label": "tb tx start date", + "description": "tb_tx_start_date", + "expression": "DATE_FORMAT(tb_tx_start_date,'%m-%d-%Y')" + }, + { + "name": "is_on_tb_medication", + "label": "is_on_tb_medication", + "description": "Is on TB medication", + "expression": "tb_tx_start_date is not null and timestampdiff(year,tb_tx_start_date,@startDate) <= 1" + }, + { + "name": "pcp_prophylaxis_start_date", + "label": "pcp prophylaxis start date", + "description": "pcp_prophylaxis_start_date", + "expression": "DATE_FORMAT(pcp_prophylaxis_start_date,'%m-%d-%Y')" + }, + { + "name": "cd4_resulted", + "label": "cd4 resulted", + "description": "cd4_resulted", + "expression": "cd4_resulted" + }, + { + "name": "cd4_resulted_date", + "label": "cd4 resulted date", + "description": "cd4_resulted_date", + "expression": "DATE_FORMAT(cd4_resulted_date,'%m-%d-%Y')" + }, + { + "name": "cd4_1", + "label": "cd4 1", + "description": "cd4 1", + "expression": "cd4_1" + }, + { + "name": "cd4_1_date", + "label": "cd4 1 date", + "description": "cd4 1 date", + "expression": "DATE_FORMAT(cd4_1_date,'%m-%d-%Y')" + }, + { + "name": "cd4_2", + "label": "cd4 2", + "description": "cd4 2", + "expression": "cd4_2" + }, + { + "name": "cd4_2_date", + "label": "cd4 2 date", + "description": "cd4 2 date", + "expression": "DATE_FORMAT(cd4_2_date,'%m-%d-%Y')" + }, + { + "name": "cd4_percent_1", + "label": "cd4 percent 1", + "description": "cd4 percent 1", + "expression": "cd4_percent_1" + }, + { + "name": "cd4_percent_1_date", + "label": "cd4 percent 1 date", + "description": "cd4 percent 1 date", + "expression": "DATE_FORMAT(cd4_percent_1_date,'%m-%d-%Y')" + }, + { + "name": "cd4_percent_2", + "label": "cd4 percent 2", + "description": "cd4 percent 2", + "expression": "cd4_percent_2" + }, + { + "name": "cd4_percent_2_date", + "label": "cd4 percent 2 date", + "description": "cd4 percent 2 date", + "expression": "DATE_FORMAT(cd4_percent_2_date,'%m-%d-%Y')" + }, + { + "name": "vl_resulted", + "label": "vl resulted", + "description": "vl resulted", + "expression": "vl_resulted" + }, + { + "name": "vl_resulted_date", + "label": "vl resulted date", + "description": "vl resulted date", + "expression": "DATE_FORMAT(vl_resulted_date,'%m-%d-%Y')" + }, + { + "name": "vl_1", + "label": "vl 1", + "description": "vl 1", + "expression": "vl_1" + }, + { + "name": "vl_1_date", + "label": "vl 1 date", + "description": "vl 1 date", + "expression": "DATE_FORMAT(vl_1_date,'%m-%d-%Y')" + }, + { + "name": "vl_2", + "label": "vl 2", + "description": "vl 2", + "expression": "vl_2" + }, + { + "name": "vl_2_date", + "label": "vl 2 date", + "description": "vl 2 date", + "expression": "DATE_FORMAT(vl_2_date,'%m-%d-%Y')" + }, + { + "name": "vl_order_date", + "label": "vl order date", + "description": "vl order date", + "expression": "DATE_FORMAT(vl_order_date,'%m-%d-%Y')" + }, + { + "name": "cd4_order_date", + "label": "cd4 order date", + "description": "cd4 order date", + "expression": "DATE_FORMAT(cd4_order_date,'%m-%d-%Y')" + } ] diff --git a/reports/patient-monthly-care-status.json b/reports/patient-monthly-care-status.json index 8932f6684..8591d3013 100755 --- a/reports/patient-monthly-care-status.json +++ b/reports/patient-monthly-care-status.json @@ -1,84 +1,80 @@ [ - { - "name": "patient-monthly-care-status-report", - "table": { - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t1" - }, - "joins": [ - { - "joinType": "INNER JOIN", - "schema": "etl", - "tableName": "dates", - "alias": "t2", - "joinExpression": "t1.encounter_datetime <= t2.endDate" - } - ], - "parameters": [ - { - "name": "startDate", - "defaultValue": [ - "10-10-2015" - ] - }, - { - "name": "endDate", - "defaultValue": [ - "defaultValue" - ] - }, - { - "name": "patient_uuid", - "defaultValue": "" - }, - { - "name": "groupByEndDate", - "defaultValue": [ - { - "label": "endDate", - "expression": "endDate" - } - ] - } - ], - "filters": [ - { - "expression": "t1.uuid = ?", - "parameter": "patient_uuid" - }, - { - "expression": "(t1.next_clinical_datetime_hiv IS NULL OR t1.next_clinical_datetime_hiv > t2.endDate)", - "processForce": true - }, - { - "expression": "t2.endDate >= ?", - "parameter": "startDate" - }, - { - "expression": "t2.endDate <= ?", - "parameter": "endDate" - } - ], - "groupClause": [ - { - "parameter": "groupByEndDate" - } - ], - "indicators": [ - { - "label": "monthly_patient_care_status", - "expression": "monthly_patient_care_status", - "sql": "$expression" - } - ], - "supplementColumns": [ - { - "label": "month", - "type": "single", - "sql": "DATE_FORMAT(t2.endDate,'%M %Y')" - } - ], - "indicatorHandlers": [] - } -] \ No newline at end of file + { + "name": "patient-monthly-care-status-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "etl", + "tableName": "dates", + "alias": "t2", + "joinExpression": "t1.encounter_datetime <= t2.endDate" + } + ], + "parameters": [ + { + "name": "startDate", + "defaultValue": ["10-10-2015"] + }, + { + "name": "endDate", + "defaultValue": ["defaultValue"] + }, + { + "name": "patient_uuid", + "defaultValue": "" + }, + { + "name": "groupByEndDate", + "defaultValue": [ + { + "label": "endDate", + "expression": "endDate" + } + ] + } + ], + "filters": [ + { + "expression": "t1.uuid = ?", + "parameter": "patient_uuid" + }, + { + "expression": "(t1.next_clinical_datetime_hiv IS NULL OR t1.next_clinical_datetime_hiv > t2.endDate)", + "processForce": true + }, + { + "expression": "t2.endDate >= ?", + "parameter": "startDate" + }, + { + "expression": "t2.endDate <= ?", + "parameter": "endDate" + } + ], + "groupClause": [ + { + "parameter": "groupByEndDate" + } + ], + "indicators": [ + { + "label": "monthly_patient_care_status", + "expression": "monthly_patient_care_status", + "sql": "$expression" + } + ], + "supplementColumns": [ + { + "label": "month", + "type": "single", + "sql": "DATE_FORMAT(t2.endDate,'%M %Y')" + } + ], + "indicatorHandlers": [] + } +] diff --git a/reports/patient-peer-navigator-referral-report.json b/reports/patient-peer-navigator-referral-report.json index 39eac9a2a..6fb71b27e 100644 --- a/reports/patient-peer-navigator-referral-report.json +++ b/reports/patient-peer-navigator-referral-report.json @@ -80,23 +80,24 @@ } ], "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2010"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"programUuids","defaultValue":[]}, - {"name":"providerUuids","defaultValue":[]}, - {"name":"stateUuids","defaultValue":[]}, - {"name":"conceptUuids","defaultValue":[]}, - {"name":"startAge", "defaultValue":[]}, - {"name":"endAge", "defaultValue":[]}, - {"name":"gender", "defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - { - "label": "location", - "expression": "t4.location_id" - } - - ] + { "name": "startDate", "defaultValue": ["10-10-2010"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locationUuids", "defaultValue": [] }, + { "name": "programUuids", "defaultValue": [] }, + { "name": "providerUuids", "defaultValue": [] }, + { "name": "stateUuids", "defaultValue": [] }, + { "name": "conceptUuids", "defaultValue": [] }, + { "name": "startAge", "defaultValue": [] }, + { "name": "endAge", "defaultValue": [] }, + { "name": "gender", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [ + { + "label": "location", + "expression": "t4.location_id" + } + ] }, { "name": "groupByState", @@ -118,7 +119,6 @@ } ], "filters": [ - { "expression": "t2.uuid in ?", "parameter": "programUuids" @@ -129,8 +129,8 @@ }, { - "expression":"t10.gender in ?", - "parameter":"gender" + "expression": "t10.gender in ?", + "parameter": "gender" }, { "expression": "t8.uuid in ?", @@ -141,19 +141,18 @@ "parameter": "providerUuids" }, { - "expression":"DATE_FORMAT(t5.date_created, '%Y-%m-%d') >= ?", - "parameter":"startDate" + "expression": "DATE_FORMAT(t5.date_created, '%Y-%m-%d') >= ?", + "parameter": "startDate" }, { - "expression":" DATE_FORMAT(t5.date_created, '%Y-%m-%d') <= ?", - "parameter":"endDate" + "expression": " DATE_FORMAT(t5.date_created, '%Y-%m-%d') <= ?", + "parameter": "endDate" } ], "groupClause": [ - {"parameter":"groupByLocation"}, - {"parameter":"groupByProgram"}, - {"parameter":"groupByState"} - + { "parameter": "groupByLocation" }, + { "parameter": "groupByProgram" }, + { "parameter": "groupByState" } ], "orderBy": [], "indicators": [], @@ -236,8 +235,6 @@ "indicators": [] } ] - - }, { "name": "referral-patient-list", @@ -326,22 +323,23 @@ } ], "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2010"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"programUuids","defaultValue":[]}, - {"name":"stateUuids","defaultValue":[]}, - {"name":"startAge", "defaultValue":[]}, - {"name":"endAge", "defaultValue":[]}, - {"name":"gender", "defaultValue":[]}, - {"name":"providerUuids", "defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - { - "label": "location", - "expression": "t1.location_id" - } - - ] + { "name": "startDate", "defaultValue": ["10-10-2010"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locationUuids", "defaultValue": [] }, + { "name": "programUuids", "defaultValue": [] }, + { "name": "stateUuids", "defaultValue": [] }, + { "name": "startAge", "defaultValue": [] }, + { "name": "endAge", "defaultValue": [] }, + { "name": "gender", "defaultValue": [] }, + { "name": "providerUuids", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [ + { + "label": "location", + "expression": "t1.location_id" + } + ] }, { "name": "groupByState", @@ -373,12 +371,12 @@ ], "filters": [ { - "expression":"DATE_FORMAT(t6.date_created, '%Y-%m-%d') >= ?", - "parameter":"startDate" + "expression": "DATE_FORMAT(t6.date_created, '%Y-%m-%d') >= ?", + "parameter": "startDate" }, { - "expression":" DATE_FORMAT(t6.date_created, '%Y-%m-%d') <= ?", - "parameter":"endDate" + "expression": " DATE_FORMAT(t6.date_created, '%Y-%m-%d') <= ?", + "parameter": "endDate" }, { "expression": "t9.uuid in ?", @@ -444,12 +442,12 @@ "type": "single", "sql": "extract(year from (from_days(datediff(now(),t4.birthdate))))" }, - { + { "label": "program_name", "type": "single", "sql": "t5.name" }, - { + { "label": "location_name", "type": "single", "sql": "t9.name" @@ -458,7 +456,6 @@ "label": "state_name", "type": "single", "sql": "t8.name" - }, { "label": "current_state_date", @@ -468,7 +465,7 @@ { "label": "initial_referral_date", "type": "single", - "sql": "t10.date_created" + "sql": "t10.date_created" } ] } diff --git a/reports/patient-referral-report.json b/reports/patient-referral-report.json index 7b65de7af..272a3cde2 100755 --- a/reports/patient-referral-report.json +++ b/reports/patient-referral-report.json @@ -78,27 +78,26 @@ "alias": "t14", "joinExpression": "t14.provider_id = t1.provider_id" } - - ], "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2010"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"programUuids","defaultValue":[]}, - {"name":"providerUuids","defaultValue":[]}, - {"name":"stateUuids","defaultValue":[]}, - {"name":"conceptUuids","defaultValue":[]}, - {"name":"startAge", "defaultValue":[]}, - {"name":"endAge", "defaultValue":[]}, - {"name":"gender", "defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - { - "label": "location", - "expression": "t4.location_id" - } - - ] + { "name": "startDate", "defaultValue": ["10-10-2010"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locationUuids", "defaultValue": [] }, + { "name": "programUuids", "defaultValue": [] }, + { "name": "providerUuids", "defaultValue": [] }, + { "name": "stateUuids", "defaultValue": [] }, + { "name": "conceptUuids", "defaultValue": [] }, + { "name": "startAge", "defaultValue": [] }, + { "name": "endAge", "defaultValue": [] }, + { "name": "gender", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [ + { + "label": "location", + "expression": "t4.location_id" + } + ] }, { "name": "groupByState", @@ -120,7 +119,6 @@ } ], "filters": [ - { "expression": "t2.uuid in ?", "parameter": "programUuids" @@ -131,8 +129,8 @@ }, { - "expression":"t10.gender in ?", - "parameter":"gender" + "expression": "t10.gender in ?", + "parameter": "gender" }, { "expression": "t8.uuid in ?", @@ -143,23 +141,18 @@ "parameter": "providerUuids" }, { - "expression":"DATE_FORMAT(t5.date_created, '%Y-%m-%d') >= ?", - "parameter":"startDate" + "expression": "DATE_FORMAT(t5.date_created, '%Y-%m-%d') >= ?", + "parameter": "startDate" }, { - "expression":" DATE_FORMAT(t5.date_created, '%Y-%m-%d') <= ?", - "parameter":"endDate" + "expression": " DATE_FORMAT(t5.date_created, '%Y-%m-%d') <= ?", + "parameter": "endDate" } - - - - ], "groupClause": [ - {"parameter":"groupByLocation"}, - {"parameter":"groupByProgram"}, - {"parameter":"groupByState"} - + { "parameter": "groupByLocation" }, + { "parameter": "groupByProgram" }, + { "parameter": "groupByState" } ], "orderBy": [], "indicators": [], @@ -235,9 +228,6 @@ "type": "single", "sql": "t1.date_created" } - - - ], "indicatorHandlers": [ { @@ -245,8 +235,6 @@ "indicators": [] } ] - - }, { "name": "referral-patient-list", @@ -318,14 +306,14 @@ "tableName": "location", "alias": "t9", "joinExpression": "t1.location_id = t9.location_id" - }, + }, { "joinType": "INNER JOIN", "schema": "amrs", "tableName": "concept", "alias": "t11", "joinExpression": "t11.concept_id = t7.concept_id" - }, + }, { "joinType": "INNER JOIN", "schema": "amrs", @@ -335,22 +323,23 @@ } ], "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2010"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"programUuids","defaultValue":[]}, - {"name":"stateUuids","defaultValue":[]}, - {"name":"startAge", "defaultValue":[]}, - {"name":"endAge", "defaultValue":[]}, - {"name":"gender", "defaultValue":[]}, - {"name":"providerUuids", "defaultValue":[]}, - {"name":"groupByLocation", "defaultValue":[ - { - "label": "location", - "expression": "t1.location_id" - } - - ] + { "name": "startDate", "defaultValue": ["10-10-2010"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locationUuids", "defaultValue": [] }, + { "name": "programUuids", "defaultValue": [] }, + { "name": "stateUuids", "defaultValue": [] }, + { "name": "startAge", "defaultValue": [] }, + { "name": "endAge", "defaultValue": [] }, + { "name": "gender", "defaultValue": [] }, + { "name": "providerUuids", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [ + { + "label": "location", + "expression": "t1.location_id" + } + ] }, { "name": "groupByState", @@ -382,12 +371,12 @@ ], "filters": [ { - "expression":"DATE_FORMAT(t6.date_created, '%Y-%m-%d') >= ?", - "parameter":"startDate" + "expression": "DATE_FORMAT(t6.date_created, '%Y-%m-%d') >= ?", + "parameter": "startDate" }, { - "expression":" DATE_FORMAT(t6.date_created, '%Y-%m-%d') <= ?", - "parameter":"endDate" + "expression": " DATE_FORMAT(t6.date_created, '%Y-%m-%d') <= ?", + "parameter": "endDate" }, { "expression": "t9.uuid in ?", @@ -453,12 +442,12 @@ "type": "single", "sql": "extract(year from (from_days(datediff(now(),t4.birthdate))))" }, - { + { "label": "program_name", "type": "single", "sql": "t5.name" }, - { + { "label": "location_name", "type": "single", "sql": "t9.name" @@ -467,7 +456,6 @@ "label": "state_name", "type": "single", "sql": "t8.name" - }, { "label": "current_state_date", @@ -477,8 +465,8 @@ { "label": "initial_referral_date", "type": "single", - "sql": "t10.date_created" + "sql": "t10.date_created" } ] } -] \ No newline at end of file +] diff --git a/reports/patient-register-report.json b/reports/patient-register-report.json index 66d8708b0..7e87633dd 100755 --- a/reports/patient-register-report.json +++ b/reports/patient-register-report.json @@ -1,438 +1,447 @@ -[{ - "name": "patient-register-report", - "table": { - "schema": "etl", - "tableName": "flat_hiv_summary", - "alias": "t1" - }, - "joins": [{ - "joinType": "INNER JOIN", - "schema": "amrs", - "tableName": "location", - "alias": "t2", - "joinExpression": "t1.location_uuid = t2.uuid" - }, - { - "joinType": "INNER JOIN", - "schema": "amrs", - "tableName": "person_name", - "alias": "t3", - "joinExpression": "t1.person_id = t3.person_id and (t3.voided is null || t3.voided = 0)" - }, - { - "joinType": "LEFT OUTER JOIN", - "schema": "amrs", - "tableName": "patient_identifier", - "alias": "t4", - "joinExpression": "t1.person_id = t4.patient_id" - }, - { - "joinType": "INNER JOIN", - "schema": "amrs", - "tableName": "person", - "alias": "t5", - "joinExpression": "t1.person_id = t5.person_id" - } - ], - "parameters": [{ - "name": "startDate", - "defaultValue": ["10-10-2015"] - }, - { - "name": "endDate", - "defaultValue": ["defaultValue"] - }, - { - "name": "locationUuids", - "defaultValue": [] - }, - { - "name": "startAge", - "defaultValue": [] - }, - { - "name": "endAge", - "defaultValue": [] - }, - { - "name": "gender", - "defaultValue": [] - }, - { - "name": "groupByEncounter", - "defaultValue": [{ - "label": "encounter", - "expression": "encounter_id" - }] - } - ], - "filters": [{ - "expression": "t1.encounter_datetime >= ?", - "parameter": "startDate" - }, - { - "expression": "t1.encounter_datetime <= ?", - "parameter": "endDate" - }, - { - "expression": "t1.location_uuid in ?", - "parameter": "locationUuids" - }, - { - "expression": "round(datediff(t1.encounter_datetime,t5.birthdate)/365) >= ?", - "parameter": "startAge" - }, - { - "expression": "round(datediff(t1.encounter_datetime,t5.birthdate)/365) <= ?", - "parameter": "endAge" - }, - { - "expression": "t5.gender in ?", - "parameter": "gender" - } - ], - "groupClause": [{ - "parameter": "groupByEncounter" - }], - "indicators": [{ - "label": "on_arvs", - "expression": "on_arvs", - "sql": "if($expression,true,false)" - - }, - { - "label": "on_arvs_first_line", - "expression": "on_arvs_first_line", - "sql": "if($expression,true,false)" - }, - { - "label": "on_arvs_second_line", - "expression": "on_arvs_second_line", - "sql": "if($expression,true,false)" - }, - { - "label": "prev_rtc_date", - "expression": "prev_rtc_date", - "sql": "$expression" - }, - { - "label": "rtc_date", - "expression": "rtc_date", - "sql": "$expression" - }, - { - "label": "arv_start_date", - "expression": "arv_start_date", - "sql": "$expression" - }, - { - "label": "arv_first_regimen", - "expression": "arv_first_regimen", - "sql": "$expression" - }, - { - "label": "cur_arv_meds", - "expression": "cur_arv_meds", - "sql": "$expression" - }, - { - "label": "on_arvs_third_line", - "expression": "on_arvs_third_line", - "sql": "if($expression,true,false)" - }, - { - "label": "vl_done_past_year", - "expression": "vl_done_past_year", - "sql": "if($expression,true,false)" - }, - { - "label": "no_vl_done_past_year", - "expression": "no_vl_done_past_year", - "sql": "if($expression,true,false)" - }, - { - "label": "vl_done_past_year_lte_1000", - "expression": "vl_done_past_year_lte_1000", - "sql": "if($expression,true,false)" - }, - { - "label": "vl_done_past_year_gt_1000", - "expression": "vl_done_past_year_gt_1000", - "sql": "if($expression,true,false)" - }, - { - "label": "vl_done_this_encounter", - "expression": "vl_done_this_encounter", - "sql": "if($expression,true,false)" - }, - { - "label": "vl_done_this_encounter_lte_1000", - "expression": "vl_done_this_encounter_lte_1000", - "sql": "if($expression,true,false)" - }, - { - "label": "vl_done_this_encounter_gt_1000", - "expression": "vl_done_this_encounter_gt_1000", - "sql": "if($expression,true,false)" - }, - { - "label": "vl_ordered", - "expression": "vl_ordered", - "sql": "if($expression,true,false)" - }, - { - "label": "pending_vl_order", - "expression": "pending_vl_order", - "sql": "if($expression,true,false)" - }, - { - "label": "pending_vl_order_no_result_after_4_weeks", - "expression": "pending_vl_order_no_result_after_4_weeks", - "sql": "if($expression,true,false)" - }, - { - "label": "on_arvs_lte_26_weeks", - "expression": "on_arvs_lte_26_weeks", - "sql": "if($expression,true,false)" - }, - { - "label": "on_arvs_lte_52_weeks", - "expression": "on_arvs_lte_52_weeks", - "sql": "if($expression,true,false)" - }, - { - "label": "on_arvs_lte_52_weeks_and_have_vl", - "expression": "on_arvs_lte_52_weeks_and_have_vl", - "sql": "if($expression,true,false)" - }, - { - "label": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "expression": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", - "sql": "if($expression,true,false)" - }, - { - "label": "not_on_arvs_cd4_lte_500", - "expression": "not_on_arvs_cd4_lte_500", - "sql": "if($expression,true,false)" - }, - { - "label": "pregnant", - "expression": "pregnant", - "sql": "if($expression,true,false)" - }, - { - "label": "pregnant_and_on_arvs", - "expression": "pregnant_and_on_arvs", - "sql": "if($expression,true,false)" - }, - - { - "label": "encounter_type", - "expression": "encounter_type", - "sql": "$expression" - }, - { - "label": "visit_num", - "expression": "visit_num", - "sql": "$expression" - }, - { - "label": "newly_enrolled", - "expression": "newly_enrolled", - "sql": "$expression" - }, - { - "label": "enrollment_date", - "expression": "enrollment_date", - "sql": "$expression" - }, - { - "label": "death_date", - "expression": "death_date", - "sql": "$expression" - }, - { - "label": "scheduled_visit", - "expression": "scheduled_visit", - "sql": "$expression" - }, - { - "label": "transfer_out", - "expression": "transfer_out", - "sql": "$expression" - }, - { - "label": "out_of_care", - "expression": "out_of_care", - "sql": "$expression" - }, - { - "label": "cur_arv_line", - "expression": "cur_arv_line", - "sql": "$expression" - }, - { - "label": "first_evidence_patient_pregnant", - "expression": "first_evidence_patient_pregnant", - "sql": "$expression" - }, - { - "label": "edd", - "expression": "edd", - "sql": "$expression" - }, - { - "label": "screened_for_tb", - "expression": "screened_for_tb", - "sql": "$expression" - }, - { - "label": "tb_tx_start_date", - "expression": "tb_tx_start_date", - "sql": "$expression" - }, - { - "label": "pcp_prophylaxis_start_date", - "expression": "pcp_prophylaxis_start_date", - "sql": "$expression" - }, - { - "label": "cd4_resulted", - "expression": "cd4_resulted", - "sql": "$expression" - }, - { - "label": "cd4_resulted_date", - "expression": "cd4_resulted_date", - "sql": "$expression" - }, - { - "label": "cd4_1", - "expression": "cd4_1", - "sql": "$expression" - }, - { - "label": "cd4_1_date", - "expression": "cd4_1_date", - "sql": "$expression" - }, - { - "label": "cd4_2", - "expression": "cd4_2", - "sql": "$expression" - }, - { - "label": "cd4_2_date", - "expression": "cd4_2_date", - "sql": "$expression" - }, - { - "label": "cd4_percent_1", - "expression": "cd4_percent_1", - "sql": "$expression" - }, - { - "label": "cd4_percent_1_date", - "expression": "cd4_percent_1_date", - "sql": "$expression" - }, - { - "label": "cd4_percent_2", - "expression": "cd4_percent_2", - "sql": "$expression" - }, - { - "label": "cd4_percent_2_date", - "expression": "cd4_percent_2_date", - "sql": "$expression" - }, - { - "label": "vl_resulted", - "expression": "vl_resulted", - "sql": "$expression" - }, - { - "label": "vl_resulted_date", - "expression": "vl_resulted_date", - "sql": "$expression" - }, - { - "label": "vl_1", - "expression": "vl_1", - "sql": "$expression" - }, - { - "label": "vl_1_date", - "expression": "vl_1_date", - "sql": "$expression" - }, - { - "label": "vl_2", - "expression": "vl_2", - "sql": "$expression" - }, - { - "label": "vl_2_date", - "expression": "vl_2_date", - "sql": "$expression" - }, - { - "label": "vl_order_date", - "expression": "vl_order_date", - "sql": "$expression" - }, - { - "label": "cd4_order_date", - "expression": "cd4_order_date", - "sql": "$expression" - } - - ], - "supplementColumns": [{ - "label": "location", - "type": "single", - "sql": "t2.name" - }, - { - "label": "location_uuid", - "type": "single", - "sql": "t1.location_uuid" - }, - { - "label": "location_id", - "type": "single", - "sql": "t1.location_id" - }, - { - "label": "encounter_date", - "type": "single", - "sql": "t1.encounter_datetime" - }, - { - "label": "person_id", - "type": "single", - "sql": "t1.person_id" - }, - { - "label": "person_uuid", - "type": "single", - "sql": "t1.uuid" - }, - { - "label": "identifiers", - "type": "multiple", - "sql": "group_concat(distinct t4.identifier separator ', ')" - }, - { - "label": "person_name", - "type": "multiple", - "sql": "concat(COALESCE(t3.given_name,''),' ',COALESCE(t3.middle_name,''),' ',COALESCE(t3.family_name,''))" - } - ], - "indicatorHandlers": [{ - "processor": "convertConceptIdToName", - "indicators": ["arv_first_regimen", "cur_arv_meds"] - }] - +[ + { + "name": "patient-register-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person_name", + "alias": "t3", + "joinExpression": "t1.person_id = t3.person_id and (t3.voided is null || t3.voided = 0)" + }, + { + "joinType": "LEFT OUTER JOIN", + "schema": "amrs", + "tableName": "patient_identifier", + "alias": "t4", + "joinExpression": "t1.person_id = t4.patient_id" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t5", + "joinExpression": "t1.person_id = t5.person_id" + } + ], + "parameters": [ + { + "name": "startDate", + "defaultValue": ["10-10-2015"] + }, + { + "name": "endDate", + "defaultValue": ["defaultValue"] + }, + { + "name": "locationUuids", + "defaultValue": [] + }, + { + "name": "startAge", + "defaultValue": [] + }, + { + "name": "endAge", + "defaultValue": [] + }, + { + "name": "gender", + "defaultValue": [] + }, + { + "name": "groupByEncounter", + "defaultValue": [ + { + "label": "encounter", + "expression": "encounter_id" + } + ] + } + ], + "filters": [ + { + "expression": "t1.encounter_datetime >= ?", + "parameter": "startDate" + }, + { + "expression": "t1.encounter_datetime <= ?", + "parameter": "endDate" + }, + { + "expression": "t1.location_uuid in ?", + "parameter": "locationUuids" + }, + { + "expression": "round(datediff(t1.encounter_datetime,t5.birthdate)/365) >= ?", + "parameter": "startAge" + }, + { + "expression": "round(datediff(t1.encounter_datetime,t5.birthdate)/365) <= ?", + "parameter": "endAge" + }, + { + "expression": "t5.gender in ?", + "parameter": "gender" + } + ], + "groupClause": [ + { + "parameter": "groupByEncounter" + } + ], + "indicators": [ + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "if($expression,true,false)" + }, + { + "label": "on_arvs_first_line", + "expression": "on_arvs_first_line", + "sql": "if($expression,true,false)" + }, + { + "label": "on_arvs_second_line", + "expression": "on_arvs_second_line", + "sql": "if($expression,true,false)" + }, + { + "label": "prev_rtc_date", + "expression": "prev_rtc_date", + "sql": "$expression" + }, + { + "label": "rtc_date", + "expression": "rtc_date", + "sql": "$expression" + }, + { + "label": "arv_start_date", + "expression": "arv_start_date", + "sql": "$expression" + }, + { + "label": "arv_first_regimen", + "expression": "arv_first_regimen", + "sql": "$expression" + }, + { + "label": "cur_arv_meds", + "expression": "cur_arv_meds", + "sql": "$expression" + }, + { + "label": "on_arvs_third_line", + "expression": "on_arvs_third_line", + "sql": "if($expression,true,false)" + }, + { + "label": "vl_done_past_year", + "expression": "vl_done_past_year", + "sql": "if($expression,true,false)" + }, + { + "label": "no_vl_done_past_year", + "expression": "no_vl_done_past_year", + "sql": "if($expression,true,false)" + }, + { + "label": "vl_done_past_year_lte_1000", + "expression": "vl_done_past_year_lte_1000", + "sql": "if($expression,true,false)" + }, + { + "label": "vl_done_past_year_gt_1000", + "expression": "vl_done_past_year_gt_1000", + "sql": "if($expression,true,false)" + }, + { + "label": "vl_done_this_encounter", + "expression": "vl_done_this_encounter", + "sql": "if($expression,true,false)" + }, + { + "label": "vl_done_this_encounter_lte_1000", + "expression": "vl_done_this_encounter_lte_1000", + "sql": "if($expression,true,false)" + }, + { + "label": "vl_done_this_encounter_gt_1000", + "expression": "vl_done_this_encounter_gt_1000", + "sql": "if($expression,true,false)" + }, + { + "label": "vl_ordered", + "expression": "vl_ordered", + "sql": "if($expression,true,false)" + }, + { + "label": "pending_vl_order", + "expression": "pending_vl_order", + "sql": "if($expression,true,false)" + }, + { + "label": "pending_vl_order_no_result_after_4_weeks", + "expression": "pending_vl_order_no_result_after_4_weeks", + "sql": "if($expression,true,false)" + }, + { + "label": "on_arvs_lte_26_weeks", + "expression": "on_arvs_lte_26_weeks", + "sql": "if($expression,true,false)" + }, + { + "label": "on_arvs_lte_52_weeks", + "expression": "on_arvs_lte_52_weeks", + "sql": "if($expression,true,false)" + }, + { + "label": "on_arvs_lte_52_weeks_and_have_vl", + "expression": "on_arvs_lte_52_weeks_and_have_vl", + "sql": "if($expression,true,false)" + }, + { + "label": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "expression": "on_arvs_lte_52_weeks_and_have_vl_lte_1000", + "sql": "if($expression,true,false)" + }, + { + "label": "not_on_arvs_cd4_lte_500", + "expression": "not_on_arvs_cd4_lte_500", + "sql": "if($expression,true,false)" + }, + { + "label": "pregnant", + "expression": "pregnant", + "sql": "if($expression,true,false)" + }, + { + "label": "pregnant_and_on_arvs", + "expression": "pregnant_and_on_arvs", + "sql": "if($expression,true,false)" + }, -}] \ No newline at end of file + { + "label": "encounter_type", + "expression": "encounter_type", + "sql": "$expression" + }, + { + "label": "visit_num", + "expression": "visit_num", + "sql": "$expression" + }, + { + "label": "newly_enrolled", + "expression": "newly_enrolled", + "sql": "$expression" + }, + { + "label": "enrollment_date", + "expression": "enrollment_date", + "sql": "$expression" + }, + { + "label": "death_date", + "expression": "death_date", + "sql": "$expression" + }, + { + "label": "scheduled_visit", + "expression": "scheduled_visit", + "sql": "$expression" + }, + { + "label": "transfer_out", + "expression": "transfer_out", + "sql": "$expression" + }, + { + "label": "out_of_care", + "expression": "out_of_care", + "sql": "$expression" + }, + { + "label": "cur_arv_line", + "expression": "cur_arv_line", + "sql": "$expression" + }, + { + "label": "first_evidence_patient_pregnant", + "expression": "first_evidence_patient_pregnant", + "sql": "$expression" + }, + { + "label": "edd", + "expression": "edd", + "sql": "$expression" + }, + { + "label": "screened_for_tb", + "expression": "screened_for_tb", + "sql": "$expression" + }, + { + "label": "tb_tx_start_date", + "expression": "tb_tx_start_date", + "sql": "$expression" + }, + { + "label": "pcp_prophylaxis_start_date", + "expression": "pcp_prophylaxis_start_date", + "sql": "$expression" + }, + { + "label": "cd4_resulted", + "expression": "cd4_resulted", + "sql": "$expression" + }, + { + "label": "cd4_resulted_date", + "expression": "cd4_resulted_date", + "sql": "$expression" + }, + { + "label": "cd4_1", + "expression": "cd4_1", + "sql": "$expression" + }, + { + "label": "cd4_1_date", + "expression": "cd4_1_date", + "sql": "$expression" + }, + { + "label": "cd4_2", + "expression": "cd4_2", + "sql": "$expression" + }, + { + "label": "cd4_2_date", + "expression": "cd4_2_date", + "sql": "$expression" + }, + { + "label": "cd4_percent_1", + "expression": "cd4_percent_1", + "sql": "$expression" + }, + { + "label": "cd4_percent_1_date", + "expression": "cd4_percent_1_date", + "sql": "$expression" + }, + { + "label": "cd4_percent_2", + "expression": "cd4_percent_2", + "sql": "$expression" + }, + { + "label": "cd4_percent_2_date", + "expression": "cd4_percent_2_date", + "sql": "$expression" + }, + { + "label": "vl_resulted", + "expression": "vl_resulted", + "sql": "$expression" + }, + { + "label": "vl_resulted_date", + "expression": "vl_resulted_date", + "sql": "$expression" + }, + { + "label": "vl_1", + "expression": "vl_1", + "sql": "$expression" + }, + { + "label": "vl_1_date", + "expression": "vl_1_date", + "sql": "$expression" + }, + { + "label": "vl_2", + "expression": "vl_2", + "sql": "$expression" + }, + { + "label": "vl_2_date", + "expression": "vl_2_date", + "sql": "$expression" + }, + { + "label": "vl_order_date", + "expression": "vl_order_date", + "sql": "$expression" + }, + { + "label": "cd4_order_date", + "expression": "cd4_order_date", + "sql": "$expression" + } + ], + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t2.name" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "t1.location_uuid" + }, + { + "label": "location_id", + "type": "single", + "sql": "t1.location_id" + }, + { + "label": "encounter_date", + "type": "single", + "sql": "t1.encounter_datetime" + }, + { + "label": "person_id", + "type": "single", + "sql": "t1.person_id" + }, + { + "label": "person_uuid", + "type": "single", + "sql": "t1.uuid" + }, + { + "label": "identifiers", + "type": "multiple", + "sql": "group_concat(distinct t4.identifier separator ', ')" + }, + { + "label": "person_name", + "type": "multiple", + "sql": "concat(COALESCE(t3.given_name,''),' ',COALESCE(t3.middle_name,''),' ',COALESCE(t3.family_name,''))" + } + ], + "indicatorHandlers": [ + { + "processor": "convertConceptIdToName", + "indicators": ["arv_first_regimen", "cur_arv_meds"] + } + ] + } +] diff --git a/reports/patient-status-change-tracker-report.json b/reports/patient-status-change-tracker-report.json index b3fb0c58f..7e48aff95 100755 --- a/reports/patient-status-change-tracker-report.json +++ b/reports/patient-status-change-tracker-report.json @@ -19,21 +19,15 @@ "parameters": [ { "name": "startDate", - "defaultValue": [ - "01-01-1980" - ] + "defaultValue": ["01-01-1980"] }, { "name": "endDate", - "defaultValue": [ - "Now()" - ] + "defaultValue": ["Now()"] }, { "name": "locationUuids", - "defaultValue": [ - 1 - ] + "defaultValue": [1] }, { "name": "locations", @@ -127,8 +121,6 @@ "expression": "transfer_in", "sql": "count($expression)" } - - ], "supplementColumns": [ { @@ -177,9 +169,6 @@ "t1.prev_rtc_date", "t1.prev_encounter_datetime_hiv", "timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) as days_since_last_RTC" - ] } - - ] diff --git a/reports/real-time-hiv-report.json b/reports/real-time-hiv-report.json index 7a070eb46..bf3a657e7 100755 --- a/reports/real-time-hiv-report.json +++ b/reports/real-time-hiv-report.json @@ -1,214 +1,220 @@ [ - { - "name": "real-time-hiv-report", - "table":{"schema":"etl","tableName":"flat_hiv_summary","alias":"t1"}, - "joins":[ - ], - "parameters": [ - {"name":"start_date", "defaultValue":["01-10-2016"]}, - {"name":"report_date", "defaultValue":["Now()"]}, - {"name":"projection_date", "defaultValue":["2018-09-01"]}, - {"name":"locations","defaultValue":[1]} - ], - "filters": [ - {"expression":"encounter_datetime between @start_date and @report_date"}, - {"expression":"is_clinical_encounter = 1", "processForce":true}, - {"expression":"next_clinical_datetime_hiv is null", "processForce":true}, - {"expression":"(death_date is null or death_date > @report_date)", "processForce":true}, - {"expression":"(transfer_out is null or transfer_date_bncd > @report_date)", "processForce":true} - - ], - "groupClause":[ - {"parameter":"groupBylocation_id"} - ], - "indicators": [ - { - "label":"patients", - "expression":"patients", - "sql":"count(distinct person_id)" - }, - { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(if($expression,1,null))" - - }, - { - "label":"not_on_art", - "expression":"not_on_art", - "sql":"count(if($expression,1,null))" - - }, - { - "label":"on_arvs_first_line", - "expression":"on_arvs_first_line", - "sql":"count(if($expression,1,null))" - }, - { - "label":"non_arvs_first_line", - "expression":"non_arvs_first_line", - "sql":"count(if($expression,1,null))" - }, - { - "label":"active_in_care1", - "expression":"active_in_care1", - "sql":"count(if($expression,1,null))" - }, - { - "label":"active_in_care_not_on_art", - "expression":"active_in_care_not_on_art", - "sql":"count(if($expression,1,null))" - }, - { - "label":"active_in_care_on_art", - "expression":"active_in_care_on_art", - "sql":"count(if($expression,t1.person_id,null))" - }, - { - "label":"active_in_care_on_first_line", - "expression":"active_in_care_on_first_liner", - "sql":"count(if($expression,1,null))" - }, - { - "label": "active_in_care_not_on_first_line", - "expression": "active_in_care_not_on_first_line", - "sql": "count(if($expression,1,null))" - }, - { - "label":"ltf", - "expression":"ltf", - "sql":"count(if($expression,1,null))" - }, - { - "label":"ltf_on_art", - "expression":"ltf_on_art", - "sql":"count(if($expression,1,null))" - }, - { - "label":"ltf_not_on_art", - "expression":"ltf_not_on_art", - "sql":"count(if($expression,1,null))" - }, - { - "label":"ltf_on_first_line", - "expression":"ltf_on_first_line", - "sql":"count(if($expression,1,null))" - }, - { - "label":"ltf_not_on_first_line", - "expression":"ltf_not_on_first_line", - "sql":"count(if($expression,1,null))" - }, - { - "label":"qualify_for_vl", - "expression":"qualify_for_vl", - "sql":"count(if($expression,1,null))" - }, - { - "label":"have_vl_past_one_year", - "expression":"have_vl_past_one_year", - "sql":"count(if($expression,1,null))" - }, - { - "label":"have_no_vl_past_one_year", - "expression":"have_no_vl_past_one_year", - "sql":"count(if($expression,1,null))" - }, - { - "label":"vl_suppressed", - "expression":"vl_suppressed", - "sql":"count(if($expression,1,null))" - }, - { - "label":"vl_non_suppressed", - "expression":"vl_non_suppressed", - "sql":"count(if($expression,1,null))" - }, - { - "label":"active_qualify_for_vls", - "expression":"active_qualify_for_vl", - "sql":"count(if($expression,1,null))" - }, - { - "label":"active_have_vl_past_one_year", - "expression":"active_have_vl_past_one_year", - "sql":"count(if($expression,1,null))" - }, - { - "label":"active_have_no_vl_past_one_year", - "expression":"active_have_no_vl_past_one_year", - "sql":"count(if($expression,1,null))" - }, - { - "label":"active_vl_suppressed", - "expression":"active_vl_suppressed", - "sql":"count(if($expression,1,null))" - }, - { - "label":"active_vl_non_suppressed", - "expression":"active_vl_non_suppressed", - "sql":"count(if($expression,1,null))" - }, - { - "label":"ltf_qualify_for_vl", - "expression":"ltf_qualify_for_vl", - "sql":"count(if($expression,1,null))" - }, - { - "label":"ltf_have_vl_past_one_year", - "expression":"ltf_have_vl_past_one_year", - "sql":"count(if($expression,1,null))" - }, - { - "label":"ltf_have_no_vl_past_one_year", - "expression":"ltf_have_no_vl_past_one_year", - "sql": "count(if($expression,1,null))" - }, - { - "label":"ltf_vl_suppressed", - "expression":"ltf_vl_suppressed", - "sql": "count(if($expression,1,null))" - - }, - { - "label":"ltf_vl_non_suppressed", - "expression":"ltf_vl_non_suppressed", - "sql": "count(if($expression,1,null))" - - }, - { - "label":"projection_qualify_for_vl", - "expression":"projection_qualify_for_vl", - "sql": "count(if($expression,1,null))" - - }, - { - "label":"projection_have_no_vl_past_one_year", - "expression":"projection_have_no_vl_past_one_year", - "sql": "count(if($expression,1,null))" - }, - { - "label":"projection_vl_suppressed", - "expression":"projection_vl_suppressed", - "sql": "count(if($expression,1,null))" - }, - { - "label":"projection_vl_non_suppressed", - "expression":"projection_vl_non_suppressed", - "sql": "count(if($expression,1,null))" - } - ], - "supplementColumns":[ - { - "label":"person_id", - "type":"single", - "sql":"t1.person_id" - }, - { - "label":"location_uuid", - "type":"single", - "sql":"location_uuid" - } - ] - } -] \ No newline at end of file + { + "name": "real-time-hiv-report", + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary", + "alias": "t1" + }, + "joins": [], + "parameters": [ + { "name": "start_date", "defaultValue": ["01-10-2016"] }, + { "name": "report_date", "defaultValue": ["Now()"] }, + { "name": "projection_date", "defaultValue": ["2018-09-01"] }, + { "name": "locations", "defaultValue": [1] } + ], + "filters": [ + { + "expression": "encounter_datetime between @start_date and @report_date" + }, + { "expression": "is_clinical_encounter = 1", "processForce": true }, + { + "expression": "next_clinical_datetime_hiv is null", + "processForce": true + }, + { + "expression": "(death_date is null or death_date > @report_date)", + "processForce": true + }, + { + "expression": "(transfer_out is null or transfer_date_bncd > @report_date)", + "processForce": true + } + ], + "groupClause": [{ "parameter": "groupBylocation_id" }], + "indicators": [ + { + "label": "patients", + "expression": "patients", + "sql": "count(distinct person_id)" + }, + { + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(if($expression,1,null))" + }, + { + "label": "not_on_art", + "expression": "not_on_art", + "sql": "count(if($expression,1,null))" + }, + { + "label": "on_arvs_first_line", + "expression": "on_arvs_first_line", + "sql": "count(if($expression,1,null))" + }, + { + "label": "non_arvs_first_line", + "expression": "non_arvs_first_line", + "sql": "count(if($expression,1,null))" + }, + { + "label": "active_in_care1", + "expression": "active_in_care1", + "sql": "count(if($expression,1,null))" + }, + { + "label": "active_in_care_not_on_art", + "expression": "active_in_care_not_on_art", + "sql": "count(if($expression,1,null))" + }, + { + "label": "active_in_care_on_art", + "expression": "active_in_care_on_art", + "sql": "count(if($expression,t1.person_id,null))" + }, + { + "label": "active_in_care_on_first_line", + "expression": "active_in_care_on_first_liner", + "sql": "count(if($expression,1,null))" + }, + { + "label": "active_in_care_not_on_first_line", + "expression": "active_in_care_not_on_first_line", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf", + "expression": "ltf", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf_on_art", + "expression": "ltf_on_art", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf_not_on_art", + "expression": "ltf_not_on_art", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf_on_first_line", + "expression": "ltf_on_first_line", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf_not_on_first_line", + "expression": "ltf_not_on_first_line", + "sql": "count(if($expression,1,null))" + }, + { + "label": "qualify_for_vl", + "expression": "qualify_for_vl", + "sql": "count(if($expression,1,null))" + }, + { + "label": "have_vl_past_one_year", + "expression": "have_vl_past_one_year", + "sql": "count(if($expression,1,null))" + }, + { + "label": "have_no_vl_past_one_year", + "expression": "have_no_vl_past_one_year", + "sql": "count(if($expression,1,null))" + }, + { + "label": "vl_suppressed", + "expression": "vl_suppressed", + "sql": "count(if($expression,1,null))" + }, + { + "label": "vl_non_suppressed", + "expression": "vl_non_suppressed", + "sql": "count(if($expression,1,null))" + }, + { + "label": "active_qualify_for_vls", + "expression": "active_qualify_for_vl", + "sql": "count(if($expression,1,null))" + }, + { + "label": "active_have_vl_past_one_year", + "expression": "active_have_vl_past_one_year", + "sql": "count(if($expression,1,null))" + }, + { + "label": "active_have_no_vl_past_one_year", + "expression": "active_have_no_vl_past_one_year", + "sql": "count(if($expression,1,null))" + }, + { + "label": "active_vl_suppressed", + "expression": "active_vl_suppressed", + "sql": "count(if($expression,1,null))" + }, + { + "label": "active_vl_non_suppressed", + "expression": "active_vl_non_suppressed", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf_qualify_for_vl", + "expression": "ltf_qualify_for_vl", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf_have_vl_past_one_year", + "expression": "ltf_have_vl_past_one_year", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf_have_no_vl_past_one_year", + "expression": "ltf_have_no_vl_past_one_year", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf_vl_suppressed", + "expression": "ltf_vl_suppressed", + "sql": "count(if($expression,1,null))" + }, + { + "label": "ltf_vl_non_suppressed", + "expression": "ltf_vl_non_suppressed", + "sql": "count(if($expression,1,null))" + }, + { + "label": "projection_qualify_for_vl", + "expression": "projection_qualify_for_vl", + "sql": "count(if($expression,1,null))" + }, + { + "label": "projection_have_no_vl_past_one_year", + "expression": "projection_have_no_vl_past_one_year", + "sql": "count(if($expression,1,null))" + }, + { + "label": "projection_vl_suppressed", + "expression": "projection_vl_suppressed", + "sql": "count(if($expression,1,null))" + }, + { + "label": "projection_vl_non_suppressed", + "expression": "projection_vl_non_suppressed", + "sql": "count(if($expression,1,null))" + } + ], + "supplementColumns": [ + { + "label": "person_id", + "type": "single", + "sql": "t1.person_id" + }, + { + "label": "location_uuid", + "type": "single", + "sql": "location_uuid" + } + ] + } +] diff --git a/reports/viral-load-monitoring-report.json b/reports/viral-load-monitoring-report.json index 7b1ec3299..8702b3166 100755 --- a/reports/viral-load-monitoring-report.json +++ b/reports/viral-load-monitoring-report.json @@ -1,244 +1,266 @@ -[ { +[ + { "name": "viral-load-monitoring-report", - "table":{"schema":"etl","tableName":"flat_hiv_summary_v15b","alias":"t1"}, - "joins":[ - {"joinType":"INNER JOIN","schema":"amrs","tableName":"location","alias":"t2","joinExpression":"t1.location_uuid = t2.uuid"}, - {"joinType":"INNER JOIN","schema":"amrs","tableName":"person","alias":"t5","joinExpression":"t1.person_id = t5.person_id"} + "table": { + "schema": "etl", + "tableName": "flat_hiv_summary_v15b", + "alias": "t1" + }, + "joins": [ + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "location", + "alias": "t2", + "joinExpression": "t1.location_uuid = t2.uuid" + }, + { + "joinType": "INNER JOIN", + "schema": "amrs", + "tableName": "person", + "alias": "t5", + "joinExpression": "t1.person_id = t5.person_id" + } ], "parameters": [ - {"name":"startDate", "defaultValue":["10-10-2015"]}, - {"name":"endDate", "defaultValue":["defaultValue"]}, - {"name":"locationUuids","defaultValue":[]}, - {"name":"startAge", "defaultValue":[]}, - {"name":"endAge", "defaultValue":[]}, - {"name":"gender", "defaultValue":[]}, - { - "name": "groupByLocation", - "defaultValue": [ - { - "label": "location", - "expression": "t1.location_id" - } - ] - } + { "name": "startDate", "defaultValue": ["10-10-2015"] }, + { "name": "endDate", "defaultValue": ["defaultValue"] }, + { "name": "locationUuids", "defaultValue": [] }, + { "name": "startAge", "defaultValue": [] }, + { "name": "endAge", "defaultValue": [] }, + { "name": "gender", "defaultValue": [] }, + { + "name": "groupByLocation", + "defaultValue": [ + { + "label": "location", + "expression": "t1.location_id" + } + ] + } ], "filters": [ - {"expression":"t1.location_uuid in ?", "parameter":"locationUuids"}, - {"expression":"round(datediff(t1.encounter_datetime,t5.birthdate)/365) >= ?", "parameter":"startAge"}, - {"expression":"round(datediff(t1.encounter_datetime,t5.birthdate)/365) <= ?", "parameter":"endAge"}, - {"expression":"t5.gender in ?", "parameter":"gender"}, - {"expression":"t1.out_of_care IS NULL", "processForce":true}, - {"expression":"t1.death_date IS NULL", "processForce":true}, - {"expression":"TIMESTAMPDIFF(DAY, IF(t1.encounter_type = 21, t1.prev_clinical_datetime_hiv, t1.encounter_datetime),?) < 366", "parameter":"endDate"}, - {"expression":"(next_encounter_datetime_hiv is null or next_encounter_datetime_hiv >= ?)", "parameter":"endDate"} - ], - "groupClause":[ - {"parameter":"groupByLocation"} + { "expression": "t1.location_uuid in ?", "parameter": "locationUuids" }, + { + "expression": "round(datediff(t1.encounter_datetime,t5.birthdate)/365) >= ?", + "parameter": "startAge" + }, + { + "expression": "round(datediff(t1.encounter_datetime,t5.birthdate)/365) <= ?", + "parameter": "endAge" + }, + { "expression": "t5.gender in ?", "parameter": "gender" }, + { "expression": "t1.out_of_care IS NULL", "processForce": true }, + { "expression": "t1.death_date IS NULL", "processForce": true }, + { + "expression": "TIMESTAMPDIFF(DAY, IF(t1.encounter_type = 21, t1.prev_clinical_datetime_hiv, t1.encounter_datetime),?) < 366", + "parameter": "endDate" + }, + { + "expression": "(next_encounter_datetime_hiv is null or next_encounter_datetime_hiv >= ?)", + "parameter": "endDate" + } ], + "groupClause": [{ "parameter": "groupByLocation" }], "indicators": [ { - "label":"on_arvs", - "expression":"on_arvs", - "sql":"count(distinct if($expression,t1.person_id,null))" + "label": "on_arvs", + "expression": "on_arvs", + "sql": "count(distinct if($expression,t1.person_id,null))" }, { - "label":"patients", - "expression":"patients", - "sql":"count(distinct t1.person_id)" + "label": "patients", + "expression": "patients", + "sql": "count(distinct t1.person_id)" }, { - "label":"total_with_vl", - "expression":"total_with_vl", - "sql":"count(if($expression, t1.person_id, null))" + "label": "total_with_vl", + "expression": "total_with_vl", + "sql": "count(if($expression, t1.person_id, null))" }, { - "label":"num_with_two_vls_past_year", - "expression":"num_with_two_vls_past_year", - "sql":"count(if($expression,1,null))" + "label": "num_with_two_vls_past_year", + "expression": "num_with_two_vls_past_year", + "sql": "count(if($expression,1,null))" }, { - "label":"second_vl_gt_one_yo", - "expression":"second_vl_gt_one_yo", - "sql":"count(if($expression,1,null))" + "label": "second_vl_gt_one_yo", + "expression": "second_vl_gt_one_yo", + "sql": "count(if($expression,1,null))" }, { - "label":"last_vl_undetected", - "expression":"last_vl_undetected", - "sql":"count(if($expression ,1,null))" + "label": "last_vl_undetected", + "expression": "last_vl_undetected", + "sql": "count(if($expression ,1,null))" }, { - "label":"last_vl_unsuppressed", - "expression":"last_vl_unsuppressed", - "sql":"count(if($expression ,1,null))" + "label": "last_vl_unsuppressed", + "expression": "last_vl_unsuppressed", + "sql": "count(if($expression ,1,null))" }, { - "label":"last_vl_suppressed", - "expression":"last_vl_suppressed", - "sql":"count(if(timestampdiff(day,vl_1_date,now()) <= 366 and vl_1 < 1000,1,null))" + "label": "last_vl_suppressed", + "expression": "last_vl_suppressed", + "sql": "count(if(timestampdiff(day,vl_1_date,now()) <= 366 and vl_1 < 1000,1,null))" }, { - "label":"perc_unsuppressed", - "expression":"perc_unsuppressed", - "sql":"100*[last_vl_unsuppressed] /[num_with_at_least_one_vl_past_year]" + "label": "perc_unsuppressed", + "expression": "perc_unsuppressed", + "sql": "100*[last_vl_unsuppressed] /[num_with_at_least_one_vl_past_year]" }, { - "label":"num_with_at_least_one_vl_past_year", - "expression":"num_with_at_least_one_vl_past_year", - "sql":"count(if($expression,1,null))" + "label": "num_with_at_least_one_vl_past_year", + "expression": "num_with_at_least_one_vl_past_year", + "sql": "count(if($expression,1,null))" }, { - "label":"one_vl_unsuppressed", - "expression":"one_vl_unsuppressed", - "sql":"count(if($expression,1,null))" + "label": "one_vl_unsuppressed", + "expression": "one_vl_unsuppressed", + "sql": "count(if($expression,1,null))" }, { - "label":"one_vl_suppressed", - "expression":"one_vl_suppressed", - "sql":"count(if($expression,1,null))" + "label": "one_vl_suppressed", + "expression": "one_vl_suppressed", + "sql": "count(if($expression,1,null))" }, { - "label":"avg_time_since_last_unsuppressed_vl_one_vl", - "expression":"avg_time_since_last_unsuppressed_vl_one_vl", - "sql":"avg(if($expression,timestampdiff(day,vl_1_date,now()),null))" + "label": "avg_time_since_last_unsuppressed_vl_one_vl", + "expression": "avg_time_since_last_unsuppressed_vl_one_vl", + "sql": "avg(if($expression,timestampdiff(day,vl_1_date,now()),null))" }, { - "label":"total_with_two_vls", - "expression":"total_with_two_vls", - "sql":"count(if($expression,1,null))" + "label": "total_with_two_vls", + "expression": "total_with_two_vls", + "sql": "count(if($expression,1,null))" }, { - "label":"init_vl_unsuppressed_follow_up_unsuppressed", - "expression":"init_vl_unsuppressed_follow_up_unsuppressed", - "sql":"count(if($expression,1,null))" + "label": "init_vl_unsuppressed_follow_up_unsuppressed", + "expression": "init_vl_unsuppressed_follow_up_unsuppressed", + "sql": "count(if($expression,1,null))" }, { - "label":"follow_up_suppressed", - "expression":"follow_up_suppressed", - "sql":"count(if($expression,1,null))" + "label": "follow_up_suppressed", + "expression": "follow_up_suppressed", + "sql": "count(if($expression,1,null))" }, { - "label":"num_requiring_followup_vl", - "expression":"num_requiring_followup_vl", - "sql":"count(if($expression,1,null))" + "label": "num_requiring_followup_vl", + "expression": "num_requiring_followup_vl", + "sql": "count(if($expression,1,null))" }, { - "label":"getting_followup_vl", - "expression":"getting_followup_vl", - "sql":"count(if($expression,1,null))" + "label": "getting_followup_vl", + "expression": "getting_followup_vl", + "sql": "count(if($expression,1,null))" }, { - "label":"getting_followup_vl_180_days", - "expression":"getting_followup_vl_180_days", - "sql":"count(if($expression,1,null))" + "label": "getting_followup_vl_180_days", + "expression": "getting_followup_vl_180_days", + "sql": "count(if($expression,1,null))" }, { - "label":"perc_getting_followup_vl_180_days", - "expression":"perc_getting_followup_vl_180_days", - "sql":"[getting_followup_vl_180_days]/[num_requiring_followup_vl]" + "label": "perc_getting_followup_vl_180_days", + "expression": "perc_getting_followup_vl_180_days", + "sql": "[getting_followup_vl_180_days]/[num_requiring_followup_vl]" }, { - "label":"perc_getting_followup_vl", - "expression":"perc_getting_followup_vl", - "sql":"[getting_followup_vl]/[num_requiring_followup_vl]" + "label": "perc_getting_followup_vl", + "expression": "perc_getting_followup_vl", + "sql": "[getting_followup_vl]/[num_requiring_followup_vl]" }, { - "label":"perc_fu_suppressed", - "expression":"perc_fu_suppressed", - "sql":" [follow_up_suppressed]/[total_with_two_vls]" + "label": "perc_fu_suppressed", + "expression": "perc_fu_suppressed", + "sql": " [follow_up_suppressed]/[total_with_two_vls]" }, { - "label":"avg_length_btwn_vls_first_unsuppressed", - "expression":"avg_length_btwn_vls_first_unsuppressed", - "sql":"avg(if($expression,timestampdiff(day,vl_2_date,vl_1_date),null))" + "label": "avg_length_btwn_vls_first_unsuppressed", + "expression": "avg_length_btwn_vls_first_unsuppressed", + "sql": "avg(if($expression,timestampdiff(day,vl_2_date,vl_1_date),null))" }, { - "label":"avg_length_btwn_vls_first_unsuppressed", - "expression":"avg_length_btwn_vls_first_unsuppressed", - "sql":"avg(if($expression,timestampdiff(day,vl_2_date,vl_1_date),null))" + "label": "avg_length_btwn_vls_first_unsuppressed", + "expression": "avg_length_btwn_vls_first_unsuppressed", + "sql": "avg(if($expression,timestampdiff(day,vl_2_date,vl_1_date),null))" }, { - "label":"days_since_last_vl_first_unsuppressed", - "expression":"days_since_last_vl_first_unsuppressed", - "sql":"avg(if($expression, timestampdiff(day,vl_1_date,now()),null))" + "label": "days_since_last_vl_first_unsuppressed", + "expression": "days_since_last_vl_first_unsuppressed", + "sql": "avg(if($expression, timestampdiff(day,vl_1_date,now()),null))" }, { - "label":"no_switch_after_unsuppressed", - "expression":"no_switch_after_unsuppressed", - "sql":"count(if($expression,1,null))" + "label": "no_switch_after_unsuppressed", + "expression": "no_switch_after_unsuppressed", + "sql": "count(if($expression,1,null))" }, { - "label":"switch_after_unsuppressed", - "expression":"switch_after_unsuppressed", - "sql":"count(if($expression,1,null))" + "label": "switch_after_unsuppressed", + "expression": "switch_after_unsuppressed", + "sql": "count(if($expression,1,null))" }, { - "label":"no_switch_after_unsuppressed_x1", - "expression":"no_switch_after_unsuppressed_x1", - "sql":"count(if($expression,1,null))" + "label": "no_switch_after_unsuppressed_x1", + "expression": "no_switch_after_unsuppressed_x1", + "sql": "count(if($expression,1,null))" }, { - "label":"switch_after_unsuppressed_x1", - "expression":"switch_after_unsuppressed_x1", - "sql":"count(if($expression,1,null))" + "label": "switch_after_unsuppressed_x1", + "expression": "switch_after_unsuppressed_x1", + "sql": "count(if($expression,1,null))" }, { - "label":"switch_after_unsuppressed_x_2", - "expression":"switch_after_unsuppressed_x_2", - "sql":"count(if($expression,1,null))" + "label": "switch_after_unsuppressed_x_2", + "expression": "switch_after_unsuppressed_x_2", + "sql": "count(if($expression,1,null))" }, { - "label":"no_switch_after_unsuppressed_x_2", - "expression":"no_switch_after_unsuppressed_x_2", - "sql":"count(if($expression,1,null)) " + "label": "no_switch_after_unsuppressed_x_2", + "expression": "no_switch_after_unsuppressed_x_2", + "sql": "count(if($expression,1,null)) " }, { - "label":"avg_time_to_switch_after_unsuppressed", - "expression":"avg_time_to_switch_after_unsuppressed", - "sql":"avg(if($expression,timestampdiff(day,vl_1_date,arv_start_date),null))" + "label": "avg_time_to_switch_after_unsuppressed", + "expression": "avg_time_to_switch_after_unsuppressed", + "sql": "avg(if($expression,timestampdiff(day,vl_1_date,arv_start_date),null))" }, { - "label":"avg_time_to_switch_after_unsuppressed_x2", - "expression":"avg_time_to_switch_after_unsuppressed_x2", - "sql":"AVG(IF(arv_start_date > vl_1_date AND vl_1 >= 1000 AND TIMESTAMPDIFF(DAY, vl_1_date, NOW()) <= 366 AND vl_2 > 1000 AND TIMESTAMPDIFF(DAY, vl_2_date, NOW()) <= 366, TIMESTAMPDIFF(DAY,vl_1_date, arv_start_date), NULL))" + "label": "avg_time_to_switch_after_unsuppressed_x2", + "expression": "avg_time_to_switch_after_unsuppressed_x2", + "sql": "AVG(IF(arv_start_date > vl_1_date AND vl_1 >= 1000 AND TIMESTAMPDIFF(DAY, vl_1_date, NOW()) <= 366 AND vl_2 > 1000 AND TIMESTAMPDIFF(DAY, vl_2_date, NOW()) <= 366, TIMESTAMPDIFF(DAY,vl_1_date, arv_start_date), NULL))" }, { - "label":"avg_days_to_switch_after_unsuppressed", - "expression":"avg_days_to_switch_after_unsuppressed", - "sql":"avg(if($expression,timestampdiff(day,vl_1_date,arv_start_date),null))" + "label": "avg_days_to_switch_after_unsuppressed", + "expression": "avg_days_to_switch_after_unsuppressed", + "sql": "avg(if($expression,timestampdiff(day,vl_1_date,arv_start_date),null))" }, { - "label":"num_with_vl_after_switch", - "expression":"num_with_vl_after_switch", - "sql":"count(if($expression,1,null))" + "label": "num_with_vl_after_switch", + "expression": "num_with_vl_after_switch", + "sql": "count(if($expression,1,null))" }, { - "label":"num_with_vl_after_switch_suppressed", - "expression":"num_with_vl_after_switch_suppressed", - "sql":"count(if($expression,1,null))" + "label": "num_with_vl_after_switch_suppressed", + "expression": "num_with_vl_after_switch_suppressed", + "sql": "count(if($expression,1,null))" }, { - "label":"num_with_vl_after_switch_unsuppressed", - "expression":"num_with_vl_after_switch_unsuppressed", - "sql":"count(if($expression,1,null))" + "label": "num_with_vl_after_switch_unsuppressed", + "expression": "num_with_vl_after_switch_unsuppressed", + "sql": "count(if($expression,1,null))" }, { - "label":"perc_switched_with_suppressed_fu", - "expression":"perc_switched_with_suppressed_fu", - "sql":"[num_with_vl_after_switch_suppressed]/[total_with_two_vls]" + "label": "perc_switched_with_suppressed_fu", + "expression": "perc_switched_with_suppressed_fu", + "sql": "[num_with_vl_after_switch_suppressed]/[total_with_two_vls]" } - ], - "supplementColumns":[ - { - "label":"location", - "type":"single", - "sql":"t2.name" - } + "supplementColumns": [ + { + "label": "location", + "type": "single", + "sql": "t2.name" + } ], - "indicatorHandlers":[ - - ] - - -} + "indicatorHandlers": [] + } ] diff --git a/request-config.js b/request-config.js index 69de10d01..96608f179 100755 --- a/request-config.js +++ b/request-config.js @@ -1,54 +1,54 @@ 'use strict'; var rp = require('request-promise'); var cache = require('./session-cache'); -module.exports = function() { - var sessionCookie = ''; - return { - getRequestPromise: function getRequestPromise(queryString,url) { - var options = { - uri: url, - qs:queryString, +module.exports = (function () { + var sessionCookie = ''; + return { + getRequestPromise: function getRequestPromise(queryString, url) { + var options = { + uri: url, + qs: queryString, headers: { 'User-Agent': 'Request-Promise', - 'Cookie': sessionCookie + Cookie: sessionCookie }, json: true, rejectUnauthorized: false, requestCert: true }; return rp(options); - }, - setAuthorization:function (authorization) { - sessionCookie = authorization; - }, - getAuthorization:function () { - return sessionCookie; - }, - postRequestPromise:function postRequestPromise(payload,uri){ - var options = { - method: 'POST', - uri: uri, - headers: { - 'User-Agent': 'Request-Promise', - 'Cookie': sessionCookie, - 'content-type':'application/json' - }, - body:payload, - json: true - }; - return rp(options); - }, - deleteRequestPromise:function deleteRequestPromise(uri){ - var options = { - method: 'DELETE', - headers: { - 'User-Agent': 'Request-Promise', - 'Cookie': sessionCookie - }, - uri: uri, - resolveWithFullResponse: true + }, + setAuthorization: function (authorization) { + sessionCookie = authorization; + }, + getAuthorization: function () { + return sessionCookie; + }, + postRequestPromise: function postRequestPromise(payload, uri) { + var options = { + method: 'POST', + uri: uri, + headers: { + 'User-Agent': 'Request-Promise', + Cookie: sessionCookie, + 'content-type': 'application/json' + }, + body: payload, + json: true + }; + return rp(options); + }, + deleteRequestPromise: function deleteRequestPromise(uri) { + var options = { + method: 'DELETE', + headers: { + 'User-Agent': 'Request-Promise', + Cookie: sessionCookie + }, + uri: uri, + resolveWithFullResponse: true + }; + return rp(options); + } }; - return rp(options); - } - }; -}(); +})(); diff --git a/resolve-program-visit-encounter-Ids/resolve-program-visit-encounter-Ids.js b/resolve-program-visit-encounter-Ids/resolve-program-visit-encounter-Ids.js index 8700749bc..be81dba7c 100755 --- a/resolve-program-visit-encounter-Ids/resolve-program-visit-encounter-Ids.js +++ b/resolve-program-visit-encounter-Ids/resolve-program-visit-encounter-Ids.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; const _ = require('lodash'); const dao = require('../etl-dao'); @@ -10,312 +10,287 @@ var encounterUuidtoIdMapping; var visitTypeUuidMapping; var def = { - getProgramConf: getProgramConf, - getProgramVisitEncounterUUidIdMap: getProgramVisitEncounterUUidIdMap, - resolveProgramVisitTypeEncounterUuidsParamsToIds: resolveProgramVisitTypeEncounterUuidsParamsToIds, - + getProgramConf: getProgramConf, + getProgramVisitEncounterUUidIdMap: getProgramVisitEncounterUUidIdMap, + resolveProgramVisitTypeEncounterUuidsParamsToIds: resolveProgramVisitTypeEncounterUuidsParamsToIds }; - module.exports = def; -function getProgramConf(){ - return programsConfig; +function getProgramConf() { + return programsConfig; } //Get ProgramType, Visit Type , Encounter Type uuid-id map -function getProgramVisitEncounterUUidIdMap(){ - - var programTypeMap = new Map(); - var visitTypeMap = new Map(); - var encounterMap = new Map(); - var resolveCount = 0; - - return new Promise(function (resolve, reject) { - - function checkResolveCount(){ - // console.log('Resolve Count', resolveCount); - if(resolveCount == 3){ - - let resolvedIds = { - 'programType':programTypeMap, - 'visitType': visitTypeMap, - 'encounterMap': encounterMap - - } - - resolve(resolvedIds); - - } - } - - //first get the program map - - programTypeService.loadAndMapProgramUuidToId().then((result)=>{ - programTypeMap = result; - resolveCount++; - checkResolveCount(); - // console.log('All Program Types', result); - }) - .catch(function(e) { - resolveCount++; - checkResolveCount(); - console.log("handled error", e); - });; - - // next get the visit type map - - visitTypeService.loadAndMapVisitTypeUuidToId().then((result)=>{ - visitTypeMap = result; - resolveCount++; - checkResolveCount(); - // console.log('All Visit Types', result); - }) - .catch(function(e) { - resolveCount++; - checkResolveCount(); - console.log("handled error", e); - });; - - // get encounter type map - - encounterTypeService.loadAndMapEncounterUuidToId().then((result)=>{ - encounterMap = result; - resolveCount++; - checkResolveCount(); - // console.log('All Encounter Types', result); - }) - .catch(function(e) { - resolveCount++; - checkResolveCount(); - console.log("handled error", e); - });; - - - - - - }); - +function getProgramVisitEncounterUUidIdMap() { + var programTypeMap = new Map(); + var visitTypeMap = new Map(); + var encounterMap = new Map(); + var resolveCount = 0; + + return new Promise(function (resolve, reject) { + function checkResolveCount() { + // console.log('Resolve Count', resolveCount); + if (resolveCount == 3) { + let resolvedIds = { + programType: programTypeMap, + visitType: visitTypeMap, + encounterMap: encounterMap + }; + + resolve(resolvedIds); + } + } + + //first get the program map + + programTypeService + .loadAndMapProgramUuidToId() + .then((result) => { + programTypeMap = result; + resolveCount++; + checkResolveCount(); + // console.log('All Program Types', result); + }) + .catch(function (e) { + resolveCount++; + checkResolveCount(); + console.log('handled error', e); + }); + + // next get the visit type map + + visitTypeService + .loadAndMapVisitTypeUuidToId() + .then((result) => { + visitTypeMap = result; + resolveCount++; + checkResolveCount(); + // console.log('All Visit Types', result); + }) + .catch(function (e) { + resolveCount++; + checkResolveCount(); + console.log('handled error', e); + }); + + // get encounter type map + + encounterTypeService + .loadAndMapEncounterUuidToId() + .then((result) => { + encounterMap = result; + resolveCount++; + checkResolveCount(); + // console.log('All Encounter Types', result); + }) + .catch(function (e) { + resolveCount++; + checkResolveCount(); + console.log('handled error', e); + }); + }); } -function resolveProgramVisitTypeEncounterUuidsParamsToIds(request){ - - var programVisitTypeEncounterMap = {}; - var resolvedPrograms = [-1]; - var resolvedVisitTypes = [-1]; - var resolvedEncounterTypes = [-1]; - var resolveCount = 0; - var resolvedProgramVisitEncounterTypes = { - 'programTypeIds': [], - 'visitTypesIds': [], - 'encounterTypeIds': [] - }; - - var encodedUrl = request.programVisitEncounter; - var decodedUrl = JSON.parse((decodeURI(encodedUrl))); - // console.log('Decoded Url', decodedUrl); - var programTypeUuid = [], visitTypeUuid = [] , encounterTypeUuid = []; - var visitTypeEncounterUUid = []; - - if(typeof decodedUrl.programType !== 'undefined'){ - programTypeUuid = decodedUrl.programType; - } - if(typeof decodedUrl.visitType !== 'undefined'){ - visitTypeUuid = decodedUrl.visitType; +function resolveProgramVisitTypeEncounterUuidsParamsToIds(request) { + var programVisitTypeEncounterMap = {}; + var resolvedPrograms = [-1]; + var resolvedVisitTypes = [-1]; + var resolvedEncounterTypes = [-1]; + var resolveCount = 0; + var resolvedProgramVisitEncounterTypes = { + programTypeIds: [], + visitTypesIds: [], + encounterTypeIds: [] + }; + + var encodedUrl = request.programVisitEncounter; + var decodedUrl = JSON.parse(decodeURI(encodedUrl)); + // console.log('Decoded Url', decodedUrl); + var programTypeUuid = [], + visitTypeUuid = [], + encounterTypeUuid = []; + var visitTypeEncounterUUid = []; + + if (typeof decodedUrl.programType !== 'undefined') { + programTypeUuid = decodedUrl.programType; + } + if (typeof decodedUrl.visitType !== 'undefined') { + visitTypeUuid = decodedUrl.visitType; + } + if (typeof decodedUrl.encounterType !== 'undefined') { + encounterTypeUuid = decodedUrl.encounterType; + } + + return new Promise(function (resolve, reject) { + function checkResolveCount() { + if (resolveCount > 0) { + resolve(resolvedProgramVisitEncounterTypes); + } else { + reject('Error'); } - if(typeof decodedUrl.encounterType !== 'undefined'){ - encounterTypeUuid = decodedUrl.encounterType; - } - - return new Promise(function (resolve, reject) { - - function checkResolveCount(){ - if(resolveCount > 0){ - resolve(resolvedProgramVisitEncounterTypes); - }else{ - reject('Error') - } - } - - getProgramVisitEncounterUUidIdMap(). - then((result)=>{ - programVisitTypeEncounterMap = result; - var programMap = programVisitTypeEncounterMap.programType; - var visitTypeMap = programVisitTypeEncounterMap.visitType; - var encounterMap = programVisitTypeEncounterMap.encounterMap; - // console.log('All Program/VisitType/Encounter Types', result); - if (programTypeUuid.length > 0 && visitTypeUuid.length === 0 && encounterTypeUuid.length === 0) { - _.each(programsConfig, (program, index) => { - if (_.includes(programTypeUuid, index) === true) { - var programUUid = index; - var programId = programMap.get(index); - if(typeof programId !== 'undefined'){ - - resolvedPrograms.push(programId); - - }else{ - console.error('ERROR : Undefined ProgramType uuid', programUUid); - } - var visitTypes = program.visitTypes; - _.each(visitTypes, (visitType) => { - var visitUuid = visitType.uuid; - var visitId = visitTypeMap.get(visitUuid); - if(typeof visitId !== 'undefined'){ - - resolvedVisitTypes.push(visitId); - - }else{ - console.error('ERROR : Undefined VisitType uuid', visitUuid); - } - var encounterTypes = visitType.encounterTypes; - _.each(encounterTypes, (encounterType) => { - var encounterUuid = encounterType.uuid; - var encounterId = encounterMap.get(encounterUuid); - if(typeof encounterId !== 'undefined'){ - - resolvedEncounterTypes.push(encounterId); - - }else{ - - console.error('ERROR : Undefined EncounterType uuid', encounterUuid); - - } - - }); - - }); - - } - - }); - - - - } - - else if (programTypeUuid.length > 0 && visitTypeUuid.length > 0 && encounterTypeUuid.length === 0) { - _.each(programsConfig, (program, index) => { - if (_.includes(programTypeUuid, index) === true) { - var programUUid = index; - var programId = programMap.get(index); - if(typeof programId !== 'undefined'){ - resolvedPrograms.push(programId); - - }else{ - - console.error('ERROR : Undefined ProgramType uuid', programUUid); - - } - var visitTypes = program.visitTypes; - _.each(visitTypes, (visitType) => { - var visitUuid = visitType.uuid; - if (_.includes(visitTypeUuid, visitUuid) === true) { - var visitId = visitTypeMap.get(visitUuid); - if(typeof visitId !== 'undefined'){ - resolvedVisitTypes.push(visitId); - - }else{ - console.error('ERROR : Undefined VisitType uuid', visitUuid); - } - var encounterTypes = visitType.encounterTypes; - _.each(encounterTypes, (encounterType) => { - var encounterUuid = encounterType.uuid; - var encounterId = encounterMap.get(encounterUuid); - if(typeof encounterId !== 'undefined'){ - resolvedEncounterTypes.push(encounterId); - - }else{ - console.error('ERROR : Undefined EncounterType uuid', encounterUuid); - } - - - }); - } - }); - - } - - }); - - - } - else if (programTypeUuid.length > 0 && visitTypeUuid.length > 0 && encounterTypeUuid.length > 0) { - _.each(programsConfig, (program, index) => { - if (_.includes(programTypeUuid, index) === true) { - var programUUid = index; - var programId = programMap.get(index); - if(typeof programId !== 'undefined'){ - resolvedPrograms.push(programId); - - }else{ - - console.error('ERROR : Undefined ProgramType uuid', programUUid); - - } - var visitTypes = program.visitTypes; - _.each(visitTypes, (visitType) => { - var visitUuid = visitType.uuid; - if (_.includes(visitTypeUuid, visitUuid) === true) { - var visitId = visitTypeMap.get(visitUuid); - if(typeof visitId !== 'undefined'){ - - resolvedVisitTypes.push(visitId); - - }else{ - - console.error('ERROR : Undefined VisitType uuid', visitUuid); - - } - var encounterTypes = visitType.encounterTypes; - _.each(encounterTypes, (encounterType) => { - var encounterUuid = encounterType.uuid; - if (_.includes(encounterTypeUuid, encounterUuid) === true) { - var encounterId = encounterMap.get(encounterUuid); - if(typeof encounterId !== 'undefined'){ - - resolvedEncounterTypes.push(encounterId); - - }else{ - - console.error('ERROR:Undefined EncounterType uuid', encounterUuid); - - } - }; - }); - } - }); - - } - - }); - - } - - resolvedProgramVisitEncounterTypes = { - 'programTypeIds': _.uniq(resolvedPrograms), - 'visitTypesIds': _.uniq(resolvedVisitTypes), - 'encounterTypeIds': _.uniq(resolvedEncounterTypes) - } - - resolveCount++; - - - checkResolveCount(); - }) - .catch(function(e) { - console.log("handled error", e); - });; - - }); - + } + + getProgramVisitEncounterUUidIdMap() + .then((result) => { + programVisitTypeEncounterMap = result; + var programMap = programVisitTypeEncounterMap.programType; + var visitTypeMap = programVisitTypeEncounterMap.visitType; + var encounterMap = programVisitTypeEncounterMap.encounterMap; + // console.log('All Program/VisitType/Encounter Types', result); + if ( + programTypeUuid.length > 0 && + visitTypeUuid.length === 0 && + encounterTypeUuid.length === 0 + ) { + _.each(programsConfig, (program, index) => { + if (_.includes(programTypeUuid, index) === true) { + var programUUid = index; + var programId = programMap.get(index); + if (typeof programId !== 'undefined') { + resolvedPrograms.push(programId); + } else { + console.error( + 'ERROR : Undefined ProgramType uuid', + programUUid + ); + } + var visitTypes = program.visitTypes; + _.each(visitTypes, (visitType) => { + var visitUuid = visitType.uuid; + var visitId = visitTypeMap.get(visitUuid); + if (typeof visitId !== 'undefined') { + resolvedVisitTypes.push(visitId); + } else { + console.error('ERROR : Undefined VisitType uuid', visitUuid); + } + var encounterTypes = visitType.encounterTypes; + _.each(encounterTypes, (encounterType) => { + var encounterUuid = encounterType.uuid; + var encounterId = encounterMap.get(encounterUuid); + if (typeof encounterId !== 'undefined') { + resolvedEncounterTypes.push(encounterId); + } else { + console.error( + 'ERROR : Undefined EncounterType uuid', + encounterUuid + ); + } + }); + }); + } + }); + } else if ( + programTypeUuid.length > 0 && + visitTypeUuid.length > 0 && + encounterTypeUuid.length === 0 + ) { + _.each(programsConfig, (program, index) => { + if (_.includes(programTypeUuid, index) === true) { + var programUUid = index; + var programId = programMap.get(index); + if (typeof programId !== 'undefined') { + resolvedPrograms.push(programId); + } else { + console.error( + 'ERROR : Undefined ProgramType uuid', + programUUid + ); + } + var visitTypes = program.visitTypes; + _.each(visitTypes, (visitType) => { + var visitUuid = visitType.uuid; + if (_.includes(visitTypeUuid, visitUuid) === true) { + var visitId = visitTypeMap.get(visitUuid); + if (typeof visitId !== 'undefined') { + resolvedVisitTypes.push(visitId); + } else { + console.error( + 'ERROR : Undefined VisitType uuid', + visitUuid + ); + } + var encounterTypes = visitType.encounterTypes; + _.each(encounterTypes, (encounterType) => { + var encounterUuid = encounterType.uuid; + var encounterId = encounterMap.get(encounterUuid); + if (typeof encounterId !== 'undefined') { + resolvedEncounterTypes.push(encounterId); + } else { + console.error( + 'ERROR : Undefined EncounterType uuid', + encounterUuid + ); + } + }); + } + }); + } + }); + } else if ( + programTypeUuid.length > 0 && + visitTypeUuid.length > 0 && + encounterTypeUuid.length > 0 + ) { + _.each(programsConfig, (program, index) => { + if (_.includes(programTypeUuid, index) === true) { + var programUUid = index; + var programId = programMap.get(index); + if (typeof programId !== 'undefined') { + resolvedPrograms.push(programId); + } else { + console.error( + 'ERROR : Undefined ProgramType uuid', + programUUid + ); + } + var visitTypes = program.visitTypes; + _.each(visitTypes, (visitType) => { + var visitUuid = visitType.uuid; + if (_.includes(visitTypeUuid, visitUuid) === true) { + var visitId = visitTypeMap.get(visitUuid); + if (typeof visitId !== 'undefined') { + resolvedVisitTypes.push(visitId); + } else { + console.error( + 'ERROR : Undefined VisitType uuid', + visitUuid + ); + } + var encounterTypes = visitType.encounterTypes; + _.each(encounterTypes, (encounterType) => { + var encounterUuid = encounterType.uuid; + if (_.includes(encounterTypeUuid, encounterUuid) === true) { + var encounterId = encounterMap.get(encounterUuid); + if (typeof encounterId !== 'undefined') { + resolvedEncounterTypes.push(encounterId); + } else { + console.error( + 'ERROR:Undefined EncounterType uuid', + encounterUuid + ); + } + } + }); + } + }); + } + }); + } + + resolvedProgramVisitEncounterTypes = { + programTypeIds: _.uniq(resolvedPrograms), + visitTypesIds: _.uniq(resolvedVisitTypes), + encounterTypeIds: _.uniq(resolvedEncounterTypes) + }; + + resolveCount++; + + checkResolveCount(); + }) + .catch(function (e) { + console.log('handled error', e); + }); + }); } - - - - - - - - diff --git a/resolve-program-visit-encounter-Ids/resolve-program-visit-encounter-idsv2.js b/resolve-program-visit-encounter-Ids/resolve-program-visit-encounter-idsv2.js index a98249a0d..acc9af84f 100755 --- a/resolve-program-visit-encounter-Ids/resolve-program-visit-encounter-idsv2.js +++ b/resolve-program-visit-encounter-Ids/resolve-program-visit-encounter-idsv2.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; const _ = require('lodash'); const dao = require('../etl-dao'); @@ -11,287 +11,278 @@ var encounterUuidtoIdMapping; var visitTypeUuidMapping; var def = { - getProgramConf: getProgramConf, - getProgramVisitEncounterUUidIdMap: getProgramVisitEncounterUUidIdMap, - resolveProgramVisitTypeEncounterUuidsParamsToIds: resolveProgramVisitTypeEncounterUuidsParamsToIds + getProgramConf: getProgramConf, + getProgramVisitEncounterUUidIdMap: getProgramVisitEncounterUUidIdMap, + resolveProgramVisitTypeEncounterUuidsParamsToIds: resolveProgramVisitTypeEncounterUuidsParamsToIds }; - module.exports = def; -function getProgramConf(){ - return programsConfig; +function getProgramConf() { + return programsConfig; } //Get ProgramType, Visit Type , Encounter Type uuid-id map -function getProgramVisitEncounterUUidIdMap(){ - - var programTypeMap = new Map(); - var visitTypeMap = new Map(); - var encounterMap = new Map(); - var resolveCount = 0; - - return new Promise(function (resolve, reject) { - - function checkResolveCount(){ - // console.log('Resolve Count', resolveCount); - if(resolveCount == 3){ - - let resolvedIds = { - 'programType':programTypeMap, - 'visitType': visitTypeMap, - 'encounterMap': encounterMap - - } - - resolve(resolvedIds); - - } - } - - //first get the program map - - programTypeService.loadAndMapProgramUuidToId().then((result)=>{ - programTypeMap = result; - resolveCount++; - checkResolveCount(); - // console.log('All Program Types', result); - }) - .catch(function(e) { - resolveCount++; - checkResolveCount(); - console.log("handled error", e); - });; - - // next get the visit type map - - visitTypeService.loadAndMapVisitTypeUuidToId().then((result)=>{ - visitTypeMap = result; - resolveCount++; - checkResolveCount(); - // console.log('All Visit Types', result); - }) - .catch(function(e) { - resolveCount++; - checkResolveCount(); - console.log("handled error", e); - });; - - // get encounter type map - - encounterTypeService.loadAndMapEncounterUuidToId().then((result)=>{ - encounterMap = result; - resolveCount++; - checkResolveCount(); - // console.log('All Encounter Types', result); - }) - .catch(function(e) { - resolveCount++; - checkResolveCount(); - console.log("handled error", e); - });; - - - - - - }); - +function getProgramVisitEncounterUUidIdMap() { + var programTypeMap = new Map(); + var visitTypeMap = new Map(); + var encounterMap = new Map(); + var resolveCount = 0; + + return new Promise(function (resolve, reject) { + function checkResolveCount() { + // console.log('Resolve Count', resolveCount); + if (resolveCount == 3) { + let resolvedIds = { + programType: programTypeMap, + visitType: visitTypeMap, + encounterMap: encounterMap + }; + + resolve(resolvedIds); + } + } + + //first get the program map + + programTypeService + .loadAndMapProgramUuidToId() + .then((result) => { + programTypeMap = result; + resolveCount++; + checkResolveCount(); + // console.log('All Program Types', result); + }) + .catch(function (e) { + resolveCount++; + checkResolveCount(); + console.log('handled error', e); + }); + + // next get the visit type map + + visitTypeService + .loadAndMapVisitTypeUuidToId() + .then((result) => { + visitTypeMap = result; + resolveCount++; + checkResolveCount(); + // console.log('All Visit Types', result); + }) + .catch(function (e) { + resolveCount++; + checkResolveCount(); + console.log('handled error', e); + }); + + // get encounter type map + + encounterTypeService + .loadAndMapEncounterUuidToId() + .then((result) => { + encounterMap = result; + resolveCount++; + checkResolveCount(); + // console.log('All Encounter Types', result); + }) + .catch(function (e) { + resolveCount++; + checkResolveCount(); + console.log('handled error', e); + }); + }); } -function resolveProgramVisitTypeEncounterUuidsParamsToIds(request){ - - var programVisitTypeEncounterMap = {}; - var resolvedPrograms = []; - var resolvedVisitTypes = []; - var resolvedEncounterTypes = []; - var resolveCount = 0; - var resolvedProgramVisitEncounterTypes = { - 'programTypeIds': [], - 'visitTypesIds': [], - 'encounterTypeIds': [], - 'locationUuids': [] - }; - - if(typeof request.department !== 'undefined'){ - let department = request.department; - var programTypeUuid = departmentService.getDepartmentProgramUuids(department) - } - if(typeof request.programType !== 'undefined'){ - var programTypeUuid = request.programType; +function resolveProgramVisitTypeEncounterUuidsParamsToIds(request) { + var programVisitTypeEncounterMap = {}; + var resolvedPrograms = []; + var resolvedVisitTypes = []; + var resolvedEncounterTypes = []; + var resolveCount = 0; + var resolvedProgramVisitEncounterTypes = { + programTypeIds: [], + visitTypesIds: [], + encounterTypeIds: [], + locationUuids: [] + }; + + if (typeof request.department !== 'undefined') { + let department = request.department; + var programTypeUuid = departmentService.getDepartmentProgramUuids( + department + ); + } + if (typeof request.programType !== 'undefined') { + var programTypeUuid = request.programType; + } + if (typeof request.visitType !== 'undefined') { + var visitTypeUuid = request.visitType; + } + if (typeof request.encounterType !== 'undefined') { + var encounterTypeUuid = request.encounterType; + } + if (typeof request.locationUuids !== 'undefined') { + var locationUuid = request.locationUuids; + } + + // console.log('Program Type', decodedUrl); + + return new Promise(function (resolve, reject) { + function checkResolveCount() { + if (resolveCount > 0) { + resolve(resolvedProgramVisitEncounterTypes); + } else { + reject('Error'); } - if(typeof request.visitType !== 'undefined'){ - var visitTypeUuid = request.visitType; - } - if(typeof request.encounterType !== 'undefined'){ - var encounterTypeUuid = request.encounterType; - } - if(typeof request.locationUuids !== 'undefined'){ - var locationUuid = request.locationUuids; - } - - // console.log('Program Type', decodedUrl); - - return new Promise(function (resolve, reject) { - - function checkResolveCount(){ - if(resolveCount > 0){ - resolve(resolvedProgramVisitEncounterTypes); - }else{ - reject('Error'); - } - } - - getProgramVisitEncounterUUidIdMap(). - then((result)=>{ - programVisitTypeEncounterMap = result; - var programMap = programVisitTypeEncounterMap.programType; - var visitTypeMap = programVisitTypeEncounterMap.visitType; - var encounterMap = programVisitTypeEncounterMap.encounterMap; - let programDefined = typeof programTypeUuid; - let visittypeDefined = typeof visitTypeUuid; - let encounterDefined = typeof encounterUuid; - if (programDefined !== 'undefined' && visittypeDefined === 'undefined' && encounterDefined === 'undefined') { - console.log('programTypeUuid.length > 0 && visitTypeUuid.length === 0 && encounterTypeUuid.length === 0'); - _.each(programsConfig, (program, index) => { - if (_.includes(programTypeUuid, index) === true) { - var programUUid = index; - var programId = programMap.get(index); - if(typeof programId !== 'undefined'){ - - resolvedPrograms.push(programId); - - }else{ - console.error('ERROR : Undefined ProgramType uuid', programUUid); - } - - } - - }); - - - - } - - else if (programDefined !== 'undefined' && visittypeDefined !== 'undefined' && encounterDefined === 'undefined') { - console.log('programTypeUuid.length > 0 && visitTypeUuid.length > 0 && encounterTypeUuid.length === 0'); - _.each(programsConfig, (program, index) => { - if (_.includes(programTypeUuid, index) === true) { - var programUUid = index; - var programId = programMap.get(index); - if(typeof programId !== 'undefined'){ - resolvedPrograms.push(programId); - - }else{ - - console.error('ERROR : Undefined ProgramType uuid', programUUid); - - } - var visitTypes = program.visitTypes; - _.each(visitTypes, (visitType) => { - var visitUuid = visitType.uuid; - if (_.includes(visitTypeUuid, visitUuid) === true) { - var visitId = visitTypeMap.get(visitUuid); - if(typeof visitId !== 'undefined'){ - resolvedVisitTypes.push(visitId); - - }else{ - console.error('ERROR : Undefined VisitType uuid', visitUuid); - } - } - }); - - } - - }); - - - } - else if (programDefined !== 'undefined' && visittypeDefined !== 'undefined' && encounterDefined !== 'Undefined') { - console.log('programTypeUuid.length > 0 && visitTypeUuid.length > 0 && encounterTypeUuid.length > 0'); - _.each(programsConfig, (program, index) => { - if (_.includes(programTypeUuid, index) === true) { - var programUUid = index; - var programId = programMap.get(index); - if(typeof programId !== 'undefined'){ - resolvedPrograms.push(programId); - - }else{ - - console.error('ERROR : Undefined ProgramType uuid', programUUid); - - } - var visitTypes = program.visitTypes; - _.each(visitTypes, (visitType) => { - var visitUuid = visitType.uuid; - if (_.includes(visitTypeUuid, visitUuid) === true) { - var visitId = visitTypeMap.get(visitUuid); - if(typeof visitId !== 'undefined'){ - - resolvedVisitTypes.push(visitId); - - }else{ - - console.error('ERROR : Undefined VisitType uuid', visitUuid); - - } - var encounterTypes = visitType.encounterTypes; - _.each(encounterTypes, (encounterType) => { - var encounterUuid = encounterType.uuid; - if (_.includes(encounterTypeUuid, encounterUuid) === true) { - var encounterId = encounterMap.get(encounterUuid); - if(typeof encounterId !== 'undefined'){ - - resolvedEncounterTypes.push(encounterId); - - }else{ - - console.error('ERROR:Undefined EncounterType uuid', encounterUuid); - - } - }; - }); - } - }); - - } - - }); - - } - else if (programDefined === 'undefined' && visittypeDefined === 'undefined' && encounterDefined === 'undefined') { - // else just load everything - console.log('programTypeUuid.length == 0 && visitTypeUuid.length == 0 && encounterTypeUuid.length == 0'); - - } - - resolvedProgramVisitEncounterTypes = { - 'programTypeIds': _.uniq(resolvedPrograms), - 'visitTypesIds': _.uniq(resolvedVisitTypes), - 'encounterTypeIds': _.uniq(resolvedEncounterTypes), - 'locationUuids': locationUuid - } - - resolveCount++; - - console.log('Resolved Ids', resolvedProgramVisitEncounterTypes); - - - checkResolveCount(); - }) - .catch(function(e) { - console.log("handled error", e); + } + + getProgramVisitEncounterUUidIdMap() + .then((result) => { + programVisitTypeEncounterMap = result; + var programMap = programVisitTypeEncounterMap.programType; + var visitTypeMap = programVisitTypeEncounterMap.visitType; + var encounterMap = programVisitTypeEncounterMap.encounterMap; + let programDefined = typeof programTypeUuid; + let visittypeDefined = typeof visitTypeUuid; + let encounterDefined = typeof encounterUuid; + if ( + programDefined !== 'undefined' && + visittypeDefined === 'undefined' && + encounterDefined === 'undefined' + ) { + console.log( + 'programTypeUuid.length > 0 && visitTypeUuid.length === 0 && encounterTypeUuid.length === 0' + ); + _.each(programsConfig, (program, index) => { + if (_.includes(programTypeUuid, index) === true) { + var programUUid = index; + var programId = programMap.get(index); + if (typeof programId !== 'undefined') { + resolvedPrograms.push(programId); + } else { + console.error( + 'ERROR : Undefined ProgramType uuid', + programUUid + ); + } + } + }); + } else if ( + programDefined !== 'undefined' && + visittypeDefined !== 'undefined' && + encounterDefined === 'undefined' + ) { + console.log( + 'programTypeUuid.length > 0 && visitTypeUuid.length > 0 && encounterTypeUuid.length === 0' + ); + _.each(programsConfig, (program, index) => { + if (_.includes(programTypeUuid, index) === true) { + var programUUid = index; + var programId = programMap.get(index); + if (typeof programId !== 'undefined') { + resolvedPrograms.push(programId); + } else { + console.error( + 'ERROR : Undefined ProgramType uuid', + programUUid + ); + } + var visitTypes = program.visitTypes; + _.each(visitTypes, (visitType) => { + var visitUuid = visitType.uuid; + if (_.includes(visitTypeUuid, visitUuid) === true) { + var visitId = visitTypeMap.get(visitUuid); + if (typeof visitId !== 'undefined') { + resolvedVisitTypes.push(visitId); + } else { + console.error( + 'ERROR : Undefined VisitType uuid', + visitUuid + ); + } + } + }); + } + }); + } else if ( + programDefined !== 'undefined' && + visittypeDefined !== 'undefined' && + encounterDefined !== 'Undefined' + ) { + console.log( + 'programTypeUuid.length > 0 && visitTypeUuid.length > 0 && encounterTypeUuid.length > 0' + ); + _.each(programsConfig, (program, index) => { + if (_.includes(programTypeUuid, index) === true) { + var programUUid = index; + var programId = programMap.get(index); + if (typeof programId !== 'undefined') { + resolvedPrograms.push(programId); + } else { + console.error( + 'ERROR : Undefined ProgramType uuid', + programUUid + ); + } + var visitTypes = program.visitTypes; + _.each(visitTypes, (visitType) => { + var visitUuid = visitType.uuid; + if (_.includes(visitTypeUuid, visitUuid) === true) { + var visitId = visitTypeMap.get(visitUuid); + if (typeof visitId !== 'undefined') { + resolvedVisitTypes.push(visitId); + } else { + console.error( + 'ERROR : Undefined VisitType uuid', + visitUuid + ); + } + var encounterTypes = visitType.encounterTypes; + _.each(encounterTypes, (encounterType) => { + var encounterUuid = encounterType.uuid; + if (_.includes(encounterTypeUuid, encounterUuid) === true) { + var encounterId = encounterMap.get(encounterUuid); + if (typeof encounterId !== 'undefined') { + resolvedEncounterTypes.push(encounterId); + } else { + console.error( + 'ERROR:Undefined EncounterType uuid', + encounterUuid + ); + } + } }); - - }); - + } + }); + } + }); + } else if ( + programDefined === 'undefined' && + visittypeDefined === 'undefined' && + encounterDefined === 'undefined' + ) { + // else just load everything + console.log( + 'programTypeUuid.length == 0 && visitTypeUuid.length == 0 && encounterTypeUuid.length == 0' + ); + } + + resolvedProgramVisitEncounterTypes = { + programTypeIds: _.uniq(resolvedPrograms), + visitTypesIds: _.uniq(resolvedVisitTypes), + encounterTypeIds: _.uniq(resolvedEncounterTypes), + locationUuids: locationUuid + }; + + resolveCount++; + + console.log('Resolved Ids', resolvedProgramVisitEncounterTypes); + + checkResolveCount(); + }) + .catch(function (e) { + console.log('handled error', e); + }); + }); } - - - - - - - - diff --git a/service/breast-cancer-monthly-summary.service.js b/service/breast-cancer-monthly-summary.service.js index 71a83eab8..29c65c3be 100644 --- a/service/breast-cancer-monthly-summary.service.js +++ b/service/breast-cancer-monthly-summary.service.js @@ -1,9 +1,9 @@ -const Promise = require("bluebird"); +const Promise = require('bluebird'); -const _ = require("lodash"); -const oncologyReportsService = require("../oncology-reports/oncology-reports-service"); -import { BaseMysqlReport } from "../app/reporting-framework/base-mysql.report"; -import { PatientlistMysqlReport } from "../app/reporting-framework/patientlist-mysql.report"; +const _ = require('lodash'); +const oncologyReportsService = require('../oncology-reports/oncology-reports-service'); +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; import { titleCase } from '../etl-helpers'; export class BreastCancerMonthlySummaryService { @@ -11,26 +11,26 @@ export class BreastCancerMonthlySummaryService { return new Promise((resolve, reject) => { let report; - if (reportParams.requestParams.period === "daily") { + if (reportParams.requestParams.period === 'daily') { report = new BaseMysqlReport( - "breastCancerDailySummaryAggregate", + 'breastCancerDailySummaryAggregate', reportParams.requestParams ); - } else if (reportParams.requestParams.period === "monthly") { + } else if (reportParams.requestParams.period === 'monthly') { report = new BaseMysqlReport( - "breastCancerMonthlySummaryAggregate", + 'breastCancerMonthlySummaryAggregate', reportParams.requestParams ); } - Promise.join(report.generateReport(), results => { + Promise.join(report.generateReport(), (results) => { let result = results.results.results; results.size = result ? result.length : 0; results.result = result; - delete results["results"]; + delete results['results']; resolve(results); // TODO Do some post processing - }).catch(errors => { + }).catch((errors) => { reject(errors); }); }); @@ -38,27 +38,27 @@ export class BreastCancerMonthlySummaryService { getPatientListReport(reportParams) { let indicators = reportParams.indicators - ? reportParams.indicators.split(",") + ? reportParams.indicators.split(',') : []; if (reportParams.locationUuids) { let locationUuids = reportParams.locationUuids - ? reportParams.locationUuids.split(",") + ? reportParams.locationUuids.split(',') : []; reportParams.locationUuids = locationUuids; } if (reportParams.genders) { - let genders = reportParams.genders ? reportParams.genders.split(",") : []; + let genders = reportParams.genders ? reportParams.genders.split(',') : []; reportParams.genders = genders; } let report = new PatientlistMysqlReport( - "breastCancerMonthlySummaryAggregate", + 'breastCancerMonthlySummaryAggregate', reportParams ); return new Promise((resolve, reject) => { // TODO: Do some pre processing - Promise.join(report.generatePatientListReport(indicators), results => { + Promise.join(report.generatePatientListReport(indicators), (results) => { for (const key in results.results.results) { if (results.results.results.hasOwnProperty(key)) { if (results.results.results[key].person_name) { @@ -71,18 +71,18 @@ export class BreastCancerMonthlySummaryService { oncologyReportsService .getPatientListCols( reportParams.indicators, - "142939b0-28a9-4649-baf9-a9d012bf3b3d" + '142939b0-28a9-4649-baf9-a9d012bf3b3d' ) - .then(patientListCols => { - results["patientListCols"] = patientListCols; + .then((patientListCols) => { + results['patientListCols'] = patientListCols; resolve(results); }) - .catch(error => { - console.error("ERROR: Error getting patient list cols", error); + .catch((error) => { + console.error('ERROR: Error getting patient list cols', error); reject(error); }); - }).catch(errors => { - console.error("Error", errors); + }).catch((errors) => { + console.error('Error', errors); reject(errors); }); }); diff --git a/service/cdm/cdm-reporting.service.js b/service/cdm/cdm-reporting.service.js index 7a9cf6097..c1a492b61 100644 --- a/service/cdm/cdm-reporting.service.js +++ b/service/cdm/cdm-reporting.service.js @@ -1,53 +1,59 @@ -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); var processors = require('../../etl-processors.js'); -import { - BaseMysqlReport -} from '../../app/reporting-framework/base-mysql.report' +import { BaseMysqlReport } from '../../app/reporting-framework/base-mysql.report'; export class CDMReportingService { + getPatientSummaryReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + let report = new BaseMysqlReport('cdmPatientSummary', reportParams); + Promise.join(report.generateReport(), (results) => { + results.result = results.results.results; + delete results['results']; + processors + .convertCdmConceptIdToName( + ['dm_meds', 'htn_meds', 'problems', 'dm_status', 'htn_status'], + results, + '' + ) + .then(function (processedResult) { + resolve(processedResult); + }) + .catch(function (err) { + reject(err); + }); + }).catch((errors) => { + reject(errors); + }); + }); + } - - getPatientSummaryReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - let report = new BaseMysqlReport('cdmPatientSummary',reportParams); - Promise.join(report.generateReport(), - (results) => { - results.result=results.results.results; - delete results['results']; - processors.convertCdmConceptIdToName(["dm_meds","htn_meds","problems","dm_status","htn_status"],results,'').then(function(processedResult){ - resolve(processedResult); - }).catch(function(err){ - reject(err); - }); - }).catch((errors) => { - reject(errors); - }); - }); - } - - getPatientMedicationHistoryReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - let report = new BaseMysqlReport('cdmPatientSummary',reportParams); - Promise.join(report.generateReport(), - (results) => { - results.result=results.results.results; - delete results['results']; - processors.convertCdmConceptIdToName(["dm_meds","htn_meds"],results,'').then(function(processedResult){ - processors.cdmMedicationChange(processedResult).then(function(_processedResult) { - resolve(_processedResult); - }).catch(function (err) { - reject(err); - }); - }).catch(function (err) { - reject(err); - }); - }).catch((errors) => { - reject(errors); - }); - }); - } - -} \ No newline at end of file + getPatientMedicationHistoryReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + let report = new BaseMysqlReport('cdmPatientSummary', reportParams); + Promise.join(report.generateReport(), (results) => { + results.result = results.results.results; + delete results['results']; + processors + .convertCdmConceptIdToName(['dm_meds', 'htn_meds'], results, '') + .then(function (processedResult) { + processors + .cdmMedicationChange(processedResult) + .then(function (_processedResult) { + resolve(_processedResult); + }) + .catch(function (err) { + reject(err); + }); + }) + .catch(function (err) { + reject(err); + }); + }).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/cervical-cancer-monthly-summary.service.js b/service/cervical-cancer-monthly-summary.service.js index dff018edd..8e54dd8f4 100644 --- a/service/cervical-cancer-monthly-summary.service.js +++ b/service/cervical-cancer-monthly-summary.service.js @@ -1,61 +1,61 @@ -const Promise = require("bluebird"); -const _ = require("lodash"); -const oncologyReportsService = require("../oncology-reports/oncology-reports-service"); -import { BaseMysqlReport } from "../app/reporting-framework/base-mysql.report"; -import { PatientlistMysqlReport } from "../app/reporting-framework/patientlist-mysql.report"; -import { titleCase } from "../etl-helpers"; +const Promise = require('bluebird'); +const _ = require('lodash'); +const oncologyReportsService = require('../oncology-reports/oncology-reports-service'); +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; +import { titleCase } from '../etl-helpers'; export class CervicalCancerMonthlySummaryService { getAggregateReport(reportParams) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { let report; - if (reportParams.requestParams.period === "daily") { + if (reportParams.requestParams.period === 'daily') { report = new BaseMysqlReport( - "cervicalCancerDailySummaryAggregate", + 'cervicalCancerDailySummaryAggregate', reportParams.requestParams ); - } else if (reportParams.requestParams.period === "monthly") { + } else if (reportParams.requestParams.period === 'monthly') { report = new BaseMysqlReport( - "cervicalCancerMonthlySummaryAggregate", + 'cervicalCancerMonthlySummaryAggregate', reportParams.requestParams ); } - Promise.join(report.generateReport(), results => { + Promise.join(report.generateReport(), (results) => { let result = results.results.results; results.size = result ? result.length : 0; results.result = result; - delete results["results"]; + delete results['results']; resolve(results); //TODO Do some post processing - }).catch(errors => { + }).catch((errors) => { reject(errors); }); }); } getPatientListReport(reportParams) { let indicators = reportParams.indicators - ? reportParams.indicators.split(",") + ? reportParams.indicators.split(',') : []; if (reportParams.locationUuids) { let locationUuids = reportParams.locationUuids - ? reportParams.locationUuids.split(",") + ? reportParams.locationUuids.split(',') : []; reportParams.locationUuids = locationUuids; } if (reportParams.genders) { - let genders = reportParams.genders ? reportParams.genders.split(",") : []; + let genders = reportParams.genders ? reportParams.genders.split(',') : []; reportParams.genders = genders; } let report = new PatientlistMysqlReport( - "cervicalCancerMonthlySummaryAggregate", + 'cervicalCancerMonthlySummaryAggregate', reportParams ); - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { //TODO: Do some pre processing - Promise.join(report.generatePatientListReport(indicators), results => { + Promise.join(report.generatePatientListReport(indicators), (results) => { for (const key in results.results.results) { if (results.results.results.hasOwnProperty(key)) { if (results.results.results[key].person_name) { @@ -68,18 +68,18 @@ export class CervicalCancerMonthlySummaryService { oncologyReportsService .getPatientListCols( reportParams.indicators, - "cad71628-692c-4d8f-8dac-b2e20bece27f" + 'cad71628-692c-4d8f-8dac-b2e20bece27f' ) - .then(patientListCols => { - results["patientListCols"] = patientListCols; + .then((patientListCols) => { + results['patientListCols'] = patientListCols; resolve(results); }) - .catch(error => { - console.error("ERROR: Error getting patient list cols", error); + .catch((error) => { + console.error('ERROR: Error getting patient list cols', error); reject(error); }); - }).catch(errors => { - console.error("Error", errors); + }).catch((errors) => { + console.error('Error', errors); reject(errors); }); }); diff --git a/service/clinical-art-overview.service.js b/service/clinical-art-overview.service.js index 82a0c35e8..e4a0596e4 100755 --- a/service/clinical-art-overview.service.js +++ b/service/clinical-art-overview.service.js @@ -1,47 +1,45 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report'; -import { - PatientlistMysqlReport -} from '../app/reporting-framework/patientlist-mysql.report'; +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; export class clinicalArtOverviewService { - - getAggregateReport(reportParams) { - let self = this; - let report = new BaseMysqlReport('clinicalArtOverviewAggregeate', reportParams) - Promise.join(report.generateReport(), - (result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - //TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - } - getPatientListReport(reportParams) { - let self = this; - let indicators = reportParams.indicator.split(','); - let report = new PatientlistMysqlReport('clinicalArtOverviewAggregeate', reportParams) - return new Promise(function (resolve, reject) { - //TODO: Do some pre processing - Promise.join(report.generatePatientListReport(indicators), - (result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - }).catch((errors) => { - reject(errors); - }); - }); - - } -} \ No newline at end of file + getAggregateReport(reportParams) { + let self = this; + let report = new BaseMysqlReport( + 'clinicalArtOverviewAggregeate', + reportParams + ); + Promise.join(report.generateReport(), (result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + //TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + } + getPatientListReport(reportParams) { + let self = this; + let indicators = reportParams.indicator.split(','); + let report = new PatientlistMysqlReport( + 'clinicalArtOverviewAggregeate', + reportParams + ); + return new Promise(function (resolve, reject) { + //TODO: Do some pre processing + Promise.join(report.generatePatientListReport(indicators), (result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + }).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/clinical-patient-care-status-overview.js b/service/clinical-patient-care-status-overview.js index 72a12e3be..50f37e54e 100755 --- a/service/clinical-patient-care-status-overview.js +++ b/service/clinical-patient-care-status-overview.js @@ -1,32 +1,29 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); export class clinicalPatientCareStatusOverviewService { - - getAggregateReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - Promise.join(dao.runReport(reportParams), - (results) => { - resolve(results); - //TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - }); - } - getPatientListReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - //TODO: Do some pre processing - Promise.join(dao.getPatientListReport(reportParams), - (results) => { - resolve(results); - }).catch((errors) => { - reject(errors); - }); - }); - } -} \ No newline at end of file + getAggregateReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + Promise.join(dao.runReport(reportParams), (results) => { + resolve(results); + //TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + }); + } + getPatientListReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + //TODO: Do some pre processing + Promise.join(dao.getPatientListReport(reportParams), (results) => { + resolve(results); + }).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/cohort-user.service.js b/service/cohort-user.service.js index b9e7cb111..22c5e5ba6 100755 --- a/service/cohort-user.service.js +++ b/service/cohort-user.service.js @@ -1,25 +1,25 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report' +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; export class cohortUserService { - getAggregateReport(reportParams) { - let report = new BaseMysqlReport('cohortReport',reportParams.requestParams); - let self = this; - return new Promise(function (resolve, reject) { - Promise.join(report.generateReport(), - (results) => { - results.result=results.results.results; - delete results['results']; - resolve(results); - //TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - }); - } -} \ No newline at end of file + getAggregateReport(reportParams) { + let report = new BaseMysqlReport( + 'cohortReport', + reportParams.requestParams + ); + let self = this; + return new Promise(function (resolve, reject) { + Promise.join(report.generateReport(), (results) => { + results.result = results.results.results; + delete results['results']; + resolve(results); + //TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/combined-breast-cervical-cancer-monthly-summary.service.js b/service/combined-breast-cervical-cancer-monthly-summary.service.js index 82429655e..8b3c2ba46 100644 --- a/service/combined-breast-cervical-cancer-monthly-summary.service.js +++ b/service/combined-breast-cervical-cancer-monthly-summary.service.js @@ -1,35 +1,35 @@ -const Promise = require("bluebird"); -const _ = require("lodash"); -const oncologyReportsService = require("../oncology-reports/oncology-reports-service"); -import { BaseMysqlReport } from "../app/reporting-framework/base-mysql.report"; -import { PatientlistMysqlReport } from "../app/reporting-framework/patientlist-mysql.report"; +const Promise = require('bluebird'); +const _ = require('lodash'); +const oncologyReportsService = require('../oncology-reports/oncology-reports-service'); +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; import { titleCase } from '../etl-helpers'; export class CombinedBreastCervicalCancerMonthlySummary { getAggregateReport(reportParams) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { let report; - if (reportParams.requestParams.period === "daily") { + if (reportParams.requestParams.period === 'daily') { report = new BaseMysqlReport( - "combinedBreastCervicalCancerDailySummaryAggregate", + 'combinedBreastCervicalCancerDailySummaryAggregate', reportParams.requestParams ); - } else if (reportParams.requestParams.period === "monthly") { + } else if (reportParams.requestParams.period === 'monthly') { report = new BaseMysqlReport( - "combinedBreastCervicalCancerMonthlySummaryAggregate", + 'combinedBreastCervicalCancerMonthlySummaryAggregate', reportParams.requestParams ); } - Promise.join(report.generateReport(), results => { + Promise.join(report.generateReport(), (results) => { let result = results.results.results; results.size = result ? result.length : 0; results.result = result; - delete results["results"]; + delete results['results']; resolve(results); // TODO Do some post processing - }).catch(errors => { + }).catch((errors) => { reject(errors); }); }); @@ -37,27 +37,27 @@ export class CombinedBreastCervicalCancerMonthlySummary { getPatientListReport(reportParams) { let indicators = reportParams.indicators - ? reportParams.indicators.split(",") + ? reportParams.indicators.split(',') : []; if (reportParams.locationUuids) { let locationUuids = reportParams.locationUuids - ? reportParams.locationUuids.split(",") + ? reportParams.locationUuids.split(',') : []; reportParams.locationUuids = locationUuids; } if (reportParams.genders) { - let genders = reportParams.genders ? reportParams.genders.split(",") : []; + let genders = reportParams.genders ? reportParams.genders.split(',') : []; reportParams.genders = genders; } let report = new PatientlistMysqlReport( - "combinedBreastCervicalCancerMonthlySummaryAggregate", + 'combinedBreastCervicalCancerMonthlySummaryAggregate', reportParams ); - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { // TODO: Do some pre processing - Promise.join(report.generatePatientListReport(indicators), results => { + Promise.join(report.generatePatientListReport(indicators), (results) => { for (const key in results.results.results) { if (results.results.results.hasOwnProperty(key)) { if (results.results.results[key].person_name) { @@ -70,29 +70,29 @@ export class CombinedBreastCervicalCancerMonthlySummary { oncologyReportsService .getPatientListCols( reportParams.indicators, - "b2837614-e144-4bec-abc2-e9f5e3116bb9" + 'b2837614-e144-4bec-abc2-e9f5e3116bb9' ) - .then(patientListCols => { + .then((patientListCols) => { if ( - reportParams.indicators === "total_breast_and_cervical_screened" + reportParams.indicators === 'total_breast_and_cervical_screened' ) { let data = results.results.results; - _.remove(data, element => { + _.remove(data, (element) => { return ( element.fbcs_person_id === null || element.fccs_person_id === null ); }); } - results["patientListCols"] = patientListCols; + results['patientListCols'] = patientListCols; resolve(results); }) - .catch(error => { - console.error("ERROR: Error getting patient list cols", error); + .catch((error) => { + console.error('ERROR: Error getting patient list cols', error); reject(error); }); - }).catch(errors => { - console.error("Error", errors); + }).catch((errors) => { + console.error('Error', errors); reject(errors); }); }); diff --git a/service/eid.service.js b/service/eid.service.js index 7bb934afe..b186aff0c 100755 --- a/service/eid.service.js +++ b/service/eid.service.js @@ -1,24 +1,25 @@ /*jshint -W003, -W097, -W117, -W026 */ 'use strict'; -var - Promise = require('bluebird') - , _ = require('underscore') - , http = require('http') - , https = require('https') - , Promise = require('bluebird') - , rp = require('../request-config') - , config = require('../conf/config') - , moment = require('moment') - , comparison = require('../eid-obs-compare') - , obsService = require('./openmrs-rest/obs.service') - , patientService = require('./openmrs-rest/patient.service') - , etlLogger = require('../etl-file-logger') - , db = require('../etl-db') - , curl = require('curlrequest') - , eidResultsSchema = require('../eid-lab-results'); - - var logger = etlLogger.logger(config.logging.eidPath + '/' + config.logging.eidFile); +var Promise = require('bluebird'), + _ = require('underscore'), + http = require('http'), + https = require('https'), + Promise = require('bluebird'), + rp = require('../request-config'), + config = require('../conf/config'), + moment = require('moment'), + comparison = require('../eid-obs-compare'), + obsService = require('./openmrs-rest/obs.service'), + patientService = require('./openmrs-rest/patient.service'), + etlLogger = require('../etl-file-logger'), + db = require('../etl-db'), + curl = require('curlrequest'), + eidResultsSchema = require('../eid-lab-results'); + +var logger = etlLogger.logger( + config.logging.eidPath + '/' + config.logging.eidFile +); var definition = { getSynchronizedPatientLabResults: getSynchronizedPatientLabResults, @@ -47,8 +48,8 @@ module.exports = definition; function getPatientIdentifiersFromEIDResults(startDate, endDate) { return new Promise(function (resolve, reject) { - - definition.getAllEidResultsFromAllSites(startDate, endDate) + definition + .getAllEidResultsFromAllSites(startDate, endDate) .then(function (labResults) { var ids = _extractPatientIdentifiersFromResults(labResults); @@ -57,42 +58,48 @@ function getPatientIdentifiersFromEIDResults(startDate, endDate) { .catch(function (error) { reject(error); }); - }); } -function getPatientIdentifiersWithEidResultsByType(host, apikey, startDate, endDate, fetchingFunc) { - +function getPatientIdentifiersWithEidResultsByType( + host, + apikey, + startDate, + endDate, + fetchingFunc +) { var results = { patientIdentifiers: [] }; return new Promise(function (resolve, reject) { - - definition.getAllEidResultsByType(host, apikey, startDate, endDate, fetchingFunc) + definition + .getAllEidResultsByType(host, apikey, startDate, endDate, fetchingFunc) .then(function (response) { - results.patientIdentifiers = _extractPatientIdentifiersFromResults([{ + results.patientIdentifiers = _extractPatientIdentifiersFromResults([ + { viralLoad: response - }]); - resolve(results); + } + ]); + resolve(results); }) .catch(function (error) { results.error = error; results.host = host; reject(results); }); - }); } function getPatientsWithEidResults(startDate, endDate) { return new Promise(function (resolve, reject) { - - definition.getAllEidResultsFromAllSites(startDate, endDate) + definition + .getAllEidResultsFromAllSites(startDate, endDate) .then(function (labResults) { var ids = _extractPatientIdentifiersFromResults(labResults); - patientService.getPatientUuidsByIdentifiers(ids) + patientService + .getPatientUuidsByIdentifiers(ids) .then(function (patientUuids) { var uuids = []; _.each(patientUuids, function (patient) { @@ -110,7 +117,6 @@ function getPatientsWithEidResults(startDate, endDate) { .catch(function (error) { reject(error); }); - }); } @@ -125,12 +131,9 @@ function _extractPatientIdentifiersFromResults(labResults) { if (result.viralLoad) allResults = allResults.concat(result.viralLoad.posts); - if (result.cd4) - allResults = allResults.concat(result.cd4.posts); - - if (result.dnaPcr) - allResults = allResults.concat(result.dnaPcr.posts); + if (result.cd4) allResults = allResults.concat(result.cd4.posts); + if (result.dnaPcr) allResults = allResults.concat(result.dnaPcr.posts); }); _.each(allResults, function (result) { @@ -148,42 +151,45 @@ function _extractPatientIdentifiersFromResults(labResults) { function getAllEidResultsFromAllSites(startDate, endDate) { return new Promise(function (resolve, reject) { - definition.getAvailableLabServers() + definition + .getAvailableLabServers() .then(function (servers) { var resultsByLab = []; - Promise.reduce(servers, function (previousServer, server) { - return new Promise(function (resolve, reject) { - - definition.getAllEidResults(server, startDate, endDate) - .then(function (response) { - response.lab = server.name; - resultsByLab.push(response); - resolve(resultsByLab); - }) - .catch(function (error) { - // catch errors and continue - var response = { - lab: server.name, - error: error - }; - - resultsByLab.push(response); - resolve(resultsByLab); - }); - }); - - }, 0) + Promise.reduce( + servers, + function (previousServer, server) { + return new Promise(function (resolve, reject) { + definition + .getAllEidResults(server, startDate, endDate) + .then(function (response) { + response.lab = server.name; + resultsByLab.push(response); + resolve(resultsByLab); + }) + .catch(function (error) { + // catch errors and continue + var response = { + lab: server.name, + error: error + }; + + resultsByLab.push(response); + resolve(resultsByLab); + }); + }); + }, + 0 + ) .then(function (results) { resolve(results); }) .catch(function (error) { reject(error); }); - }) .catch(function (error) { reject(error); - }) + }); }); } @@ -195,17 +201,32 @@ function getAllEidResults(server, startDate, endDate) { }; return new Promise(function (resolve, reject) { - _getEidResultsPerTypeDisregardingErrors(server.host, server.generalApiKey, startDate, endDate, - definition.getEidViralLoadResults) + _getEidResultsPerTypeDisregardingErrors( + server.host, + server.generalApiKey, + startDate, + endDate, + definition.getEidViralLoadResults + ) .then(function (viralLoad) { results.viralLoad = viralLoad; - return _getEidResultsPerTypeDisregardingErrors(server.host, server.cd4ApiKey, startDate, endDate, - definition.getEidCD4Results); + return _getEidResultsPerTypeDisregardingErrors( + server.host, + server.cd4ApiKey, + startDate, + endDate, + definition.getEidCD4Results + ); }) .then(function (cd4) { results.cd4 = cd4; - return _getEidResultsPerTypeDisregardingErrors(server.host, server.generalApiKey, startDate, endDate, - definition.getEidDnaPcrResults); + return _getEidResultsPerTypeDisregardingErrors( + server.host, + server.generalApiKey, + startDate, + endDate, + definition.getEidDnaPcrResults + ); }) .then(function (dnaPcr) { results.dnaPcr = dnaPcr; @@ -214,8 +235,13 @@ function getAllEidResults(server, startDate, endDate) { }); } -function _getEidResultsPerTypeDisregardingErrors(host, apikey, startDate, endDate, - fetchingFunc) { +function _getEidResultsPerTypeDisregardingErrors( + host, + apikey, + startDate, + endDate, + fetchingFunc +) { return new Promise(function (resolve, reject) { getAllEidResultsByType(host, apikey, startDate, endDate, fetchingFunc) .then(function (response) { @@ -227,25 +253,58 @@ function _getEidResultsPerTypeDisregardingErrors(host, apikey, startDate, endDat }); } -function getAllEidResultsByType(host, apikey, startDate, endDate, fetchingFunc) { +function getAllEidResultsByType( + host, + apikey, + startDate, + endDate, + fetchingFunc +) { var page = 0; var results = { posts: [] }; return new Promise(function (resolve, reject) { - _increamentPageAndGetAllEidResultsByType(host, apikey, startDate, endDate, fetchingFunc, - page, results, resolve, reject); + _increamentPageAndGetAllEidResultsByType( + host, + apikey, + startDate, + endDate, + fetchingFunc, + page, + results, + resolve, + reject + ); }); } -function _getAllEidResultsByType(host, apiKey, startDate, endDate, fetchingFunc, - page, results, finalResolve, reject) { +function _getAllEidResultsByType( + host, + apiKey, + startDate, + endDate, + fetchingFunc, + page, + results, + finalResolve, + reject +) { fetchingFunc(host, apiKey, startDate, endDate, page) .then(function (response) { if (response.posts.length > 0 && page <= 100) { results.posts = results.posts.concat(response.posts); - _increamentPageAndGetAllEidResultsByType(host, apiKey, startDate, endDate, fetchingFunc, - page, results, finalResolve, reject); + _increamentPageAndGetAllEidResultsByType( + host, + apiKey, + startDate, + endDate, + fetchingFunc, + page, + results, + finalResolve, + reject + ); } else { finalResolve(results); } @@ -255,11 +314,29 @@ function _getAllEidResultsByType(host, apiKey, startDate, endDate, fetchingFunc, }); } -function _increamentPageAndGetAllEidResultsByType(host, apiKey, startDate, endDate, - fetchingFunc, page, results, finalResolve, reject) { +function _increamentPageAndGetAllEidResultsByType( + host, + apiKey, + startDate, + endDate, + fetchingFunc, + page, + results, + finalResolve, + reject +) { page = page + 1; - _getAllEidResultsByType(host, apiKey, startDate, endDate, - fetchingFunc, page, results, finalResolve, reject); + _getAllEidResultsByType( + host, + apiKey, + startDate, + endDate, + fetchingFunc, + page, + results, + finalResolve, + reject + ); } function getEidViralLoadResults(host, apiKey, startDate, endDate, page) { @@ -270,7 +347,7 @@ function getEidViralLoadResults(host, apiKey, startDate, endDate, page) { if (!moment(startDate).isValid()) { reject('Invalid start date supplied', startDate); - } + } if (!moment(endDate).isValid()) { reject('Invalid end date supplied', endDate); @@ -288,10 +365,9 @@ function getEidViralLoadResults(host, apiKey, startDate, endDate, page) { console.log('Querying EID', host); }) .catch(function (error) { - console.log('Error querying EID', host, error); + console.log('Error querying EID', host, error); reject(error); }); - }); } @@ -323,7 +399,6 @@ function getEidDnaPcrResults(host, apiKey, startDate, endDate, page) { .catch(function (error) { reject(error); }); - }); } @@ -358,90 +433,89 @@ function getEidCD4Results(host, apiKey, startDate, endDate, page) { .catch(function (error) { reject(error); }); - }); } function listReachableServers(filter_locations) { - var locations = config.eid.locations; var reachable_servers = []; var port = config.eid.port; - return Promise.reduce(locations, function (previous, row) { - - return new Promise(function (resolve, reject) { - - var url = row.host + '/' + port + '/eid/orders/api.php' - - curl.request({ url: url, pretend: true }, function (err, stdout, meta) { - - if (err) { - resolve(reachable_servers); - } else { - - if (filter_locations && filter_locations.length > 0) { + return Promise.reduce( + locations, + function (previous, row) { + return new Promise(function (resolve, reject) { + var url = row.host + '/' + port + '/eid/orders/api.php'; - if (_.indexOf(filter_locations, row.name) > -1) - reachable_servers.push(row); + curl.request({ url: url, pretend: true }, function (err, stdout, meta) { + if (err) { + resolve(reachable_servers); } else { - reachable_servers.push(row); - } + if (filter_locations && filter_locations.length > 0) { + if (_.indexOf(filter_locations, row.name) > -1) + reachable_servers.push(row); + } else { + reachable_servers.push(row); + } - resolve(reachable_servers); - } + resolve(reachable_servers); + } + }); }); - }); - }, 0); + }, + 0 + ); } function getSynchronizedPatientLabResults(patientUuId, locations) { - var results = { data: [], errors: [] - } - - return listReachableServers(locations) - .then(function (reachable) { - console.log("REachable servers", reachable); - return new Promise(function (resolve, reject) { - - Promise.reduce(reachable, function (previous, row) { + }; + return listReachableServers(locations).then(function (reachable) { + console.log('REachable servers', reachable); + return new Promise(function (resolve, reject) { + Promise.reduce( + reachable, + function (previous, row) { return _getSynchronizedPatientLabResults(row, patientUuId) .then(function (obj) { results.data.push(obj); return new Promise(function (resolve, reject) { resolve(results); - }) + }); }) .catch(function (error) { - //catch errors and continue results.errors.push(error); return new Promise(function (resolve, reject) { resolve(results); - }) + }); }); - }, 0) - .then(function (data) { - resolve(results); - }).catch(function (error) { - reject(error); - }); - }) + }, + 0 + ) + .then(function (data) { + resolve(results); + }) + .catch(function (error) { + reject(error); + }); }); + }); } function _getSynchronizedPatientLabResults(server, patientUuId) { - var mergedEidResults = []; - var table = eidResultsSchema.patientLabResultsSchema.table.schema + '.' + eidResultsSchema.patientLabResultsSchema.table.tableName; + var table = + eidResultsSchema.patientLabResultsSchema.table.schema + + '.' + + eidResultsSchema.patientLabResultsSchema.table.tableName; var fields = [ { person_uuid: patientUuId, @@ -452,52 +526,57 @@ function _getSynchronizedPatientLabResults(server, patientUuId) { } ]; - return obsService.getPatientIdentifiers(patientUuId) + return obsService + .getPatientIdentifiers(patientUuId) .then(function (response) { - if(response.identifiers.length === 0) { + if (response.identifiers.length === 0) { throw new Error('Patient without identifiers!'); } return getEIDTestResultsByPatientIdentifier(response.identifiers, server); }) .then(function (testResultsResponse) { - mergedEidResults = testResultsResponse; return obsService.getPatientAllTestObsByPatientUuId(patientUuId); }) .then(function (obsResponse) { - var missingResult = comparison.findAllMissingEidResults(mergedEidResults, obsResponse); - var conflicts = - comparison.findConflictingEidAmrsViralLoadResults(mergedEidResults.viralLoad, obsResponse); + var missingResult = comparison.findAllMissingEidResults( + mergedEidResults, + obsResponse + ); + var conflicts = comparison.findConflictingEidAmrsViralLoadResults( + mergedEidResults.viralLoad, + obsResponse + ); if (conflicts.length > 0) { // console.log('conflicts', JSON.stringify(conflicts)); fields[0].conflicts = JSON.stringify(conflicts); } - console.log("posting obs to AMRS", missingResult); + console.log('posting obs to AMRS', missingResult); return obsService.postAllObsToAMRS(missingResult, patientUuId); }) .then(function (postResponse) { - fields[0].status = 0; return saveEidSyncLog(table, fields); }) .then(function () { - return new Promise(function (resolve, reject) { resolve({ uuid: patientUuId, site: server.name }); }); - }).catch(function (err) { - + }) + .catch(function (err) { return new Promise(function (resolve, reject) { - var err_msg = err.message; if (err_msg.indexOf("Object with given uuid doesn't exist") != -1) err_msg = "Object with given uuid doesn't exist"; - else if (err_msg.indexOf('Unable to convert object into response content') != -1) + else if ( + err_msg.indexOf('Unable to convert object into response content') != + -1 + ) err_msg = 'Unable to convert object into response content'; //log error @@ -526,8 +605,12 @@ function _getSynchronizedPatientLabResults(server, patientUuId) { }); } -function getTimedPendingEIDTestResultsByPatientIdentifiers(patientIdentifiers, referenceDate, server) { - return new Promise(function(resolveTestResults, rejectTestResults){ +function getTimedPendingEIDTestResultsByPatientIdentifiers( + patientIdentifiers, + referenceDate, + server +) { + return new Promise(function (resolveTestResults, rejectTestResults) { let counter = 1; const wait = setInterval(abortOnLongWait, 1000); function abortOnLongWait() { @@ -540,41 +623,52 @@ function getTimedPendingEIDTestResultsByPatientIdentifiers(patientIdentifiers, r }); } // call EID on first counter - if(counter == 1) { - getPendingEIDTestResultsByPatientIdentifiers(patientIdentifiers, referenceDate, server).then(function(result){ - clearInterval(wait); - resolveTestResults(result); - }).catch(function(err){ - clearInterval(wait); - rejectTestResults(err); - }); + if (counter == 1) { + getPendingEIDTestResultsByPatientIdentifiers( + patientIdentifiers, + referenceDate, + server + ) + .then(function (result) { + clearInterval(wait); + resolveTestResults(result); + }) + .catch(function (err) { + clearInterval(wait); + rejectTestResults(err); + }); } counter++; } }); } -function getPendingEIDTestResultsByPatientIdentifiers(patientIdentifiers, referenceDate, server) { - +function getPendingEIDTestResultsByPatientIdentifiers( + patientIdentifiers, + referenceDate, + server +) { var pending = { viralLoad: [], pcr: [], cd4Panel: [] }; - + var conf = server; - + pending[server.name] = {}; var location_name = server.name; - - var logAndGetFilteredResults = function(results) { + + var logAndGetFilteredResults = function (results) { //let _referenceDate = moment(referenceDate).format('DD-MMM-YYYY'); let complete = []; let inprocess = []; _.each(results, function (row) { logger.info('viral load result: %s', JSON.stringify(row)); if (row && row.SampleStatus) { - if (['Completed', 'Rejected', 'Complete'].indexOf(row.SampleStatus) != -1) { + if ( + ['Completed', 'Rejected', 'Complete'].indexOf(row.SampleStatus) != -1 + ) { complete.push(row); } if ('Inprocess' === row.SampleStatus) { @@ -583,43 +677,60 @@ function getPendingEIDTestResultsByPatientIdentifiers(patientIdentifiers, refere } }); // remove duplicate dates for complete and inprocess - let completeByDay = complete.length > 0 ? - _.uniq(complete, (result) => { return result.DateCollected; }) : []; - let inProcessByDay = inprocess.length > 0 ? - _.uniq(inprocess, (result) => { return result.DateCollected; }) : []; - + let completeByDay = + complete.length > 0 + ? _.uniq(complete, (result) => { + return result.DateCollected; + }) + : []; + let inProcessByDay = + inprocess.length > 0 + ? _.uniq(inprocess, (result) => { + return result.DateCollected; + }) + : []; + // check if we have a pending on same day as complete let hasInprocessAndCompleteByDay = []; - if(completeByDay.length > 0 && inProcessByDay.length> 0){ + if (completeByDay.length > 0 && inProcessByDay.length > 0) { hasInprocessAndCompleteByDay = _.filter(completeByDay, function (_row) { return _row.DateCollected === _.last(inProcessByDay).DateCollected; }); - }; - + } + return hasInprocessAndCompleteByDay.length === 0 ? inProcessByDay : []; }; - + return new Promise(function (resolve, reject) { - - getViralLoadTestResultsByPatientIdentifier(patientIdentifiers, conf.host, conf.generalApiKey) + getViralLoadTestResultsByPatientIdentifier( + patientIdentifiers, + conf.host, + conf.generalApiKey + ) .then(function (response) { if (response.posts instanceof Array) { let inProcessOnSameDay = logAndGetFilteredResults(response.posts); pending.viralLoad = inProcessOnSameDay; - } else - pending[location_name].viralLoadErrorMsg = response; - - return getPcrTestResultsByPatientIdentifier(patientIdentifiers, conf.host, conf.generalApiKey); - }).then(function (response) { - + } else pending[location_name].viralLoadErrorMsg = response; + + return getPcrTestResultsByPatientIdentifier( + patientIdentifiers, + conf.host, + conf.generalApiKey + ); + }) + .then(function (response) { if (response.posts instanceof Array) { let inProcessOnSameDay = logAndGetFilteredResults(response.posts); - pending.pcr = inProcessOnSameDay; - } else - pending[location_name].pcrErrorMsg = response; - + pending.pcr = inProcessOnSameDay; + } else pending[location_name].pcrErrorMsg = response; + if (conf.loadCd4) - return getCd4TestResultsByPatientIdentifier(patientIdentifiers, conf.host, conf.cd4ApiKey); + return getCd4TestResultsByPatientIdentifier( + patientIdentifiers, + conf.host, + conf.cd4ApiKey + ); else { return new Promise(function (resolve, reject) { resolve({ @@ -628,17 +739,16 @@ function getPendingEIDTestResultsByPatientIdentifiers(patientIdentifiers, refere }); }); } - }).then(function (response) { + }) + .then(function (response) { if (response.posts instanceof Array) { let inProcessOnSameDay = logAndGetFilteredResults(response.posts); - pending.cd4Panel = inProcessOnSameDay; - } else - pending[location_name].cd4ErrorMsg = response; - + pending.cd4Panel = inProcessOnSameDay; + } else pending[location_name].cd4ErrorMsg = response; + resolve(pending); }) .catch(function (err) { - reject({ message: err.message, results: pending, @@ -649,7 +759,6 @@ function getPendingEIDTestResultsByPatientIdentifiers(patientIdentifiers, refere } function getEIDTestResultsByPatientIdentifier(patientIdentifier, server) { - var results = { viralLoad: [], pcr: [], @@ -662,36 +771,53 @@ function getEIDTestResultsByPatientIdentifier(patientIdentifier, server) { var location_name = server.name; return new Promise(function (resolve, reject) { - - getViralLoadTestResultsByPatientIdentifier(patientIdentifier, conf.host, conf.generalApiKey) + getViralLoadTestResultsByPatientIdentifier( + patientIdentifier, + conf.host, + conf.generalApiKey + ) .then(function (response) { - if (response.posts instanceof Array) { _.each(response.posts, function (row) { logger.info('viral load result: %s', JSON.stringify(row)); - if (row && row.SampleStatus && ['Completed', 'Rejected', 'Complete'].indexOf(row.SampleStatus) != -1) { + if ( + row && + row.SampleStatus && + ['Completed', 'Rejected', 'Complete'].indexOf(row.SampleStatus) != + -1 + ) { results.viralLoad.push(row); } }); - } else - results[location_name].viralLoadErrorMsg = response; - - return getPcrTestResultsByPatientIdentifier(patientIdentifier, conf.host, conf.generalApiKey); - }).then(function (response) { + } else results[location_name].viralLoadErrorMsg = response; + return getPcrTestResultsByPatientIdentifier( + patientIdentifier, + conf.host, + conf.generalApiKey + ); + }) + .then(function (response) { if (response.posts instanceof Array) { - _.each(response.posts, function (row) { - if (row && row.SampleStatus && ['Completed', 'Rejected', 'Complete'].indexOf(row.SampleStatus) != -1) { + if ( + row && + row.SampleStatus && + ['Completed', 'Rejected', 'Complete'].indexOf(row.SampleStatus) != + -1 + ) { results.pcr.push(row); } }); - } else - results[location_name].pcrErrorMsg = response; + } else results[location_name].pcrErrorMsg = response; if (conf.loadCd4) - return getCd4TestResultsByPatientIdentifier(patientIdentifier, conf.host, conf.cd4ApiKey); + return getCd4TestResultsByPatientIdentifier( + patientIdentifier, + conf.host, + conf.cd4ApiKey + ); else { return new Promise(function (resolve, reject) { resolve({ @@ -704,18 +830,20 @@ function getEIDTestResultsByPatientIdentifier(patientIdentifier, server) { .then(function (response) { if (response.posts instanceof Array) { _.each(response.posts, function (row) { - if (row && row.SampleStatus && ['Completed', 'Rejected', 'Complete'].indexOf(row.SampleStatus) != -1) { + if ( + row && + row.SampleStatus && + ['Completed', 'Rejected', 'Complete'].indexOf(row.SampleStatus) != + -1 + ) { results.cd4Panel.push(row); } }); - - } else - results[location_name].cd4ErrorMsg = response; + } else results[location_name].cd4ErrorMsg = response; resolve(results); }) .catch(function (err) { - reject({ message: err.message, results: results, @@ -725,8 +853,11 @@ function getEIDTestResultsByPatientIdentifier(patientIdentifier, server) { }); } -function getViralLoadTestResultsByPatientIdentifier(patientIdentifier, host, key) { - +function getViralLoadTestResultsByPatientIdentifier( + patientIdentifier, + host, + key +) { var resource = definition.getResource(host, key); var queryString = resource.query; queryString.patientID = patientIdentifier; @@ -744,9 +875,12 @@ function getPcrTestResultsByPatientIdentifier(patientIdentifier, host, key) { } function getCd4TestResultsByPatientIdentifier(patientIdentifier, host, key) { - - var startDate = moment(new Date('2004-01-01')).startOf('day').format('YYYY-MM-DDTHH:mm:ss.SSSZZ'); - var endDate = moment(new Date()).startOf('day').format('YYYY-MM-DDTHH:mm:ss.SSSZZ'); + var startDate = moment(new Date('2004-01-01')) + .startOf('day') + .format('YYYY-MM-DDTHH:mm:ss.SSSZZ'); + var endDate = moment(new Date()) + .startOf('day') + .format('YYYY-MM-DDTHH:mm:ss.SSSZZ'); var resource = definition.getCd4Resource(host, key); var queryString = resource.query; @@ -757,7 +891,6 @@ function getCd4TestResultsByPatientIdentifier(patientIdentifier, host, key) { } function saveEidSyncLog(table, fields) { - return db.saveRecord(table, fields); } @@ -768,31 +901,29 @@ function updateEidSyncLog(queryParts, callback) { } function getResource(host, apiKey) { - var link = host + ':' + config.eid.port + config.eid.generalPath; var queryString = { apikey: apiKey - } + }; var resource = { uri: link, query: queryString - } + }; return resource; -}; +} function getCd4Resource(host, apiKey) { - var link = host + ':' + config.eid.port + config.eid.cd4PanelPath; var queryString = { apikey: apiKey - } + }; var resource = { uri: link, query: queryString - } + }; return resource; } diff --git a/service/eid/eid-facility-mappings.json b/service/eid/eid-facility-mappings.json index ffb1b0eff..8044527c8 100755 --- a/service/eid/eid-facility-mappings.json +++ b/service/eid/eid-facility-mappings.json @@ -1,2172 +1,2171 @@ { - "08feae7c-1352-11df-a1f1-0026b9348838": { - "mrsId": 1, - "mrsDisplay": "MTRH Module 1", - "cityVillage": "Eldoret", - "county": "", - "description": "Moi Teaching and Referral Hospital - Module 1", - "mflCode": "15204", - "eidDisplay": "" - }, - "08feb14c-1352-11df-a1f1-0026b9348838": { - "mrsId": 2, - "mrsDisplay": "Mosoriot", - "cityVillage": "", - "county": "", - "description": "Mosoriot Outpatient Center", - "mflCode": "15229", - "eidDisplay": "" - }, - "08feb2dc-1352-11df-a1f1-0026b9348838": { - "mrsId": 3, - "mrsDisplay": "Turbo", - "cityVillage": "", - "county": "Rift Valley", - "description": "Turbo heath center Clinic", - "mflCode": "15753", - "eidDisplay": "" - }, - "08feb444-1352-11df-a1f1-0026b9348838": { - "mrsId": 4, - "mrsDisplay": "Burnt Forest", - "cityVillage": "Burnt Forest", - "county": "Rift Valley", - "description": "Burnt Forest RHDC Clinic", - "mflCode": "16347", - "eidDisplay": "" - }, - "08feb5b6-1352-11df-a1f1-0026b9348838": { - "mrsId": 5, - "mrsDisplay": "Amukura", - "cityVillage": "Malaba", - "county": "Western", - "description": "Amukura Health Center", - "mflCode": "15798", - "eidDisplay": "" - }, - "08feb6b0-1352-11df-a1f1-0026b9348838": { - "mrsId": 6, - "mrsDisplay": "Naitiri", - "cityVillage": "Naitiri", - "county": "Western", - "description": "Naitiri Health center", - "mflCode": "16061", - "eidDisplay": "" - }, - "08feb7b4-1352-11df-a1f1-0026b9348838": { - "mrsId": 7, - "mrsDisplay": "Chulaimbo", - "cityVillage": "Maseno", - "county": "Nyanza", - "description": "Chulaimbo Sub-district hospital (Clinic)", - "mflCode": "13528", - "eidDisplay": "" - }, - "08feb8ae-1352-11df-a1f1-0026b9348838": { - "mrsId": 8, - "mrsDisplay": "Webuye", - "cityVillage": "Webuye", - "county": "Western", - "description": "Webuye Hospital ", - "mflCode": "16161", - "eidDisplay": "" - }, - "08feb9a8-1352-11df-a1f1-0026b9348838": { - "mrsId": 9, - "mrsDisplay": "Mt. Elgon", - "cityVillage": "", - "county": "", - "description": "Mount Elgon Clinic (Kapsokwony)", - "mflCode": "16025", - "eidDisplay": "" - }, - "08feba98-1352-11df-a1f1-0026b9348838": { - "mrsId": 10, - "mrsDisplay": "Kapenguria", - "cityVillage": "", - "county": "", - "description": "Kapenguria Clinic", - "mflCode": "19088", - "eidDisplay": "" - }, - "08febb92-1352-11df-a1f1-0026b9348838": { - "mrsId": 11, - "mrsDisplay": "Kitale", - "cityVillage": "", - "county": "", - "description": "Kitale District Hospital", - "mflCode": "14947", - "eidDisplay": "" - }, - "08febf52-1352-11df-a1f1-0026b9348838": { - "mrsId": 12, - "mrsDisplay": "Teso", - "cityVillage": "", - "county": "", - "description": "Teso Clinic", - "mflCode": "16150", - "eidDisplay": "" - }, - "08fec056-1352-11df-a1f1-0026b9348838": { - "mrsId": 13, - "mrsDisplay": "MTRH Module 2", - "cityVillage": "", - "county": "", - "description": "Moi Teaching and Referral Hospital - Module 2", - "mflCode": "15204", - "eidDisplay": "" - }, - "08fec150-1352-11df-a1f1-0026b9348838": { - "mrsId": 14, - "mrsDisplay": "MTRH Module 3", - "cityVillage": "", - "county": "", - "description": "Moi Teaching and Referral Hospital - Module 3", - "mflCode": "15204", - "eidDisplay": "" - }, - "08fec24a-1352-11df-a1f1-0026b9348838": { - "mrsId": 15, - "mrsDisplay": "MTRH Module 4", - "cityVillage": "", - "county": "", - "description": "Moi Teaching and Referral Hospital - Module 4", - "mflCode": "15204", - "eidDisplay": "" - }, - "08fec33a-1352-11df-a1f1-0026b9348838": { - "mrsId": 16, - "mrsDisplay": "Unknown", - "cityVillage": null, - "county": null, - "description": "Unknown Location", - "mflCode": "", - "eidDisplay": "" - }, - "08fec42a-1352-11df-a1f1-0026b9348838": { - "mrsId": 17, - "mrsDisplay": "Iten", - "cityVillage": null, - "county": null, - "description": "Iten Clinic", - "mflCode": "14586", - "eidDisplay": "" - }, - "08fec51a-1352-11df-a1f1-0026b9348838": { - "mrsId": 18, - "mrsDisplay": "Kabarnet", - "cityVillage": null, - "county": null, - "description": "Kabarnet Clinic", - "mflCode": "14607", - "eidDisplay": "" - }, - "08fec60a-1352-11df-a1f1-0026b9348838": { - "mrsId": 19, - "mrsDisplay": "Busia", - "cityVillage": "Busia", - "county": "Western", - "description": "Busia Clinic", - "mflCode": "15834", - "eidDisplay": "" - }, - "08fec704-1352-11df-a1f1-0026b9348838": { - "mrsId": 20, - "mrsDisplay": "Port Victoria", - "cityVillage": "Port Victoria", - "county": "Western", - "description": "Port Victoria AMPATH clinic", - "mflCode": "16091", - "eidDisplay": "" - }, - "08fec808-1352-11df-a1f1-0026b9348838": { - "mrsId": 21, - "mrsDisplay": "Non-AMPATH Site", - "cityVillage": "", - "county": "", - "description": "All clinical locations outside the AMPATH system.", - "mflCode": "", - "eidDisplay": "" - }, - "08fec916-1352-11df-a1f1-0026b9348838": { - "mrsId": 22, - "mrsDisplay": "None", - "cityVillage": "", - "county": "", - "description": "No location.", - "mflCode": "", - "eidDisplay": "" - }, - "09004e76-1352-11df-a1f1-0026b9348838": { - "mrsId": 23, - "mrsDisplay": "Khuyangu", - "cityVillage": "Khuyangu", - "county": "Western", - "description": "Khuyangu District Hospital ", - "mflCode": "15939", - "eidDisplay": "" - }, - "09004fca-1352-11df-a1f1-0026b9348838": { - "mrsId": 24, - "mrsDisplay": "Chulaimbo Module 1", - "cityVillage": "Maseno", - "county": "Nyanza", - "description": "Chulaimbo Adult Clinic", - "mflCode": "13528", - "eidDisplay": "" - }, - "090050ce-1352-11df-a1f1-0026b9348838": { - "mrsId": 25, - "mrsDisplay": "Chulaimbo Module 2", - "cityVillage": "Maseno", - "county": "Nyanza", - "description": "Chulaimbo Pediatric Clinic", - "mflCode": "13528", - "eidDisplay": "" - }, - "090051c8-1352-11df-a1f1-0026b9348838": { - "mrsId": 26, - "mrsDisplay": "Busia Module 1", - "cityVillage": "Busia", - "county": "Western", - "description": "Busia Module 1", - "mflCode": "15834", - "eidDisplay": "" - }, - "090052b8-1352-11df-a1f1-0026b9348838": { - "mrsId": 27, - "mrsDisplay": "Busia Module 2", - "cityVillage": "", - "county": "", - "description": "Busia Module 2", - "mflCode": "15834", - "eidDisplay": "" - }, - "090053b2-1352-11df-a1f1-0026b9348838": { - "mrsId": 28, - "mrsDisplay": "Ziwa", - "cityVillage": null, - "county": null, - "description": "Ziwa Clinic", - "mflCode": "15788", - "eidDisplay": "" - }, - "090054a2-1352-11df-a1f1-0026b9348838": { - "mrsId": 30, - "mrsDisplay": "Anderson", - "cityVillage": null, - "county": null, - "description": "Anderson Clinic", - "mflCode": "14203", - "eidDisplay": "" - }, - "0900559c-1352-11df-a1f1-0026b9348838": { - "mrsId": 31, - "mrsDisplay": "Uasin Gishu District Hospital", - "cityVillage": "", - "county": "", - "description": "Uasin Gishu District Hospital (DH)", - "mflCode": "15758", - "eidDisplay": "" - }, - "090056be-1352-11df-a1f1-0026b9348838": { - "mrsId": 32, - "mrsDisplay": "Eldoret Catholic Church(IDP)", - "cityVillage": "Eldoret", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "090057cc-1352-11df-a1f1-0026b9348838": { - "mrsId": 33, - "mrsDisplay": "Eldoret Police Station(IDP)", - "cityVillage": "Eldoret", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "090058e4-1352-11df-a1f1-0026b9348838": { - "mrsId": 34, - "mrsDisplay": "Majengo (Our Lady) Church(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "090059f2-1352-11df-a1f1-0026b9348838": { - "mrsId": 35, - "mrsDisplay": "Turbo Police Station", - "cityVillage": "Turbo", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09005b0a-1352-11df-a1f1-0026b9348838": { - "mrsId": 36, - "mrsDisplay": "Nakuru(IDP)", - "cityVillage": "Nakuru", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09005c0e-1352-11df-a1f1-0026b9348838": { - "mrsId": 37, - "mrsDisplay": "Nairobi(IDP)", - "cityVillage": "Nairobi", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09005d1c-1352-11df-a1f1-0026b9348838": { - "mrsId": 38, - "mrsDisplay": "Eldoret Showground(IDP)", - "cityVillage": "Eldoret", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09005e34-1352-11df-a1f1-0026b9348838": { - "mrsId": 39, - "mrsDisplay": "Yamumbi (IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09005f38-1352-11df-a1f1-0026b9348838": { - "mrsId": 40, - "mrsDisplay": "Matharu Center(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09006050-1352-11df-a1f1-0026b9348838": { - "mrsId": 41, - "mrsDisplay": "Munyaka PCEA Church(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "0900615e-1352-11df-a1f1-0026b9348838": { - "mrsId": 42, - "mrsDisplay": "Maji Mazuri(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "0900626c-1352-11df-a1f1-0026b9348838": { - "mrsId": 43, - "mrsDisplay": "Kamara(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09006370-1352-11df-a1f1-0026b9348838": { - "mrsId": 44, - "mrsDisplay": "Eldamaravine Police Station(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "0900647e-1352-11df-a1f1-0026b9348838": { - "mrsId": 45, - "mrsDisplay": "Moisbridge(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09006582-1352-11df-a1f1-0026b9348838": { - "mrsId": 46, - "mrsDisplay": "Langas police station(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09007acc-1352-11df-a1f1-0026b9348838": { - "mrsId": 47, - "mrsDisplay": "Timboroa Police Station", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09007be4-1352-11df-a1f1-0026b9348838": { - "mrsId": 48, - "mrsDisplay": "Bishop Muge(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09007ce8-1352-11df-a1f1-0026b9348838": { - "mrsId": 49, - "mrsDisplay": "Kipkenyo(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09007df6-1352-11df-a1f1-0026b9348838": { - "mrsId": 50, - "mrsDisplay": "Endebes(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09007efa-1352-11df-a1f1-0026b9348838": { - "mrsId": 51, - "mrsDisplay": "Kachibora(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09007ffe-1352-11df-a1f1-0026b9348838": { - "mrsId": 52, - "mrsDisplay": "Cherangany(IDP)", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09008102-1352-11df-a1f1-0026b9348838": { - "mrsId": 53, - "mrsDisplay": "Nzioa Scheme", - "cityVillage": "", - "county": "", - "description": "Internally Displaced AMPATH Patients", - "mflCode": "", - "eidDisplay": "" - }, - "09008206-1352-11df-a1f1-0026b9348838": { - "mrsId": 54, - "mrsDisplay": "Plateau Mission Hospital", - "cityVillage": "", - "county": "Rift valley", - "description": "Burnt Forest Satellite Clinic", - "mflCode": "15464", - "eidDisplay": "" - }, - "0900831e-1352-11df-a1f1-0026b9348838": { - "mrsId": 55, - "mrsDisplay": "Bumala A", - "cityVillage": "Bumala", - "county": "Western", - "description": "Bumala \"A\" Health Center(Busia Satellite Clinic)", - "mflCode": "15823", - "eidDisplay": "" - }, - "09008422-1352-11df-a1f1-0026b9348838": { - "mrsId": 56, - "mrsDisplay": "Eldoret Prison", - "cityVillage": null, - "county": null, - "description": "Satellite Clinic of MTRH Module 3", - "mflCode": "15204", - "eidDisplay": "" - }, - "0900851c-1352-11df-a1f1-0026b9348838": { - "mrsId": 57, - "mrsDisplay": "Kitale Prison", - "cityVillage": "", - "county": "", - "description": "Satellite Clinic of Kitale", - "mflCode": "14947", - "eidDisplay": "" - }, - "09008620-1352-11df-a1f1-0026b9348838": { - "mrsId": 58, - "mrsDisplay": "Ngeria Prison", - "cityVillage": null, - "county": null, - "description": "Satellite Clinic of MTRH Module 3", - "mflCode": "15204", - "eidDisplay": "" - }, - "0900871a-1352-11df-a1f1-0026b9348838": { - "mrsId": 59, - "mrsDisplay": "MAUTUMA", - "cityVillage": null, - "county": null, - "description": "Satellite Clinic of Turbo", - "mflCode": "16010", - "eidDisplay": "" - }, - "0900880a-1352-11df-a1f1-0026b9348838": { - "mrsId": 60, - "mrsDisplay": "Chepsaita", - "cityVillage": "Turbo", - "county": "Uasin Gishu", - "description": "Chepsaita Dispensary(Turbo Satellite Clinic)", - "mflCode": "14358", - "eidDisplay": "" - }, - "09008904-1352-11df-a1f1-0026b9348838": { - "mrsId": 61, - "mrsDisplay": "KAPTAGAT", - "cityVillage": null, - "county": null, - "description": "Satellite Clinic of Burnt Forest", - "mflCode": "16347", - "eidDisplay": "" - }, - "090089ea-1352-11df-a1f1-0026b9348838": { - "mrsId": 62, - "mrsDisplay": "KESSES", - "cityVillage": null, - "county": null, - "description": "Satellite Clinic of Burnt Forest", - "mflCode": "16347", - "eidDisplay": "" - }, - "09008ada-1352-11df-a1f1-0026b9348838": { - "mrsId": 63, - "mrsDisplay": "LUKOLIS", - "cityVillage": "Malaba", - "county": "Western", - "description": "Lukolis Dispensary(Amukura satellite clinic)", - "mflCode": "15968", - "eidDisplay": "" - }, - "09008fda-1352-11df-a1f1-0026b9348838": { - "mrsId": 64, - "mrsDisplay": "BOKOLI", - "cityVillage": "Bokoli", - "county": "Western", - "description": "Bokoli Hospital(Webuye satellite clinic)", - "mflCode": "15808", - "eidDisplay": "" - }, - "090090d4-1352-11df-a1f1-0026b9348838": { - "mrsId": 65, - "mrsDisplay": "ANGURAI", - "cityVillage": "Malaba", - "county": "Western", - "description": "Angurai Health Center(Teso satellite clinic)", - "mflCode": "15800", - "eidDisplay": "" - }, - "090091c4-1352-11df-a1f1-0026b9348838": { - "mrsId": 66, - "mrsDisplay": "Cheptais", - "cityVillage": "Cheptais", - "county": "Western", - "description": "Cheptais Sub-District Hospital(Mt. Elgon Satellite Clinic)", - "mflCode": "15855", - "eidDisplay": "" - }, - "090092b4-1352-11df-a1f1-0026b9348838": { - "mrsId": 67, - "mrsDisplay": "CHESKAKI", - "cityVillage": "", - "county": "", - "description": "Mt. Elgon Satellite Clinic", - "mflCode": "15856", - "eidDisplay": "" - }, - "0900939a-1352-11df-a1f1-0026b9348838": { - "mrsId": 68, - "mrsDisplay": "MARIGAT", - "cityVillage": null, - "county": null, - "description": "Satellite Clinic of Kabarnet", - "mflCode": "15138", - "eidDisplay": "" - }, - "0900948a-1352-11df-a1f1-0026b9348838": { - "mrsId": 69, - "mrsDisplay": "Huruma SDH", - "cityVillage": null, - "county": null, - "description": "Satellite Clinic of Uasin Gishu District Hospital", - "mflCode": "14555", - "eidDisplay": "" - }, - "0900a9ac-1352-11df-a1f1-0026b9348838": { - "mrsId": 70, - "mrsDisplay": "Pioneer Sub-District Hospital", - "cityVillage": "", - "county": "", - "description": "Satellite clinic for Mosoriot Health Centre", - "mflCode": "15463", - "eidDisplay": "" - }, - "0900aace-1352-11df-a1f1-0026b9348838": { - "mrsId": 71, - "mrsDisplay": "Mois Bridge", - "cityVillage": "", - "county": "", - "description": "Moi's Bridge Clinic", - "mflCode": "15209", - "eidDisplay": "" - }, - "0900abdc-1352-11df-a1f1-0026b9348838": { - "mrsId": 72, - "mrsDisplay": "Moi University", - "cityVillage": "Kesses", - "county": "", - "description": "Moi University Main Campus clinic", - "mflCode": "15205", - "eidDisplay": "" - }, - "0900acea-1352-11df-a1f1-0026b9348838": { - "mrsId": 73, - "mrsDisplay": "Soy", - "cityVillage": "", - "county": "", - "description": "Soy Clinic", - "mflCode": "15623", - "eidDisplay": "" - }, - "0900adee-1352-11df-a1f1-0026b9348838": { - "mrsId": 74, - "mrsDisplay": "Mihuu ", - "cityVillage": "Webuye", - "county": "Western", - "description": "Mihuu Dispensary(Webuye satellite clinic)", - "mflCode": "16161", - "eidDisplay": "" - }, - "0900aefc-1352-11df-a1f1-0026b9348838": { - "mrsId": 75, - "mrsDisplay": "Sinoko", - "cityVillage": "Misikhu", - "county": "Western", - "description": "Sinoko Dispensary(Bungoma East)", - "mflCode": "16126", - "eidDisplay": "" - }, - "0900b000-1352-11df-a1f1-0026b9348838": { - "mrsId": 76, - "mrsDisplay": "Milo", - "cityVillage": "WE", - "county": "we", - "description": "Milo Health Center (Satellite clinic to Webuye)", - "mflCode": "16161", - "eidDisplay": "" - }, - "0900b104-1352-11df-a1f1-0026b9348838": { - "mrsId": 77, - "mrsDisplay": "Moiben", - "cityVillage": "", - "county": "", - "description": "Satellite Clinic of Ziwa", - "mflCode": "15206", - "eidDisplay": "" - }, - "0900b212-1352-11df-a1f1-0026b9348838": { - "mrsId": 78, - "mrsDisplay": "Mukhobola", - "cityVillage": "", - "county": "", - "description": "Mukhobola Clinic ", - "mflCode": "16029", - "eidDisplay": "" - }, - "0900b316-1352-11df-a1f1-0026b9348838": { - "mrsId": 79, - "mrsDisplay": "Nambale", - "cityVillage": "", - "county": "", - "description": "Nambale Clinic ", - "mflCode": "16066", - "eidDisplay": "" - }, - "0900b424-1352-11df-a1f1-0026b9348838": { - "mrsId": 80, - "mrsDisplay": "MOI BARRACKS", - "cityVillage": "", - "county": "Rift valley", - "description": "Satellite Clinic of Module 3", - "mflCode": "15204", - "eidDisplay": "" - }, - "0900b532-1352-11df-a1f1-0026b9348838": { - "mrsId": 81, - "mrsDisplay": "Busia Prison", - "cityVillage": "15834", - "county": "Western", - "description": "Busia Satellite Clinic", - "mflCode": "15834", - "eidDisplay": "" - }, - "0900b636-1352-11df-a1f1-0026b9348838": { - "mrsId": 82, - "mrsDisplay": "Saboti", - "cityVillage": "", - "county": "Rift Valley", - "description": "Kitale satellite clinic", - "mflCode": "14947", - "eidDisplay": "" - }, - "0900b74e-1352-11df-a1f1-0026b9348838": { - "mrsId": 83, - "mrsDisplay": "Bumala B", - "cityVillage": "Busia", - "county": "Western", - "description": "Bumala \"B\" Health Center (Khunyangu Satellite clinic)", - "mflCode": "15824", - "eidDisplay": "" - }, - "0900b866-1352-11df-a1f1-0026b9348838": { - "mrsId": 84, - "mrsDisplay": "MOI TEACHING AND REFERRAL HOSPITAL", - "cityVillage": "", - "county": "", - "description": "Primary Health Care Clinic Location", - "mflCode": "15204", - "eidDisplay": "" - }, - "0900b974-1352-11df-a1f1-0026b9348838": { - "mrsId": 85, - "mrsDisplay": "Makutano", - "cityVillage": "", - "county": "Western", - "description": "Satellite Clinic Site for Naitiri", - "mflCode": "16061", - "eidDisplay": "" - }, - "25972cec-2e14-4047-a537-404c6ad18389": { - "mrsId": 86, - "mrsDisplay": "Kaptama (Friends) dispensary", - "cityVillage": "Kaptama", - "county": "Western", - "description": "Satellite clinic of Mount Elgon(Kapsokwony)\r\n", - "mflCode": "15925", - "eidDisplay": "" - }, - "ffb2c2f0-a62c-4be8-960a-05b704bd66cd": { - "mrsId": 87, - "mrsDisplay": "Sio Port", - "cityVillage": "", - "county": "", - "description": "Sio port", - "mflCode": "16128", - "eidDisplay": "" - }, - "1be88533-0a70-40a4-9c45-1a7a936fd23a": { - "mrsId": 88, - "mrsDisplay": "Tulwet", - "cityVillage": "Tulwet", - "county": "Rift Valley", - "description": "Satellite clinic of Kitale", - "mflCode": "14947", - "eidDisplay": "" - }, - "8d502f10-dcaf-41fc-8677-34a6b498ac7a": { - "mrsId": 89, - "mrsDisplay": "Kopsiro", - "cityVillage": "Kopsiro", - "county": "Western", - "description": "Satellite Clinic of Mt. elgon.", - "mflCode": "15956", - "eidDisplay": "" - }, - "7a8c0cc5-be43-48e1-aa41-33cb1e9cc26f": { - "mrsId": 90, - "mrsDisplay": "Changara", - "cityVillage": "Changara", - "county": "Western", - "description": "Teso Satellte Clinic", - "mflCode": "16421", - "eidDisplay": "" - }, - "cb31d052-b668-4321-80ad-c0aaa571f87b": { - "mrsId": 91, - "mrsDisplay": "Malaba", - "cityVillage": "Malaba", - "county": "Western", - "description": "Satellite clinic of Teso", - "mflCode": "15993", - "eidDisplay": "" - }, - "096ac36e-47f9-49e0-a62b-d87a09753b61": { - "mrsId": 92, - "mrsDisplay": "Amase", - "cityVillage": "Amagoro", - "county": "Western", - "description": "Amase Dispensary(Amukura satellite clinic)", - "mflCode": "15797", - "eidDisplay": "" - }, - "69d9a87d-18f2-4113-840d-95668d1e9e16": { - "mrsId": 93, - "mrsDisplay": "Obekai", - "cityVillage": "Busia", - "county": "Western", - "description": "Obekai Dispensary(Amukura satellite clinic)", - "mflCode": "16087", - "eidDisplay": "" - }, - "19874e26-f614-47bb-99c7-a3756bfe3c64": { - "mrsId": 94, - "mrsDisplay": "Tambach", - "cityVillage": "", - "county": "Rift valley", - "description": "Satellite Clinic to Iten", - "mflCode": "15703", - "eidDisplay": "" - }, - "bcc27a76-1980-4efe-b72e-ca40019ef6ce": { - "mrsId": 95, - "mrsDisplay": "Tenges", - "cityVillage": "", - "county": "Rift Valley", - "description": "Satellite clinic to Kabarnet.", - "mflCode": "15718", - "eidDisplay": "" - }, - "dba01903-14bd-4978-9264-f6ca896b0ca4": { - "mrsId": 96, - "mrsDisplay": "Kibisi", - "cityVillage": "", - "county": "Western", - "description": "Satellite clinic to Naitiri", - "mflCode": "15943", - "eidDisplay": "" - }, - "56cf9621-d946-4ac0-a587-4024792c0934": { - "mrsId": 97, - "mrsDisplay": "Sango", - "cityVillage": "", - "county": "Western", - "description": "Satellite clinic to Naitiri.", - "mflCode": "17986", - "eidDisplay": "" - }, - "65bdb112-a254-4cf9-a5a7-29dce997312d": { - "mrsId": 98, - "mrsDisplay": "AIC Diguna Royal Toto Childrens Home,Ngechek", - "cityVillage": "Mosoriot", - "county": "Riftvalley", - "description": "Mosoriot satellite clinic", - "mflCode": "15229", - "eidDisplay": "" - }, - "851d4b92-763a-4c4a-a9bc-63b12586429f": { - "mrsId": 99, - "mrsDisplay": "Lupida", - "cityVillage": "Nambale", - "county": "Western", - "description": "Nambale Satellite Clinic", - "mflCode": "15975", - "eidDisplay": "" - }, - "00b47ef5-a29b-40a2-a7f4-6851df8d6532": { - "mrsId": 100, - "mrsDisplay": "Osieko", - "cityVillage": "", - "county": "", - "description": "A satellite to Port Victoria", - "mflCode": "17680", - "eidDisplay": "" - }, - "79fcf21c-8a00-44ba-9555-dde4dd877c4a": { - "mrsId": 101, - "mrsDisplay": "Room 7", - "cityVillage": "", - "county": "", - "description": "Casualty", - "mflCode": "", - "eidDisplay": "" - }, - "6cd0b441-d644-487c-8466-5820a73f9ce5": { - "mrsId": 102, - "mrsDisplay": "Elgeyo Border", - "cityVillage": "", - "county": "", - "description": "These is a health centre ", - "mflCode": "14437", - "eidDisplay": "" - }, - "2b0419c2-275f-4354-8b49-4c97d033ecbb": { - "mrsId": 103, - "mrsDisplay": "Riat", - "cityVillage": "", - "county": "", - "description": "This is a dispensary and its Chulaimbo's Satellites", - "mflCode": "14046", - "eidDisplay": "" - }, - "01c73fdc-65ce-4349-abdf-bbc554178b47": { - "mrsId": 104, - "mrsDisplay": "Sunga", - "cityVillage": "", - "county": "", - "description": "This is a dispensary and its Chulaimbo's Satellites", - "mflCode": "17175", - "eidDisplay": "" - }, - "b5d03983-f24e-4fdc-9ff5-33fc87dee02b": { - "mrsId": 105, - "mrsDisplay": "Siriba", - "cityVillage": "", - "county": "", - "description": "This is a dispensary and its Chulaimbo's Satellites", - "mflCode": "14094", - "eidDisplay": "" - }, - "8f537fab-0b7f-4b72-a462-042eefad058c": { - "mrsId": 106, - "mrsDisplay": "Kamolo", - "cityVillage": "", - "county": "", - "description": "satelite at Kamolo Dispensary,to be run by Teso, AMPATH clinic", - "mflCode": "17242", - "eidDisplay": "" - }, - "8ce15cad-c7ff-41d9-b55c-5230116c3bf7": { - "mrsId": 107, - "mrsDisplay": "Kapteren Health Center", - "cityVillage": "", - "county": "", - "description": "A satellite of Iten Clinic", - "mflCode": "14781", - "eidDisplay": "" - }, - "27edd245-5205-4e66-82bd-d314c547d16b": { - "mrsId": 108, - "mrsDisplay": "Madende Health Center", - "cityVillage": "", - "county": "", - "description": "A satellite of Nambale", - "mflCode": "15985", - "eidDisplay": "" - }, - "e2d2926e-49e6-4a27-b701-73b6e263a4fd": { - "mrsId": 109, - "mrsDisplay": "Rai-plywood", - "cityVillage": "Huruma", - "county": "Rift Valley", - "description": "Satellite clinic to UGDH", - "mflCode": "14555", - "eidDisplay": "" - }, - "4fb82b14-c0e4-46d0-9864-a36e2d6b6c8a": { - "mrsId": 110, - "mrsDisplay": "Mogoget", - "cityVillage": "", - "county": "", - "description": "Dispensary in Kosirai Division", - "mflCode": "15194", - "eidDisplay": "" - }, - "53c7ebb2-78c2-4ce3-a504-f37a6cb998aa": { - "mrsId": 111, - "mrsDisplay": "Birbiriet", - "cityVillage": null, - "county": null, - "description": "Dispensary in Kosirai Division", - "mflCode": "14257", - "eidDisplay": "" - }, - "17cc5ee1-b702-4b4b-9ea7-9fc7083dd56e": { - "mrsId": 112, - "mrsDisplay": "Itigo", - "cityVillage": "", - "county": "", - "description": "Dispensary in Kosirai Division", - "mflCode": "14587", - "eidDisplay": "" - }, - "469471e2-5b1e-46be-9232-a738f8cd717b": { - "mrsId": 113, - "mrsDisplay": "Lelmokwo", - "cityVillage": "", - "county": "", - "description": "Dispensary in Kosirai Division", - "mflCode": "15022", - "eidDisplay": "" - }, - "8eedf128-40ed-4fba-9240-3cc92234720f": { - "mrsId": 114, - "mrsDisplay": "Kokwet", - "cityVillage": "", - "county": "", - "description": "Dispensary in Kosirai Division", - "mflCode": "14977", - "eidDisplay": "" - }, - "a30955e0-275f-48ca-974d-438368a0685a": { - "mrsId": 115, - "mrsDisplay": "Ngechek", - "cityVillage": "", - "county": "", - "description": "Dispensary in Kosirai Division", - "mflCode": "15342", - "eidDisplay": "" - }, - "96d2964e-8cec-4eca-ad05-a9c1fb29a045": { - "mrsId": 116, - "mrsDisplay": "cheramei", - "cityVillage": "", - "county": "", - "description": "Dispensary in Turbo Division", - "mflCode": "14377", - "eidDisplay": "" - }, - "2003e950-5b62-4330-a94c-cf8165f75084": { - "mrsId": 117, - "mrsDisplay": "Murgusi", - "cityVillage": "", - "county": "", - "description": "Dispensary in Turbo Division", - "mflCode": "15255", - "eidDisplay": "" - }, - "441451e5-aabd-4e71-87dd-8b7c5f651434": { - "mrsId": 118, - "mrsDisplay": "Cheplaskei", - "cityVillage": null, - "county": null, - "description": "Dispensary in Turbo Division", - "mflCode": "14354", - "eidDisplay": "" - }, - "4de54b6f-6f60-4b56-a801-087603d2f294": { - "mrsId": 119, - "mrsDisplay": "Sigot", - "cityVillage": "", - "county": "", - "description": "Dispensary in Turbo Division", - "mflCode": "15753", - "eidDisplay": "" - }, - "f030c7f2-9790-41d0-a704-f5a164909d17": { - "mrsId": 120, - "mrsDisplay": "Sugoi A", - "cityVillage": "", - "county": "", - "description": "Dispensary in Turbo Division", - "mflCode": "17331", - "eidDisplay": "" - }, - "a27cec49-110c-41a1-9a6f-964d6ac2359d": { - "mrsId": 121, - "mrsDisplay": "Sugoi B", - "cityVillage": "", - "county": "", - "description": "Dispensary in Turbo Division", - "mflCode": "15680", - "eidDisplay": "" - }, - "d09c6925-1e9a-4973-921d-d0014d7825ec": { - "mrsId": 122, - "mrsDisplay": "Chepkemel", - "cityVillage": "", - "county": "", - "description": "Dispensary in Turbo Division", - "mflCode": "14337", - "eidDisplay": "" - }, - "12aeb8ab-690c-47e0-b41f-e261dac1279c": { - "mrsId": 123, - "mrsDisplay": "Chepkemel", - "cityVillage": "", - "county": "", - "description": "Dispensary in Turbo Division", - "mflCode": "14339", - "eidDisplay": "" - }, - "eb32b031-30df-40d9-8aef-d88fbb763852": { - "mrsId": 124, - "mrsDisplay": "Akichelesit", - "cityVillage": "", - "county": "", - "description": "Dispensary in Teso Division", - "mflCode": "15792", - "eidDisplay": "" - }, - "291bdf8e-93ed-4898-a58f-7d9f7f74128e": { - "mrsId": 125, - "mrsDisplay": "Aboloi", - "cityVillage": "", - "county": "", - "description": "Dispensary in Teso Division", - "mflCode": "15789", - "eidDisplay": "" - }, - "1243cf8b-fced-482c-9d95-c92f28bfcbea": { - "mrsId": 126, - "mrsDisplay": "Moding", - "cityVillage": "", - "county": "", - "description": "Dispensary in Teso Division", - "mflCode": "16021", - "eidDisplay": "" - }, - "e8c7759a-c99a-46de-82f8-d7c9f67eb237": { - "mrsId": 127, - "mrsDisplay": "Sambut ", - "cityVillage": "", - "county": "", - "description": "Sambut - Dispensary in Turbo division", - "mflCode": "15525", - "eidDisplay": "" - }, - "00ce435c-3f27-4e89-a7f8-80fd102ff410": { - "mrsId": 128, - "mrsDisplay": "Ngenyilel", - "cityVillage": "", - "county": "", - "description": "Dispensary in Turbo division", - "mflCode": "15344", - "eidDisplay": "" - }, - "2b338894-e81d-48e9-83d5-9280c8f549d4": { - "mrsId": 129, - "mrsDisplay": "Sosiani", - "cityVillage": "", - "county": "", - "description": "Health Centre in Turbo division", - "mflCode": "15616", - "eidDisplay": "" - }, - "1d3bc503-925b-4a31-91da-337b611cc27a": { - "mrsId": 130, - "mrsDisplay": "Matayos Health Centre", - "cityVillage": "", - "county": "Western", - "description": "New site from Aphia", - "mflCode": "16004", - "eidDisplay": "" - }, - "5c8705ef-3a36-4806-a907-381232f88834": { - "mrsId": 131, - "mrsDisplay": "Chebaiywa", - "cityVillage": "", - "county": "", - "description": "Used by CDM team and their forms being entered to AMRS", - "mflCode": "17243", - "eidDisplay": "" - }, - "8bb0593f-5dca-4828-a443-53d41f040d8c": { - "mrsId": 132, - "mrsDisplay": "Kapsara Sub-district hospital", - "cityVillage": "", - "county": "", - "description": "New location in Kitale", - "mflCode": "14753", - "eidDisplay": "" - }, - "a8f5b2b9-d2f0-454b-a7aa-46a1fbca17d3": { - "mrsId": 133, - "mrsDisplay": "Chepterit ", - "cityVillage": "", - "county": "", - "description": "A dispensary in Mosoriot Division", - "mflCode": "14368", - "eidDisplay": "" - }, - "e05cbb83-9418-4ebc-9240-ae2512d70321": { - "mrsId": 134, - "mrsDisplay": "Kapyemit", - "cityVillage": "", - "county": "", - "description": "A dispensary in Turbo division and Uasin Gishu county", - "mflCode": "14799", - "eidDisplay": "" - }, - "b77f94ea-62ea-469a-8a88-5aa2d33bdaaf": { - "mrsId": 135, - "mrsDisplay": "Kaborom", - "cityVillage": "", - "county": "Western", - "description": " Dispensary - a satellite of Mt Elgon.\r\n ", - "mflCode": "15910", - "eidDisplay": "" - }, - "e2546b92-17df-4640-a38b-c4f30b0cfd81": { - "mrsId": 136, - "mrsDisplay": "Murgor Hills", - "cityVillage": "", - "county": "", - "description": "A dispensary in Turbo", - "mflCode": "15254", - "eidDisplay": "" - }, - "3e04788f-6761-412a-8db6-08a713f59afc": { - "mrsId": 137, - "mrsDisplay": "Osorongai", - "cityVillage": "", - "county": "", - "description": "A dispensary in Turbo", - "mflCode": "15449", - "eidDisplay": "" - }, - "098148c6-9ffd-4c30-9dca-c8fa26c39eaf": { - "mrsId": 138, - "mrsDisplay": "Family Health Care Otpions Kenya - Eldoret", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "16348", - "eidDisplay": "" - }, - "b0773cd5-e0c0-4cc7-8cbd-482407311b50": { - "mrsId": 139, - "mrsDisplay": "Elgon View Hospital", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "14438", - "eidDisplay": "" - }, - "dfa41633-bef8-4465-b773-8254cef7cc7f": { - "mrsId": 140, - "mrsDisplay": "Cedar Clinical Associates", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "14280", - "eidDisplay": "" - }, - "2f4c8dde-1bc1-4224-9e1e-a4d915e74210": { - "mrsId": 141, - "mrsDisplay": "Glory health centre and Chemists", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "", - "eidDisplay": "" - }, - "22ef1733-f776-4d04-bf5d-2e0c48fe3ca5": { - "mrsId": 142, - "mrsDisplay": "Amani Health Centre", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "", - "eidDisplay": "" - }, - "d29bad2f-0b89-402f-835e-4e37c7d9334a": { - "mrsId": 143, - "mrsDisplay": "Gynocare Health Centre", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "19205", - "eidDisplay": "" - }, - "f83a6fbc-ad66-491e-82d3-72155661c498": { - "mrsId": 144, - "mrsDisplay": "St. Marys Health Centre - Kapsoya", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "15655", - "eidDisplay": "" - }, - "f4121927-e8ac-46d1-8b7d-fa6d9adcb677": { - "mrsId": 145, - "mrsDisplay": "SOS Medical Centre - Eldoret", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "17945", - "eidDisplay": "" - }, - "b99d3714-9715-484e-8ad9-bf0ada16fdf4": { - "mrsId": 146, - "mrsDisplay": "Imani Hospital ", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "16357", - "eidDisplay": "" - }, - "f6d67dad-cdf4-4756-82c8-cb34d1eecc3a": { - "mrsId": 147, - "mrsDisplay": "Fountain Health Centre", - "cityVillage": "Eldoret", - "county": "", - "description": "Private Hospital in Eldoret", - "mflCode": "19173", - "eidDisplay": "" - }, - "294efcca-cf90-40da-8abb-1e082866388d": { - "mrsId": 148, - "mrsDisplay": "St. Luke", - "cityVillage": null, - "county": null, - "description": "A Private Hospital in Eldoret", - "mflCode": "18776", - "eidDisplay": "" - }, - "8f1c7aca-97e5-4cca-be46-21969abde1c8": { - "mrsId": 149, - "mrsDisplay": "EldoretHosp", - "cityVillage": null, - "county": null, - "description": "A private hospital in Eldoret.", - "mflCode": "14435", - "eidDisplay": "" - }, - "717758f6-8dec-443e-bf1c-ca0bf8a5ec6d": { - "mrsId": 150, - "mrsDisplay": "Sisenye Dispensary", - "cityVillage": null, - "county": null, - "description": "Dispensary in Bunyala sub-county", - "mflCode": "16131", - "eidDisplay": "" - }, - "fece02d9-b3cd-4eaf-802f-8ad33ace4c30": { - "mrsId": 151, - "mrsDisplay": "Rukala Dispensary", - "cityVillage": null, - "county": null, - "description": "Dispensary in Bunyala Sub-County.", - "mflCode": "16095", - "eidDisplay": "" - }, - "68df53ea-d990-4769-ae2d-34ec85218325": { - "mrsId": 152, - "mrsDisplay": "Budalangi Dispensary", - "cityVillage": null, - "county": null, - "description": "A dispensary in Bunyala Sub-county", - "mflCode": "15811", - "eidDisplay": "" - }, - "0c2b5af9-43e1-4182-9292-59f499d23c9c": { - "mrsId": 153, - "mrsDisplay": "Reale Hospital", - "cityVillage": "Eldoret", - "county": "Uasin-Gishu", - "description": "Private Hospital in Eldoret\r\nunder the Private Sector Engagement program\r\n(formally PPP)", - "mflCode": "18983", - "eidDisplay": "" - }, - "402e0744-82be-4784-bb6e-e5a30d1055cf": { - "mrsId": 154, - "mrsDisplay": "sokyot", - "cityVillage": "Kosachei", - "county": "Uasin Gishu", - "description": "A community based in Turbo", - "mflCode": "", - "eidDisplay": "" - }, - "3824461a-1289-4108-b5b0-98f0f6f8f509": { - "mrsId": 155, - "mrsDisplay": "Turbo/Kaptebee", - "cityVillage": null, - "county": "UasinGishu", - "description": "A community in Turbo", - "mflCode": "15753", - "eidDisplay": "" - }, - "ac339ab6-49e3-4b33-949d-505358797d5a": { - "mrsId": 156, - "mrsDisplay": "Ngechek", - "cityVillage": "kapngetich", - "county": "Nandi", - "description": "A community In Kosirai Division", - "mflCode": "15342", - "eidDisplay": "" - }, - "8bfe3e63-ce86-4d5b-b3ae-b9ec13628530": { - "mrsId": 157, - "mrsDisplay": "Tuigoin", - "cityVillage": "Suigoi", - "county": "Uasin Gishu", - "description": "A community Unit in Turbo Division", - "mflCode": "", - "eidDisplay": "" - }, - "825a2541-49ff-41b5-b267-7ff0a059f290": { - "mrsId": 158, - "mrsDisplay": "Leseru", - "cityVillage": "Chemalal", - "county": "Uasin Gishu", - "description": "A community Unit in Turbo Division", - "mflCode": "", - "eidDisplay": "" - }, - "1dc7a1c9-e553-48a9-8a1e-e97b18a480c5": { - "mrsId": 159, - "mrsDisplay": "Kosirai", - "cityVillage": "Belekenya", - "county": "Nandi", - "description": "A community Unit in Kosirai Division", - "mflCode": "", - "eidDisplay": "" - }, - "52645ed9-c8c4-4912-b66a-a05b201ddb5f": { - "mrsId": 160, - "mrsDisplay": "Mutwot", - "cityVillage": "Mutwot Village", - "county": "Nandi", - "description": "A Community unit in Kosirai Division", - "mflCode": "", - "eidDisplay": "" - }, - "a4001a80-ac34-4a6f-a7fd-80d689f2b18b": { - "mrsId": 161, - "mrsDisplay": "Laikipia", - "cityVillage": null, - "county": "Laikipia", - "description": "An amrs site in Laikipia County", - "mflCode": "", - "eidDisplay": "" - }, - "25ff6c5b-d46d-4d8c-bf4c-dae135efa70b": { - "mrsId": 162, - "mrsDisplay": "Sirimba Mission Hospital", - "cityVillage": null, - "county": "Busia", - "description": "A health Facility in Busia County", - "mflCode": "16129", - "eidDisplay": "" - }, - "cf044cde-d23b-4bf2-a152-e83a0e9a2288": { - "mrsId": 163, - "mrsDisplay": "Nasewa Health Centre", - "cityVillage": null, - "county": "Busia", - "description": "A Health Facility in Nasewa", - "mflCode": "16074", - "eidDisplay": "" - }, - "751a05f1-6889-48ec-911b-d626ac02d9cd": { - "mrsId": 164, - "mrsDisplay": "Mabunge", - "cityVillage": null, - "county": "Busia", - "description": "A community unit in Nasewa", - "mflCode": "Mabunge", - "eidDisplay": "" - }, - "f7896a4a-2348-4493-ac02-0772255f49f6": { - "mrsId": 165, - "mrsDisplay": "Buyama", - "cityVillage": null, - "county": "Busia", - "description": "A community unit in Nasewa", - "mflCode": "Buyama", - "eidDisplay": "" - }, - "356f3aaa-bd92-4823-a602-33ea6efe44d4": { - "mrsId": 166, - "mrsDisplay": "Lung'a", - "cityVillage": null, - "county": "Busia", - "description": "A community unit in Nasewa", - "mflCode": "16074", - "eidDisplay": "" - }, - "eb85f1ae-6d39-4929-bd99-2002f4eb96a8": { - "mrsId": 167, - "mrsDisplay": "Nasewa", - "cityVillage": null, - "county": "Busia", - "description": "A community unit in Nasewa", - "mflCode": "16074", - "eidDisplay": "" - }, - "97157544-80c4-469d-b7bc-92e3053ded8e": { - "mrsId": 168, - "mrsDisplay": "Sikarira Dispensary", - "cityVillage": null, - "county": "Busia", - "description": "A health facility in Sikarira", - "mflCode": "16485", - "eidDisplay": "" - }, - "a49aa7a3-c5ae-4c7a-a6a0-3b9e5ba60522": { - "mrsId": 169, - "mrsDisplay": "Bulwani", - "cityVillage": null, - "county": "Busia", - "description": "A Community Unit in Bwaliro", - "mflCode": "15822", - "eidDisplay": "" - }, - "b940a5af-07ce-4fb0-ae5c-3271943c8ce1": { - "mrsId": 170, - "mrsDisplay": "Kanjala", - "cityVillage": null, - "county": "Busia", - "description": "A community unit in Sikarira", - "mflCode": "16485", - "eidDisplay": "" - }, - "1e92054b-9aed-42b7-b358-95cd311f98e2": { - "mrsId": 171, - "mrsDisplay": "Sirimba Mission Hospital", - "cityVillage": null, - "county": "Busia", - "description": "A health Facility in Busia County", - "mflCode": "16129", - "eidDisplay": "" - }, - "8d2265b4-d311-4a92-a792-2097d22ac174": { - "mrsId": 172, - "mrsDisplay": "Ruambwa", - "cityVillage": null, - "county": "Busia", - "description": "A community unit in Sirimba", - "mflCode": "16129", - "eidDisplay": "" - }, - "7f95db31-e91b-4753-8b92-1d52aa9b4abf": { - "mrsId": 173, - "mrsDisplay": "Ikonzo Dispensary", - "cityVillage": null, - "county": "Busia", - "description": "A Health Facility in Busia", - "mflCode": "17165", - "eidDisplay": "" - }, - "c88683c8-988c-4580-afaa-c2909597f758": { - "mrsId": 174, - "mrsDisplay": "Namwitsula", - "cityVillage": null, - "county": "Busia", - "description": "A community unit in Ikonzo", - "mflCode": "17165", - "eidDisplay": "" - }, - "57e7d161-13da-464f-a7b5-bffbade5b2de": { - "mrsId": 175, - "mrsDisplay": "Ikonzo", - "cityVillage": null, - "county": "Busia", - "description": "A community Unit in Ikonzo", - "mflCode": "17165", - "eidDisplay": "" - }, - "d83e9d9e-8211-414d-8269-7b9308184b82": { - "mrsId": 176, - "mrsDisplay": "West Clinic Health Centre", - "cityVillage": null, - "county": "Uasin Gishu", - "description": "A health facility in Uasin Gishu", - "mflCode": "", - "eidDisplay": "" - }, - "d332cd41-99d5-47bb-baab-0b61a59aadc2": { - "mrsId": 177, - "mrsDisplay": "Kibulgeng", - "cityVillage": null, - "county": "Uasin Gihu", - "description": "A community facility in Uasin Gishu", - "mflCode": "", - "eidDisplay": "" - }, - "b35dfc65-80f8-41fa-9932-cd347edd346d": { - "mrsId": 178, - "mrsDisplay": "Bujumba Dispensary", - "cityVillage": null, - "county": "Busia", - "description": "Is a health Facility in Bujumba", - "mflCode": "15816", - "eidDisplay": "" - }, - "1646cb1f-2e3c-4ca3-9157-a4ad2f67fe38": { - "mrsId": 179, - "mrsDisplay": "Bujumba", - "cityVillage": null, - "county": "Busia", - "description": "Is a community Facility in Bujumba", - "mflCode": "15816", - "eidDisplay": "" - }, - "956794fa-2193-4ff6-bad1-65b947d0faa3": { - "mrsId": 183, - "mrsDisplay": "Ikonzo Dispensary", - "cityVillage": null, - "county": "Busia", - "description": "A dispensary in Busia", - "mflCode": "17165", - "eidDisplay": "" - }, - "49066b8b-2b9a-43cf-b3e4-18d3759ecd00": { - "mrsId": 184, - "mrsDisplay": "Ikonzo Dispensary", - "cityVillage": null, - "county": "Busia", - "description": "A dispensary in Busia", - "mflCode": "17165", - "eidDisplay": "" - }, - "cb0a7e64-dd5d-4c46-9cb3-c382d95e9c50": { - "mrsId": 185, - "mrsDisplay": "Sikarira", - "cityVillage": null, - "county": "Busia", - "description": "A community unit in Ikonzo", - "mflCode": "16485", - "eidDisplay": "" - }, - "e155b8b0-e89d-4916-8b6c-3af9d93b582b": { - "mrsId": 186, - "mrsDisplay": "MTRH-Memorial Hospital", - "cityVillage": null, - "county": "Uasin Gishu", - "description": "PPP Clinic", - "mflCode": "15204", - "eidDisplay": "" - }, - "e02b0e78-4312-4006-9e39-0994a759acb2": { - "mrsId": 187, - "mrsDisplay": "Chep'ngoror Dispensary", - "cityVillage": null, - "county": "A dispensary in Burnt forest", - "description": "A dispensary in Burnt Forest", - "mflCode": "16347", - "eidDisplay": "" - }, - "659f2926-4712-4bd9-a532-7c1b20a0d47b": { - "mrsId": 188, - "mrsDisplay": "Matunda Health Centre", - "cityVillage": null, - "county": "Uasin Gishu", - "description": "A community unit in Matunda", - "mflCode": "16364", - "eidDisplay": "" - }, - "f8bf061a-8ef2-4145-9522-03e642d23eaf": { - "mrsId": 189, - "mrsDisplay": "Endebes Health Centre", - "cityVillage": null, - "county": "trans nzoia", - "description": "A Health Centre in Trans nzoia", - "mflCode": "14455", - "eidDisplay": "" - }, - "67001f34-4df1-4cfa-8552-04d5236dd3a3": { - "mrsId": 190, - "mrsDisplay": "Kwanza Health Centre", - "cityVillage": null, - "county": "Trans-Nzoia", - "description": "A Health Facility in Trans Nzoia", - "mflCode": "15003", - "eidDisplay": "" - }, - "4dbd0c2b-cb9f-491a-8dbc-c4e552db1515": { - "mrsId": 191, - "mrsDisplay": "Anderson", - "cityVillage": null, - "county": "Transzoia", - "description": "A health centre in transzoia", - "mflCode": "", - "eidDisplay": "" - }, - "b56b5219-0c8f-4520-810e-ba43302c63eb": { - "mrsId": 192, - "mrsDisplay": "Kapsoya Health Centre", - "cityVillage": null, - "county": "Uasin Gishu", - "description": "A health centre in Kapsoya", - "mflCode": "14769", - "eidDisplay": "" - }, - "c8ede412-a5da-47be-ae7f-f76a4ffc5065": { - "mrsId": 193, - "mrsDisplay": "Sister Freda Medical", - "cityVillage": "Kitale", - "county": "Trans Nzoia", - "description": "A Health facility in Trans Nzoia", - "mflCode": "14947", - "eidDisplay": "" - }, - "b3bf1ec7-ea9c-4bc6-af5b-ddb6864b7975": { - "mrsId": 194, - "mrsDisplay": "St. Ladislaus Dispensary", - "cityVillage": null, - "county": "Uasin Gishu", - "description": "A health facility in Uasin Gishu County", - "mflCode": "16345", - "eidDisplay": "" - }, - "18c343eb-b353-462a-9139-b16606e6b6c2": { - "mrsId": 195, - "mrsDisplay": "Location Test", - "cityVillage": null, - "county": "test", - "description": "This is a test location for POC Testers.", - "mflCode": "15204", - "eidDisplay": "" - }, - "10446739-2ef2-4fb3-b134-29840d97acbe": { - "mrsId": 198, - "mrsDisplay": "MTRH Adolescent Clinic", - "cityVillage": "Eldoret", - "county": "", - "description": "Moi Teaching and Referral Hospital Adolescent Clinic.", - "mflCode": "15204", - "eidDisplay": "" - }, - "af0d01d4-7c15-491d-be73-50512ab67e3a":{ - "mrsId": 211, - "mrsDisplay": "Alphima Medical Clinic", - "cityVillage": "Eldoret", - "county": "", - "description": "A Private Hospital in Eldoret.", - "mflCode": "23646", - "eidDisplay": "" - }, - "538c14c2-c98a-49a2-9e11-0af6f7b912dc":{ - "mrsId": 196, - "mrsDisplay": "Mediheal Hospital", - "cityVillage": "Eldoret", - "county": "", - "description": "A ppp Clinic in Eldoret", - "mflCode": "15167", - "eidDisplay": "" - - }, - "02e85257-94d6-43bf-8603-322248c1a210": { - "mrsId": 197, - "mrsDisplay": "MTRH MCH", - "description": "Used to collect PMTCT data.", - "mflCode": "15204", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "4ff7f723-95ce-4481-ba47-6539f22aae3c": { - "mrsId": 199, - "mrsDisplay": "MTRH Nyayo Ward", - "description": "MTRH clinic Nyayo Ward", - "mflCode": "15204", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "3ce46ae0-7eca-48c9-86d3-d5bdde1c7dab": { - "mrsId": 200, - "mrsDisplay": "MTRH Mother & Baby Ward", - "description": "MTRH Mother & Baby Ward", - "mflCode": "15204", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "0d599936-1a29-464b-87ad-c92cf51a6a84": { - "mrsId": 201, - "mrsDisplay": "MTRH Pediatric Ward", - "description": "MTRH Pediatric Ward", - "mflCode": "15204", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "2a901f42-bf51-428c-8be3-a135075abcb2": { - "mrsId": 202, - "mrsDisplay": "MTRH Other", - "description": "MTRH Other", - "mflCode": "15204", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "20bd486d-5c84-44f4-9ffa-2f1c1d9e79f8": { - "mrsId": 203, - "mrsDisplay": "Langas", - "description": "Facility", - "mflCode": "15011", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "20967b54-63b5-4311-a68e-2fc04406e56a": { - "mrsId": 204, - "mrsDisplay": "MTRH Oncology", - "description": "Moi Teaching and Referral Hospital - \nOncology", - "mflCode": "15204", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "584b1638-b11d-4cbe-8e81-ff25b684d63c": { - "mrsId": 205, - "mrsDisplay": "Busagwa Dispensary", - "description": "Busagwa Dispensary", - "mflCode": "21037", - "county": "Busia", - "cityVillage": "", - "eidDisplay": "" - }, - "7fb68709-6e7b-4eaf-a984-ea111fa45853": { - "mrsId": 206, - "mrsDisplay": "MTRH ACTG", - "description": "MTRH ACTG", - "mflCode": "15204", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "1ee4e702-913b-40a6-ab9c-26f9b4fced1c": { - "mrsId": 208, - "mrsDisplay": "Huruma MCH", - "description": "Huruma MCH", - "mflCode": "14555", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "7bc85590-2de6-4780-b4d8-f167b71c1834": { - "mrsId": 209, - "mrsDisplay": "Kakamega", - "description": "Is a Kakamega County Referral hospital", - "mflCode": null, - "county": "Kakamega", - "cityVillage": "", - "eidDisplay": "" - }, - "d4f8de72-5058-4db8-b556-324c7020b83b": { - "mrsId": 210, - "mrsDisplay": "Homabay", - "description": "Oncology site", - "mflCode": null, - "county": "Homabay", - "cityVillage": "", - "eidDisplay": "" - }, - "21beec4b-d6d0-4fe3-9711-acab0d577067": { - "mrsId": 212, - "mrsDisplay": "Jaramogi Oginga Odinga TRH", - "description": "Jaramogi Oginga Odinga Training and Referral Hospital.", - "mflCode": "13939", - "county": "Kisumu", - "cityVillage": "", - "eidDisplay": "" - }, - "db2bdd7c-5fe6-4ea3-adc1-d2d8dfb3d658": { - "mrsId": 213, - "mrsDisplay": "Bomet", - "description": "Oncology clinic at Bomet", - "mflCode": null, - "county": "Kericho", - "cityVillage": "", - "eidDisplay": "" - }, - "1ce5034b-f05d-46b6-910f-fc959e091641": { - "mrsId": 214, - "mrsDisplay": "Kapenguria County Referral Hospital", - "description": "Referral hospital in Kapenguria.", - "mflCode": "14701", - "county": "West Pokot", - "cityVillage": "", - "eidDisplay": "" - }, - "c54cbafc-3d6a-41a0-ae6c-ef40df16e2c9": { - "mrsId": 215, - "mrsDisplay": "Hamisi Sub County Hospital", - "description": "A sub county hospital in Hamisi", - "mflCode": null, - "county": "Vihiga", - "cityVillage": "", - "eidDisplay": "" - }, - "3acdbf65-644a-44c6-b6fa-9dad734ec442": { - "mrsId": 216, - "mrsDisplay": "BUTERE", - "description": "An Oncology Clinic", - "mflCode": null, - "county": "Kakamega", - "cityVillage": "", - "eidDisplay": "" - }, - "2a7ef5d8-28b6-4285-8313-c356ebbd3305": { - "mrsId": 219, - "mrsDisplay": "St. Elizabeth Lwak Mission Health center", - "description": "A health Center in Siaya County", - "mflCode": null, - "county": "Siaya", - "cityVillage": "", - "eidDisplay": "" - }, - "d6155afe-9258-4632-9723-08de6d7e2602": { - "mrsId": 220, - "mrsDisplay": "Madiany sub county hospital", - "description": "Madiany sub county in Siaya County- Oncology study", - "mflCode": "13747", - "county": "Siaya", - "cityVillage": "", - "eidDisplay": "" - }, - "3d65bfd3-c134-4133-a7aa-f44a2206f403": { - "mrsId": 221, - "mrsDisplay": "Bungoma County Referral Hospital", - "description": "A referral hospital in Bungoma county", - "mflCode": "15828", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "bf02fef0-0330-4247-82b0-d9ed490206a2": { - "mrsId": 222, - "mrsDisplay": "Nyahururu District Hospital", - "description": "A district Hospital in Laikipia County", - "mflCode": "10890", - "county": "Laikipia", - "cityVillage": "", - "eidDisplay": "" - }, - "68cb63f3-992d-4fd0-a80d-47a27fcf8021": { - "mrsId": 223, - "mrsDisplay": "MTRH TB", - "description": "TB Clinic at MTRH", - "mflCode": "15204", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - }, - "dfc36b77-c059-4a29-8a92-a40d5ad60774": { - "mrsId": 224, - "mrsDisplay": "Chemundu Dispensary", - "description": "A dispensary in Nandi County.", - "mflCode": "14324", - "county": "Nandi", - "cityVillage": "", - "eidDisplay": "" - }, - "261a0504-17fa-4fae-989f-4d4f30767842": { - "mrsId": 225, - "mrsDisplay": "AIC Kapsowar Mission Hospital", - "description": "Mission Hospital in Kapsowar.", - "mflCode": "14767", - "county": "Elgeyo Marakwet", - "cityVillage": "", - "eidDisplay": "" - }, - "65225dcd-81cc-4c8f-92e1-bb687995cf24": { - "mrsId": 226, - "mrsDisplay": "Vihiga County Referral Hospital.", - "description": "Referral Hospital in Vihiga county.", - "mflCode": "16157", - "county": "Vihiga", - "cityVillage": "", - "eidDisplay": "" - }, - "a36c86bb-7ca3-4319-8674-28c66ba14deb": { - "mrsId": 227, - "mrsDisplay": "Iten MCH", - "description": "An mch facility", - "mflCode": "14586", - "county": "Elgeyo Marakwet", - "cityVillage": "", - "eidDisplay": "" - }, - "535dc3bd-842b-4ca1-bc7c-357635ab985e": { - "mrsId": 229, - "mrsDisplay": "Kitale MCH", - "description": "mch clinic at kitale", - "mflCode": "14947", - "county": "transzoia", - "cityVillage": "", - "eidDisplay": "" - }, - "17c97881-90e5-43c8-b8a3-cc0322f89a89": { - "mrsId": 230, - "mrsDisplay": "Busia MCH", - "description": "mch clinic at busia.", - "mflCode": "15834", - "county": "Busia", - "cityVillage": "", - "eidDisplay": "" - }, - "f2320960-28de-41cf-b7d5-4734b75bafef": { - "mrsId": 231, - "mrsDisplay": "Chulaimbo MCH", - "description": "mch clinic at chulaimbo.", - "mflCode": "13528", - "county": "Kisumu", - "cityVillage": "", - "eidDisplay": "" - }, - "aa65d6b1-fad8-46a7-94cb-f5247d21509d": { - "mrsId": 232, - "mrsDisplay": "Meru County Referral Hospital", - "description": null, - "mflCode": "12516", - "county": "Meru County", - "cityVillage": "", - "eidDisplay": "" - }, - "ff95cb97-3d9e-4016-aff9-930fed3c55ec": { - "mrsId": 233, - "mrsDisplay": "Sori Lake side Hospital", - "description": "A hospital in Migori County", - "mflCode": "14098", - "county": "Migori", - "cityVillage": "", - "eidDisplay": "" - }, - "c79828e4-16cd-4c30-8164-13d6005aa879": { - "mrsId": 234, - "mrsDisplay": "Nyamira County Referral Hospital", - "description": "Nyamira County Referral Hospital - Oncology Clinic", - "mflCode": "13912", - "county": "Nyamira", - "cityVillage": "", - "eidDisplay": "" - }, - "dbe94e9c-c882-4ec0-9edc-d0038069cd00": { - "mrsId": 235, - "mrsDisplay": "Webuye Health Centre", - "description": "Health Centre in Bungoma County", - "mflCode": "16160", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "c0f4fd82-0d65-4b0b-aa04-be5914063959": { - "mrsId": 236, - "mrsDisplay": "Mulachi Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": null, - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "cb7fae6f-8daa-4a84-b4b0-7a1852b0526c": { - "mrsId": 237, - "mrsDisplay": "Lukusi Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": "16711", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "e2bb5611-a016-4440-951d-f35e42ad4821": { - "mrsId": 238, - "mrsDisplay": "Khaoya Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": "15933", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "df1f80fa-8c43-429d-93b9-bc01d0c898cf": { - "mrsId": 239, - "mrsDisplay": "Miendo Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": "16015", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "52d0a75a-b281-4f6d-a7c4-07c0cd5b1ee4": { - "mrsId": 240, - "mrsDisplay": "Matulo Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": "16389", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "61492482-4cde-4c71-8d20-e5ab9e858583": { - "mrsId": 241, - "mrsDisplay": "Khayaya Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": "16710", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "89442596-43af-4e32-a185-d1b5fbd86549": { - "mrsId": 242, - "mrsDisplay": "Namwatikho Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": "22501", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "90d8e717-36a6-4df2-a321-2fb2e9956bc0": { - "mrsId": 243, - "mrsDisplay": "Mukhe Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": "16028", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "299c8c3a-121a-4931-b1fa-fff949292ac3": { - "mrsId": 244, - "mrsDisplay": "Khalala Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": "18362", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "a568c19e-cfcb-416a-83ae-9c24b72d2c38": { - "mrsId": 245, - "mrsDisplay": "Chemalal Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": null, - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "6ae719f8-1805-4680-82d3-2bf58c617047": { - "mrsId": 246, - "mrsDisplay": "Namarambi Dispensary", - "description": "A dispensary in Bungoma County", - "mflCode": "21771", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "122addaa-dc8a-4e86-ad76-695aa35e2f6e": { - "mrsId": 247, - "mrsDisplay": "Lurare Dispensary", - "description": "CDM site", - "mflCode": "15976", - "county": "Bungoma", - "cityVillage": "", - "eidDisplay": "" - }, - "34aec983-646e-4d8f-93a9-fa8156de15ec": { - "mrsId": 248, - "mrsDisplay": "Garissa County Referral Hospital", - "description": "This is an Oncology clinic that the AMPATH oncology will be supporting.", - "mflCode": "13346", - "county": "Garissa", - "cityVillage": "", - "eidDisplay": "" - }, - "379ff09d-c72f-4859-a9dc-3c0295738252": { - "mrsId": 249, - "mrsDisplay": "MTRH Anti-coagulation", - "description": "oncology anti-coagulation treatment.", - "mflCode": "15204", - "county": "Uasin Gishu", - "cityVillage": "", - "eidDisplay": "" - } -} \ No newline at end of file + "08feae7c-1352-11df-a1f1-0026b9348838": { + "mrsId": 1, + "mrsDisplay": "MTRH Module 1", + "cityVillage": "Eldoret", + "county": "", + "description": "Moi Teaching and Referral Hospital - Module 1", + "mflCode": "15204", + "eidDisplay": "" + }, + "08feb14c-1352-11df-a1f1-0026b9348838": { + "mrsId": 2, + "mrsDisplay": "Mosoriot", + "cityVillage": "", + "county": "", + "description": "Mosoriot Outpatient Center", + "mflCode": "15229", + "eidDisplay": "" + }, + "08feb2dc-1352-11df-a1f1-0026b9348838": { + "mrsId": 3, + "mrsDisplay": "Turbo", + "cityVillage": "", + "county": "Rift Valley", + "description": "Turbo heath center Clinic", + "mflCode": "15753", + "eidDisplay": "" + }, + "08feb444-1352-11df-a1f1-0026b9348838": { + "mrsId": 4, + "mrsDisplay": "Burnt Forest", + "cityVillage": "Burnt Forest", + "county": "Rift Valley", + "description": "Burnt Forest RHDC Clinic", + "mflCode": "16347", + "eidDisplay": "" + }, + "08feb5b6-1352-11df-a1f1-0026b9348838": { + "mrsId": 5, + "mrsDisplay": "Amukura", + "cityVillage": "Malaba", + "county": "Western", + "description": "Amukura Health Center", + "mflCode": "15798", + "eidDisplay": "" + }, + "08feb6b0-1352-11df-a1f1-0026b9348838": { + "mrsId": 6, + "mrsDisplay": "Naitiri", + "cityVillage": "Naitiri", + "county": "Western", + "description": "Naitiri Health center", + "mflCode": "16061", + "eidDisplay": "" + }, + "08feb7b4-1352-11df-a1f1-0026b9348838": { + "mrsId": 7, + "mrsDisplay": "Chulaimbo", + "cityVillage": "Maseno", + "county": "Nyanza", + "description": "Chulaimbo Sub-district hospital (Clinic)", + "mflCode": "13528", + "eidDisplay": "" + }, + "08feb8ae-1352-11df-a1f1-0026b9348838": { + "mrsId": 8, + "mrsDisplay": "Webuye", + "cityVillage": "Webuye", + "county": "Western", + "description": "Webuye Hospital ", + "mflCode": "16161", + "eidDisplay": "" + }, + "08feb9a8-1352-11df-a1f1-0026b9348838": { + "mrsId": 9, + "mrsDisplay": "Mt. Elgon", + "cityVillage": "", + "county": "", + "description": "Mount Elgon Clinic (Kapsokwony)", + "mflCode": "16025", + "eidDisplay": "" + }, + "08feba98-1352-11df-a1f1-0026b9348838": { + "mrsId": 10, + "mrsDisplay": "Kapenguria", + "cityVillage": "", + "county": "", + "description": "Kapenguria Clinic", + "mflCode": "19088", + "eidDisplay": "" + }, + "08febb92-1352-11df-a1f1-0026b9348838": { + "mrsId": 11, + "mrsDisplay": "Kitale", + "cityVillage": "", + "county": "", + "description": "Kitale District Hospital", + "mflCode": "14947", + "eidDisplay": "" + }, + "08febf52-1352-11df-a1f1-0026b9348838": { + "mrsId": 12, + "mrsDisplay": "Teso", + "cityVillage": "", + "county": "", + "description": "Teso Clinic", + "mflCode": "16150", + "eidDisplay": "" + }, + "08fec056-1352-11df-a1f1-0026b9348838": { + "mrsId": 13, + "mrsDisplay": "MTRH Module 2", + "cityVillage": "", + "county": "", + "description": "Moi Teaching and Referral Hospital - Module 2", + "mflCode": "15204", + "eidDisplay": "" + }, + "08fec150-1352-11df-a1f1-0026b9348838": { + "mrsId": 14, + "mrsDisplay": "MTRH Module 3", + "cityVillage": "", + "county": "", + "description": "Moi Teaching and Referral Hospital - Module 3", + "mflCode": "15204", + "eidDisplay": "" + }, + "08fec24a-1352-11df-a1f1-0026b9348838": { + "mrsId": 15, + "mrsDisplay": "MTRH Module 4", + "cityVillage": "", + "county": "", + "description": "Moi Teaching and Referral Hospital - Module 4", + "mflCode": "15204", + "eidDisplay": "" + }, + "08fec33a-1352-11df-a1f1-0026b9348838": { + "mrsId": 16, + "mrsDisplay": "Unknown", + "cityVillage": null, + "county": null, + "description": "Unknown Location", + "mflCode": "", + "eidDisplay": "" + }, + "08fec42a-1352-11df-a1f1-0026b9348838": { + "mrsId": 17, + "mrsDisplay": "Iten", + "cityVillage": null, + "county": null, + "description": "Iten Clinic", + "mflCode": "14586", + "eidDisplay": "" + }, + "08fec51a-1352-11df-a1f1-0026b9348838": { + "mrsId": 18, + "mrsDisplay": "Kabarnet", + "cityVillage": null, + "county": null, + "description": "Kabarnet Clinic", + "mflCode": "14607", + "eidDisplay": "" + }, + "08fec60a-1352-11df-a1f1-0026b9348838": { + "mrsId": 19, + "mrsDisplay": "Busia", + "cityVillage": "Busia", + "county": "Western", + "description": "Busia Clinic", + "mflCode": "15834", + "eidDisplay": "" + }, + "08fec704-1352-11df-a1f1-0026b9348838": { + "mrsId": 20, + "mrsDisplay": "Port Victoria", + "cityVillage": "Port Victoria", + "county": "Western", + "description": "Port Victoria AMPATH clinic", + "mflCode": "16091", + "eidDisplay": "" + }, + "08fec808-1352-11df-a1f1-0026b9348838": { + "mrsId": 21, + "mrsDisplay": "Non-AMPATH Site", + "cityVillage": "", + "county": "", + "description": "All clinical locations outside the AMPATH system.", + "mflCode": "", + "eidDisplay": "" + }, + "08fec916-1352-11df-a1f1-0026b9348838": { + "mrsId": 22, + "mrsDisplay": "None", + "cityVillage": "", + "county": "", + "description": "No location.", + "mflCode": "", + "eidDisplay": "" + }, + "09004e76-1352-11df-a1f1-0026b9348838": { + "mrsId": 23, + "mrsDisplay": "Khuyangu", + "cityVillage": "Khuyangu", + "county": "Western", + "description": "Khuyangu District Hospital ", + "mflCode": "15939", + "eidDisplay": "" + }, + "09004fca-1352-11df-a1f1-0026b9348838": { + "mrsId": 24, + "mrsDisplay": "Chulaimbo Module 1", + "cityVillage": "Maseno", + "county": "Nyanza", + "description": "Chulaimbo Adult Clinic", + "mflCode": "13528", + "eidDisplay": "" + }, + "090050ce-1352-11df-a1f1-0026b9348838": { + "mrsId": 25, + "mrsDisplay": "Chulaimbo Module 2", + "cityVillage": "Maseno", + "county": "Nyanza", + "description": "Chulaimbo Pediatric Clinic", + "mflCode": "13528", + "eidDisplay": "" + }, + "090051c8-1352-11df-a1f1-0026b9348838": { + "mrsId": 26, + "mrsDisplay": "Busia Module 1", + "cityVillage": "Busia", + "county": "Western", + "description": "Busia Module 1", + "mflCode": "15834", + "eidDisplay": "" + }, + "090052b8-1352-11df-a1f1-0026b9348838": { + "mrsId": 27, + "mrsDisplay": "Busia Module 2", + "cityVillage": "", + "county": "", + "description": "Busia Module 2", + "mflCode": "15834", + "eidDisplay": "" + }, + "090053b2-1352-11df-a1f1-0026b9348838": { + "mrsId": 28, + "mrsDisplay": "Ziwa", + "cityVillage": null, + "county": null, + "description": "Ziwa Clinic", + "mflCode": "15788", + "eidDisplay": "" + }, + "090054a2-1352-11df-a1f1-0026b9348838": { + "mrsId": 30, + "mrsDisplay": "Anderson", + "cityVillage": null, + "county": null, + "description": "Anderson Clinic", + "mflCode": "14203", + "eidDisplay": "" + }, + "0900559c-1352-11df-a1f1-0026b9348838": { + "mrsId": 31, + "mrsDisplay": "Uasin Gishu District Hospital", + "cityVillage": "", + "county": "", + "description": "Uasin Gishu District Hospital (DH)", + "mflCode": "15758", + "eidDisplay": "" + }, + "090056be-1352-11df-a1f1-0026b9348838": { + "mrsId": 32, + "mrsDisplay": "Eldoret Catholic Church(IDP)", + "cityVillage": "Eldoret", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "090057cc-1352-11df-a1f1-0026b9348838": { + "mrsId": 33, + "mrsDisplay": "Eldoret Police Station(IDP)", + "cityVillage": "Eldoret", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "090058e4-1352-11df-a1f1-0026b9348838": { + "mrsId": 34, + "mrsDisplay": "Majengo (Our Lady) Church(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "090059f2-1352-11df-a1f1-0026b9348838": { + "mrsId": 35, + "mrsDisplay": "Turbo Police Station", + "cityVillage": "Turbo", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09005b0a-1352-11df-a1f1-0026b9348838": { + "mrsId": 36, + "mrsDisplay": "Nakuru(IDP)", + "cityVillage": "Nakuru", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09005c0e-1352-11df-a1f1-0026b9348838": { + "mrsId": 37, + "mrsDisplay": "Nairobi(IDP)", + "cityVillage": "Nairobi", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09005d1c-1352-11df-a1f1-0026b9348838": { + "mrsId": 38, + "mrsDisplay": "Eldoret Showground(IDP)", + "cityVillage": "Eldoret", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09005e34-1352-11df-a1f1-0026b9348838": { + "mrsId": 39, + "mrsDisplay": "Yamumbi (IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09005f38-1352-11df-a1f1-0026b9348838": { + "mrsId": 40, + "mrsDisplay": "Matharu Center(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09006050-1352-11df-a1f1-0026b9348838": { + "mrsId": 41, + "mrsDisplay": "Munyaka PCEA Church(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "0900615e-1352-11df-a1f1-0026b9348838": { + "mrsId": 42, + "mrsDisplay": "Maji Mazuri(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "0900626c-1352-11df-a1f1-0026b9348838": { + "mrsId": 43, + "mrsDisplay": "Kamara(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09006370-1352-11df-a1f1-0026b9348838": { + "mrsId": 44, + "mrsDisplay": "Eldamaravine Police Station(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "0900647e-1352-11df-a1f1-0026b9348838": { + "mrsId": 45, + "mrsDisplay": "Moisbridge(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09006582-1352-11df-a1f1-0026b9348838": { + "mrsId": 46, + "mrsDisplay": "Langas police station(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09007acc-1352-11df-a1f1-0026b9348838": { + "mrsId": 47, + "mrsDisplay": "Timboroa Police Station", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09007be4-1352-11df-a1f1-0026b9348838": { + "mrsId": 48, + "mrsDisplay": "Bishop Muge(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09007ce8-1352-11df-a1f1-0026b9348838": { + "mrsId": 49, + "mrsDisplay": "Kipkenyo(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09007df6-1352-11df-a1f1-0026b9348838": { + "mrsId": 50, + "mrsDisplay": "Endebes(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09007efa-1352-11df-a1f1-0026b9348838": { + "mrsId": 51, + "mrsDisplay": "Kachibora(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09007ffe-1352-11df-a1f1-0026b9348838": { + "mrsId": 52, + "mrsDisplay": "Cherangany(IDP)", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09008102-1352-11df-a1f1-0026b9348838": { + "mrsId": 53, + "mrsDisplay": "Nzioa Scheme", + "cityVillage": "", + "county": "", + "description": "Internally Displaced AMPATH Patients", + "mflCode": "", + "eidDisplay": "" + }, + "09008206-1352-11df-a1f1-0026b9348838": { + "mrsId": 54, + "mrsDisplay": "Plateau Mission Hospital", + "cityVillage": "", + "county": "Rift valley", + "description": "Burnt Forest Satellite Clinic", + "mflCode": "15464", + "eidDisplay": "" + }, + "0900831e-1352-11df-a1f1-0026b9348838": { + "mrsId": 55, + "mrsDisplay": "Bumala A", + "cityVillage": "Bumala", + "county": "Western", + "description": "Bumala \"A\" Health Center(Busia Satellite Clinic)", + "mflCode": "15823", + "eidDisplay": "" + }, + "09008422-1352-11df-a1f1-0026b9348838": { + "mrsId": 56, + "mrsDisplay": "Eldoret Prison", + "cityVillage": null, + "county": null, + "description": "Satellite Clinic of MTRH Module 3", + "mflCode": "15204", + "eidDisplay": "" + }, + "0900851c-1352-11df-a1f1-0026b9348838": { + "mrsId": 57, + "mrsDisplay": "Kitale Prison", + "cityVillage": "", + "county": "", + "description": "Satellite Clinic of Kitale", + "mflCode": "14947", + "eidDisplay": "" + }, + "09008620-1352-11df-a1f1-0026b9348838": { + "mrsId": 58, + "mrsDisplay": "Ngeria Prison", + "cityVillage": null, + "county": null, + "description": "Satellite Clinic of MTRH Module 3", + "mflCode": "15204", + "eidDisplay": "" + }, + "0900871a-1352-11df-a1f1-0026b9348838": { + "mrsId": 59, + "mrsDisplay": "MAUTUMA", + "cityVillage": null, + "county": null, + "description": "Satellite Clinic of Turbo", + "mflCode": "16010", + "eidDisplay": "" + }, + "0900880a-1352-11df-a1f1-0026b9348838": { + "mrsId": 60, + "mrsDisplay": "Chepsaita", + "cityVillage": "Turbo", + "county": "Uasin Gishu", + "description": "Chepsaita Dispensary(Turbo Satellite Clinic)", + "mflCode": "14358", + "eidDisplay": "" + }, + "09008904-1352-11df-a1f1-0026b9348838": { + "mrsId": 61, + "mrsDisplay": "KAPTAGAT", + "cityVillage": null, + "county": null, + "description": "Satellite Clinic of Burnt Forest", + "mflCode": "16347", + "eidDisplay": "" + }, + "090089ea-1352-11df-a1f1-0026b9348838": { + "mrsId": 62, + "mrsDisplay": "KESSES", + "cityVillage": null, + "county": null, + "description": "Satellite Clinic of Burnt Forest", + "mflCode": "16347", + "eidDisplay": "" + }, + "09008ada-1352-11df-a1f1-0026b9348838": { + "mrsId": 63, + "mrsDisplay": "LUKOLIS", + "cityVillage": "Malaba", + "county": "Western", + "description": "Lukolis Dispensary(Amukura satellite clinic)", + "mflCode": "15968", + "eidDisplay": "" + }, + "09008fda-1352-11df-a1f1-0026b9348838": { + "mrsId": 64, + "mrsDisplay": "BOKOLI", + "cityVillage": "Bokoli", + "county": "Western", + "description": "Bokoli Hospital(Webuye satellite clinic)", + "mflCode": "15808", + "eidDisplay": "" + }, + "090090d4-1352-11df-a1f1-0026b9348838": { + "mrsId": 65, + "mrsDisplay": "ANGURAI", + "cityVillage": "Malaba", + "county": "Western", + "description": "Angurai Health Center(Teso satellite clinic)", + "mflCode": "15800", + "eidDisplay": "" + }, + "090091c4-1352-11df-a1f1-0026b9348838": { + "mrsId": 66, + "mrsDisplay": "Cheptais", + "cityVillage": "Cheptais", + "county": "Western", + "description": "Cheptais Sub-District Hospital(Mt. Elgon Satellite Clinic)", + "mflCode": "15855", + "eidDisplay": "" + }, + "090092b4-1352-11df-a1f1-0026b9348838": { + "mrsId": 67, + "mrsDisplay": "CHESKAKI", + "cityVillage": "", + "county": "", + "description": "Mt. Elgon Satellite Clinic", + "mflCode": "15856", + "eidDisplay": "" + }, + "0900939a-1352-11df-a1f1-0026b9348838": { + "mrsId": 68, + "mrsDisplay": "MARIGAT", + "cityVillage": null, + "county": null, + "description": "Satellite Clinic of Kabarnet", + "mflCode": "15138", + "eidDisplay": "" + }, + "0900948a-1352-11df-a1f1-0026b9348838": { + "mrsId": 69, + "mrsDisplay": "Huruma SDH", + "cityVillage": null, + "county": null, + "description": "Satellite Clinic of Uasin Gishu District Hospital", + "mflCode": "14555", + "eidDisplay": "" + }, + "0900a9ac-1352-11df-a1f1-0026b9348838": { + "mrsId": 70, + "mrsDisplay": "Pioneer Sub-District Hospital", + "cityVillage": "", + "county": "", + "description": "Satellite clinic for Mosoriot Health Centre", + "mflCode": "15463", + "eidDisplay": "" + }, + "0900aace-1352-11df-a1f1-0026b9348838": { + "mrsId": 71, + "mrsDisplay": "Mois Bridge", + "cityVillage": "", + "county": "", + "description": "Moi's Bridge Clinic", + "mflCode": "15209", + "eidDisplay": "" + }, + "0900abdc-1352-11df-a1f1-0026b9348838": { + "mrsId": 72, + "mrsDisplay": "Moi University", + "cityVillage": "Kesses", + "county": "", + "description": "Moi University Main Campus clinic", + "mflCode": "15205", + "eidDisplay": "" + }, + "0900acea-1352-11df-a1f1-0026b9348838": { + "mrsId": 73, + "mrsDisplay": "Soy", + "cityVillage": "", + "county": "", + "description": "Soy Clinic", + "mflCode": "15623", + "eidDisplay": "" + }, + "0900adee-1352-11df-a1f1-0026b9348838": { + "mrsId": 74, + "mrsDisplay": "Mihuu ", + "cityVillage": "Webuye", + "county": "Western", + "description": "Mihuu Dispensary(Webuye satellite clinic)", + "mflCode": "16161", + "eidDisplay": "" + }, + "0900aefc-1352-11df-a1f1-0026b9348838": { + "mrsId": 75, + "mrsDisplay": "Sinoko", + "cityVillage": "Misikhu", + "county": "Western", + "description": "Sinoko Dispensary(Bungoma East)", + "mflCode": "16126", + "eidDisplay": "" + }, + "0900b000-1352-11df-a1f1-0026b9348838": { + "mrsId": 76, + "mrsDisplay": "Milo", + "cityVillage": "WE", + "county": "we", + "description": "Milo Health Center (Satellite clinic to Webuye)", + "mflCode": "16161", + "eidDisplay": "" + }, + "0900b104-1352-11df-a1f1-0026b9348838": { + "mrsId": 77, + "mrsDisplay": "Moiben", + "cityVillage": "", + "county": "", + "description": "Satellite Clinic of Ziwa", + "mflCode": "15206", + "eidDisplay": "" + }, + "0900b212-1352-11df-a1f1-0026b9348838": { + "mrsId": 78, + "mrsDisplay": "Mukhobola", + "cityVillage": "", + "county": "", + "description": "Mukhobola Clinic ", + "mflCode": "16029", + "eidDisplay": "" + }, + "0900b316-1352-11df-a1f1-0026b9348838": { + "mrsId": 79, + "mrsDisplay": "Nambale", + "cityVillage": "", + "county": "", + "description": "Nambale Clinic ", + "mflCode": "16066", + "eidDisplay": "" + }, + "0900b424-1352-11df-a1f1-0026b9348838": { + "mrsId": 80, + "mrsDisplay": "MOI BARRACKS", + "cityVillage": "", + "county": "Rift valley", + "description": "Satellite Clinic of Module 3", + "mflCode": "15204", + "eidDisplay": "" + }, + "0900b532-1352-11df-a1f1-0026b9348838": { + "mrsId": 81, + "mrsDisplay": "Busia Prison", + "cityVillage": "15834", + "county": "Western", + "description": "Busia Satellite Clinic", + "mflCode": "15834", + "eidDisplay": "" + }, + "0900b636-1352-11df-a1f1-0026b9348838": { + "mrsId": 82, + "mrsDisplay": "Saboti", + "cityVillage": "", + "county": "Rift Valley", + "description": "Kitale satellite clinic", + "mflCode": "14947", + "eidDisplay": "" + }, + "0900b74e-1352-11df-a1f1-0026b9348838": { + "mrsId": 83, + "mrsDisplay": "Bumala B", + "cityVillage": "Busia", + "county": "Western", + "description": "Bumala \"B\" Health Center (Khunyangu Satellite clinic)", + "mflCode": "15824", + "eidDisplay": "" + }, + "0900b866-1352-11df-a1f1-0026b9348838": { + "mrsId": 84, + "mrsDisplay": "MOI TEACHING AND REFERRAL HOSPITAL", + "cityVillage": "", + "county": "", + "description": "Primary Health Care Clinic Location", + "mflCode": "15204", + "eidDisplay": "" + }, + "0900b974-1352-11df-a1f1-0026b9348838": { + "mrsId": 85, + "mrsDisplay": "Makutano", + "cityVillage": "", + "county": "Western", + "description": "Satellite Clinic Site for Naitiri", + "mflCode": "16061", + "eidDisplay": "" + }, + "25972cec-2e14-4047-a537-404c6ad18389": { + "mrsId": 86, + "mrsDisplay": "Kaptama (Friends) dispensary", + "cityVillage": "Kaptama", + "county": "Western", + "description": "Satellite clinic of Mount Elgon(Kapsokwony)\r\n", + "mflCode": "15925", + "eidDisplay": "" + }, + "ffb2c2f0-a62c-4be8-960a-05b704bd66cd": { + "mrsId": 87, + "mrsDisplay": "Sio Port", + "cityVillage": "", + "county": "", + "description": "Sio port", + "mflCode": "16128", + "eidDisplay": "" + }, + "1be88533-0a70-40a4-9c45-1a7a936fd23a": { + "mrsId": 88, + "mrsDisplay": "Tulwet", + "cityVillage": "Tulwet", + "county": "Rift Valley", + "description": "Satellite clinic of Kitale", + "mflCode": "14947", + "eidDisplay": "" + }, + "8d502f10-dcaf-41fc-8677-34a6b498ac7a": { + "mrsId": 89, + "mrsDisplay": "Kopsiro", + "cityVillage": "Kopsiro", + "county": "Western", + "description": "Satellite Clinic of Mt. elgon.", + "mflCode": "15956", + "eidDisplay": "" + }, + "7a8c0cc5-be43-48e1-aa41-33cb1e9cc26f": { + "mrsId": 90, + "mrsDisplay": "Changara", + "cityVillage": "Changara", + "county": "Western", + "description": "Teso Satellte Clinic", + "mflCode": "16421", + "eidDisplay": "" + }, + "cb31d052-b668-4321-80ad-c0aaa571f87b": { + "mrsId": 91, + "mrsDisplay": "Malaba", + "cityVillage": "Malaba", + "county": "Western", + "description": "Satellite clinic of Teso", + "mflCode": "15993", + "eidDisplay": "" + }, + "096ac36e-47f9-49e0-a62b-d87a09753b61": { + "mrsId": 92, + "mrsDisplay": "Amase", + "cityVillage": "Amagoro", + "county": "Western", + "description": "Amase Dispensary(Amukura satellite clinic)", + "mflCode": "15797", + "eidDisplay": "" + }, + "69d9a87d-18f2-4113-840d-95668d1e9e16": { + "mrsId": 93, + "mrsDisplay": "Obekai", + "cityVillage": "Busia", + "county": "Western", + "description": "Obekai Dispensary(Amukura satellite clinic)", + "mflCode": "16087", + "eidDisplay": "" + }, + "19874e26-f614-47bb-99c7-a3756bfe3c64": { + "mrsId": 94, + "mrsDisplay": "Tambach", + "cityVillage": "", + "county": "Rift valley", + "description": "Satellite Clinic to Iten", + "mflCode": "15703", + "eidDisplay": "" + }, + "bcc27a76-1980-4efe-b72e-ca40019ef6ce": { + "mrsId": 95, + "mrsDisplay": "Tenges", + "cityVillage": "", + "county": "Rift Valley", + "description": "Satellite clinic to Kabarnet.", + "mflCode": "15718", + "eidDisplay": "" + }, + "dba01903-14bd-4978-9264-f6ca896b0ca4": { + "mrsId": 96, + "mrsDisplay": "Kibisi", + "cityVillage": "", + "county": "Western", + "description": "Satellite clinic to Naitiri", + "mflCode": "15943", + "eidDisplay": "" + }, + "56cf9621-d946-4ac0-a587-4024792c0934": { + "mrsId": 97, + "mrsDisplay": "Sango", + "cityVillage": "", + "county": "Western", + "description": "Satellite clinic to Naitiri.", + "mflCode": "17986", + "eidDisplay": "" + }, + "65bdb112-a254-4cf9-a5a7-29dce997312d": { + "mrsId": 98, + "mrsDisplay": "AIC Diguna Royal Toto Childrens Home,Ngechek", + "cityVillage": "Mosoriot", + "county": "Riftvalley", + "description": "Mosoriot satellite clinic", + "mflCode": "15229", + "eidDisplay": "" + }, + "851d4b92-763a-4c4a-a9bc-63b12586429f": { + "mrsId": 99, + "mrsDisplay": "Lupida", + "cityVillage": "Nambale", + "county": "Western", + "description": "Nambale Satellite Clinic", + "mflCode": "15975", + "eidDisplay": "" + }, + "00b47ef5-a29b-40a2-a7f4-6851df8d6532": { + "mrsId": 100, + "mrsDisplay": "Osieko", + "cityVillage": "", + "county": "", + "description": "A satellite to Port Victoria", + "mflCode": "17680", + "eidDisplay": "" + }, + "79fcf21c-8a00-44ba-9555-dde4dd877c4a": { + "mrsId": 101, + "mrsDisplay": "Room 7", + "cityVillage": "", + "county": "", + "description": "Casualty", + "mflCode": "", + "eidDisplay": "" + }, + "6cd0b441-d644-487c-8466-5820a73f9ce5": { + "mrsId": 102, + "mrsDisplay": "Elgeyo Border", + "cityVillage": "", + "county": "", + "description": "These is a health centre ", + "mflCode": "14437", + "eidDisplay": "" + }, + "2b0419c2-275f-4354-8b49-4c97d033ecbb": { + "mrsId": 103, + "mrsDisplay": "Riat", + "cityVillage": "", + "county": "", + "description": "This is a dispensary and its Chulaimbo's Satellites", + "mflCode": "14046", + "eidDisplay": "" + }, + "01c73fdc-65ce-4349-abdf-bbc554178b47": { + "mrsId": 104, + "mrsDisplay": "Sunga", + "cityVillage": "", + "county": "", + "description": "This is a dispensary and its Chulaimbo's Satellites", + "mflCode": "17175", + "eidDisplay": "" + }, + "b5d03983-f24e-4fdc-9ff5-33fc87dee02b": { + "mrsId": 105, + "mrsDisplay": "Siriba", + "cityVillage": "", + "county": "", + "description": "This is a dispensary and its Chulaimbo's Satellites", + "mflCode": "14094", + "eidDisplay": "" + }, + "8f537fab-0b7f-4b72-a462-042eefad058c": { + "mrsId": 106, + "mrsDisplay": "Kamolo", + "cityVillage": "", + "county": "", + "description": "satelite at Kamolo Dispensary,to be run by Teso, AMPATH clinic", + "mflCode": "17242", + "eidDisplay": "" + }, + "8ce15cad-c7ff-41d9-b55c-5230116c3bf7": { + "mrsId": 107, + "mrsDisplay": "Kapteren Health Center", + "cityVillage": "", + "county": "", + "description": "A satellite of Iten Clinic", + "mflCode": "14781", + "eidDisplay": "" + }, + "27edd245-5205-4e66-82bd-d314c547d16b": { + "mrsId": 108, + "mrsDisplay": "Madende Health Center", + "cityVillage": "", + "county": "", + "description": "A satellite of Nambale", + "mflCode": "15985", + "eidDisplay": "" + }, + "e2d2926e-49e6-4a27-b701-73b6e263a4fd": { + "mrsId": 109, + "mrsDisplay": "Rai-plywood", + "cityVillage": "Huruma", + "county": "Rift Valley", + "description": "Satellite clinic to UGDH", + "mflCode": "14555", + "eidDisplay": "" + }, + "4fb82b14-c0e4-46d0-9864-a36e2d6b6c8a": { + "mrsId": 110, + "mrsDisplay": "Mogoget", + "cityVillage": "", + "county": "", + "description": "Dispensary in Kosirai Division", + "mflCode": "15194", + "eidDisplay": "" + }, + "53c7ebb2-78c2-4ce3-a504-f37a6cb998aa": { + "mrsId": 111, + "mrsDisplay": "Birbiriet", + "cityVillage": null, + "county": null, + "description": "Dispensary in Kosirai Division", + "mflCode": "14257", + "eidDisplay": "" + }, + "17cc5ee1-b702-4b4b-9ea7-9fc7083dd56e": { + "mrsId": 112, + "mrsDisplay": "Itigo", + "cityVillage": "", + "county": "", + "description": "Dispensary in Kosirai Division", + "mflCode": "14587", + "eidDisplay": "" + }, + "469471e2-5b1e-46be-9232-a738f8cd717b": { + "mrsId": 113, + "mrsDisplay": "Lelmokwo", + "cityVillage": "", + "county": "", + "description": "Dispensary in Kosirai Division", + "mflCode": "15022", + "eidDisplay": "" + }, + "8eedf128-40ed-4fba-9240-3cc92234720f": { + "mrsId": 114, + "mrsDisplay": "Kokwet", + "cityVillage": "", + "county": "", + "description": "Dispensary in Kosirai Division", + "mflCode": "14977", + "eidDisplay": "" + }, + "a30955e0-275f-48ca-974d-438368a0685a": { + "mrsId": 115, + "mrsDisplay": "Ngechek", + "cityVillage": "", + "county": "", + "description": "Dispensary in Kosirai Division", + "mflCode": "15342", + "eidDisplay": "" + }, + "96d2964e-8cec-4eca-ad05-a9c1fb29a045": { + "mrsId": 116, + "mrsDisplay": "cheramei", + "cityVillage": "", + "county": "", + "description": "Dispensary in Turbo Division", + "mflCode": "14377", + "eidDisplay": "" + }, + "2003e950-5b62-4330-a94c-cf8165f75084": { + "mrsId": 117, + "mrsDisplay": "Murgusi", + "cityVillage": "", + "county": "", + "description": "Dispensary in Turbo Division", + "mflCode": "15255", + "eidDisplay": "" + }, + "441451e5-aabd-4e71-87dd-8b7c5f651434": { + "mrsId": 118, + "mrsDisplay": "Cheplaskei", + "cityVillage": null, + "county": null, + "description": "Dispensary in Turbo Division", + "mflCode": "14354", + "eidDisplay": "" + }, + "4de54b6f-6f60-4b56-a801-087603d2f294": { + "mrsId": 119, + "mrsDisplay": "Sigot", + "cityVillage": "", + "county": "", + "description": "Dispensary in Turbo Division", + "mflCode": "15753", + "eidDisplay": "" + }, + "f030c7f2-9790-41d0-a704-f5a164909d17": { + "mrsId": 120, + "mrsDisplay": "Sugoi A", + "cityVillage": "", + "county": "", + "description": "Dispensary in Turbo Division", + "mflCode": "17331", + "eidDisplay": "" + }, + "a27cec49-110c-41a1-9a6f-964d6ac2359d": { + "mrsId": 121, + "mrsDisplay": "Sugoi B", + "cityVillage": "", + "county": "", + "description": "Dispensary in Turbo Division", + "mflCode": "15680", + "eidDisplay": "" + }, + "d09c6925-1e9a-4973-921d-d0014d7825ec": { + "mrsId": 122, + "mrsDisplay": "Chepkemel", + "cityVillage": "", + "county": "", + "description": "Dispensary in Turbo Division", + "mflCode": "14337", + "eidDisplay": "" + }, + "12aeb8ab-690c-47e0-b41f-e261dac1279c": { + "mrsId": 123, + "mrsDisplay": "Chepkemel", + "cityVillage": "", + "county": "", + "description": "Dispensary in Turbo Division", + "mflCode": "14339", + "eidDisplay": "" + }, + "eb32b031-30df-40d9-8aef-d88fbb763852": { + "mrsId": 124, + "mrsDisplay": "Akichelesit", + "cityVillage": "", + "county": "", + "description": "Dispensary in Teso Division", + "mflCode": "15792", + "eidDisplay": "" + }, + "291bdf8e-93ed-4898-a58f-7d9f7f74128e": { + "mrsId": 125, + "mrsDisplay": "Aboloi", + "cityVillage": "", + "county": "", + "description": "Dispensary in Teso Division", + "mflCode": "15789", + "eidDisplay": "" + }, + "1243cf8b-fced-482c-9d95-c92f28bfcbea": { + "mrsId": 126, + "mrsDisplay": "Moding", + "cityVillage": "", + "county": "", + "description": "Dispensary in Teso Division", + "mflCode": "16021", + "eidDisplay": "" + }, + "e8c7759a-c99a-46de-82f8-d7c9f67eb237": { + "mrsId": 127, + "mrsDisplay": "Sambut ", + "cityVillage": "", + "county": "", + "description": "Sambut - Dispensary in Turbo division", + "mflCode": "15525", + "eidDisplay": "" + }, + "00ce435c-3f27-4e89-a7f8-80fd102ff410": { + "mrsId": 128, + "mrsDisplay": "Ngenyilel", + "cityVillage": "", + "county": "", + "description": "Dispensary in Turbo division", + "mflCode": "15344", + "eidDisplay": "" + }, + "2b338894-e81d-48e9-83d5-9280c8f549d4": { + "mrsId": 129, + "mrsDisplay": "Sosiani", + "cityVillage": "", + "county": "", + "description": "Health Centre in Turbo division", + "mflCode": "15616", + "eidDisplay": "" + }, + "1d3bc503-925b-4a31-91da-337b611cc27a": { + "mrsId": 130, + "mrsDisplay": "Matayos Health Centre", + "cityVillage": "", + "county": "Western", + "description": "New site from Aphia", + "mflCode": "16004", + "eidDisplay": "" + }, + "5c8705ef-3a36-4806-a907-381232f88834": { + "mrsId": 131, + "mrsDisplay": "Chebaiywa", + "cityVillage": "", + "county": "", + "description": "Used by CDM team and their forms being entered to AMRS", + "mflCode": "17243", + "eidDisplay": "" + }, + "8bb0593f-5dca-4828-a443-53d41f040d8c": { + "mrsId": 132, + "mrsDisplay": "Kapsara Sub-district hospital", + "cityVillage": "", + "county": "", + "description": "New location in Kitale", + "mflCode": "14753", + "eidDisplay": "" + }, + "a8f5b2b9-d2f0-454b-a7aa-46a1fbca17d3": { + "mrsId": 133, + "mrsDisplay": "Chepterit ", + "cityVillage": "", + "county": "", + "description": "A dispensary in Mosoriot Division", + "mflCode": "14368", + "eidDisplay": "" + }, + "e05cbb83-9418-4ebc-9240-ae2512d70321": { + "mrsId": 134, + "mrsDisplay": "Kapyemit", + "cityVillage": "", + "county": "", + "description": "A dispensary in Turbo division and Uasin Gishu county", + "mflCode": "14799", + "eidDisplay": "" + }, + "b77f94ea-62ea-469a-8a88-5aa2d33bdaaf": { + "mrsId": 135, + "mrsDisplay": "Kaborom", + "cityVillage": "", + "county": "Western", + "description": " Dispensary - a satellite of Mt Elgon.\r\n ", + "mflCode": "15910", + "eidDisplay": "" + }, + "e2546b92-17df-4640-a38b-c4f30b0cfd81": { + "mrsId": 136, + "mrsDisplay": "Murgor Hills", + "cityVillage": "", + "county": "", + "description": "A dispensary in Turbo", + "mflCode": "15254", + "eidDisplay": "" + }, + "3e04788f-6761-412a-8db6-08a713f59afc": { + "mrsId": 137, + "mrsDisplay": "Osorongai", + "cityVillage": "", + "county": "", + "description": "A dispensary in Turbo", + "mflCode": "15449", + "eidDisplay": "" + }, + "098148c6-9ffd-4c30-9dca-c8fa26c39eaf": { + "mrsId": 138, + "mrsDisplay": "Family Health Care Otpions Kenya - Eldoret", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "16348", + "eidDisplay": "" + }, + "b0773cd5-e0c0-4cc7-8cbd-482407311b50": { + "mrsId": 139, + "mrsDisplay": "Elgon View Hospital", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "14438", + "eidDisplay": "" + }, + "dfa41633-bef8-4465-b773-8254cef7cc7f": { + "mrsId": 140, + "mrsDisplay": "Cedar Clinical Associates", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "14280", + "eidDisplay": "" + }, + "2f4c8dde-1bc1-4224-9e1e-a4d915e74210": { + "mrsId": 141, + "mrsDisplay": "Glory health centre and Chemists", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "", + "eidDisplay": "" + }, + "22ef1733-f776-4d04-bf5d-2e0c48fe3ca5": { + "mrsId": 142, + "mrsDisplay": "Amani Health Centre", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "", + "eidDisplay": "" + }, + "d29bad2f-0b89-402f-835e-4e37c7d9334a": { + "mrsId": 143, + "mrsDisplay": "Gynocare Health Centre", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "19205", + "eidDisplay": "" + }, + "f83a6fbc-ad66-491e-82d3-72155661c498": { + "mrsId": 144, + "mrsDisplay": "St. Marys Health Centre - Kapsoya", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "15655", + "eidDisplay": "" + }, + "f4121927-e8ac-46d1-8b7d-fa6d9adcb677": { + "mrsId": 145, + "mrsDisplay": "SOS Medical Centre - Eldoret", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "17945", + "eidDisplay": "" + }, + "b99d3714-9715-484e-8ad9-bf0ada16fdf4": { + "mrsId": 146, + "mrsDisplay": "Imani Hospital ", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "16357", + "eidDisplay": "" + }, + "f6d67dad-cdf4-4756-82c8-cb34d1eecc3a": { + "mrsId": 147, + "mrsDisplay": "Fountain Health Centre", + "cityVillage": "Eldoret", + "county": "", + "description": "Private Hospital in Eldoret", + "mflCode": "19173", + "eidDisplay": "" + }, + "294efcca-cf90-40da-8abb-1e082866388d": { + "mrsId": 148, + "mrsDisplay": "St. Luke", + "cityVillage": null, + "county": null, + "description": "A Private Hospital in Eldoret", + "mflCode": "18776", + "eidDisplay": "" + }, + "8f1c7aca-97e5-4cca-be46-21969abde1c8": { + "mrsId": 149, + "mrsDisplay": "EldoretHosp", + "cityVillage": null, + "county": null, + "description": "A private hospital in Eldoret.", + "mflCode": "14435", + "eidDisplay": "" + }, + "717758f6-8dec-443e-bf1c-ca0bf8a5ec6d": { + "mrsId": 150, + "mrsDisplay": "Sisenye Dispensary", + "cityVillage": null, + "county": null, + "description": "Dispensary in Bunyala sub-county", + "mflCode": "16131", + "eidDisplay": "" + }, + "fece02d9-b3cd-4eaf-802f-8ad33ace4c30": { + "mrsId": 151, + "mrsDisplay": "Rukala Dispensary", + "cityVillage": null, + "county": null, + "description": "Dispensary in Bunyala Sub-County.", + "mflCode": "16095", + "eidDisplay": "" + }, + "68df53ea-d990-4769-ae2d-34ec85218325": { + "mrsId": 152, + "mrsDisplay": "Budalangi Dispensary", + "cityVillage": null, + "county": null, + "description": "A dispensary in Bunyala Sub-county", + "mflCode": "15811", + "eidDisplay": "" + }, + "0c2b5af9-43e1-4182-9292-59f499d23c9c": { + "mrsId": 153, + "mrsDisplay": "Reale Hospital", + "cityVillage": "Eldoret", + "county": "Uasin-Gishu", + "description": "Private Hospital in Eldoret\r\nunder the Private Sector Engagement program\r\n(formally PPP)", + "mflCode": "18983", + "eidDisplay": "" + }, + "402e0744-82be-4784-bb6e-e5a30d1055cf": { + "mrsId": 154, + "mrsDisplay": "sokyot", + "cityVillage": "Kosachei", + "county": "Uasin Gishu", + "description": "A community based in Turbo", + "mflCode": "", + "eidDisplay": "" + }, + "3824461a-1289-4108-b5b0-98f0f6f8f509": { + "mrsId": 155, + "mrsDisplay": "Turbo/Kaptebee", + "cityVillage": null, + "county": "UasinGishu", + "description": "A community in Turbo", + "mflCode": "15753", + "eidDisplay": "" + }, + "ac339ab6-49e3-4b33-949d-505358797d5a": { + "mrsId": 156, + "mrsDisplay": "Ngechek", + "cityVillage": "kapngetich", + "county": "Nandi", + "description": "A community In Kosirai Division", + "mflCode": "15342", + "eidDisplay": "" + }, + "8bfe3e63-ce86-4d5b-b3ae-b9ec13628530": { + "mrsId": 157, + "mrsDisplay": "Tuigoin", + "cityVillage": "Suigoi", + "county": "Uasin Gishu", + "description": "A community Unit in Turbo Division", + "mflCode": "", + "eidDisplay": "" + }, + "825a2541-49ff-41b5-b267-7ff0a059f290": { + "mrsId": 158, + "mrsDisplay": "Leseru", + "cityVillage": "Chemalal", + "county": "Uasin Gishu", + "description": "A community Unit in Turbo Division", + "mflCode": "", + "eidDisplay": "" + }, + "1dc7a1c9-e553-48a9-8a1e-e97b18a480c5": { + "mrsId": 159, + "mrsDisplay": "Kosirai", + "cityVillage": "Belekenya", + "county": "Nandi", + "description": "A community Unit in Kosirai Division", + "mflCode": "", + "eidDisplay": "" + }, + "52645ed9-c8c4-4912-b66a-a05b201ddb5f": { + "mrsId": 160, + "mrsDisplay": "Mutwot", + "cityVillage": "Mutwot Village", + "county": "Nandi", + "description": "A Community unit in Kosirai Division", + "mflCode": "", + "eidDisplay": "" + }, + "a4001a80-ac34-4a6f-a7fd-80d689f2b18b": { + "mrsId": 161, + "mrsDisplay": "Laikipia", + "cityVillage": null, + "county": "Laikipia", + "description": "An amrs site in Laikipia County", + "mflCode": "", + "eidDisplay": "" + }, + "25ff6c5b-d46d-4d8c-bf4c-dae135efa70b": { + "mrsId": 162, + "mrsDisplay": "Sirimba Mission Hospital", + "cityVillage": null, + "county": "Busia", + "description": "A health Facility in Busia County", + "mflCode": "16129", + "eidDisplay": "" + }, + "cf044cde-d23b-4bf2-a152-e83a0e9a2288": { + "mrsId": 163, + "mrsDisplay": "Nasewa Health Centre", + "cityVillage": null, + "county": "Busia", + "description": "A Health Facility in Nasewa", + "mflCode": "16074", + "eidDisplay": "" + }, + "751a05f1-6889-48ec-911b-d626ac02d9cd": { + "mrsId": 164, + "mrsDisplay": "Mabunge", + "cityVillage": null, + "county": "Busia", + "description": "A community unit in Nasewa", + "mflCode": "Mabunge", + "eidDisplay": "" + }, + "f7896a4a-2348-4493-ac02-0772255f49f6": { + "mrsId": 165, + "mrsDisplay": "Buyama", + "cityVillage": null, + "county": "Busia", + "description": "A community unit in Nasewa", + "mflCode": "Buyama", + "eidDisplay": "" + }, + "356f3aaa-bd92-4823-a602-33ea6efe44d4": { + "mrsId": 166, + "mrsDisplay": "Lung'a", + "cityVillage": null, + "county": "Busia", + "description": "A community unit in Nasewa", + "mflCode": "16074", + "eidDisplay": "" + }, + "eb85f1ae-6d39-4929-bd99-2002f4eb96a8": { + "mrsId": 167, + "mrsDisplay": "Nasewa", + "cityVillage": null, + "county": "Busia", + "description": "A community unit in Nasewa", + "mflCode": "16074", + "eidDisplay": "" + }, + "97157544-80c4-469d-b7bc-92e3053ded8e": { + "mrsId": 168, + "mrsDisplay": "Sikarira Dispensary", + "cityVillage": null, + "county": "Busia", + "description": "A health facility in Sikarira", + "mflCode": "16485", + "eidDisplay": "" + }, + "a49aa7a3-c5ae-4c7a-a6a0-3b9e5ba60522": { + "mrsId": 169, + "mrsDisplay": "Bulwani", + "cityVillage": null, + "county": "Busia", + "description": "A Community Unit in Bwaliro", + "mflCode": "15822", + "eidDisplay": "" + }, + "b940a5af-07ce-4fb0-ae5c-3271943c8ce1": { + "mrsId": 170, + "mrsDisplay": "Kanjala", + "cityVillage": null, + "county": "Busia", + "description": "A community unit in Sikarira", + "mflCode": "16485", + "eidDisplay": "" + }, + "1e92054b-9aed-42b7-b358-95cd311f98e2": { + "mrsId": 171, + "mrsDisplay": "Sirimba Mission Hospital", + "cityVillage": null, + "county": "Busia", + "description": "A health Facility in Busia County", + "mflCode": "16129", + "eidDisplay": "" + }, + "8d2265b4-d311-4a92-a792-2097d22ac174": { + "mrsId": 172, + "mrsDisplay": "Ruambwa", + "cityVillage": null, + "county": "Busia", + "description": "A community unit in Sirimba", + "mflCode": "16129", + "eidDisplay": "" + }, + "7f95db31-e91b-4753-8b92-1d52aa9b4abf": { + "mrsId": 173, + "mrsDisplay": "Ikonzo Dispensary", + "cityVillage": null, + "county": "Busia", + "description": "A Health Facility in Busia", + "mflCode": "17165", + "eidDisplay": "" + }, + "c88683c8-988c-4580-afaa-c2909597f758": { + "mrsId": 174, + "mrsDisplay": "Namwitsula", + "cityVillage": null, + "county": "Busia", + "description": "A community unit in Ikonzo", + "mflCode": "17165", + "eidDisplay": "" + }, + "57e7d161-13da-464f-a7b5-bffbade5b2de": { + "mrsId": 175, + "mrsDisplay": "Ikonzo", + "cityVillage": null, + "county": "Busia", + "description": "A community Unit in Ikonzo", + "mflCode": "17165", + "eidDisplay": "" + }, + "d83e9d9e-8211-414d-8269-7b9308184b82": { + "mrsId": 176, + "mrsDisplay": "West Clinic Health Centre", + "cityVillage": null, + "county": "Uasin Gishu", + "description": "A health facility in Uasin Gishu", + "mflCode": "", + "eidDisplay": "" + }, + "d332cd41-99d5-47bb-baab-0b61a59aadc2": { + "mrsId": 177, + "mrsDisplay": "Kibulgeng", + "cityVillage": null, + "county": "Uasin Gihu", + "description": "A community facility in Uasin Gishu", + "mflCode": "", + "eidDisplay": "" + }, + "b35dfc65-80f8-41fa-9932-cd347edd346d": { + "mrsId": 178, + "mrsDisplay": "Bujumba Dispensary", + "cityVillage": null, + "county": "Busia", + "description": "Is a health Facility in Bujumba", + "mflCode": "15816", + "eidDisplay": "" + }, + "1646cb1f-2e3c-4ca3-9157-a4ad2f67fe38": { + "mrsId": 179, + "mrsDisplay": "Bujumba", + "cityVillage": null, + "county": "Busia", + "description": "Is a community Facility in Bujumba", + "mflCode": "15816", + "eidDisplay": "" + }, + "956794fa-2193-4ff6-bad1-65b947d0faa3": { + "mrsId": 183, + "mrsDisplay": "Ikonzo Dispensary", + "cityVillage": null, + "county": "Busia", + "description": "A dispensary in Busia", + "mflCode": "17165", + "eidDisplay": "" + }, + "49066b8b-2b9a-43cf-b3e4-18d3759ecd00": { + "mrsId": 184, + "mrsDisplay": "Ikonzo Dispensary", + "cityVillage": null, + "county": "Busia", + "description": "A dispensary in Busia", + "mflCode": "17165", + "eidDisplay": "" + }, + "cb0a7e64-dd5d-4c46-9cb3-c382d95e9c50": { + "mrsId": 185, + "mrsDisplay": "Sikarira", + "cityVillage": null, + "county": "Busia", + "description": "A community unit in Ikonzo", + "mflCode": "16485", + "eidDisplay": "" + }, + "e155b8b0-e89d-4916-8b6c-3af9d93b582b": { + "mrsId": 186, + "mrsDisplay": "MTRH-Memorial Hospital", + "cityVillage": null, + "county": "Uasin Gishu", + "description": "PPP Clinic", + "mflCode": "15204", + "eidDisplay": "" + }, + "e02b0e78-4312-4006-9e39-0994a759acb2": { + "mrsId": 187, + "mrsDisplay": "Chep'ngoror Dispensary", + "cityVillage": null, + "county": "A dispensary in Burnt forest", + "description": "A dispensary in Burnt Forest", + "mflCode": "16347", + "eidDisplay": "" + }, + "659f2926-4712-4bd9-a532-7c1b20a0d47b": { + "mrsId": 188, + "mrsDisplay": "Matunda Health Centre", + "cityVillage": null, + "county": "Uasin Gishu", + "description": "A community unit in Matunda", + "mflCode": "16364", + "eidDisplay": "" + }, + "f8bf061a-8ef2-4145-9522-03e642d23eaf": { + "mrsId": 189, + "mrsDisplay": "Endebes Health Centre", + "cityVillage": null, + "county": "trans nzoia", + "description": "A Health Centre in Trans nzoia", + "mflCode": "14455", + "eidDisplay": "" + }, + "67001f34-4df1-4cfa-8552-04d5236dd3a3": { + "mrsId": 190, + "mrsDisplay": "Kwanza Health Centre", + "cityVillage": null, + "county": "Trans-Nzoia", + "description": "A Health Facility in Trans Nzoia", + "mflCode": "15003", + "eidDisplay": "" + }, + "4dbd0c2b-cb9f-491a-8dbc-c4e552db1515": { + "mrsId": 191, + "mrsDisplay": "Anderson", + "cityVillage": null, + "county": "Transzoia", + "description": "A health centre in transzoia", + "mflCode": "", + "eidDisplay": "" + }, + "b56b5219-0c8f-4520-810e-ba43302c63eb": { + "mrsId": 192, + "mrsDisplay": "Kapsoya Health Centre", + "cityVillage": null, + "county": "Uasin Gishu", + "description": "A health centre in Kapsoya", + "mflCode": "14769", + "eidDisplay": "" + }, + "c8ede412-a5da-47be-ae7f-f76a4ffc5065": { + "mrsId": 193, + "mrsDisplay": "Sister Freda Medical", + "cityVillage": "Kitale", + "county": "Trans Nzoia", + "description": "A Health facility in Trans Nzoia", + "mflCode": "14947", + "eidDisplay": "" + }, + "b3bf1ec7-ea9c-4bc6-af5b-ddb6864b7975": { + "mrsId": 194, + "mrsDisplay": "St. Ladislaus Dispensary", + "cityVillage": null, + "county": "Uasin Gishu", + "description": "A health facility in Uasin Gishu County", + "mflCode": "16345", + "eidDisplay": "" + }, + "18c343eb-b353-462a-9139-b16606e6b6c2": { + "mrsId": 195, + "mrsDisplay": "Location Test", + "cityVillage": null, + "county": "test", + "description": "This is a test location for POC Testers.", + "mflCode": "15204", + "eidDisplay": "" + }, + "10446739-2ef2-4fb3-b134-29840d97acbe": { + "mrsId": 198, + "mrsDisplay": "MTRH Adolescent Clinic", + "cityVillage": "Eldoret", + "county": "", + "description": "Moi Teaching and Referral Hospital Adolescent Clinic.", + "mflCode": "15204", + "eidDisplay": "" + }, + "af0d01d4-7c15-491d-be73-50512ab67e3a": { + "mrsId": 211, + "mrsDisplay": "Alphima Medical Clinic", + "cityVillage": "Eldoret", + "county": "", + "description": "A Private Hospital in Eldoret.", + "mflCode": "23646", + "eidDisplay": "" + }, + "538c14c2-c98a-49a2-9e11-0af6f7b912dc": { + "mrsId": 196, + "mrsDisplay": "Mediheal Hospital", + "cityVillage": "Eldoret", + "county": "", + "description": "A ppp Clinic in Eldoret", + "mflCode": "15167", + "eidDisplay": "" + }, + "02e85257-94d6-43bf-8603-322248c1a210": { + "mrsId": 197, + "mrsDisplay": "MTRH MCH", + "description": "Used to collect PMTCT data.", + "mflCode": "15204", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "4ff7f723-95ce-4481-ba47-6539f22aae3c": { + "mrsId": 199, + "mrsDisplay": "MTRH Nyayo Ward", + "description": "MTRH clinic Nyayo Ward", + "mflCode": "15204", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "3ce46ae0-7eca-48c9-86d3-d5bdde1c7dab": { + "mrsId": 200, + "mrsDisplay": "MTRH Mother & Baby Ward", + "description": "MTRH Mother & Baby Ward", + "mflCode": "15204", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "0d599936-1a29-464b-87ad-c92cf51a6a84": { + "mrsId": 201, + "mrsDisplay": "MTRH Pediatric Ward", + "description": "MTRH Pediatric Ward", + "mflCode": "15204", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "2a901f42-bf51-428c-8be3-a135075abcb2": { + "mrsId": 202, + "mrsDisplay": "MTRH Other", + "description": "MTRH Other", + "mflCode": "15204", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "20bd486d-5c84-44f4-9ffa-2f1c1d9e79f8": { + "mrsId": 203, + "mrsDisplay": "Langas", + "description": "Facility", + "mflCode": "15011", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "20967b54-63b5-4311-a68e-2fc04406e56a": { + "mrsId": 204, + "mrsDisplay": "MTRH Oncology", + "description": "Moi Teaching and Referral Hospital - \nOncology", + "mflCode": "15204", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "584b1638-b11d-4cbe-8e81-ff25b684d63c": { + "mrsId": 205, + "mrsDisplay": "Busagwa Dispensary", + "description": "Busagwa Dispensary", + "mflCode": "21037", + "county": "Busia", + "cityVillage": "", + "eidDisplay": "" + }, + "7fb68709-6e7b-4eaf-a984-ea111fa45853": { + "mrsId": 206, + "mrsDisplay": "MTRH ACTG", + "description": "MTRH ACTG", + "mflCode": "15204", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "1ee4e702-913b-40a6-ab9c-26f9b4fced1c": { + "mrsId": 208, + "mrsDisplay": "Huruma MCH", + "description": "Huruma MCH", + "mflCode": "14555", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "7bc85590-2de6-4780-b4d8-f167b71c1834": { + "mrsId": 209, + "mrsDisplay": "Kakamega", + "description": "Is a Kakamega County Referral hospital", + "mflCode": null, + "county": "Kakamega", + "cityVillage": "", + "eidDisplay": "" + }, + "d4f8de72-5058-4db8-b556-324c7020b83b": { + "mrsId": 210, + "mrsDisplay": "Homabay", + "description": "Oncology site", + "mflCode": null, + "county": "Homabay", + "cityVillage": "", + "eidDisplay": "" + }, + "21beec4b-d6d0-4fe3-9711-acab0d577067": { + "mrsId": 212, + "mrsDisplay": "Jaramogi Oginga Odinga TRH", + "description": "Jaramogi Oginga Odinga Training and Referral Hospital.", + "mflCode": "13939", + "county": "Kisumu", + "cityVillage": "", + "eidDisplay": "" + }, + "db2bdd7c-5fe6-4ea3-adc1-d2d8dfb3d658": { + "mrsId": 213, + "mrsDisplay": "Bomet", + "description": "Oncology clinic at Bomet", + "mflCode": null, + "county": "Kericho", + "cityVillage": "", + "eidDisplay": "" + }, + "1ce5034b-f05d-46b6-910f-fc959e091641": { + "mrsId": 214, + "mrsDisplay": "Kapenguria County Referral Hospital", + "description": "Referral hospital in Kapenguria.", + "mflCode": "14701", + "county": "West Pokot", + "cityVillage": "", + "eidDisplay": "" + }, + "c54cbafc-3d6a-41a0-ae6c-ef40df16e2c9": { + "mrsId": 215, + "mrsDisplay": "Hamisi Sub County Hospital", + "description": "A sub county hospital in Hamisi", + "mflCode": null, + "county": "Vihiga", + "cityVillage": "", + "eidDisplay": "" + }, + "3acdbf65-644a-44c6-b6fa-9dad734ec442": { + "mrsId": 216, + "mrsDisplay": "BUTERE", + "description": "An Oncology Clinic", + "mflCode": null, + "county": "Kakamega", + "cityVillage": "", + "eidDisplay": "" + }, + "2a7ef5d8-28b6-4285-8313-c356ebbd3305": { + "mrsId": 219, + "mrsDisplay": "St. Elizabeth Lwak Mission Health center", + "description": "A health Center in Siaya County", + "mflCode": null, + "county": "Siaya", + "cityVillage": "", + "eidDisplay": "" + }, + "d6155afe-9258-4632-9723-08de6d7e2602": { + "mrsId": 220, + "mrsDisplay": "Madiany sub county hospital", + "description": "Madiany sub county in Siaya County- Oncology study", + "mflCode": "13747", + "county": "Siaya", + "cityVillage": "", + "eidDisplay": "" + }, + "3d65bfd3-c134-4133-a7aa-f44a2206f403": { + "mrsId": 221, + "mrsDisplay": "Bungoma County Referral Hospital", + "description": "A referral hospital in Bungoma county", + "mflCode": "15828", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "bf02fef0-0330-4247-82b0-d9ed490206a2": { + "mrsId": 222, + "mrsDisplay": "Nyahururu District Hospital", + "description": "A district Hospital in Laikipia County", + "mflCode": "10890", + "county": "Laikipia", + "cityVillage": "", + "eidDisplay": "" + }, + "68cb63f3-992d-4fd0-a80d-47a27fcf8021": { + "mrsId": 223, + "mrsDisplay": "MTRH TB", + "description": "TB Clinic at MTRH", + "mflCode": "15204", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + }, + "dfc36b77-c059-4a29-8a92-a40d5ad60774": { + "mrsId": 224, + "mrsDisplay": "Chemundu Dispensary", + "description": "A dispensary in Nandi County.", + "mflCode": "14324", + "county": "Nandi", + "cityVillage": "", + "eidDisplay": "" + }, + "261a0504-17fa-4fae-989f-4d4f30767842": { + "mrsId": 225, + "mrsDisplay": "AIC Kapsowar Mission Hospital", + "description": "Mission Hospital in Kapsowar.", + "mflCode": "14767", + "county": "Elgeyo Marakwet", + "cityVillage": "", + "eidDisplay": "" + }, + "65225dcd-81cc-4c8f-92e1-bb687995cf24": { + "mrsId": 226, + "mrsDisplay": "Vihiga County Referral Hospital.", + "description": "Referral Hospital in Vihiga county.", + "mflCode": "16157", + "county": "Vihiga", + "cityVillage": "", + "eidDisplay": "" + }, + "a36c86bb-7ca3-4319-8674-28c66ba14deb": { + "mrsId": 227, + "mrsDisplay": "Iten MCH", + "description": "An mch facility", + "mflCode": "14586", + "county": "Elgeyo Marakwet", + "cityVillage": "", + "eidDisplay": "" + }, + "535dc3bd-842b-4ca1-bc7c-357635ab985e": { + "mrsId": 229, + "mrsDisplay": "Kitale MCH", + "description": "mch clinic at kitale", + "mflCode": "14947", + "county": "transzoia", + "cityVillage": "", + "eidDisplay": "" + }, + "17c97881-90e5-43c8-b8a3-cc0322f89a89": { + "mrsId": 230, + "mrsDisplay": "Busia MCH", + "description": "mch clinic at busia.", + "mflCode": "15834", + "county": "Busia", + "cityVillage": "", + "eidDisplay": "" + }, + "f2320960-28de-41cf-b7d5-4734b75bafef": { + "mrsId": 231, + "mrsDisplay": "Chulaimbo MCH", + "description": "mch clinic at chulaimbo.", + "mflCode": "13528", + "county": "Kisumu", + "cityVillage": "", + "eidDisplay": "" + }, + "aa65d6b1-fad8-46a7-94cb-f5247d21509d": { + "mrsId": 232, + "mrsDisplay": "Meru County Referral Hospital", + "description": null, + "mflCode": "12516", + "county": "Meru County", + "cityVillage": "", + "eidDisplay": "" + }, + "ff95cb97-3d9e-4016-aff9-930fed3c55ec": { + "mrsId": 233, + "mrsDisplay": "Sori Lake side Hospital", + "description": "A hospital in Migori County", + "mflCode": "14098", + "county": "Migori", + "cityVillage": "", + "eidDisplay": "" + }, + "c79828e4-16cd-4c30-8164-13d6005aa879": { + "mrsId": 234, + "mrsDisplay": "Nyamira County Referral Hospital", + "description": "Nyamira County Referral Hospital - Oncology Clinic", + "mflCode": "13912", + "county": "Nyamira", + "cityVillage": "", + "eidDisplay": "" + }, + "dbe94e9c-c882-4ec0-9edc-d0038069cd00": { + "mrsId": 235, + "mrsDisplay": "Webuye Health Centre", + "description": "Health Centre in Bungoma County", + "mflCode": "16160", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "c0f4fd82-0d65-4b0b-aa04-be5914063959": { + "mrsId": 236, + "mrsDisplay": "Mulachi Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": null, + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "cb7fae6f-8daa-4a84-b4b0-7a1852b0526c": { + "mrsId": 237, + "mrsDisplay": "Lukusi Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": "16711", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "e2bb5611-a016-4440-951d-f35e42ad4821": { + "mrsId": 238, + "mrsDisplay": "Khaoya Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": "15933", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "df1f80fa-8c43-429d-93b9-bc01d0c898cf": { + "mrsId": 239, + "mrsDisplay": "Miendo Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": "16015", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "52d0a75a-b281-4f6d-a7c4-07c0cd5b1ee4": { + "mrsId": 240, + "mrsDisplay": "Matulo Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": "16389", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "61492482-4cde-4c71-8d20-e5ab9e858583": { + "mrsId": 241, + "mrsDisplay": "Khayaya Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": "16710", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "89442596-43af-4e32-a185-d1b5fbd86549": { + "mrsId": 242, + "mrsDisplay": "Namwatikho Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": "22501", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "90d8e717-36a6-4df2-a321-2fb2e9956bc0": { + "mrsId": 243, + "mrsDisplay": "Mukhe Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": "16028", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "299c8c3a-121a-4931-b1fa-fff949292ac3": { + "mrsId": 244, + "mrsDisplay": "Khalala Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": "18362", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "a568c19e-cfcb-416a-83ae-9c24b72d2c38": { + "mrsId": 245, + "mrsDisplay": "Chemalal Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": null, + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "6ae719f8-1805-4680-82d3-2bf58c617047": { + "mrsId": 246, + "mrsDisplay": "Namarambi Dispensary", + "description": "A dispensary in Bungoma County", + "mflCode": "21771", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "122addaa-dc8a-4e86-ad76-695aa35e2f6e": { + "mrsId": 247, + "mrsDisplay": "Lurare Dispensary", + "description": "CDM site", + "mflCode": "15976", + "county": "Bungoma", + "cityVillage": "", + "eidDisplay": "" + }, + "34aec983-646e-4d8f-93a9-fa8156de15ec": { + "mrsId": 248, + "mrsDisplay": "Garissa County Referral Hospital", + "description": "This is an Oncology clinic that the AMPATH oncology will be supporting.", + "mflCode": "13346", + "county": "Garissa", + "cityVillage": "", + "eidDisplay": "" + }, + "379ff09d-c72f-4859-a9dc-3c0295738252": { + "mrsId": 249, + "mrsDisplay": "MTRH Anti-coagulation", + "description": "oncology anti-coagulation treatment.", + "mflCode": "15204", + "county": "Uasin Gishu", + "cityVillage": "", + "eidDisplay": "" + } +} diff --git a/service/eid/eid-lab-reminder.service.js b/service/eid/eid-lab-reminder.service.js index 7ae6f7c2f..f547c0237 100755 --- a/service/eid/eid-lab-reminder.service.js +++ b/service/eid/eid-lab-reminder.service.js @@ -10,49 +10,49 @@ let serviceDef = { module.exports = serviceDef; function pendingEIDReminders(params, config) { - const reflect = (promise) => { - return promise.then(result => ({ success: true, result })).catch(error => ({ success: false, error })); + return promise + .then((result) => ({ success: true, result })) + .catch((error) => ({ success: false, error })); }; console.log('Config', config); - return ObsService.getPatientIdentifiers(params.patientUuid).then((identifiers) => { - let batch = []; - console.log('identifiers', identifiers); - if (config && identifiers) { - Object.keys(config).forEach((labLocation) => { - console.log('labLocation', labLocation); - let labClient = new LabClient(config[labLocation]); - let filterOptions = { - patient_id: identifiers.identifiers.join() - } - batch.push(labClient.fetchPendingViralLoad(filterOptions)) - }); - } - - - return Promise.all(batch.map(reflect)).then((results) => { - // merge results from all sites - - let mergedResults = []; - // console.log('Data',results); - for (let result of results) { - mergedResults = mergedResults.concat(result.result.data) + return ObsService.getPatientIdentifiers(params.patientUuid) + .then((identifiers) => { + let batch = []; + console.log('identifiers', identifiers); + if (config && identifiers) { + Object.keys(config).forEach((labLocation) => { + console.log('labLocation', labLocation); + let labClient = new LabClient(config[labLocation]); + let filterOptions = { + patient_id: identifiers.identifiers.join() + }; + batch.push(labClient.fetchPendingViralLoad(filterOptions)); + }); } - return new Promise((resolve, reject) => { - resolve(mergedResults); - }); - }).catch((err) => { + return Promise.all(batch.map(reflect)) + .then((results) => { + // merge results from all sites + + let mergedResults = []; + // console.log('Data',results); + for (let result of results) { + mergedResults = mergedResults.concat(result.result.data); + } + return new Promise((resolve, reject) => { + resolve(mergedResults); + }); + }) + .catch((err) => { + return new Promise((resolve, reject) => { + reject(err); + }); + }); + }) + .catch((err) => { return new Promise((resolve, reject) => { reject(err); }); }); - - }).catch((err) => { - return new Promise((resolve, reject) => { - reject(err); - }); - }); - } - diff --git a/service/eid/eid-patient-cohort.service.js b/service/eid/eid-patient-cohort.service.js index b7a514a90..4b9f831f4 100755 --- a/service/eid/eid-patient-cohort.service.js +++ b/service/eid/eid-patient-cohort.service.js @@ -1,18 +1,16 @@ 'use strict'; -var - syncService = require('../eid.service'), +var syncService = require('../eid.service'), _ = require('underscore'), Promise = require('bluebird'), moment = require('moment'), config = require('../../conf/config'), etlLogger = require('../../etl-file-logger'); - module.exports = { - synchronizePatientCohort: synchronizePatientCohort - }; +module.exports = { + synchronizePatientCohort: synchronizePatientCohort +}; function synchronizePatientCohort(patientUuIdCohort, locations, reply) { - var responses = { success: [], fail: [] @@ -20,9 +18,11 @@ function synchronizePatientCohort(patientUuIdCohort, locations, reply) { var logger = getLogger(); - Promise.reduce(patientUuIdCohort, function (previous, patientUuId) { - - return syncService.getSynchronizedPatientLabResults(patientUuId, locations) + Promise.reduce( + patientUuIdCohort, + function (previous, patientUuId) { + return syncService + .getSynchronizedPatientLabResults(patientUuId, locations) .then(function (response) { logger.info('%s successfully syncd', response.uuid); _.each(response.data, function (row) { @@ -39,13 +39,16 @@ function synchronizePatientCohort(patientUuIdCohort, locations, reply) { .catch(function (errors) { return errors; }); - }, 0) - .then(function (data) { - reply(responses); - logger.close(); - }); + }, + 0 + ).then(function (data) { + reply(responses); + logger.close(); + }); } function getLogger() { - return etlLogger.logger(config.logging.eidPath + '/' + config.logging.eidFile); -} \ No newline at end of file + return etlLogger.logger( + config.logging.eidPath + '/' + config.logging.eidFile + ); +} diff --git a/service/eid/eid.service.js b/service/eid/eid.service.js index f521e417f..f730410dc 100755 --- a/service/eid/eid.service.js +++ b/service/eid/eid.service.js @@ -1,278 +1,288 @@ (function () { - 'use strict'; - const _ = require('underscore'); - const moment = require('moment'); - const eidFacilityMap = require('../eid/eid-facility-mappings'); - const eidOrderMap = require('../../app/lab-integration/utils/regimen-config-loader'); - const config = require('../../conf/config'); - - function generatePayloadByOrderType(rawPayload, callback, failback) { - //now generate the payload - switch (rawPayload.type) { - case 'DNAPCR': - callback({ - "mflCode": getLocation(rawPayload, 'mflCode'), - "mrsLocation": getLocation(rawPayload, 'mrsId'), - "mrsOrderNumber": rawPayload.orderNumber, - "providerIdentifier": rawPayload.providerIdentifier, - "patientName": rawPayload.patientName, - "patientId": rawPayload.patientIdentifier, - "sex": rawPayload.sex, - "birthdate": rawPayload.birthDate, - "dateDrawn": rawPayload.dateDrawn, - "dateReceived": rawPayload.dateReceived, - "receivedStatus": 1, - "infantProphylaxis": getInfantProphylaxis(rawPayload) || 5, - "pmtctIntervention": getPmtctIntervention(rawPayload) || 5, - "feedingType": getInfantFeedingPlan(rawPayload) || 0, - "entryPoint": getDnaPcrEntryPoint(rawPayload) || 0, - "motherHivStatus": getHivStatus(rawPayload) || 0, - "numberOfSpots": 1 - }); - break; - case 'VL': - callback({ - "mflCode": getLocation(rawPayload, 'mflCode'), - "mrsLocation": getLocation(rawPayload, 'mrsId'), - "mrsOrderNumber": rawPayload.orderNumber, - "providerIdentifier": rawPayload.providerIdentifier, - "patientName": rawPayload.patientName, - "patientId": rawPayload.patientIdentifier, - "sex": rawPayload.sex, - "birthdate": rawPayload.birthDate, - "dateDrawn": rawPayload.dateDrawn, - "dateReceived": rawPayload.dateReceived, - "receivedStatus": 1, - "sampletype": rawPayload.sampleType ? rawPayload.sampleType : 1, //default to 3 to prevent code breaking - "artStartDateInitial": rawPayload.artStartDateInitial, - "artStartDateCurrent": rawPayload.artStartDateCurrent, - "artRegimen": getArtRegimen(rawPayload) || 14, - "justification": getTestOrderJustification(rawPayload) || 0 - - }); - break; - case 'CD4': - callback({ - "mflCode": getLocation(rawPayload, 'mflCode'), - "mrsLocation": getLocation(rawPayload, 'mrsId'), - "mrsOrderNumber": rawPayload.orderNumber, - "providerIdentifier": rawPayload.providerIdentifier, - "patientName": rawPayload.patientName, - "patientId": rawPayload.patientIdentifier, - "sex": rawPayload.sex.toUpperCase(), - "birthdate": rawPayload.birthDate, - "dateDrawn": rawPayload.dateDrawn, - "dateReceived": rawPayload.dateReceived, - "receivedStatus": 1 - }); - break; - default: - failback('This type of lab order can not be posted by POC (CD4, DNAPCR and VL can only be processed)'); - } + 'use strict'; + const _ = require('underscore'); + const moment = require('moment'); + const eidFacilityMap = require('../eid/eid-facility-mappings'); + const eidOrderMap = require('../../app/lab-integration/utils/regimen-config-loader'); + const config = require('../../conf/config'); + + function generatePayloadByOrderType(rawPayload, callback, failback) { + //now generate the payload + switch (rawPayload.type) { + case 'DNAPCR': + callback({ + mflCode: getLocation(rawPayload, 'mflCode'), + mrsLocation: getLocation(rawPayload, 'mrsId'), + mrsOrderNumber: rawPayload.orderNumber, + providerIdentifier: rawPayload.providerIdentifier, + patientName: rawPayload.patientName, + patientId: rawPayload.patientIdentifier, + sex: rawPayload.sex, + birthdate: rawPayload.birthDate, + dateDrawn: rawPayload.dateDrawn, + dateReceived: rawPayload.dateReceived, + receivedStatus: 1, + infantProphylaxis: getInfantProphylaxis(rawPayload) || 5, + pmtctIntervention: getPmtctIntervention(rawPayload) || 5, + feedingType: getInfantFeedingPlan(rawPayload) || 0, + entryPoint: getDnaPcrEntryPoint(rawPayload) || 0, + motherHivStatus: getHivStatus(rawPayload) || 0, + numberOfSpots: 1 + }); + break; + case 'VL': + callback({ + mflCode: getLocation(rawPayload, 'mflCode'), + mrsLocation: getLocation(rawPayload, 'mrsId'), + mrsOrderNumber: rawPayload.orderNumber, + providerIdentifier: rawPayload.providerIdentifier, + patientName: rawPayload.patientName, + patientId: rawPayload.patientIdentifier, + sex: rawPayload.sex, + birthdate: rawPayload.birthDate, + dateDrawn: rawPayload.dateDrawn, + dateReceived: rawPayload.dateReceived, + receivedStatus: 1, + sampletype: rawPayload.sampleType ? rawPayload.sampleType : 1, //default to 3 to prevent code breaking + artStartDateInitial: rawPayload.artStartDateInitial, + artStartDateCurrent: rawPayload.artStartDateCurrent, + artRegimen: getArtRegimen(rawPayload) || 14, + justification: getTestOrderJustification(rawPayload) || 0 + }); + break; + case 'CD4': + callback({ + mflCode: getLocation(rawPayload, 'mflCode'), + mrsLocation: getLocation(rawPayload, 'mrsId'), + mrsOrderNumber: rawPayload.orderNumber, + providerIdentifier: rawPayload.providerIdentifier, + patientName: rawPayload.patientName, + patientId: rawPayload.patientIdentifier, + sex: rawPayload.sex.toUpperCase(), + birthdate: rawPayload.birthDate, + dateDrawn: rawPayload.dateDrawn, + dateReceived: rawPayload.dateReceived, + receivedStatus: 1 + }); + break; + default: + failback( + 'This type of lab order can not be posted by POC (CD4, DNAPCR and VL can only be processed)' + ); } - - function generatePocToEidPayLoad(payload){ - console.log('generatePocToEidPayLoad', payload); - var eidPayload = { + } + + function generatePocToEidPayLoad(payload) { + console.log('generatePocToEidPayLoad', payload); + var eidPayload = {}; + switch (payload.type) { + case 'VL': + eidPayload = { + mflCode: getLocation(payload, 'mflCode'), + patient_identifier: payload.patientIdentifier, + dob: payload.birthDate, + datecollected: payload.dateDrawn, + sex: getGenderCode(payload.sex), + prophylaxis: getArtRegimen(payload) || 14, + regimenline: 1, + sampletype: payload.sampleType ? payload.sampleType : 1, + justification: getTestOrderJustification(payload) || 0, + pmtct: getPmtctIntervention(payload) || 5 }; - switch(payload.type){ - case 'VL': - eidPayload = { - "mflCode": getLocation(payload, 'mflCode'), - "patient_identifier": payload.patientIdentifier, - "dob": payload.birthDate, - "datecollected": payload.dateDrawn, - "sex": getGenderCode(payload.sex), - "prophylaxis": getArtRegimen(payload) || 14, - "regimenline": 1, - "sampletype": payload.sampleType ? payload.sampleType : 1, - "justification": getTestOrderJustification(payload) || 0, - "pmtct": getPmtctIntervention(payload) || 5 - }; - break; - case 'DNAPCR': - eidPayload = { - "mflCode": getLocation(payload, 'mflCode'), - "patient_identifier": payload.patientIdentifier, - "dob": payload.birthDate, - "datecollected": payload.dateDrawn, - "sex": getGenderCode(payload.sex), - "feeding": getInfantFeedingPlan(payload) || 0, - "pcrtype": "", - "regimen": getInfantProphylaxis(payload) || 5, - "entry_point": getDnaPcrEntryPoint(payload) || 0, - "mother_prophylaxis": getPmtctIntervention(payload) || 5, - "mother_last_result": "", - "spots": "", - "mother_age": "", - "ccc_no": "", - "lab": "" - }; - break; - case 'CD4': - eidPayload = { - "mflCode": getLocation(payload, 'mflCode'), - "dob": payload.birthDate, - "datecollected": payload.dateDrawn, - "sex": getGenderCode(payload.sex), - "patient_name": payload.patientName, - "medicalrecordno": payload.patientIdentifier, - "order_no": payload.orderNumber, - "amrs_location": getLocation(payload, 'mrsId'), - "provider_identifier": payload.providerIdentifier - }; - break; - default: - - + break; + case 'DNAPCR': + eidPayload = { + mflCode: getLocation(payload, 'mflCode'), + patient_identifier: payload.patientIdentifier, + dob: payload.birthDate, + datecollected: payload.dateDrawn, + sex: getGenderCode(payload.sex), + feeding: getInfantFeedingPlan(payload) || 0, + pcrtype: '', + regimen: getInfantProphylaxis(payload) || 5, + entry_point: getDnaPcrEntryPoint(payload) || 0, + mother_prophylaxis: getPmtctIntervention(payload) || 5, + mother_last_result: '', + spots: '', + mother_age: '', + ccc_no: '', + lab: '' }; - - console.log('generatePocToEidPayLoad', eidPayload); - - return eidPayload; - - } - - function getEidServerUrl(lab, orderType, apiCall) { - var serverConfig = config.eidServer[lab]; - switch (orderType) { - case 'DNAPCR': - return { - url: serverConfig.host + ':' + serverConfig.port + serverConfig[apiCall].dnaPcr + 'orders/eid.php', - apiKey: serverConfig.apiKey - }; - break; - case 'VL': - return { - url: serverConfig.host + ':' + serverConfig.port + serverConfig[apiCall].vl + 'orders/vl.php', - apiKey: serverConfig.apiKey - }; - break; - case 'CD4': - return { - url: serverConfig.host + ':' + serverConfig.port + serverConfig[apiCall].cd4 + 'orders/cd4.php', - apiKey: serverConfig.apiKey - }; - break; - default: - return { - url: serverConfig.host + ':' + serverConfig.port + config.eid.generalPath, - apiKey: serverConfig.apiKey - } - - } - } - - //helpers - function getInfantProphylaxis(rawPayload) { - var result = eidOrderMap.infantProphylaxis[rawPayload.infantProphylaxisUuid]; - if (result) return result.eidId; - } - - function getPmtctIntervention(rawPayload) { - var result = eidOrderMap.pmtctIntervention[rawPayload.pmtctInterventionUuid]; - if (result) return result.eidId; + break; + case 'CD4': + eidPayload = { + mflCode: getLocation(payload, 'mflCode'), + dob: payload.birthDate, + datecollected: payload.dateDrawn, + sex: getGenderCode(payload.sex), + patient_name: payload.patientName, + medicalrecordno: payload.patientIdentifier, + order_no: payload.orderNumber, + amrs_location: getLocation(payload, 'mrsId'), + provider_identifier: payload.providerIdentifier + }; + break; + default: } - function getInfantFeedingPlan(rawPayload) { - var result = eidOrderMap.infantFeedingPlan[rawPayload.feedingTypeUuid]; - if (result) return result.eidId; + console.log('generatePocToEidPayLoad', eidPayload); + + return eidPayload; + } + + function getEidServerUrl(lab, orderType, apiCall) { + var serverConfig = config.eidServer[lab]; + switch (orderType) { + case 'DNAPCR': + return { + url: + serverConfig.host + + ':' + + serverConfig.port + + serverConfig[apiCall].dnaPcr + + 'orders/eid.php', + apiKey: serverConfig.apiKey + }; + break; + case 'VL': + return { + url: + serverConfig.host + + ':' + + serverConfig.port + + serverConfig[apiCall].vl + + 'orders/vl.php', + apiKey: serverConfig.apiKey + }; + break; + case 'CD4': + return { + url: + serverConfig.host + + ':' + + serverConfig.port + + serverConfig[apiCall].cd4 + + 'orders/cd4.php', + apiKey: serverConfig.apiKey + }; + break; + default: + return { + url: + serverConfig.host + + ':' + + serverConfig.port + + config.eid.generalPath, + apiKey: serverConfig.apiKey + }; } - - function getDnaPcrEntryPoint(rawPayload) { - var result = eidOrderMap.dnaPcrEntryPoint[rawPayload.entryPointUuid]; - if (result) return result.eidId; + } + + //helpers + function getInfantProphylaxis(rawPayload) { + var result = + eidOrderMap.infantProphylaxis[rawPayload.infantProphylaxisUuid]; + if (result) return result.eidId; + } + + function getPmtctIntervention(rawPayload) { + var result = + eidOrderMap.pmtctIntervention[rawPayload.pmtctInterventionUuid]; + if (result) return result.eidId; + } + + function getInfantFeedingPlan(rawPayload) { + var result = eidOrderMap.infantFeedingPlan[rawPayload.feedingTypeUuid]; + if (result) return result.eidId; + } + + function getDnaPcrEntryPoint(rawPayload) { + var result = eidOrderMap.dnaPcrEntryPoint[rawPayload.entryPointUuid]; + if (result) return result.eidId; + } + + function getHivStatus(rawPayload) { + var result = eidOrderMap.hivStatus[rawPayload.motherHivStatusUuid]; + if (result) return result.eidId; + } + + function getLocation(rawPayload, code) { + var result = eidFacilityMap[rawPayload.locationUuid]; + if (result) return result[code]; + } + function getGenderCode(gender) { + var genderCode; + switch (gender) { + case 'F': + genderCode = 2; + break; + case 'M': + genderCode = 1; + break; + default: + genderCode = 0; } + return genderCode; + } - function getHivStatus(rawPayload) { - var result = eidOrderMap.hivStatus[rawPayload.motherHivStatusUuid]; - if (result) return result.eidId; - } + function hasCode(list, code) { + var hasCode = false; - function getLocation(rawPayload, code) { - var result = eidFacilityMap[rawPayload.locationUuid]; - if (result) return result[code]; - } - function getGenderCode(gender){ - var genderCode; - switch(gender){ - case 'F': - genderCode = 2; - break; - case 'M': - genderCode = 1; - break; - default: - genderCode = 0; + try { + _.each(list, function (item) { + if (parseInt(item) === parseInt(code)) { + hasCode = true; } - return genderCode; - - } - - function hasCode(list, code) { - - var hasCode = false; + }); + } catch (e) {} - try { - - _.each(list, function (item) { - - if(parseInt(item) === parseInt(code)) { - hasCode = true; - } - }); - } catch(e) {} - - return hasCode; - } + return hasCode; + } - function getArtRegimen(rawPayload) { + function getArtRegimen(rawPayload) { + if (rawPayload.artRegimenUuid === '') return 15; //15 is none; - if (rawPayload.artRegimenUuid === "") return 15; //15 is none; + var arvCodes = rawPayload.artRegimenUuid + ? rawPayload.artRegimenUuid.split(' ## ') + : null; + var resolvedId = 14; // 14 is other - var arvCodes = rawPayload.artRegimenUuid ? rawPayload.artRegimenUuid.split(" ## ") : null; - var resolvedId=14; // 14 is other + if (!(arvCodes && arvCodes.length > 0)) return resolvedId; - if(!(arvCodes && arvCodes.length > 0)) return resolvedId; + _.each(eidOrderMap.artRegimen, function (artRegimen) { + var mrsArvRegimens = artRegimen.mrsArvRegimen.split(','); - _.each(eidOrderMap.artRegimen, function (artRegimen) { - - var mrsArvRegimens = artRegimen.mrsArvRegimen.split(","); - - if(hasCode(mrsArvRegimens, arvCodes[0])) { - - var hasCodes = true; - - if(arvCodes.length === 1 && mrsArvRegimens.length != 1) { + if (hasCode(mrsArvRegimens, arvCodes[0])) { + var hasCodes = true; + if (arvCodes.length === 1 && mrsArvRegimens.length != 1) { + hasCodes = false; + } else { + for (var i = 1; i < arvCodes.length; i++) { + var code = arvCodes[i]; + if (!hasCode(mrsArvRegimens, arvCodes[i])) { hasCodes = false; - } else { - - for(var i = 1; i < arvCodes.length; i++) { - - var code = arvCodes[i]; - if(!hasCode(mrsArvRegimens, arvCodes[i])) { - hasCodes = false; - break; - } - } + break; } - - if(hasCodes) resolvedId = artRegimen.eidId; } - }); + } - return resolvedId; - } + if (hasCodes) resolvedId = artRegimen.eidId; + } + }); - function getTestOrderJustification(rawPayload) { - var result = eidOrderMap.testOrderJustification[rawPayload.vlJustificationUuid]; - if (result) return result.eidId; - } + return resolvedId; + } + + function getTestOrderJustification(rawPayload) { + var result = + eidOrderMap.testOrderJustification[rawPayload.vlJustificationUuid]; + if (result) return result.eidId; + } - module.exports = { - generatePayload: generatePayloadByOrderType, - generatePocToEidPayLoad: generatePocToEidPayLoad, - getEidServerUrl: getEidServerUrl - }; + module.exports = { + generatePayload: generatePayloadByOrderType, + generatePocToEidPayLoad: generatePocToEidPayLoad, + getEidServerUrl: getEidServerUrl + }; })(); diff --git a/service/eid/mappings/eid-order-mappings-v1.json b/service/eid/mappings/eid-order-mappings-v1.json index 58f7ff3d3..b26c22042 100755 --- a/service/eid/mappings/eid-order-mappings-v1.json +++ b/service/eid/mappings/eid-order-mappings-v1.json @@ -415,7 +415,7 @@ "mrsDisplay": "No Data" } }, - "hivStatus":{ + "hivStatus": { "a896f3a6-1350-11df-a1f1-0026b9348838": { "eidId": 2, "eidDisplay": "Positive", @@ -432,7 +432,7 @@ "mrsDisplay": "Unknown" } }, - "infantProphylaxis":{ + "infantProphylaxis": { "a8967656-1350-11df-a1f1-0026b9348838": { "eidId": 1, "eidDisplay": "sdNVP only", @@ -474,14 +474,14 @@ "mrsDisplay": "Other" } }, - "pmtctIntervention":{ + "pmtctIntervention": { "a8967656-1350-11df-a1f1-0026b9348838": { "eidId": 1, "eidDisplay": "sdNVP only", "mrsDisplay": "sdNVP only" }, "0906b973-25da-4e87-a272-84692cdd8453": { - "eidId":5, + "eidId": 5, "eidDisplay": "Uninterrupted HAART (HAART until end of BF)", "mrsDisplay": "Uninterrupted HAART (HAART until end of BF)" }, @@ -511,9 +511,9 @@ "mrsDisplay": "Other" } }, - "infantFeedingPlan":{ + "infantFeedingPlan": { "a8a8d9b8-1350-11df-a1f1-0026b9348838": { - "eidId":1, + "eidId": 1, "eidDisplay": "EBF=Exclusive breastfeeding", "mrsDisplay": "EBF=Exclusive breastfeeding" }, diff --git a/service/eid/mappings/eid-order-mappings-v2.json b/service/eid/mappings/eid-order-mappings-v2.json index 913fa799c..b472358d2 100644 --- a/service/eid/mappings/eid-order-mappings-v2.json +++ b/service/eid/mappings/eid-order-mappings-v2.json @@ -1,1057 +1,1057 @@ { - "artRegimen": [ - { - "eidId": "1", - "eidCode": "AF2E", - "age": "1", - "line": "1", - "eidDisplay": "TDF+3TC+DTG", - "mrsArvRegimen": "10268" - }, - { - "eidId": "1", - "eidCode": "AF2E", - "age": "1", - "line": "1", - "eidDisplay": "TDF+3TC+DTG", - "mrsArvRegimen": "628,802,9759" - }, - { - "eidId": "2", - "eidCode": "AF2B", - "age": "1", - "line": "1", - "eidDisplay": "TDF+3TC+EFV", - "mrsArvRegimen": "6964,32,152,598" - }, - { - "eidId": "3", - "eidCode": "AF1D", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+DTG", - "mrsArvRegimen": "" - }, - { - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+EFV", - "mrsArvRegimen": "9053" - }, - { - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+EFV", - "mrsArvRegimen": "630,633" - }, - { - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+EFV", - "mrsArvRegimen": "628,633,797" - }, - { - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+EFV", - "mrsArvRegimen": "630,633,1065" - }, - { - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+EFV", - "mrsArvRegimen": "630,633,5424" - }, - { - "eidDisplay": "EFV/3TC/TDF", - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "mrsArvRegimen": "6964" - }, - { - "eidDisplay": "EFV/3TC/TDF", - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "mrsArvRegimen": "633,1400" - }, - { - "eidDisplay": "YES/EFV/3TC/TDF", - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "mrsArvRegimen": "1065,6964" - }, - { - "eidDisplay": "3TC/TDF/EFV/3TC/TDF", - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "mrsArvRegimen": "1400,6964" - }, - { - "eidDisplay": "3TC/EFV/TDF", - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "mrsArvRegimen": "628,633,802" - }, - { - "eidDisplay": "EFV/EFV/3TC/TDF", - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "mrsArvRegimen": "633,6964" - }, - { - "eidDisplay": "EFV/3TC/TDF/EFV/3TC/TDF", - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "mrsArvRegimen": "6964,6964" - }, - { - "eidDisplay": "OTHER/EFV/3TC/TDF", - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "mrsArvRegimen": "5424,6964" - }, - { - "eidDisplay": "EFV/YES/3TC/TDF", - "eidId": "4", - "eidCode": "AF1B", - "age": "1", - "line": "1", - "mrsArvRegimen": "633,1065,1400" - }, - { - "eidId": "5", - "eidCode": "AF4B", - "age": "1", - "line": "1", - "eidDisplay": "ABC+3TC+EFV", - "mrsArvRegimen": "" - }, - { - "eidDisplay": "EFV/ABC/3TC", - "eidId": "5", - "eidCode": "AF4B", - "age": "1", - "line": "1", - "mrsArvRegimen": "633,6679" - }, - { - "eidDisplay": "3TC/EFV/ABC", - "eidId": "5", - "eidCode": "AF4B", - "age": "1", - "line": "1", - "mrsArvRegimen": "628,633,814" - }, - { - "eidDisplay": "EFV/YES/ABC/3TC", - "eidId": "5", - "eidCode": "AF4B", - "age": "1", - "line": "1", - "mrsArvRegimen": "633,1065,6679" - }, - { - "eidDisplay": "3TC/EFV/ABC/YES", - "eidId": "5", - "eidCode": "AF4B", - "age": "1", - "line": "1", - "mrsArvRegimen": "628,633,814,1065" - }, - { - "eidDisplay": "3TC/EFV/ABC/3TC", - "eidId": "5", - "eidCode": "AF4B", - "age": "1", - "line": "1", - "mrsArvRegimen": "628,633,6679" - }, - { - "eidId": "6", - "eidCode": "AF4C", - "age": "1", - "line": "1", - "eidDisplay": "ABC+3TC+DTG", - "mrsArvRegimen": "" - }, - { - "eidId": "7", - "eidCode": "AF2D", - "age": "1", - "line": "1", - "eidDisplay": "TDF+3TC+ATV/r", - "mrsArvRegimen": "" - }, - { - "eidDisplay": "3TC/TDF/ATV/R", - "eidId": "7", - "eidCode": "AF2D", - "age": "1", - "line": "1", - "mrsArvRegimen": "1400,6160" - }, - { - "eidDisplay": "3TC/TDF/ATV", - "eidId": "7", - "eidCode": "AF2D", - "age": "1", - "line": "1", - "mrsArvRegimen": "1400,6159" - }, - { - "eidDisplay": "3TC/TDF/OTHER/ATV", - "eidId": "7", - "eidCode": "AF2D", - "age": "1", - "line": "1", - "mrsArvRegimen": "1400,5424,6159" - }, - { - "eidDisplay": "3TC/TDF/OTHER/ATV/R", - "eidId": "7", - "eidCode": "AF2D", - "age": "1", - "line": "1", - "mrsArvRegimen": "1400,5424,6160" - }, - { - "eidId": "8", - "eidCode": "AF2F", - "age": "1", - "line": "1", - "eidDisplay": "TDF+3TC+LPV/r", - "mrsArvRegimen": "9055" - }, - { - "eidDisplay": "LPV/R/3TC/TDF", - "eidId": "8", - "eidCode": "AF2F", - "age": "1", - "line": "1", - "mrsArvRegimen": "794,1400" - }, - { - "eidDisplay": "3TC/LPV/R/3TC/TDF", - "eidId": "8", - "eidCode": "AF2F", - "age": "1", - "line": "1", - "mrsArvRegimen": "628,794,1400" - }, - { - "eidDisplay": "LPV/R/YES/3TC/TDF", - "eidId": "8", - "eidCode": "AF2F", - "age": "1", - "line": "1", - "mrsArvRegimen": "794,1065,1400" - }, - { - "eidId": "9", - "eidCode": "AF1E", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+LPV/r", - "mrsArvRegimen": "" - }, - { - "eidDisplay": "AZT/3TC/LPV/R", - "eidId": "9", - "eidCode": "AF1E", - "age": "1", - "line": "1", - "mrsArvRegimen": "630,794" - }, - { - "eidDisplay": "3TC/LPV/R/AZT", - "eidId": "9", - "eidCode": "AF1E", - "age": "1", - "line": "1", - "mrsArvRegimen": "628,794,797" - }, - { - "eidDisplay": "AZT/3TC/LPV/R/YES", - "eidId": "9", - "eidCode": "AF1E", - "age": "1", - "line": "1", - "mrsArvRegimen": "630,794,1065" - }, - { - "eidId": "10", - "eidCode": "AF1F", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+ATV/r", - "mrsArvRegimen": "630,6160" - }, - { - "eidId": "10", - "eidCode": "AF1F", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+ATV/r", - "mrsArvRegimen": "630,6159" - }, - { - "eidId": "10", - "eidCode": "AF1F", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+ATV/r", - "mrsArvRegimen": "628,797,6160" - }, - { - "eidId": "10", - "eidCode": "AF1F", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+ATV/r", - "mrsArvRegimen": "630,5424,6159" - }, - { - "eidId": "10", - "eidCode": "AF1F", - "age": "1", - "line": "1", - "eidDisplay": "AZT/3TC/ATV/R", - "mrsArvRegimen": "630,6160" - }, - { - "eidId": "10", - "eidCode": "AF1F", - "age": "1", - "line": "1", - "eidDisplay": "AZT/3TC/ATV", - "mrsArvRegimen": "630,6159" - }, - { - "eidId": "10", - "eidCode": "AF1F", - "age": "1", - "line": "1", - "eidDisplay": "3TC/AZT/ATV/R", - "mrsArvRegimen": "628,797,6160" - }, - { - "eidId": "10", - "eidCode": "AF1F", - "age": "1", - "line": "1", - "eidDisplay": "AZT/3TC/OTHER/ATV", - "mrsArvRegimen": "630,5424,6159" - }, - { - "eidId": "11", - "eidCode": "AF2A", - "age": "1", - "line": "1", - "eidDisplay": "TDF+3TC+NVP", - "mrsArvRegimen": "" - }, - { - "eidId": "12", - "eidCode": "AF1A", - "age": "1", - "line": "1", - "eidDisplay": "AZT+3TC+NVP", - "mrsArvRegimen": "6467,18,19,35,154,159" - }, - { - "eidDisplay": "NVP/3TC/AZT", - "eidId": "12", - "eidCode": "AF1A", - "age": "1", - "line": "1", - "mrsArvRegimen": "6467" - }, - { - "eidDisplay": "AZT/3TC/NVP", - "eidId": "12", - "eidCode": "AF1A", - "age": "1", - "line": "1", - "mrsArvRegimen": "630,631" - }, - { - "eidDisplay": "YES/NVP/3TC/AZT", - "eidId": "12", - "eidCode": "AF1A", - "age": "1", - "line": "1", - "mrsArvRegimen": "1065,6467" - }, - { - "eidDisplay": "3TC/NVP/AZT", - "eidId": "12", - "eidCode": "AF1A", - "age": "1", - "line": "1", - "mrsArvRegimen": "628,631,797" - }, - { - "eidDisplay": "AZT/3TC/NVP/3TC/AZT", - "eidId": "12", - "eidCode": "AF1A", - "age": "1", - "line": "1", - "mrsArvRegimen": "630,6467" - }, - { - "eidDisplay": "NVP/NVP/3TC/AZT", - "eidId": "12", - "eidCode": "AF1A", - "age": "1", - "line": "1", - "mrsArvRegimen": "631,6467" - }, - { - "eidDisplay": "NVP/3TC/AZT/NVP/3TC/AZT", - "eidId": "12", - "eidCode": "AF1A", - "age": "1", - "line": "1", - "mrsArvRegimen": "6467,6467" - }, - { - "eidDisplay": "AZT/3TC/NVP/YES", - "eidId": "12", - "eidCode": "AF1A", - "age": "1", - "line": "1", - "mrsArvRegimen": "630,631,1065" - }, - { - "eidId": "13", - "eidCode": "AF4A", - "age": "1", - "line": "1", - "eidDisplay": "ABC+3TC+NVP", - "mrsArvRegimen": "9050" - }, - { - "eidDisplay": "NVP,ABC/3TC", - "eidId": "13", - "eidCode": "AF4A", - "age": "1", - "line": "1", - "mrsArvRegimen": "631,6679" - }, - { - "eidDisplay": "3TC/NVP/ABC", - "eidId": "13", - "eidCode": "AF4A", - "age": "1", - "line": "1", - "mrsArvRegimen": "628,631,814" - }, - { - "eidDisplay": "NVP/YES/ABC/3TC", - "eidId": "13", - "eidCode": "AF4A", - "age": "1", - "line": "1", - "mrsArvRegimen": "631,1065,6679" - }, - { - "eidDisplay": "3TC/NVP/ABC/3TC", - "eidId": "13", - "eidCode": "AF4A", - "age": "1", - "line": "1", - "mrsArvRegimen": "628,631,6679" - }, - { - "eidId": "14", - "eidCode": "AF5X", - "age": "1", - "line": "1", - "eidDisplay": "Other", - "mrsArvRegimen": "5622" - }, - { - "eidId": "15", - "eidCode": "AS1A", - "age": "1", - "line": "2", - "eidDisplay": "AZT+3TC+LPV/r", - "mrsArvRegimen": "" - }, - { - "eidId": "16", - "eidCode": "AS1B", - "age": "1", - "line": "2", - "eidDisplay": "AZT+3TC+ATV/r", - "mrsArvRegimen": "" - }, - { - "eidId": "17", - "eidCode": "AS1C", - "age": "1", - "line": "2", - "eidDisplay": "AZT+3TC+DTG", - "mrsArvRegimen": "" - }, - { - "eidId": "18", - "eidCode": "AS2A", - "age": "1", - "line": "2", - "eidDisplay": "TDF+3TC+LPV/r", - "mrsArvRegimen": "9055" - }, - { - "eidId": "19", - "eidCode": "AS2B", - "age": "1", - "line": "2", - "eidDisplay": "TDF+3TC+DTG", - "mrsArvRegimen": "10268,597" - }, - { - "eidId": "20", - "eidCode": "AS2C", - "age": "1", - "line": "2", - "eidDisplay": "TDF+3TC+ATV/r", - "mrsArvRegimen": "" - }, - { - "eidId": "21", - "eidCode": "AS5A", - "age": "1", - "line": "2", - "eidDisplay": "ABC+3TC+LPV/r", - "mrsArvRegimen": "9051" - }, - { - "eidDisplay": "3TC,LPV/R,ABC", - "eidId": "21", - "eidCode": "AS5A", - "age": "1", - "line": "2", - "mrsArvRegimen": "628,794,814" - }, - { - "eidDisplay": "LPV/R/ABC/3TC", - "eidId": "21", - "eidCode": "AS5A", - "age": "1", - "line": "2", - "mrsArvRegimen": "794,6679" - }, - { - "eidDisplay": "LPV/R/YES/ABC/3TC", - "eidId": "21", - "eidCode": "AS5A", - "age": "1", - "line": "2", - "mrsArvRegimen": "794,1065,6679" - }, - { - "eidDisplay": "3TC/LPV/R/ABC/YES", - "eidId": "21", - "eidCode": "AS5A", - "age": "1", - "line": "2", - "mrsArvRegimen": "628,794,814,1065" - }, - { - "eidDisplay": "3TC/LPV/R/ABC/3TC/TDF", - "eidId": "21", - "eidCode": "AS5A", - "age": "1", - "line": "2", - "mrsArvRegimen": "628,794,814,1400" - }, - { - "eidId": "22", - "eidCode": "AS5B", - "age": "1", - "line": "2", - "eidDisplay": "ABC+3TC+LPV/r", - "mrsArvRegimen": "" - }, - { - "eidDisplay": "3TC/ABC/ATV/R", - "eidId": "22", - "eidCode": "AS5B", - "age": "1", - "line": "2", - "mrsArvRegimen": "628,814,6160" - }, - { - "eidDisplay": "3TC/ABC/ATV", - "eidId": "22", - "eidCode": "AS5B", - "age": "1", - "line": "2", - "mrsArvRegimen": "628,814,6159" - }, - { - "eidDisplay": "3TC/ABC/OTHER/ATV", - "eidId": "22", - "eidCode": "AS5B", - "age": "1", - "line": "2", - "mrsArvRegimen": "628,814,5424,6159" - }, - { - "eidDisplay": "ATV/R/ABC/3TC", - "eidId": "22", - "eidCode": "AS5B", - "age": "1", - "line": "2", - "mrsArvRegimen": "6160,6679" - }, - { - "eidId": "23", - "eidCode": "AS5C", - "age": "1", - "line": "2", - "eidDisplay": "ABC+3TC+DTG", - "mrsArvRegimen": "" - }, - { - "eidId": "24", - "eidCode": "AS6X", - "age": "1", - "line": "2", - "eidDisplay": "Other", - "mrsArvRegimen": "5622" - }, - { - "eidId": "25", - "eidCode": "AT2D", - "age": "1", - "line": "3", - "eidDisplay": "TDF+3TC+DTG+DRV/r", - "mrsArvRegimen": "" - }, - { - "eidId": "26", - "eidCode": "AT2E", - "age": "1", - "line": "3", - "eidDisplay": "TDF+3TC+DTG+DRV/r", - "mrsArvRegimen": "" - }, - { - "eidId": "27", - "eidCode": "AT2F", - "age": "1", - "line": "3", - "eidDisplay": "TDF+3TC+DTG+ETV+DRV/r", - "mrsArvRegimen": "" - }, - { - "eidId": "28", - "eidCode": "AT2X", - "age": "1", - "line": "3", - "eidDisplay": "Other", - "mrsArvRegimen": "5622" - }, - { - "eidId": "29", - "eidCode": "CF2B", - "age": "2", - "line": "1", - "eidDisplay": "ABC+3TC+EFV", - "mrsArvRegimen": "" - }, - { - "eidId": "30", - "eidCode": "CF2D", - "age": "2", - "line": "1", - "eidDisplay": "ABC+3TC+LPV/r", - "mrsArvRegimen": "9051" - }, - { - "eidId": "31", - "eidCode": "CF2A", - "age": "2", - "line": "1", - "eidDisplay": "ABC+3TC+NVP", - "mrsArvRegimen": "9050" - }, - { - "eidId": "32", - "eidCode": "CF2F", - "age": "2", - "line": "1", - "eidDisplay": "ABC+3TC+RAL", - "mrsArvRegimen": "" - }, - { - "eidId": "33", - "eidCode": "CF1A", - "age": "2", - "line": "1", - "eidDisplay": "AZT+3TC+NVP", - "mrsArvRegimen": "6467" - }, - { - "eidId": "34", - "eidCode": "CF1B", - "age": "2", - "line": "1", - "eidDisplay": "AZT+3TC+EFV", - "mrsArvRegimen": "9053" - }, - { - "eidId": "35", - "eidCode": "CF1C", - "age": "2", - "line": "1", - "eidDisplay": "AZT+3TC+LPV/r", - "mrsArvRegimen": "" - }, - { - "eidId": "36", - "eidCode": "CF5X", - "age": "2", - "line": "1", - "eidDisplay": "Other", - "mrsArvRegimen": "5622" - }, - { - "eidId": "37", - "eidCode": "CS1A", - "age": "2", - "line": "2", - "eidDisplay": "AZT+3TC+LPV/r", - "mrsArvRegimen": "" - }, - { - "eidId": "38", - "eidCode": "CS2A", - "age": "2", - "line": "2", - "eidDisplay": "AZT+3TC+LPV/r", - "mrsArvRegimen": "9051" - }, - { - "eidId": "39", - "eidCode": "CS1C", - "age": "2", - "line": "2", - "eidDisplay": "AZT+3TC+DRV/r+RAL", - "mrsArvRegimen": "" - }, - { - "eidId": "40", - "eidCode": "CS1C", - "age": "2", - "line": "2", - "eidDisplay": "ABC+3TC+DRV/r+RAL", - "mrsArvRegimen": "" - }, - { - "eidId": "41", - "eidCode": "CS4X", - "age": "2", - "line": "2", - "eidDisplay": "Other", - "mrsArvRegimen": "5622" - }, - { - "eidId": "42", - "eidCode": "CT1H", - "age": "2", - "line": "3", - "eidDisplay": "AZT+3TC+DRV/r+RAL", - "mrsArvRegimen": "" - }, - { - "eidId": "43", - "eidCode": "CT2D", - "age": "2", - "line": "3", - "eidDisplay": "ABC+3TC+DRV/r+RAL", - "mrsArvRegimen": "" - }, - { - "eidId": "44", - "eidCode": "CT3X", - "age": "2", - "line": "3", - "eidDisplay": "Other", - "mrsArvRegimen": "5622" - } - ], - "testOrderJustification": { - "5931c4d4-4406-4d71-b75d-2205d905cc24": { - "eidId": 1, - "eidCode": "", - "eidDisplay": "Routine VL", - "mrsDisplay": "" - }, - "e43ddeb6-3984-499c-a280-3bade1039608": { - "eidId": 2, - "eidCode": "", - "eidDisplay": "Confirmation of Treatment Failure (Repeat VL at 3M)", - "mrsDisplay": "" - }, - "a8981934-1350-11df-a1f1-0026b9348838": { - "eidId": 3, - "eidCode": "", - "eidDisplay": "Clinical Failure", - "mrsDisplay": "" - }, - "a8a00158-1350-11df-a1f1-0026b9348838": { - "eidId": 4, - "eidCode": "", - "eidDisplay": "Single Drug Substitution", - "mrsDisplay": "" - }, - "3966e139-ca69-47c6-aad3-ebd41bb45e28": { - "eidId": 5, - "eidCode": "", - "eidDisplay": "Baseline VL (for infants diagnosed through EID)", - "mrsDisplay": "" - }, - "42cdefa2-c306-4d10-a819-c04131c4934e": { - "eidId": 6, - "eidCode": "", - "eidDisplay": "Confirmation of persistent low level viremia (PLLV)", - "mrsDisplay": "" - }, - "a8aaf3e2-1350-11df-a1f1-0026b9348838": { - "eidId": 7, - "eidCode": "", - "eidDisplay": "Other", - "mrsDisplay": "" - }, - "undefined": { - "eidId": 8, - "eidCode": "", - "eidDisplay": "No Data", - "mrsDisplay": "" - } - }, - "dnaPcrEntryPoint": { - "a8a09ac8-1350-11df-a1f1-0026b9348838": { - "eidDisplay": "OPD", - "eidId": 1, - "eidCode": "", - "mrsDisplay": "OPD" - }, - "3e5ad07b-2ced-4925-8264-cc4d8d1438d4": { - "eidDisplay": "Paediatric Ward", - "eidId": 2, - "eidCode": "", - "mrsDisplay": "Peadiatric ward" - }, - "a8a17d80-1350-11df-a1f1-0026b9348838": { - "eidDisplay": "MCH/PMTCT", - "eidId": 3, - "eidCode": "", - "mrsDisplay": "MCH" - }, - "a89fbedc-1350-11df-a1f1-0026b9348838": { - "eidDisplay": "MCH/PMTCT", - "eidId": 3, - "eidCode": "", - "mrsDisplay": "PMTCT" - }, - "a8a3899a-1350-11df-a1f1-0026b9348838": { - "eidDisplay": "CCC/PSC", - "eidId": 4, - "eidCode": "", - "mrsDisplay": "CCC" - }, - "materrnity-uuid": { - "eidDisplay": "Materrnity", - "eidId": 5, - "eidCode": "", - "mrsDisplay": "Materrnity" - }, - "a8aaf3e2-1350-11df-a1f1-0026b9348838": { - "eidDisplay": "Other", - "eidId": 6, - "eidCode": "", - "mrsDisplay": "Other" - }, - "undefined": { - "eidDisplay": "No Data", - "eidId": 7, - "eidCode": "", - "mrsDisplay": "No Data" - } - }, - "hivStatus":{ - "a896f3a6-1350-11df-a1f1-0026b9348838": { - "eidId": 2, - "eidCode": "", - "eidDisplay": "Positive", - "mrsDisplay": "Positive" - }, - "a896d2cc-1350-11df-a1f1-0026b9348838": { - "eidId": 1, - "eidCode": "", - "eidDisplay": "Negative", - "mrsDisplay": "Negative" - }, - "a899b50a-1350-11df-a1f1-0026b9348838": { - "eidId": 0, - "eidCode": "", - "eidDisplay": "", - "mrsDisplay": "Unknown" - } - }, - "infantProphylaxis":{ - "a8967656-1350-11df-a1f1-0026b9348838": { - "eidId": 1, - "eidCode": "", - "eidDisplay": "sdNVP only", - "mrsDisplay": "sdNVP only" - }, - "6a73f32d-1870-4527-af6e-74443251ded2": { - "eidId": 2, - "eidCode": "", - "eidDisplay": "sdNVP +AZT +3TC", - "mrsDisplay": "sdNVP +AZT +3TC" - }, - "a8967656-1350-11df-a1f1-0026b9348838": { - "eidId": 10, - "eidCode": "", - "eidDisplay": "NVP for 6 weeks", - "mrsDisplay": "NVP" - }, - "a897ea4a-1350-11df-a1f1-0026b9348838": { - "eidId": 5, - "eidCode": "", - "eidDisplay": "AZT", - "mrsDisplay": "AZT" - }, - "a8967656-1350-11df-a1f1-0026b9348838": { - "eidId": 5, - "eidCode": "", - "eidDisplay": "", - "mrsDisplay": "NVP during BF period" - }, - "a899e0ac-1350-11df-a1f1-0026b9348838": { - "eidId": 0, - "eidCode": "", - "eidDisplay": "None", - "mrsDisplay": "None" - }, - "undefined": { - "eidId": 0, - "eidCode": "", - "eidDisplay": "None", - "mrsDisplay": "None" - }, - "a8aaf3e2-1350-11df-a1f1-0026b9348838": { - "eidId": 5, - "eidCode": "", - "eidDisplay": "Other", - "mrsDisplay": "Other" - } - }, - "pmtctIntervention":{ - "a8967656-1350-11df-a1f1-0026b9348838": { - "eidId": 1, - "eidCode": "", - "eidDisplay": "sdNVP only", - "mrsDisplay": "sdNVP only" - }, - "0906b973-25da-4e87-a272-84692cdd8453": { - "eidId":5, - "eidDisplay": "Uninterrupted HAART (HAART until end of BF)", - "mrsDisplay": "Uninterrupted HAART (HAART until end of BF)" - }, - "6a73f32d-1870-4527-af6e-74443251ded2": { - "eidId": 2, - "eidCode": "", - "eidDisplay": "Sd NVP+AZT+3TC", - "mrsDisplay": "AZT (from 14wks or later) + sdNVP + 3TC (Tail)" - }, - "a899ccb6-1350-11df-a1f1-0026b9348838": { - "eidId": 7, - "eidCode": "", - "eidDisplay": "HAART", - "mrsDisplay": "HAART" - }, - "a899e0ac-1350-11df-a1f1-0026b9348838": { - "eidId": 6, - "eidCode": "", - "eidDisplay": "None", - "mrsDisplay": "None" - }, - "undefined": { - "eidId": 6, - "eidCode": "", - "eidDisplay": "None", - "mrsDisplay": "None" - }, - "a8aaf3e2-1350-11df-a1f1-0026b9348838": { - "eidId": 5, - "eidCode": "", - "eidDisplay": "Other", - "mrsDisplay": "Other" - } - }, - "infantFeedingPlan":{ - "a8a8d9b8-1350-11df-a1f1-0026b9348838": { - "eidId":1, - "eidCode": "", - "eidDisplay": "EBF=Exclusive breastfeeding", - "mrsDisplay": "EBF=Exclusive breastfeeding" - }, - "a8a70156-1350-11df-a1f1-0026b9348838": { - "eidId": 4, - "eidCode": "", - "eidDisplay": "ERF=Exclusive replacement feeding", - "mrsDisplay": "ERF=Exclusive replacement feeding" - }, - "a89cca10-1350-11df-a1f1-0026b9348838": { - "eidId": 2, - "eidCode": "", - "eidDisplay": "MF=Mixed Feeding", - "mrsDisplay": "MF=Mixed Feeding" - }, - "a8ae86e2-1350-11df-a1f1-0026b9348838": { - "eidId": 6, - "eidCode": "", - "eidDisplay": "BF= Breastfeeding", - "mrsDisplay": "BF= Breastfeeding" - }, - "a89cc934-1350-11df-a1f1-0026b9348838": { - "eidId": 7, - "eidCode": "", - "eidDisplay": "NBF=Not breastfeeding", - "mrsDisplay": "NBF=Not breastfeeding" - } + "artRegimen": [ + { + "eidId": "1", + "eidCode": "AF2E", + "age": "1", + "line": "1", + "eidDisplay": "TDF+3TC+DTG", + "mrsArvRegimen": "10268" + }, + { + "eidId": "1", + "eidCode": "AF2E", + "age": "1", + "line": "1", + "eidDisplay": "TDF+3TC+DTG", + "mrsArvRegimen": "628,802,9759" + }, + { + "eidId": "2", + "eidCode": "AF2B", + "age": "1", + "line": "1", + "eidDisplay": "TDF+3TC+EFV", + "mrsArvRegimen": "6964,32,152,598" + }, + { + "eidId": "3", + "eidCode": "AF1D", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+DTG", + "mrsArvRegimen": "" + }, + { + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+EFV", + "mrsArvRegimen": "9053" + }, + { + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+EFV", + "mrsArvRegimen": "630,633" + }, + { + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+EFV", + "mrsArvRegimen": "628,633,797" + }, + { + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+EFV", + "mrsArvRegimen": "630,633,1065" + }, + { + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+EFV", + "mrsArvRegimen": "630,633,5424" + }, + { + "eidDisplay": "EFV/3TC/TDF", + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "mrsArvRegimen": "6964" + }, + { + "eidDisplay": "EFV/3TC/TDF", + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "mrsArvRegimen": "633,1400" + }, + { + "eidDisplay": "YES/EFV/3TC/TDF", + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "mrsArvRegimen": "1065,6964" + }, + { + "eidDisplay": "3TC/TDF/EFV/3TC/TDF", + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "mrsArvRegimen": "1400,6964" + }, + { + "eidDisplay": "3TC/EFV/TDF", + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "mrsArvRegimen": "628,633,802" + }, + { + "eidDisplay": "EFV/EFV/3TC/TDF", + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "mrsArvRegimen": "633,6964" + }, + { + "eidDisplay": "EFV/3TC/TDF/EFV/3TC/TDF", + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "mrsArvRegimen": "6964,6964" + }, + { + "eidDisplay": "OTHER/EFV/3TC/TDF", + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "mrsArvRegimen": "5424,6964" + }, + { + "eidDisplay": "EFV/YES/3TC/TDF", + "eidId": "4", + "eidCode": "AF1B", + "age": "1", + "line": "1", + "mrsArvRegimen": "633,1065,1400" + }, + { + "eidId": "5", + "eidCode": "AF4B", + "age": "1", + "line": "1", + "eidDisplay": "ABC+3TC+EFV", + "mrsArvRegimen": "" + }, + { + "eidDisplay": "EFV/ABC/3TC", + "eidId": "5", + "eidCode": "AF4B", + "age": "1", + "line": "1", + "mrsArvRegimen": "633,6679" + }, + { + "eidDisplay": "3TC/EFV/ABC", + "eidId": "5", + "eidCode": "AF4B", + "age": "1", + "line": "1", + "mrsArvRegimen": "628,633,814" + }, + { + "eidDisplay": "EFV/YES/ABC/3TC", + "eidId": "5", + "eidCode": "AF4B", + "age": "1", + "line": "1", + "mrsArvRegimen": "633,1065,6679" + }, + { + "eidDisplay": "3TC/EFV/ABC/YES", + "eidId": "5", + "eidCode": "AF4B", + "age": "1", + "line": "1", + "mrsArvRegimen": "628,633,814,1065" + }, + { + "eidDisplay": "3TC/EFV/ABC/3TC", + "eidId": "5", + "eidCode": "AF4B", + "age": "1", + "line": "1", + "mrsArvRegimen": "628,633,6679" + }, + { + "eidId": "6", + "eidCode": "AF4C", + "age": "1", + "line": "1", + "eidDisplay": "ABC+3TC+DTG", + "mrsArvRegimen": "" + }, + { + "eidId": "7", + "eidCode": "AF2D", + "age": "1", + "line": "1", + "eidDisplay": "TDF+3TC+ATV/r", + "mrsArvRegimen": "" + }, + { + "eidDisplay": "3TC/TDF/ATV/R", + "eidId": "7", + "eidCode": "AF2D", + "age": "1", + "line": "1", + "mrsArvRegimen": "1400,6160" + }, + { + "eidDisplay": "3TC/TDF/ATV", + "eidId": "7", + "eidCode": "AF2D", + "age": "1", + "line": "1", + "mrsArvRegimen": "1400,6159" + }, + { + "eidDisplay": "3TC/TDF/OTHER/ATV", + "eidId": "7", + "eidCode": "AF2D", + "age": "1", + "line": "1", + "mrsArvRegimen": "1400,5424,6159" + }, + { + "eidDisplay": "3TC/TDF/OTHER/ATV/R", + "eidId": "7", + "eidCode": "AF2D", + "age": "1", + "line": "1", + "mrsArvRegimen": "1400,5424,6160" + }, + { + "eidId": "8", + "eidCode": "AF2F", + "age": "1", + "line": "1", + "eidDisplay": "TDF+3TC+LPV/r", + "mrsArvRegimen": "9055" + }, + { + "eidDisplay": "LPV/R/3TC/TDF", + "eidId": "8", + "eidCode": "AF2F", + "age": "1", + "line": "1", + "mrsArvRegimen": "794,1400" + }, + { + "eidDisplay": "3TC/LPV/R/3TC/TDF", + "eidId": "8", + "eidCode": "AF2F", + "age": "1", + "line": "1", + "mrsArvRegimen": "628,794,1400" + }, + { + "eidDisplay": "LPV/R/YES/3TC/TDF", + "eidId": "8", + "eidCode": "AF2F", + "age": "1", + "line": "1", + "mrsArvRegimen": "794,1065,1400" + }, + { + "eidId": "9", + "eidCode": "AF1E", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+LPV/r", + "mrsArvRegimen": "" + }, + { + "eidDisplay": "AZT/3TC/LPV/R", + "eidId": "9", + "eidCode": "AF1E", + "age": "1", + "line": "1", + "mrsArvRegimen": "630,794" + }, + { + "eidDisplay": "3TC/LPV/R/AZT", + "eidId": "9", + "eidCode": "AF1E", + "age": "1", + "line": "1", + "mrsArvRegimen": "628,794,797" + }, + { + "eidDisplay": "AZT/3TC/LPV/R/YES", + "eidId": "9", + "eidCode": "AF1E", + "age": "1", + "line": "1", + "mrsArvRegimen": "630,794,1065" + }, + { + "eidId": "10", + "eidCode": "AF1F", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+ATV/r", + "mrsArvRegimen": "630,6160" + }, + { + "eidId": "10", + "eidCode": "AF1F", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+ATV/r", + "mrsArvRegimen": "630,6159" + }, + { + "eidId": "10", + "eidCode": "AF1F", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+ATV/r", + "mrsArvRegimen": "628,797,6160" + }, + { + "eidId": "10", + "eidCode": "AF1F", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+ATV/r", + "mrsArvRegimen": "630,5424,6159" + }, + { + "eidId": "10", + "eidCode": "AF1F", + "age": "1", + "line": "1", + "eidDisplay": "AZT/3TC/ATV/R", + "mrsArvRegimen": "630,6160" + }, + { + "eidId": "10", + "eidCode": "AF1F", + "age": "1", + "line": "1", + "eidDisplay": "AZT/3TC/ATV", + "mrsArvRegimen": "630,6159" + }, + { + "eidId": "10", + "eidCode": "AF1F", + "age": "1", + "line": "1", + "eidDisplay": "3TC/AZT/ATV/R", + "mrsArvRegimen": "628,797,6160" + }, + { + "eidId": "10", + "eidCode": "AF1F", + "age": "1", + "line": "1", + "eidDisplay": "AZT/3TC/OTHER/ATV", + "mrsArvRegimen": "630,5424,6159" + }, + { + "eidId": "11", + "eidCode": "AF2A", + "age": "1", + "line": "1", + "eidDisplay": "TDF+3TC+NVP", + "mrsArvRegimen": "" + }, + { + "eidId": "12", + "eidCode": "AF1A", + "age": "1", + "line": "1", + "eidDisplay": "AZT+3TC+NVP", + "mrsArvRegimen": "6467,18,19,35,154,159" + }, + { + "eidDisplay": "NVP/3TC/AZT", + "eidId": "12", + "eidCode": "AF1A", + "age": "1", + "line": "1", + "mrsArvRegimen": "6467" + }, + { + "eidDisplay": "AZT/3TC/NVP", + "eidId": "12", + "eidCode": "AF1A", + "age": "1", + "line": "1", + "mrsArvRegimen": "630,631" + }, + { + "eidDisplay": "YES/NVP/3TC/AZT", + "eidId": "12", + "eidCode": "AF1A", + "age": "1", + "line": "1", + "mrsArvRegimen": "1065,6467" + }, + { + "eidDisplay": "3TC/NVP/AZT", + "eidId": "12", + "eidCode": "AF1A", + "age": "1", + "line": "1", + "mrsArvRegimen": "628,631,797" + }, + { + "eidDisplay": "AZT/3TC/NVP/3TC/AZT", + "eidId": "12", + "eidCode": "AF1A", + "age": "1", + "line": "1", + "mrsArvRegimen": "630,6467" + }, + { + "eidDisplay": "NVP/NVP/3TC/AZT", + "eidId": "12", + "eidCode": "AF1A", + "age": "1", + "line": "1", + "mrsArvRegimen": "631,6467" + }, + { + "eidDisplay": "NVP/3TC/AZT/NVP/3TC/AZT", + "eidId": "12", + "eidCode": "AF1A", + "age": "1", + "line": "1", + "mrsArvRegimen": "6467,6467" + }, + { + "eidDisplay": "AZT/3TC/NVP/YES", + "eidId": "12", + "eidCode": "AF1A", + "age": "1", + "line": "1", + "mrsArvRegimen": "630,631,1065" + }, + { + "eidId": "13", + "eidCode": "AF4A", + "age": "1", + "line": "1", + "eidDisplay": "ABC+3TC+NVP", + "mrsArvRegimen": "9050" + }, + { + "eidDisplay": "NVP,ABC/3TC", + "eidId": "13", + "eidCode": "AF4A", + "age": "1", + "line": "1", + "mrsArvRegimen": "631,6679" + }, + { + "eidDisplay": "3TC/NVP/ABC", + "eidId": "13", + "eidCode": "AF4A", + "age": "1", + "line": "1", + "mrsArvRegimen": "628,631,814" + }, + { + "eidDisplay": "NVP/YES/ABC/3TC", + "eidId": "13", + "eidCode": "AF4A", + "age": "1", + "line": "1", + "mrsArvRegimen": "631,1065,6679" + }, + { + "eidDisplay": "3TC/NVP/ABC/3TC", + "eidId": "13", + "eidCode": "AF4A", + "age": "1", + "line": "1", + "mrsArvRegimen": "628,631,6679" + }, + { + "eidId": "14", + "eidCode": "AF5X", + "age": "1", + "line": "1", + "eidDisplay": "Other", + "mrsArvRegimen": "5622" + }, + { + "eidId": "15", + "eidCode": "AS1A", + "age": "1", + "line": "2", + "eidDisplay": "AZT+3TC+LPV/r", + "mrsArvRegimen": "" + }, + { + "eidId": "16", + "eidCode": "AS1B", + "age": "1", + "line": "2", + "eidDisplay": "AZT+3TC+ATV/r", + "mrsArvRegimen": "" + }, + { + "eidId": "17", + "eidCode": "AS1C", + "age": "1", + "line": "2", + "eidDisplay": "AZT+3TC+DTG", + "mrsArvRegimen": "" + }, + { + "eidId": "18", + "eidCode": "AS2A", + "age": "1", + "line": "2", + "eidDisplay": "TDF+3TC+LPV/r", + "mrsArvRegimen": "9055" + }, + { + "eidId": "19", + "eidCode": "AS2B", + "age": "1", + "line": "2", + "eidDisplay": "TDF+3TC+DTG", + "mrsArvRegimen": "10268,597" + }, + { + "eidId": "20", + "eidCode": "AS2C", + "age": "1", + "line": "2", + "eidDisplay": "TDF+3TC+ATV/r", + "mrsArvRegimen": "" + }, + { + "eidId": "21", + "eidCode": "AS5A", + "age": "1", + "line": "2", + "eidDisplay": "ABC+3TC+LPV/r", + "mrsArvRegimen": "9051" + }, + { + "eidDisplay": "3TC,LPV/R,ABC", + "eidId": "21", + "eidCode": "AS5A", + "age": "1", + "line": "2", + "mrsArvRegimen": "628,794,814" + }, + { + "eidDisplay": "LPV/R/ABC/3TC", + "eidId": "21", + "eidCode": "AS5A", + "age": "1", + "line": "2", + "mrsArvRegimen": "794,6679" + }, + { + "eidDisplay": "LPV/R/YES/ABC/3TC", + "eidId": "21", + "eidCode": "AS5A", + "age": "1", + "line": "2", + "mrsArvRegimen": "794,1065,6679" + }, + { + "eidDisplay": "3TC/LPV/R/ABC/YES", + "eidId": "21", + "eidCode": "AS5A", + "age": "1", + "line": "2", + "mrsArvRegimen": "628,794,814,1065" + }, + { + "eidDisplay": "3TC/LPV/R/ABC/3TC/TDF", + "eidId": "21", + "eidCode": "AS5A", + "age": "1", + "line": "2", + "mrsArvRegimen": "628,794,814,1400" + }, + { + "eidId": "22", + "eidCode": "AS5B", + "age": "1", + "line": "2", + "eidDisplay": "ABC+3TC+LPV/r", + "mrsArvRegimen": "" + }, + { + "eidDisplay": "3TC/ABC/ATV/R", + "eidId": "22", + "eidCode": "AS5B", + "age": "1", + "line": "2", + "mrsArvRegimen": "628,814,6160" + }, + { + "eidDisplay": "3TC/ABC/ATV", + "eidId": "22", + "eidCode": "AS5B", + "age": "1", + "line": "2", + "mrsArvRegimen": "628,814,6159" + }, + { + "eidDisplay": "3TC/ABC/OTHER/ATV", + "eidId": "22", + "eidCode": "AS5B", + "age": "1", + "line": "2", + "mrsArvRegimen": "628,814,5424,6159" + }, + { + "eidDisplay": "ATV/R/ABC/3TC", + "eidId": "22", + "eidCode": "AS5B", + "age": "1", + "line": "2", + "mrsArvRegimen": "6160,6679" + }, + { + "eidId": "23", + "eidCode": "AS5C", + "age": "1", + "line": "2", + "eidDisplay": "ABC+3TC+DTG", + "mrsArvRegimen": "" + }, + { + "eidId": "24", + "eidCode": "AS6X", + "age": "1", + "line": "2", + "eidDisplay": "Other", + "mrsArvRegimen": "5622" + }, + { + "eidId": "25", + "eidCode": "AT2D", + "age": "1", + "line": "3", + "eidDisplay": "TDF+3TC+DTG+DRV/r", + "mrsArvRegimen": "" + }, + { + "eidId": "26", + "eidCode": "AT2E", + "age": "1", + "line": "3", + "eidDisplay": "TDF+3TC+DTG+DRV/r", + "mrsArvRegimen": "" + }, + { + "eidId": "27", + "eidCode": "AT2F", + "age": "1", + "line": "3", + "eidDisplay": "TDF+3TC+DTG+ETV+DRV/r", + "mrsArvRegimen": "" + }, + { + "eidId": "28", + "eidCode": "AT2X", + "age": "1", + "line": "3", + "eidDisplay": "Other", + "mrsArvRegimen": "5622" + }, + { + "eidId": "29", + "eidCode": "CF2B", + "age": "2", + "line": "1", + "eidDisplay": "ABC+3TC+EFV", + "mrsArvRegimen": "" + }, + { + "eidId": "30", + "eidCode": "CF2D", + "age": "2", + "line": "1", + "eidDisplay": "ABC+3TC+LPV/r", + "mrsArvRegimen": "9051" + }, + { + "eidId": "31", + "eidCode": "CF2A", + "age": "2", + "line": "1", + "eidDisplay": "ABC+3TC+NVP", + "mrsArvRegimen": "9050" + }, + { + "eidId": "32", + "eidCode": "CF2F", + "age": "2", + "line": "1", + "eidDisplay": "ABC+3TC+RAL", + "mrsArvRegimen": "" + }, + { + "eidId": "33", + "eidCode": "CF1A", + "age": "2", + "line": "1", + "eidDisplay": "AZT+3TC+NVP", + "mrsArvRegimen": "6467" + }, + { + "eidId": "34", + "eidCode": "CF1B", + "age": "2", + "line": "1", + "eidDisplay": "AZT+3TC+EFV", + "mrsArvRegimen": "9053" + }, + { + "eidId": "35", + "eidCode": "CF1C", + "age": "2", + "line": "1", + "eidDisplay": "AZT+3TC+LPV/r", + "mrsArvRegimen": "" + }, + { + "eidId": "36", + "eidCode": "CF5X", + "age": "2", + "line": "1", + "eidDisplay": "Other", + "mrsArvRegimen": "5622" + }, + { + "eidId": "37", + "eidCode": "CS1A", + "age": "2", + "line": "2", + "eidDisplay": "AZT+3TC+LPV/r", + "mrsArvRegimen": "" + }, + { + "eidId": "38", + "eidCode": "CS2A", + "age": "2", + "line": "2", + "eidDisplay": "AZT+3TC+LPV/r", + "mrsArvRegimen": "9051" + }, + { + "eidId": "39", + "eidCode": "CS1C", + "age": "2", + "line": "2", + "eidDisplay": "AZT+3TC+DRV/r+RAL", + "mrsArvRegimen": "" + }, + { + "eidId": "40", + "eidCode": "CS1C", + "age": "2", + "line": "2", + "eidDisplay": "ABC+3TC+DRV/r+RAL", + "mrsArvRegimen": "" + }, + { + "eidId": "41", + "eidCode": "CS4X", + "age": "2", + "line": "2", + "eidDisplay": "Other", + "mrsArvRegimen": "5622" + }, + { + "eidId": "42", + "eidCode": "CT1H", + "age": "2", + "line": "3", + "eidDisplay": "AZT+3TC+DRV/r+RAL", + "mrsArvRegimen": "" + }, + { + "eidId": "43", + "eidCode": "CT2D", + "age": "2", + "line": "3", + "eidDisplay": "ABC+3TC+DRV/r+RAL", + "mrsArvRegimen": "" + }, + { + "eidId": "44", + "eidCode": "CT3X", + "age": "2", + "line": "3", + "eidDisplay": "Other", + "mrsArvRegimen": "5622" + } + ], + "testOrderJustification": { + "5931c4d4-4406-4d71-b75d-2205d905cc24": { + "eidId": 1, + "eidCode": "", + "eidDisplay": "Routine VL", + "mrsDisplay": "" + }, + "e43ddeb6-3984-499c-a280-3bade1039608": { + "eidId": 2, + "eidCode": "", + "eidDisplay": "Confirmation of Treatment Failure (Repeat VL at 3M)", + "mrsDisplay": "" + }, + "a8981934-1350-11df-a1f1-0026b9348838": { + "eidId": 3, + "eidCode": "", + "eidDisplay": "Clinical Failure", + "mrsDisplay": "" + }, + "a8a00158-1350-11df-a1f1-0026b9348838": { + "eidId": 4, + "eidCode": "", + "eidDisplay": "Single Drug Substitution", + "mrsDisplay": "" + }, + "3966e139-ca69-47c6-aad3-ebd41bb45e28": { + "eidId": 5, + "eidCode": "", + "eidDisplay": "Baseline VL (for infants diagnosed through EID)", + "mrsDisplay": "" + }, + "42cdefa2-c306-4d10-a819-c04131c4934e": { + "eidId": 6, + "eidCode": "", + "eidDisplay": "Confirmation of persistent low level viremia (PLLV)", + "mrsDisplay": "" + }, + "a8aaf3e2-1350-11df-a1f1-0026b9348838": { + "eidId": 7, + "eidCode": "", + "eidDisplay": "Other", + "mrsDisplay": "" + }, + "undefined": { + "eidId": 8, + "eidCode": "", + "eidDisplay": "No Data", + "mrsDisplay": "" + } + }, + "dnaPcrEntryPoint": { + "a8a09ac8-1350-11df-a1f1-0026b9348838": { + "eidDisplay": "OPD", + "eidId": 1, + "eidCode": "", + "mrsDisplay": "OPD" + }, + "3e5ad07b-2ced-4925-8264-cc4d8d1438d4": { + "eidDisplay": "Paediatric Ward", + "eidId": 2, + "eidCode": "", + "mrsDisplay": "Peadiatric ward" + }, + "a8a17d80-1350-11df-a1f1-0026b9348838": { + "eidDisplay": "MCH/PMTCT", + "eidId": 3, + "eidCode": "", + "mrsDisplay": "MCH" + }, + "a89fbedc-1350-11df-a1f1-0026b9348838": { + "eidDisplay": "MCH/PMTCT", + "eidId": 3, + "eidCode": "", + "mrsDisplay": "PMTCT" + }, + "a8a3899a-1350-11df-a1f1-0026b9348838": { + "eidDisplay": "CCC/PSC", + "eidId": 4, + "eidCode": "", + "mrsDisplay": "CCC" + }, + "materrnity-uuid": { + "eidDisplay": "Materrnity", + "eidId": 5, + "eidCode": "", + "mrsDisplay": "Materrnity" + }, + "a8aaf3e2-1350-11df-a1f1-0026b9348838": { + "eidDisplay": "Other", + "eidId": 6, + "eidCode": "", + "mrsDisplay": "Other" + }, + "undefined": { + "eidDisplay": "No Data", + "eidId": 7, + "eidCode": "", + "mrsDisplay": "No Data" + } + }, + "hivStatus": { + "a896f3a6-1350-11df-a1f1-0026b9348838": { + "eidId": 2, + "eidCode": "", + "eidDisplay": "Positive", + "mrsDisplay": "Positive" + }, + "a896d2cc-1350-11df-a1f1-0026b9348838": { + "eidId": 1, + "eidCode": "", + "eidDisplay": "Negative", + "mrsDisplay": "Negative" + }, + "a899b50a-1350-11df-a1f1-0026b9348838": { + "eidId": 0, + "eidCode": "", + "eidDisplay": "", + "mrsDisplay": "Unknown" + } + }, + "infantProphylaxis": { + "a8967656-1350-11df-a1f1-0026b9348838": { + "eidId": 1, + "eidCode": "", + "eidDisplay": "sdNVP only", + "mrsDisplay": "sdNVP only" + }, + "6a73f32d-1870-4527-af6e-74443251ded2": { + "eidId": 2, + "eidCode": "", + "eidDisplay": "sdNVP +AZT +3TC", + "mrsDisplay": "sdNVP +AZT +3TC" + }, + "a8967656-1350-11df-a1f1-0026b9348838": { + "eidId": 10, + "eidCode": "", + "eidDisplay": "NVP for 6 weeks", + "mrsDisplay": "NVP" + }, + "a897ea4a-1350-11df-a1f1-0026b9348838": { + "eidId": 5, + "eidCode": "", + "eidDisplay": "AZT", + "mrsDisplay": "AZT" + }, + "a8967656-1350-11df-a1f1-0026b9348838": { + "eidId": 5, + "eidCode": "", + "eidDisplay": "", + "mrsDisplay": "NVP during BF period" + }, + "a899e0ac-1350-11df-a1f1-0026b9348838": { + "eidId": 0, + "eidCode": "", + "eidDisplay": "None", + "mrsDisplay": "None" + }, + "undefined": { + "eidId": 0, + "eidCode": "", + "eidDisplay": "None", + "mrsDisplay": "None" + }, + "a8aaf3e2-1350-11df-a1f1-0026b9348838": { + "eidId": 5, + "eidCode": "", + "eidDisplay": "Other", + "mrsDisplay": "Other" + } + }, + "pmtctIntervention": { + "a8967656-1350-11df-a1f1-0026b9348838": { + "eidId": 1, + "eidCode": "", + "eidDisplay": "sdNVP only", + "mrsDisplay": "sdNVP only" + }, + "0906b973-25da-4e87-a272-84692cdd8453": { + "eidId": 5, + "eidDisplay": "Uninterrupted HAART (HAART until end of BF)", + "mrsDisplay": "Uninterrupted HAART (HAART until end of BF)" + }, + "6a73f32d-1870-4527-af6e-74443251ded2": { + "eidId": 2, + "eidCode": "", + "eidDisplay": "Sd NVP+AZT+3TC", + "mrsDisplay": "AZT (from 14wks or later) + sdNVP + 3TC (Tail)" + }, + "a899ccb6-1350-11df-a1f1-0026b9348838": { + "eidId": 7, + "eidCode": "", + "eidDisplay": "HAART", + "mrsDisplay": "HAART" + }, + "a899e0ac-1350-11df-a1f1-0026b9348838": { + "eidId": 6, + "eidCode": "", + "eidDisplay": "None", + "mrsDisplay": "None" + }, + "undefined": { + "eidId": 6, + "eidCode": "", + "eidDisplay": "None", + "mrsDisplay": "None" + }, + "a8aaf3e2-1350-11df-a1f1-0026b9348838": { + "eidId": 5, + "eidCode": "", + "eidDisplay": "Other", + "mrsDisplay": "Other" + } + }, + "infantFeedingPlan": { + "a8a8d9b8-1350-11df-a1f1-0026b9348838": { + "eidId": 1, + "eidCode": "", + "eidDisplay": "EBF=Exclusive breastfeeding", + "mrsDisplay": "EBF=Exclusive breastfeeding" + }, + "a8a70156-1350-11df-a1f1-0026b9348838": { + "eidId": 4, + "eidCode": "", + "eidDisplay": "ERF=Exclusive replacement feeding", + "mrsDisplay": "ERF=Exclusive replacement feeding" + }, + "a89cca10-1350-11df-a1f1-0026b9348838": { + "eidId": 2, + "eidCode": "", + "eidDisplay": "MF=Mixed Feeding", + "mrsDisplay": "MF=Mixed Feeding" + }, + "a8ae86e2-1350-11df-a1f1-0026b9348838": { + "eidId": 6, + "eidCode": "", + "eidDisplay": "BF= Breastfeeding", + "mrsDisplay": "BF= Breastfeeding" + }, + "a89cc934-1350-11df-a1f1-0026b9348838": { + "eidId": 7, + "eidCode": "", + "eidDisplay": "NBF=Not breastfeeding", + "mrsDisplay": "NBF=Not breastfeeding" } } +} diff --git a/service/enrollment.service.js b/service/enrollment.service.js index 3b3a167bf..6c868489a 100755 --- a/service/enrollment.service.js +++ b/service/enrollment.service.js @@ -1,104 +1,80 @@ -var Promise = require("bluebird"); +var Promise = require('bluebird'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report'; -import { - PatientlistMysqlReport -} from '../app/reporting-framework/patientlist-mysql.report'; +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; var def = { - getActiveProgramEnrollmentSummary: getActiveProgramEnrollmentSummary, - getActiveProgramEnrollmentsPatientList: getActiveProgramEnrollmentsPatientList + getActiveProgramEnrollmentSummary: getActiveProgramEnrollmentSummary, + getActiveProgramEnrollmentsPatientList: getActiveProgramEnrollmentsPatientList }; module.exports = def; - -function getActiveProgramEnrollmentSummary(requestParams){ - - let params = { - 'endDate': '' - }; - - - if(requestParams.programTypeIds.length > 0){ - - params['programTypeIds'] = requestParams.programTypeIds; - - } - if(requestParams.locations.length > 0){ - params['locations'] = requestParams.locations; - } - if(requestParams.endDate){ - params['endDate'] = requestParams.endDate; - } - - - return new Promise(function (resolve, reject) { - - - let report = new BaseMysqlReport('currentlyEnrolledPatientsAggregate', params); - - Promise.join(report.generateReport(), - (results) => { - let result =results.results.results; - results.size =result?result.length:0; - results.result=result; - delete results['results']; - resolve(results); - }).catch((errors) => { - console.error('ERROR: ', errors); - reject(errors); - }); - +function getActiveProgramEnrollmentSummary(requestParams) { + let params = { + endDate: '' + }; + + if (requestParams.programTypeIds.length > 0) { + params['programTypeIds'] = requestParams.programTypeIds; + } + if (requestParams.locations.length > 0) { + params['locations'] = requestParams.locations; + } + if (requestParams.endDate) { + params['endDate'] = requestParams.endDate; + } + + return new Promise(function (resolve, reject) { + let report = new BaseMysqlReport( + 'currentlyEnrolledPatientsAggregate', + params + ); + + Promise.join(report.generateReport(), (results) => { + let result = results.results.results; + results.size = result ? result.length : 0; + results.result = result; + delete results['results']; + resolve(results); + }).catch((errors) => { + console.error('ERROR: ', errors); + reject(errors); }); - - + }); } -function getActiveProgramEnrollmentsPatientList(requestParams){ - - let params = { - 'endDate': '' - }; - - - if(requestParams.programTypeIds.length > 0){ - - params['programTypeIds'] = requestParams.programTypeIds; - - } - if(requestParams.locations.length > 0){ - params['locations'] = requestParams.locations; - } - if(requestParams.endDate){ - params['endDate'] = requestParams.endDate; - } - - - let indicators = []; - let report = new PatientlistMysqlReport('currentlyEnrolledPatientsAggregate', params); - - - return new Promise(function (resolve, reject) { - //TODO: Do some pre processing - Promise.join(report.generatePatientListReport(indicators), - (results) => { - results.size=results?results.results.results.length:0; - results.result=results?results.results.results:[]; - delete results['results']; - resolve(results); - }).catch((errors) => { - console.error('ERROR: ', errors); - reject(errors); - }); - }); - - +function getActiveProgramEnrollmentsPatientList(requestParams) { + let params = { + endDate: '' + }; + + if (requestParams.programTypeIds.length > 0) { + params['programTypeIds'] = requestParams.programTypeIds; + } + if (requestParams.locations.length > 0) { + params['locations'] = requestParams.locations; + } + if (requestParams.endDate) { + params['endDate'] = requestParams.endDate; + } + + let indicators = []; + let report = new PatientlistMysqlReport( + 'currentlyEnrolledPatientsAggregate', + params + ); + + return new Promise(function (resolve, reject) { + //TODO: Do some pre processing + Promise.join(report.generatePatientListReport(indicators), (results) => { + results.size = results ? results.results.results.length : 0; + results.result = results ? results.results.results : []; + delete results['results']; + resolve(results); + }).catch((errors) => { + console.error('ERROR: ', errors); + reject(errors); + }); + }); } - - - - - diff --git a/service/hei-programme-outcome-service.js b/service/hei-programme-outcome-service.js index 394033c0b..68794c266 100644 --- a/service/hei-programme-outcome-service.js +++ b/service/hei-programme-outcome-service.js @@ -1,59 +1,54 @@ const dao = require('../etl-dao'); const Promise = require('bluebird'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report'; -import { - PatientlistMysqlReport -} from '../app/reporting-framework/patientlist-mysql.report'; +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; const unknownOutcomedefs = require('../app/reporting-framework/hei/hei-unknown-programme-outcome.json'); - export class HeiProgrammeOutcomeService { - - getAggregateReport(reportParams) { - return new Promise(function (resolve, reject) { - let report; - - - report = new BaseMysqlReport('heiUknownProgramOutcomeAggregate', reportParams.requestParams); - - - Promise.join(report.generateReport(), - (results) => { - let result = results.results.results; - results.size = result ? result.length : 0; - results.result = result; - results['indicatorDefinitions'] = unknownOutcomedefs; - delete results['results']; - resolve(results); - // TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - }); - } - - getPatientListReport(reportParams) { - let indicators = reportParams.indicators ? reportParams.indicators.split(',') : []; - delete reportParams['gender']; - - let report = new PatientlistMysqlReport('heiUknownProgramOutcomeAggregate', reportParams); - - - return new Promise(function (resolve, reject) { - Promise.join(report.generatePatientListReport(indicators), - (results) => { - results['result'] = results.results.results; - resolve(results); - }).catch((errors) => { - console.log('Error', errors); - reject(errors); - }); - }); - - - } -} \ No newline at end of file + getAggregateReport(reportParams) { + return new Promise(function (resolve, reject) { + let report; + + report = new BaseMysqlReport( + 'heiUknownProgramOutcomeAggregate', + reportParams.requestParams + ); + + Promise.join(report.generateReport(), (results) => { + let result = results.results.results; + results.size = result ? result.length : 0; + results.result = result; + results['indicatorDefinitions'] = unknownOutcomedefs; + delete results['results']; + resolve(results); + // TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + }); + } + + getPatientListReport(reportParams) { + let indicators = reportParams.indicators + ? reportParams.indicators.split(',') + : []; + delete reportParams['gender']; + + let report = new PatientlistMysqlReport( + 'heiUknownProgramOutcomeAggregate', + reportParams + ); + + return new Promise(function (resolve, reject) { + Promise.join(report.generatePatientListReport(indicators), (results) => { + results['result'] = results.results.results; + resolve(results); + }).catch((errors) => { + console.log('Error', errors); + reject(errors); + }); + }); + } +} diff --git a/service/hiv-comparative-overview.service.js b/service/hiv-comparative-overview.service.js index 0162044da..5fa6d5394 100755 --- a/service/hiv-comparative-overview.service.js +++ b/service/hiv-comparative-overview.service.js @@ -1,54 +1,56 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report'; -import { - PatientlistMysqlReport -} from '../app/reporting-framework/patientlist-mysql.report'; +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; export class hivComparativeOverviewService { - - getAggregateReport(reportParams) { - let self = this; - let report = new BaseMysqlReport('clinicHivComparativeOverviewAggregate', reportParams); - return new Promise(function (resolve, reject) { - Promise.join(report.generateReport(), - (result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - //TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - }); - } - getPatientListReport(reportParams) { - let self = this; - let endDate = reportParams.endDate.split('T')[0]; - let startDate = reportParams.startDate.split('T')[0]; - reportParams.endDate = endDate; - reportParams.startDate = startDate; - let locations = reportParams.locations.split(','); - reportParams.locations = locations; - return new Promise(function (resolve, reject) { - //TODO: Do some pre processing - let report = new PatientlistMysqlReport('clinicHivComparativeOverviewAggregate', reportParams) - Promise.join(report.generatePatientListReport(reportParams.indicator.split(',')), - (result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - }).catch((errors) => { - reject(errors); - }); - }); - } -} \ No newline at end of file + getAggregateReport(reportParams) { + let self = this; + let report = new BaseMysqlReport( + 'clinicHivComparativeOverviewAggregate', + reportParams + ); + return new Promise(function (resolve, reject) { + Promise.join(report.generateReport(), (result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + //TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + }); + } + getPatientListReport(reportParams) { + let self = this; + let endDate = reportParams.endDate.split('T')[0]; + let startDate = reportParams.startDate.split('T')[0]; + reportParams.endDate = endDate; + reportParams.startDate = startDate; + let locations = reportParams.locations.split(','); + reportParams.locations = locations; + return new Promise(function (resolve, reject) { + //TODO: Do some pre processing + let report = new PatientlistMysqlReport( + 'clinicHivComparativeOverviewAggregate', + reportParams + ); + Promise.join( + report.generatePatientListReport(reportParams.indicator.split(',')), + (result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + } + ).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/indicator-processor/disaggregation-filters.json b/service/indicator-processor/disaggregation-filters.json index 9b02a6145..6d1275d7c 100755 --- a/service/indicator-processor/disaggregation-filters.json +++ b/service/indicator-processor/disaggregation-filters.json @@ -1,55 +1,55 @@ { - "female": { - "label": "female", - "expression": "gender='F'", - "description": "by gender (F)" - }, - "male": { - "label": "male", - "expression": "gender='M'", - "description": "by gender (M)" - }, + "female": { + "label": "female", + "expression": "gender='F'", + "description": "by gender (F)" + }, + "male": { + "label": "male", + "expression": "gender='M'", + "description": "by gender (M)" + }, - "age_below_1": { - "label": "age_below_1", - "expression": "timestampdiff(year,birthdate,@endDate) < 1", - "description": "by age (< 15)" - }, - "age_1_to_9": { - "label": "age_1_to_9", - "expression": "timestampdiff(year,birthdate,@endDate) >= 1 and timestampdiff(year,birthdate,@endDate) <= 9", - "description": "by age (>=1 and <=9)" - }, + "age_below_1": { + "label": "age_below_1", + "expression": "timestampdiff(year,birthdate,@endDate) < 1", + "description": "by age (< 15)" + }, + "age_1_to_9": { + "label": "age_1_to_9", + "expression": "timestampdiff(year,birthdate,@endDate) >= 1 and timestampdiff(year,birthdate,@endDate) <= 9", + "description": "by age (>=1 and <=9)" + }, - "age_15_and_older": { - "label": "age_15_and_older", - "expression": "timestampdiff(year,birthdate,@endDate) >= 15", - "description": "by age (>= 15)" - }, - "age_below_15": { - "label": "age_below_15", - "expression": "timestampdiff(year,birthdate,@endDate) < 15", - "description": "by age (< 15)" - }, + "age_15_and_older": { + "label": "age_15_and_older", + "expression": "timestampdiff(year,birthdate,@endDate) >= 15", + "description": "by age (>= 15)" + }, + "age_below_15": { + "label": "age_below_15", + "expression": "timestampdiff(year,birthdate,@endDate) < 15", + "description": "by age (< 15)" + }, - "age_10_to_14": { - "label": "age_10_to_14", - "expression": "timestampdiff(year,birthdate,@endDate) >= 10 and timestampdiff(year,birthdate,@endDate) <= 14", - "description": "by age (>=10 and <=14)" - }, - "age_15_to_19": { - "label": "age_15_to_19", - "expression": "timestampdiff(year,birthdate,@endDate) >= 15 and timestampdiff(year,birthdate,@endDate) <= 19", - "description": "by age (>=15 and <=19)" - }, - "age_20_to_24": { - "label": "age_20_to_24", - "expression": "timestampdiff(year,birthdate,@endDate) >= 20 and timestampdiff(year,birthdate,@endDate) <= 24", - "description": "by age (>=20 and <=24)" - }, - "age_25_and_older": { - "label": "age_25_and_older", - "expression": "timestampdiff(year,birthdate,@endDate) >= 25", - "description": "by age (>=25)" - } -} \ No newline at end of file + "age_10_to_14": { + "label": "age_10_to_14", + "expression": "timestampdiff(year,birthdate,@endDate) >= 10 and timestampdiff(year,birthdate,@endDate) <= 14", + "description": "by age (>=10 and <=14)" + }, + "age_15_to_19": { + "label": "age_15_to_19", + "expression": "timestampdiff(year,birthdate,@endDate) >= 15 and timestampdiff(year,birthdate,@endDate) <= 19", + "description": "by age (>=15 and <=19)" + }, + "age_20_to_24": { + "label": "age_20_to_24", + "expression": "timestampdiff(year,birthdate,@endDate) >= 20 and timestampdiff(year,birthdate,@endDate) <= 24", + "description": "by age (>=20 and <=24)" + }, + "age_25_and_older": { + "label": "age_25_and_older", + "expression": "timestampdiff(year,birthdate,@endDate) >= 25", + "description": "by age (>=25)" + } +} diff --git a/service/indicator-processor/indicator-filter-options.json b/service/indicator-processor/indicator-filter-options.json index 244cefb5a..734d42626 100755 --- a/service/indicator-processor/indicator-filter-options.json +++ b/service/indicator-processor/indicator-filter-options.json @@ -1,54 +1,51 @@ [ { - "control":"ageRangeFilter", - "type":"numeric", + "control": "ageRangeFilter", + "type": "numeric", "label": "Age Range", - "expression":"timestampdiff(year,t3.birthdate,t2.endDate) > @min and timestampdiff(year,t3.birthdate,t2.endDate) <= @max", + "expression": "timestampdiff(year,t3.birthdate,t2.endDate) > @min and timestampdiff(year,t3.birthdate,t2.endDate) <= @max", "options": { "min": 0, "max": 100 } - }, { - "control":"ageGroupFilter", - "type":"coded", + "control": "ageGroupFilter", + "type": "coded", "label": "Age Group", - "expression":"timestampdiff(year,t3.birthdate,t2.endDate) >= @min and timestampdiff(year,t3.birthdate,t2.endDate) <= @max", + "expression": "timestampdiff(year,t3.birthdate,t2.endDate) >= @min and timestampdiff(year,t3.birthdate,t2.endDate) <= @max", "options": [ - {"queryParam":[0,5], "value":"0_to_5", "label":"0 to 5"}, - {"queryParam":[6,10], "value":"6_to_10", "label":"6 to 10"}, - {"queryParam":[11,15], "value":"11_to_15", "label":"11 to 15"}, - {"queryParam":[16,20], "value":"16_to_20", "label":"16 to 20"}, - {"queryParam":[21,25], "value":"21_to_25", "label":"21 to 25"}, - {"queryParam":[26,30], "value":"26_to_30", "label":"26 to 30"} + { "queryParam": [0, 5], "value": "0_to_5", "label": "0 to 5" }, + { "queryParam": [6, 10], "value": "6_to_10", "label": "6 to 10" }, + { "queryParam": [11, 15], "value": "11_to_15", "label": "11 to 15" }, + { "queryParam": [16, 20], "value": "16_to_20", "label": "16 to 20" }, + { "queryParam": [21, 25], "value": "21_to_25", "label": "21 to 25" }, + { "queryParam": [26, 30], "value": "26_to_30", "label": "26 to 30" } ] - - }, { - "control":"genderFilter", - "type":"coded", + "control": "genderFilter", + "type": "coded", "label": "Gender", - "expression":"t3.gender='@gender'", - "options":[ - {"value":"male", "queryParam":"M", "label":"Male"}, - {"value":"female", "queryParam":"F", "label":"Female"} + "expression": "t3.gender='@gender'", + "options": [ + { "value": "male", "queryParam": "M", "label": "Male" }, + { "value": "female", "queryParam": "F", "label": "Female" } ] - }, { - "control":"patientCareStatusFilter", - "type":"coded", + "control": "patientCareStatusFilter", + "type": "coded", "label": "Patient Care Status", - "expression":"case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) @paramBound then 1 else null end", + "expression": "case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) @paramBound then 1 else null end", "options": [ - {"queryParam":">90", "value":"ltfu","label":"LTFU"}, - {"queryParam":"between 0 and 91", "value":"defaulter", "label":"Defaulter"}, - {"queryParam":"<1", "value":"active_in_care", "label":"ActiveInCare"} + { "queryParam": ">90", "value": "ltfu", "label": "LTFU" }, + { + "queryParam": "between 0 and 91", + "value": "defaulter", + "label": "Defaulter" + }, + { "queryParam": "<1", "value": "active_in_care", "label": "ActiveInCare" } ] - - } - ] diff --git a/service/indicator-processor/indicator-processor.service.js b/service/indicator-processor/indicator-processor.service.js index e0fa35a2e..60aef44ce 100755 --- a/service/indicator-processor/indicator-processor.service.js +++ b/service/indicator-processor/indicator-processor.service.js @@ -1,201 +1,284 @@ -"use strict"; +'use strict'; var _ = require('underscore'); -var s = require("underscore.string"); +var s = require('underscore.string'); var toSnakeCase = require('to-snake-case'); var disaggregationFilters = require('./disaggregation-filters.json'); var indicatorFilterOptions = require('./indicator-filter-options.json'); -module.exports = function () { - return { - disaggregateDynamicIndicators: disaggregateDynamicIndicators, - disaggregateFixedIndicators: disaggregateFixedIndicators, - replaceIndicatorParam: replaceIndicatorParam - }; +module.exports = (function () { + return { + disaggregateDynamicIndicators: disaggregateDynamicIndicators, + disaggregateFixedIndicators: disaggregateFixedIndicators, + replaceIndicatorParam: replaceIndicatorParam + }; - function disaggregateDynamicIndicators(report, indicatorsSchema, request) { - var report = _.assign({}, report); - var results = []; - report.derivedIndicators = []; - _.each(report.indicators, function (reportIndicator) { - if (reportIndicator.canBeDisaggregated && reportIndicator.canBeDisaggregated === true) { - _.each(indicatorsSchema, function (indicator) { - if (reportIndicator.expression === indicator.name) { - - _.each(indicatorFilterOptions, function (filterOption) { - switch (filterOption.control) { - case 'ageRangeFilter': - var params = request.requestParams[filterOption.control]; - if (params) { - params = params.split(',').map(Number); - for (var i = params[0]; i < params[1]; i++) { - var name = indicator.name + '_age_' + (i + 1); - var expression = s.replaceAll(filterOption.expression, '@min', i); - expression = s.replaceAll(expression, '@max', i + 1); - results.push(generateAggregateColumn(indicator, reportIndicator, name, expression, request)); - } - } - break; - case 'ageGroupFilter': - var params = request.requestParams[filterOption.control]; - if (params) { - params = params.split(','); - _.each(filterOption.options, function (option) { - _.each(params, function (param) { - if (option.value === param) { - var name = indicator.name + '_age_' + toSnakeCase(option.value); - var expression = s.replaceAll(filterOption.expression, '@min', option.queryParam[0]); - expression = s.replaceAll(expression, '@max', option.queryParam[1]); - results.push(generateAggregateColumn(indicator, reportIndicator, name, expression, request)); - } - }); - }); - } - break; - case 'genderFilter': - var params = request.requestParams[filterOption.control]; - if (params) { - params = params.split(','); - _.each(filterOption.options, function (option) { - _.each(params, function (param) { - if (option.value === param) { - var name = indicator.name + '_' + toSnakeCase(option.value); - var expression = s.replaceAll(filterOption.expression, '@gender', option.queryParam); - results.push(generateAggregateColumn(indicator, reportIndicator, name, expression, request)); - } - }); - - }); - } - break; - case 'patientCareStatusFilter': - var params = request.requestParams[filterOption.control]; - if (params) { - params = params.split(','); - _.each(filterOption.options, function (option) { - _.each(params, function (param) { - if (option.value === param) { - var name = indicator.name + '_' + toSnakeCase(option.value); - var expression = s.replaceAll(filterOption.expression, '@paramBound', option.queryParam); - results.push(generateAggregateColumn(indicator, reportIndicator, name, expression, request)); - } - }); - - }); - } - break; - } - }); + function disaggregateDynamicIndicators(report, indicatorsSchema, request) { + var report = _.assign({}, report); + var results = []; + report.derivedIndicators = []; + _.each(report.indicators, function (reportIndicator) { + if ( + reportIndicator.canBeDisaggregated && + reportIndicator.canBeDisaggregated === true + ) { + _.each(indicatorsSchema, function (indicator) { + if (reportIndicator.expression === indicator.name) { + _.each(indicatorFilterOptions, function (filterOption) { + switch (filterOption.control) { + case 'ageRangeFilter': + var params = request.requestParams[filterOption.control]; + if (params) { + params = params.split(',').map(Number); + for (var i = params[0]; i < params[1]; i++) { + var name = indicator.name + '_age_' + (i + 1); + var expression = s.replaceAll( + filterOption.expression, + '@min', + i + ); + expression = s.replaceAll(expression, '@max', i + 1); + results.push( + generateAggregateColumn( + indicator, + reportIndicator, + name, + expression, + request + ) + ); } - - }); - } - }); - return _.uniq(results); - - } - - function generateAggregateColumn(indicator, reportIndicator, name, expression, requestParam) { - - var column = reportIndicator.sql + ' as ' + name; - var indicatorExpression = replaceIndicatorParam(indicator.expression, requestParam); - indicatorExpression = indicatorExpression + ' and (' + expression + ')'; - column = column.replace('$expression', indicatorExpression); - - return column; - } - - function disaggregateFixedIndicators(reports, indicatorsSchema) { - _.each(reports, function (report) { - _.each(report.indicators, function (reportIndicator) { - if (reportIndicator.disaggregation) { - _.each(indicatorsSchema, function (indicator) { - if (reportIndicator.disaggregation.indicator === indicator.name) { - var derivedIndicator = { - label: '', - description: '', - expression: '' - } - _.each(reportIndicator.disaggregation.filters, function (filter) { - var disaggregation = disaggregationFilters[filter]; - if (disaggregation) { - derivedIndicator.label += ' ' + disaggregation.label; - derivedIndicator.description += ', ' + disaggregation.description; - derivedIndicator.expression += ' and ' + disaggregation.expression; - } - }); - if (derivedIndicator.expression !== '') { - // del repetition - indicatorsSchema = indicatorsSchema.filter(function (el) { - return el.name !== reportIndicator.expression; - }); - - // push to the arrau - indicatorsSchema.unshift({ - name: reportIndicator.expression, - label: indicator.label + ' ' + derivedIndicator.label, - description: indicator.description + 'and disaggregated ' + derivedIndicator.description, - expression: indicator.expression + derivedIndicator.expression - }); - } + } + break; + case 'ageGroupFilter': + var params = request.requestParams[filterOption.control]; + if (params) { + params = params.split(','); + _.each(filterOption.options, function (option) { + _.each(params, function (param) { + if (option.value === param) { + var name = + indicator.name + + '_age_' + + toSnakeCase(option.value); + var expression = s.replaceAll( + filterOption.expression, + '@min', + option.queryParam[0] + ); + expression = s.replaceAll( + expression, + '@max', + option.queryParam[1] + ); + results.push( + generateAggregateColumn( + indicator, + reportIndicator, + name, + expression, + request + ) + ); } + }); }); - } + } + break; + case 'genderFilter': + var params = request.requestParams[filterOption.control]; + if (params) { + params = params.split(','); + _.each(filterOption.options, function (option) { + _.each(params, function (param) { + if (option.value === param) { + var name = + indicator.name + '_' + toSnakeCase(option.value); + var expression = s.replaceAll( + filterOption.expression, + '@gender', + option.queryParam + ); + results.push( + generateAggregateColumn( + indicator, + reportIndicator, + name, + expression, + request + ) + ); + } + }); + }); + } + break; + case 'patientCareStatusFilter': + var params = request.requestParams[filterOption.control]; + if (params) { + params = params.split(','); + _.each(filterOption.options, function (option) { + _.each(params, function (param) { + if (option.value === param) { + var name = + indicator.name + '_' + toSnakeCase(option.value); + var expression = s.replaceAll( + filterOption.expression, + '@paramBound', + option.queryParam + ); + results.push( + generateAggregateColumn( + indicator, + reportIndicator, + name, + expression, + request + ) + ); + } + }); + }); + } + break; + } }); + } }); - } + } + }); + return _.uniq(results); + } - function replaceIndicatorParam(_indicatorExpression, requestParam) { - var indicatorExpression = _indicatorExpression; - var result; + function generateAggregateColumn( + indicator, + reportIndicator, + name, + expression, + requestParam + ) { + var column = reportIndicator.sql + ' as ' + name; + var indicatorExpression = replaceIndicatorParam( + indicator.expression, + requestParam + ); + indicatorExpression = indicatorExpression + ' and (' + expression + ')'; + column = column.replace('$expression', indicatorExpression); - if (s.include(indicatorExpression, '@endDate')) { - if (requestParam.whereParams) { - var dateParam = _.find(requestParam.whereParams, function (param) { - if (param.name === 'endDate') return param; - }); + return column; + } - if (dateParam) { - indicatorExpression = s.replaceAll(indicatorExpression, '@endDate', "'" + dateParam.value + "'"); + function disaggregateFixedIndicators(reports, indicatorsSchema) { + _.each(reports, function (report) { + _.each(report.indicators, function (reportIndicator) { + if (reportIndicator.disaggregation) { + _.each(indicatorsSchema, function (indicator) { + if (reportIndicator.disaggregation.indicator === indicator.name) { + var derivedIndicator = { + label: '', + description: '', + expression: '' + }; + _.each(reportIndicator.disaggregation.filters, function (filter) { + var disaggregation = disaggregationFilters[filter]; + if (disaggregation) { + derivedIndicator.label += ' ' + disaggregation.label; + derivedIndicator.description += + ', ' + disaggregation.description; + derivedIndicator.expression += + ' and ' + disaggregation.expression; } + }); + if (derivedIndicator.expression !== '') { + // del repetition + indicatorsSchema = indicatorsSchema.filter(function (el) { + return el.name !== reportIndicator.expression; + }); + + // push to the arrau + indicatorsSchema.unshift({ + name: reportIndicator.expression, + label: indicator.label + ' ' + derivedIndicator.label, + description: + indicator.description + + 'and disaggregated ' + + derivedIndicator.description, + expression: indicator.expression + derivedIndicator.expression + }); + } } + }); } + }); + }); + } - if (s.include(indicatorExpression, '@startDate')) { - if (requestParam.whereParams) { - var dateParam = _.find(requestParam.whereParams, function (param) { - if (param.name === 'startDate') return param; - }); + function replaceIndicatorParam(_indicatorExpression, requestParam) { + var indicatorExpression = _indicatorExpression; + var result; - if (dateParam) { - indicatorExpression = s.replaceAll(indicatorExpression, '@startDate', "'" + dateParam.value + "'"); - } - } + if (s.include(indicatorExpression, '@endDate')) { + if (requestParam.whereParams) { + var dateParam = _.find(requestParam.whereParams, function (param) { + if (param.name === 'endDate') return param; + }); + + if (dateParam) { + indicatorExpression = s.replaceAll( + indicatorExpression, + '@endDate', + "'" + dateParam.value + "'" + ); } + } + } - if (s.include(indicatorExpression, '@referenceDate')) { - if (requestParam.whereParams) { - var referenceParam = _.find(requestParam.whereParams, function (param) { - if (param.name === 'referenceDate') return param; - }); + if (s.include(indicatorExpression, '@startDate')) { + if (requestParam.whereParams) { + var dateParam = _.find(requestParam.whereParams, function (param) { + if (param.name === 'startDate') return param; + }); - if (referenceParam) { - indicatorExpression = s.replaceAll(indicatorExpression, '@referenceDate', "'" + referenceParam.value + "'"); - } - } + if (dateParam) { + indicatorExpression = s.replaceAll( + indicatorExpression, + '@startDate', + "'" + dateParam.value + "'" + ); } + } + } - if (s.include(indicatorExpression, '@locations')) { - if (requestParam.whereParams) { - var locationsParam = _.find(requestParam.whereParams, function (param) { - if (param.name === 'locations') return param; - }); - if (locationsParam) { - indicatorExpression = s.replaceAll(indicatorExpression, '@locations', "'" + locationsParam.value + "'"); - } - } + if (s.include(indicatorExpression, '@referenceDate')) { + if (requestParam.whereParams) { + var referenceParam = _.find(requestParam.whereParams, function (param) { + if (param.name === 'referenceDate') return param; + }); + + if (referenceParam) { + indicatorExpression = s.replaceAll( + indicatorExpression, + '@referenceDate', + "'" + referenceParam.value + "'" + ); } + } + } - return indicatorExpression; + if (s.include(indicatorExpression, '@locations')) { + if (requestParam.whereParams) { + var locationsParam = _.find(requestParam.whereParams, function (param) { + if (param.name === 'locations') return param; + }); + if (locationsParam) { + indicatorExpression = s.replaceAll( + indicatorExpression, + '@locations', + "'" + locationsParam.value + "'" + ); + } + } } -}(); + return indicatorExpression; + } +})(); diff --git a/service/kibana.service.js b/service/kibana.service.js index c5950f414..c9930c5b8 100644 --- a/service/kibana.service.js +++ b/service/kibana.service.js @@ -1,21 +1,18 @@ - const kibanaConfig = require('../conf/kibana-config.json'); var serviceDefinition = { - getKibanaDashboards: getKibanaDashboards + getKibanaDashboards: getKibanaDashboards }; module.exports = serviceDefinition; function getKibanaDashboards() { - let dashboards = kibanaConfig['dashboards']; - return new Promise(function (resolve, reject) { - if(dashboards){ - resolve(JSON.parse(JSON.stringify(dashboards))); - }else { - reject('Error fetching dashboards'); - } - - }); -}; - + let dashboards = kibanaConfig['dashboards']; + return new Promise(function (resolve, reject) { + if (dashboards) { + resolve(JSON.parse(JSON.stringify(dashboards))); + } else { + reject('Error fetching dashboards'); + } + }); +} diff --git a/service/lab-orders.service.js b/service/lab-orders.service.js index 3a835d14f..cc24ea6b0 100644 --- a/service/lab-orders.service.js +++ b/service/lab-orders.service.js @@ -1,20 +1,18 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); export class labOrdersService { - - getAggregateReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - reportParams.groupBy = 'groupByOrderId'; - Promise.join(dao.runReport(reportParams), - (results) => { - resolve(results); - //TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - }); - } -} \ No newline at end of file + getAggregateReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + reportParams.groupBy = 'groupByOrderId'; + Promise.join(dao.runReport(reportParams), (results) => { + resolve(results); + //TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/lung-cancer-monthly-summary.service.js b/service/lung-cancer-monthly-summary.service.js index 290dea8f9..f48e12f53 100644 --- a/service/lung-cancer-monthly-summary.service.js +++ b/service/lung-cancer-monthly-summary.service.js @@ -1,36 +1,36 @@ -const dao = require("../etl-dao"); -const Promise = require("bluebird"); -const _ = require("lodash"); -const oncologyReportsService = require("../oncology-reports/oncology-reports-service"); -import { BaseMysqlReport } from "../app/reporting-framework/base-mysql.report"; -import { PatientlistMysqlReport } from "../app/reporting-framework/patientlist-mysql.report"; +const dao = require('../etl-dao'); +const Promise = require('bluebird'); +const _ = require('lodash'); +const oncologyReportsService = require('../oncology-reports/oncology-reports-service'); +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; import { titleCase } from '../etl-helpers'; export class LungCancerMonthlySummaryService { getAggregateReport(reportParams) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { let report; - if (reportParams.requestParams.period === "daily") { + if (reportParams.requestParams.period === 'daily') { report = new BaseMysqlReport( - "lungCancerDailySummaryAggregate", + 'lungCancerDailySummaryAggregate', reportParams.requestParams ); - } else if (reportParams.requestParams.period === "monthly") { + } else if (reportParams.requestParams.period === 'monthly') { report = new BaseMysqlReport( - "lungCancerMonthlySummaryAggregate", + 'lungCancerMonthlySummaryAggregate', reportParams.requestParams ); } - Promise.join(report.generateReport(), results => { + Promise.join(report.generateReport(), (results) => { let result = results.results.results; results.size = result ? result.length : 0; results.result = result; - delete results["results"]; + delete results['results']; resolve(results); //TODO Do some post processing - }).catch(errors => { + }).catch((errors) => { reject(errors); }); }); @@ -38,27 +38,27 @@ export class LungCancerMonthlySummaryService { getPatientListReport(reportParams) { let indicators = reportParams.indicators - ? reportParams.indicators.split(",") + ? reportParams.indicators.split(',') : []; if (reportParams.locationUuids) { let locationUuids = reportParams.locationUuids - ? reportParams.locationUuids.split(",") + ? reportParams.locationUuids.split(',') : []; reportParams.locationUuids = locationUuids; } if (reportParams.genders) { - let genders = reportParams.genders ? reportParams.genders.split(",") : []; + let genders = reportParams.genders ? reportParams.genders.split(',') : []; reportParams.genders = genders; } let report = new PatientlistMysqlReport( - "lungCancerMonthlySummaryAggregate", + 'lungCancerMonthlySummaryAggregate', reportParams ); - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { //TODO: Do some pre processing - Promise.join(report.generatePatientListReport(indicators), results => { + Promise.join(report.generatePatientListReport(indicators), (results) => { for (const key in results.results.results) { if (results.results.results.hasOwnProperty(key)) { if (results.results.results[key].person_name) { @@ -71,18 +71,18 @@ export class LungCancerMonthlySummaryService { oncologyReportsService .getPatientListCols( reportParams.indicators, - "b2db2bdf-67e9-42c5-858c-c7e435742ef5" + 'b2db2bdf-67e9-42c5-858c-c7e435742ef5' ) - .then(patientListCols => { - results["patientListCols"] = patientListCols; + .then((patientListCols) => { + results['patientListCols'] = patientListCols; resolve(results); }) - .catch(error => { - console.error("ERROR: Error getting patient list cols", error); + .catch((error) => { + console.error('ERROR: Error getting patient list cols', error); reject(error); }); - }).catch(errors => { - console.error("Error", errors); + }).catch((errors) => { + console.error('Error', errors); reject(errors); }); }); diff --git a/service/lung-cancer-treatment-summary.service.js b/service/lung-cancer-treatment-summary.service.js index 33013eebd..be8b70579 100644 --- a/service/lung-cancer-treatment-summary.service.js +++ b/service/lung-cancer-treatment-summary.service.js @@ -1,35 +1,35 @@ -const Promise = require("bluebird"); -const _ = require("lodash"); -const oncologyReportsService = require("../oncology-reports/oncology-reports-service"); -import { BaseMysqlReport } from "../app/reporting-framework/base-mysql.report"; -import { PatientlistMysqlReport } from "../app/reporting-framework/patientlist-mysql.report"; -import { titleCase } from "../etl-helpers"; +const Promise = require('bluebird'); +const _ = require('lodash'); +const oncologyReportsService = require('../oncology-reports/oncology-reports-service'); +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; +import { titleCase } from '../etl-helpers'; export class LungCancerTreatmentSummary { getAggregateReport(reportParams) { return new Promise((resolve, reject) => { let report; - if (reportParams.requestParams.period === "daily") { + if (reportParams.requestParams.period === 'daily') { report = new BaseMysqlReport( - "lungCancerTreatmentDailySummaryAggregate", + 'lungCancerTreatmentDailySummaryAggregate', reportParams.requestParams ); - } else if (reportParams.requestParams.period === "monthly") { + } else if (reportParams.requestParams.period === 'monthly') { report = new BaseMysqlReport( - "lungCancerTreatmentMonthlySummaryAggregate", + 'lungCancerTreatmentMonthlySummaryAggregate', reportParams.requestParams ); } - Promise.join(report.generateReport(), results => { + Promise.join(report.generateReport(), (results) => { let result = results.results.results; results.size = result ? result.length : 0; results.result = result; - delete results["results"]; + delete results['results']; resolve(results); // TODO Do some post processing - }).catch(errors => { + }).catch((errors) => { reject(errors); }); }); @@ -37,26 +37,26 @@ export class LungCancerTreatmentSummary { getPatientListReport(reportParams) { let indicators = reportParams.indicators - ? reportParams.indicators.split(",") + ? reportParams.indicators.split(',') : []; if (reportParams.locationUuids) { let locationUuids = reportParams.locationUuids - ? reportParams.locationUuids.split(",") + ? reportParams.locationUuids.split(',') : []; reportParams.locationUuids = locationUuids; } if (reportParams.genders) { - let genders = reportParams.genders ? reportParams.genders.split(",") : []; + let genders = reportParams.genders ? reportParams.genders.split(',') : []; reportParams.genders = genders; } let report = new PatientlistMysqlReport( - "lungCancerTreatmentMonthlySummaryAggregate", + 'lungCancerTreatmentMonthlySummaryAggregate', reportParams ); - return new Promise(function(resolve, reject) { - Promise.join(report.generatePatientListReport(indicators), results => { + return new Promise(function (resolve, reject) { + Promise.join(report.generatePatientListReport(indicators), (results) => { for (const key in results.results.results) { if (results.results.results.hasOwnProperty(key)) { if (results.results.results[key].person_name) { @@ -69,18 +69,18 @@ export class LungCancerTreatmentSummary { oncologyReportsService .getPatientListCols( reportParams.indicators, - "1a5a9a8d-f4a8-4c48-b63a-22f84530b4b9" + '1a5a9a8d-f4a8-4c48-b63a-22f84530b4b9' ) - .then(patientListCols => { - results["patientListCols"] = patientListCols; + .then((patientListCols) => { + results['patientListCols'] = patientListCols; resolve(results); }) - .catch(error => { - console.error("ERROR: Error getting patient list cols", error); + .catch((error) => { + console.error('ERROR: Error getting patient list cols', error); reject(error); }); - }).catch(errors => { - console.error("Error", errors); + }).catch((errors) => { + console.error('Error', errors); reject(errors); }); }); diff --git a/service/moh-408-service.js b/service/moh-408-service.js index 7b28ba92d..b9699ebee 100644 --- a/service/moh-408-service.js +++ b/service/moh-408-service.js @@ -1,76 +1,78 @@ -const Promise = require("bluebird"); +const Promise = require('bluebird'); const _ = require('lodash'); -import { - MultiDatasetPatientlistReport -} from '../app/reporting-framework/multi-dataset-patientlist.report.js'; +import { MultiDatasetPatientlistReport } from '../app/reporting-framework/multi-dataset-patientlist.report.js'; import ReportProcessorHelpersService from '../app/reporting-framework/report-processor-helpers.service'; const moh408defs = require('../app/reporting-framework/hei/moh-408'); -export class HeiSummaryService extends MultiDatasetPatientlistReport{ +export class HeiSummaryService extends MultiDatasetPatientlistReport { + constructor(reportName, params) { + super(reportName, params); + } - constructor(reportName, params) { - super(reportName, params) - } + generateReport(additionalParams) { + const that = this; + return new Promise((resolve, reject) => { + super + .generateReport(additionalParams) + .then((results) => { + if (additionalParams && additionalParams.type === 'patient-list') { + resolve(results); + } else { + let finalResult = []; + const reportProcessorHelpersService = new ReportProcessorHelpersService(); + for (let result of results) { + if ( + result.report && + result.report.reportSchemas && + result.report.reportSchemas.main && + result.report.reportSchemas.main.transFormDirectives.joinColumn + ) { + finalResult = reportProcessorHelpersService.joinDataSets( + that.params[ + result.report.reportSchemas.main.transFormDirectives + .joinColumnParam + ] || + result.report.reportSchemas.main.transFormDirectives + .joinColumn, + finalResult, + result.results.results.results + ); + } + } - - generateReport(additionalParams) { - const that = this; - return new Promise((resolve, reject) => { - super.generateReport(additionalParams) - .then((results) => { - if (additionalParams && additionalParams.type === 'patient-list') { - resolve(results); - } else { - - let finalResult = [] - const reportProcessorHelpersService = new ReportProcessorHelpersService(); - for (let result of results) { - if (result.report && result.report.reportSchemas && result.report.reportSchemas.main && - result.report.reportSchemas.main.transFormDirectives.joinColumn) { - finalResult = reportProcessorHelpersService - .joinDataSets(that.params[result.report.reportSchemas.main.transFormDirectives.joinColumnParam] || - result.report.reportSchemas.main.transFormDirectives.joinColumn, - finalResult, result.results.results.results); - - } - } - - resolve({ - queriesAndSchemas: results, - result: finalResult, - sectionDefinitions: moh408defs, - indicatorDefinitions: [] - }); - - - } - }) - .catch((error) => { - console.error('MOH 408 generation error: ', error); - reject(error); - }); - - }); - } - - - getPatientListReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - Promise.join(dao.getPatientListReport(reportParams), - self.resolveLocationUuidsToName(reportParams.locationUuids), - (results, locations) => { - results.indicators = self.getIndicatorSectionDefinitions(reportParams.indicator,moh408defs); - results.locations = locations; - resolve(results); - }).catch((errors) => { - reject(errors); + resolve({ + queriesAndSchemas: results, + result: finalResult, + sectionDefinitions: moh408defs, + indicatorDefinitions: [] }); + } + }) + .catch((error) => { + console.error('MOH 408 generation error: ', error); + reject(error); }); - } - - - + }); + } -} \ No newline at end of file + getPatientListReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + Promise.join( + dao.getPatientListReport(reportParams), + self.resolveLocationUuidsToName(reportParams.locationUuids), + (results, locations) => { + results.indicators = self.getIndicatorSectionDefinitions( + reportParams.indicator, + moh408defs + ); + results.locations = locations; + resolve(results); + } + ).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/moh-731/moh-731-2017.json b/service/moh-731/moh-731-2017.json index 80fdb3adf..82c29e22c 100755 --- a/service/moh-731/moh-731-2017.json +++ b/service/moh-731/moh-731-2017.json @@ -1,542 +1,542 @@ [ - { - "sectionTitle": "3.1 Enrolled in Care", - "indicators": [ - { - "label": "Enrolled in care - Below 1yr", - "ref": "HV03-001", - "indicator": "enrolled_in_care_below_1" - }, - { - "label": "Enrolled in care - 1 to 9yrs", - "ref": "HV03-002", - "indicator": "enrolled_in_care_1_to_9" - }, - { - "label": "Enrolled in care - 10 to 14yrs(M)", - "ref": "HV03-003", - "indicator": "enrolled_in_care_males_10_to_14" - }, - { - "label": "Enrolled in care - 10 to 14yrs(F)", - "ref": "HV03-004", - "indicator": "enrolled_in_care_females_10_to_14" - }, - { - "label": "Enrolled in care - 15 to 19yrs(M)", - "ref": "HV03-005", - "indicator": "enrolled_in_care_males_15_to_19" - }, - { - "label": "Enrolled in care - 15 to 19yrs(F)", - "ref": "HV03-006", - "indicator": "enrolled_in_care_females_15_to_19" - }, - { - "label": "Enrolled in care - 20 to 24yrs(M)", - "ref": "HV03-007", - "indicator": "enrolled_in_care_males_20_to_24" - }, - { - "label": "Enrolled in care - 20 to 24yrs(F)", - "ref": "HV03-008", - "indicator": "enrolled_in_care_females_20_to_24" - }, - { - "label": "Enrolled in care - 25yrs and older(M)", - "ref": "HV03-009", - "indicator": "enrolled_in_care_males_25_and_older" - }, - { - "label": "Enrolled in care - 25yrs and older(F)", - "ref": "HV03-010", - "indicator": "enrolled_in_care_females_25_and_older" - }, - { - "label": "Enrolled in care - Total (Sum HV03-001 to HV03-010)", - "ref": "HV03-011", - "indicator": "enrolled_in_care_total" - }, - { - "label": "Enrolled in care - key population", - "ref": "HV03-012", - "indicator": "enrolled_in_care_total" - } - ] - }, - { - "sectionTitle": "3.2 Current On Pre ART", - "indicators": [ - { - "label": "In Pre ART - 0 to 14yrs", - "ref": "HV03-013", - "indicator": "pre_art_total_below_15" - }, - { - "label": "In Pre ART - 15yrs and older", - "ref": "HV03-014", - "indicator": "pre_art_total_15_and_older" - }, - { - "label": "In Pre ART - Total (Sum HV03-013 to HV013-014)", - "ref": "HV03-015", - "indicator": "pre_art_total" - } - ] - }, - { - "sectionTitle": "3.3 Starting ART", - "indicators": [ - { - "label": "Starting ART - Below 1yr", - "ref": "HV03-016", - "indicator": "starting_art_below_1" - }, - { - "label": "Starting ART - 1 to 9yrs", - "ref": "HV03-017", - "indicator": "starting_art_1_to_9" - }, - { - "label": "Starting ART - 10 to 14yrs(M)", - "ref": "HV03-018", - "indicator": "starting_art_males_10_to_14" - }, - { - "label": "Starting ART - 10 to 14yrs(F)", - "ref": "HV03-019", - "indicator": "starting_art_females_10_to_14" - }, - { - "label": "Starting ART - 15 to 19yrs(M)", - "ref": "HV03-020", - "indicator": "starting_art_males_15_to_19" - }, - { - "label": "Starting ART - 15 to 19yrs(F)", - "ref": "HV03-021", - "indicator": "starting_art_females_15_to_19" - }, - { - "label": "Starting ART - 20 to 24yrs(M)", - "ref": "HV03-022", - "indicator": "starting_art_males_20_to_24" - }, - { - "label": "Starting ART - 20 to 24yrs(F)", - "ref": "HV03-023", - "indicator": "starting_art_females_20_to_24" - }, - { - "label": "Starting ART - 25 and older(M)", - "ref": "HV03-024", - "indicator": "starting_art_males_25_and_older" - }, - { - "label": "Starting ART - 25 and older(F)", - "ref": "HV03-025", - "indicator": "starting_art_females_25_and_older" - }, - { - "label": "Starting on ART - Total (Sum HV03-016 to HV03-025)", - "ref": "HV03-026", - "indicator": "starting_art_total" - }, - { - "label": "Starting on ART - key population", - "ref": "HV03-027", - "indicator": "" - } - ] - }, - { - "sectionTitle": "3.4 Currently on ART [ALL] - (Add 3.2 and 3.3 e.g HV03-34=HV03-20+HV03-28)", - "indicators": [ - { - "label": "Currently on ART - Below 1yr", - "ref": "HV03-028", - "indicator": "on_art_below_1" - }, - { - "label": "Currently on ART - 1 to 9yrs", - "ref": "HV03-029", - "indicator": "on_art_1_to_9" - }, - { - "label": "Currently on ART - 10 to 14yrs(M)", - "ref": "HV03-030", - "indicator": "on_art_males_10_to_14" - }, - { - "label": "Currently on ART - 10 to 14yrs(F)", - "ref": "HV03-031", - "indicator": "on_art_females_10_to_14" - }, - { - "label": "Currently on ART - 15 to 19yrs(M)", - "ref": "HV03-032", - "indicator": "on_art_males_15_to_19" - }, - { - "label": "Currently on ART - 15 to 19yrs(F)", - "ref": "HV03-033", - "indicator": "on_art_females_15_to_19" - }, - { - "label": "Currently on ART - 20 to 24yrs(M)", - "ref": "HV03-034", - "indicator": "on_art_males_20_to_24" - }, - { - "label": "Currently on ART - 20 to 24yrs(F)", - "ref": "HV03-035", - "indicator": "on_art_females_20_to_24" - }, - { - "label": "Currently on ART - 25yrs and older(M)", - "ref": "HV03-036", - "indicator": "on_art_males_25_and_older" - }, - { - "label": "Currently on ART - 25yrs and older(F)", - "ref": "HV03-037", - "indicator": "on_art_females_25_and_older" - }, - { - "label": "Total currently on ART (Sum HV03-028 to HV03-037)", - "ref": "HV03-038", - "indicator": "on_art_total" - }, - { - "label": "Currently on ART - key population", - "ref": "HV03-039", - "indicator": "" - } - ] - }, - { - "sectionTitle": "3.5 Survival and Retention on ART at 12 months", - "indicators": [ - { - "label": "On ART at 12 months", - "ref": "HV03-040", - "indicator": "total_on_therapy_at_12_months" - }, - { - "label": "ART Net Cohort at 12 months", - "ref": "HV03-041", - "indicator": "art_net_cohort_at_12_months" - }, - { - "label": "Viral load less than 1000 at 12 months", - "ref": "HV03-042", - "indicator": "virally_suppressed_in_past_year" - }, - { - "label": "Viral load results at 12 months", - "ref": "HV03-043", - "indicator": "viral_load_resulted_in_past_year" - } - ] - }, - { - "sectionTitle": "3.6 On Cotrimoxazole Prophylaxis (within 2 months)", - "indicators": [ - { - "label": "On CTX - Below 1yr", - "ref": "HV03-044", - "indicator": "on_pcp_prophylaxis_below_1" - }, - { - "label": "On CTX - 1 to 9yrs", - "ref": "HV03-045", - "indicator": "on_pcp_prophylaxis_1_to_9" - }, - { - "label": "On CTX - 10 to 14yrs", - "ref": "HV03-046", - "indicator": "on_pcp_prophylaxis_10_to_14" - }, - { - "label": "On CTX - 15 to 19yrs", - "ref": "HV03-047", - "indicator": "on_pcp_prophylaxis_15_to_19" - }, - { - "label": "On CTX - 20 to 24yrs", - "ref": "HV03-048", - "indicator": "on_pcp_prophylaxis_20_to_24" - }, - { - "label": "On CTX - 25yrs and older", - "ref": "HV03-049", - "indicator": "on_pcp_prophylaxis_25_and_older" - }, - { - "label": "Total on CTX (Sum HV03-044 TO HV03-049)", - "ref": "HV03-050", - "indicator": "on_pcp_prophylaxis" - } - ] - }, - { - "sectionTitle": "3.7 Screening", - "indicators": [ - { - "label": "Screened for TB - Below 1yrs(M)", - "ref": "HV03-051", - "indicator": "screened_for_tb_below_1" - }, - { - "label": "Screened for TB - 1 to 9yrs", - "ref": "HV03-052", - "indicator": "screened_for_tb_1_to_9" - }, - { - "label": "Screened for TB - 10 to 14yrs", - "ref": "HV03-053", - "indicator": "screened_for_tb_10_to_14" - }, - { - "label": "Screened for TB - 15 to 19yrs", - "ref": "HV03-054", - "indicator": "screened_for_tb_15_to_19" - }, - { - "label": "Screened for TB - 20 to 24yrs", - "ref": "HV03-055", - "indicator": "screened_for_tb_20_to_24" - }, - { - "label": "Screened for TB - 25yrs & older", - "ref": "HV03-056", - "indicator": "screened_for_tb_25_and_older" - }, - { - "label": "Total Screened for TB (Sum HV03-51 to HV03-56)", - "ref": "HV03-057", - "indicator": "screened_for_tb" - }, - { - "label": "Presumed TB Total ", - "ref": "HV03-058", - "indicator": "" - } - ] - }, - { - "sectionTitle": "3.8 Starting IPT", - "indicators": [ - { - "label": "Starting IPT - Below 1yrs", - "ref": "HV03-059", - "indicator": "newly_started_IPT_below_1" - }, - { - "label": "Starting IPT - 1 to 9yrs", - "ref": "HV03-060", - "indicator": "newly_started_IPT_1_to_9" - }, - { - "label": "Starting IPT - 10 to 14yrs", - "ref": "HV03-061", - "indicator": "newly_started_IPT_10_to_14" - }, - { - "label": "Starting IPT - 15 to 19yrs", - "ref": "HV03-062", - "indicator": "newly_started_IPT_15_to_19" - }, - { - "label": "Starting IPT - 20 to 24yrs", - "ref": "HV03-063", - "indicator": "newly_started_IPT_20_to_24" - }, - { - "label": "Starting IPT - 25yrs and older(F)", - "ref": "HV03-064", - "indicator": "newly_started_IPT_25_and_older" - }, - { - "label": "Total Starting IPT (Sum HV03-059 to HV03-064)", - "ref": "HV03-065", - "indicator": "newly_started_IPT" - }, - { - "label": "Completed IPT 12months ", - "ref": "HV03-066", - "indicator": "completed_12_months_IPT" - } - ] - }, - { - "sectionTitle": "3.9 Nutrition and HIV", - "indicators": [ - { - "label": "Nutrition Assess less than 15yrs", - "ref": "HV03-067", - "indicator": "" - }, - { - "label": "Nutrition Assess greater than 15yrs", - "ref": "HV03-068", - "indicator": "" - }, - { - "label": "Nutrition Assess Total (Sum HV03-067 to HV03-068)", - "ref": "HV03-069", - "indicator": "" - }, - { - "label": "Malnourished less than 15", - "ref": "HV03-070", - "indicator": "" - }, - { - "label": "Malnourished greater than 15", - "ref": "HV03-071", - "indicator": "" - }, - { - "label": "Malnourished Total (Sum HV03-070 to HV03-071)", - "ref": "HV03-072", - "indicator": "" - }, - { - "label": "FBP Provided less than 15", - "ref": "HV03-073", - "indicator": "" - }, - { - "label": "FBP Provided greater than 15", - "ref": "HV03-074", - "indicator": "" - }, - { - "label": "FBP Provided (Sum HV03-073 to HV03-074)", - "ref": "HV03-075", - "indicator": "" - } - ] - }, - { - "sectionTitle": "3.10 HIV in TB Clinic", - "indicators": [ - { - "label": "TB cases New", - "ref": "HV03-076", - "indicator": "started_TB_treatment_within_reporting_period" - }, - { - "label": "TB cases KP", - "ref": "HV03-077", - "indicator": "HIV_patients_newly_enrolled_into_TB_treatment" - }, - { - "label": "TB Cases Tested HIV", - "ref": "HV03-078", - "indicator": "" - }, - { - "label": "TB Known Status (Sum HV03-077 and HV03-078)", - "ref": "HV03-079", - "indicator": "" - }, - { - "label": "TB New HIV Positive", - "ref": "HV03-080", - "indicator": "TB_patients_newly_enrolled_into_HIV_care" - }, - { - "label": "TB TOTAL HIV Positive (Sum HV03-077 and HV03-080)", - "ref": "HV03-081", - "indicator": "newly_identified_HIV_positive_patient_on_TB_treatment" - }, - { - "label": "TB already on HAART", - "ref": "HV03-082", - "indicator": "patients_on_ARV_starting_TB_treatment" - }, - { - "label": "TB starting HAART", - "ref": "HV03-083", - "indicator": "TB_patients_starting_ARV_medication" - }, - { - "label": "TB Total on HAART (Sum HV03-082 and HV03-083)", - "ref": "HV03-084", - "indicator": "newly_identified_TB_patients_on_ARVs" - } - ] - }, - { - "sectionTitle": "3.11 Community Dispensing of ARVs", - "indicators": [ - { - "label": "Community ART current(M)", - "ref": "HV03-085", - "indicator": "community_ART_dispensing_male" - }, - { - "label": "Community ART current(F)", - "ref": "HV03-086", - "indicator": "community_ART_dispensing_female" - } - ] - }, - { - "sectionTitle": "3.12 Family planning & CaCx screen in HIV CCC", - "indicators": [ - { - "label": "Screen CaCx New F18+", - "ref": "HV03-087", - "indicator": "" - }, - { - "label": "Clinical visits F18+", - "ref": "HV03-089", - "indicator": "female_gte_18yo_visits" - }, - { - "label": "On modern FP F15+", - "ref": "HV03-090", - "indicator": "" - } - ] - }, - { - "sectionTitle": "5. Post Exposure Prophylaxis", - "indicators": [ - { - "label": "Exposed Occupational", - "ref": "HV05-01", - "indicator": "hiv_exposed_occupational" - }, - { - "label": "Exposed Other", - "ref": "HV05-02", - "indicator": "hiv_exposed_non_occupational" - }, - { - "label": "Exposed Total (Sum HV05-01 and HV05-02)", - "ref": "HV05-03", - "indicator": "total_hiv_exposed" - }, - { - "label": "PEP Occupational", - "ref": "HV05-04", - "indicator": "started_PEP_occupational" - }, - { - "label": "PEP Other", - "ref": "HV05-05", - "indicator": "started_PEP_non_occupational" - }, - { - "label": "PEP Total (Sum HV05-04 and HV05-05)", - "ref": "HV03-06", - "indicator": "total_started_PEP" - } - ] - } + { + "sectionTitle": "3.1 Enrolled in Care", + "indicators": [ + { + "label": "Enrolled in care - Below 1yr", + "ref": "HV03-001", + "indicator": "enrolled_in_care_below_1" + }, + { + "label": "Enrolled in care - 1 to 9yrs", + "ref": "HV03-002", + "indicator": "enrolled_in_care_1_to_9" + }, + { + "label": "Enrolled in care - 10 to 14yrs(M)", + "ref": "HV03-003", + "indicator": "enrolled_in_care_males_10_to_14" + }, + { + "label": "Enrolled in care - 10 to 14yrs(F)", + "ref": "HV03-004", + "indicator": "enrolled_in_care_females_10_to_14" + }, + { + "label": "Enrolled in care - 15 to 19yrs(M)", + "ref": "HV03-005", + "indicator": "enrolled_in_care_males_15_to_19" + }, + { + "label": "Enrolled in care - 15 to 19yrs(F)", + "ref": "HV03-006", + "indicator": "enrolled_in_care_females_15_to_19" + }, + { + "label": "Enrolled in care - 20 to 24yrs(M)", + "ref": "HV03-007", + "indicator": "enrolled_in_care_males_20_to_24" + }, + { + "label": "Enrolled in care - 20 to 24yrs(F)", + "ref": "HV03-008", + "indicator": "enrolled_in_care_females_20_to_24" + }, + { + "label": "Enrolled in care - 25yrs and older(M)", + "ref": "HV03-009", + "indicator": "enrolled_in_care_males_25_and_older" + }, + { + "label": "Enrolled in care - 25yrs and older(F)", + "ref": "HV03-010", + "indicator": "enrolled_in_care_females_25_and_older" + }, + { + "label": "Enrolled in care - Total (Sum HV03-001 to HV03-010)", + "ref": "HV03-011", + "indicator": "enrolled_in_care_total" + }, + { + "label": "Enrolled in care - key population", + "ref": "HV03-012", + "indicator": "enrolled_in_care_total" + } + ] + }, + { + "sectionTitle": "3.2 Current On Pre ART", + "indicators": [ + { + "label": "In Pre ART - 0 to 14yrs", + "ref": "HV03-013", + "indicator": "pre_art_total_below_15" + }, + { + "label": "In Pre ART - 15yrs and older", + "ref": "HV03-014", + "indicator": "pre_art_total_15_and_older" + }, + { + "label": "In Pre ART - Total (Sum HV03-013 to HV013-014)", + "ref": "HV03-015", + "indicator": "pre_art_total" + } + ] + }, + { + "sectionTitle": "3.3 Starting ART", + "indicators": [ + { + "label": "Starting ART - Below 1yr", + "ref": "HV03-016", + "indicator": "starting_art_below_1" + }, + { + "label": "Starting ART - 1 to 9yrs", + "ref": "HV03-017", + "indicator": "starting_art_1_to_9" + }, + { + "label": "Starting ART - 10 to 14yrs(M)", + "ref": "HV03-018", + "indicator": "starting_art_males_10_to_14" + }, + { + "label": "Starting ART - 10 to 14yrs(F)", + "ref": "HV03-019", + "indicator": "starting_art_females_10_to_14" + }, + { + "label": "Starting ART - 15 to 19yrs(M)", + "ref": "HV03-020", + "indicator": "starting_art_males_15_to_19" + }, + { + "label": "Starting ART - 15 to 19yrs(F)", + "ref": "HV03-021", + "indicator": "starting_art_females_15_to_19" + }, + { + "label": "Starting ART - 20 to 24yrs(M)", + "ref": "HV03-022", + "indicator": "starting_art_males_20_to_24" + }, + { + "label": "Starting ART - 20 to 24yrs(F)", + "ref": "HV03-023", + "indicator": "starting_art_females_20_to_24" + }, + { + "label": "Starting ART - 25 and older(M)", + "ref": "HV03-024", + "indicator": "starting_art_males_25_and_older" + }, + { + "label": "Starting ART - 25 and older(F)", + "ref": "HV03-025", + "indicator": "starting_art_females_25_and_older" + }, + { + "label": "Starting on ART - Total (Sum HV03-016 to HV03-025)", + "ref": "HV03-026", + "indicator": "starting_art_total" + }, + { + "label": "Starting on ART - key population", + "ref": "HV03-027", + "indicator": "" + } + ] + }, + { + "sectionTitle": "3.4 Currently on ART [ALL] - (Add 3.2 and 3.3 e.g HV03-34=HV03-20+HV03-28)", + "indicators": [ + { + "label": "Currently on ART - Below 1yr", + "ref": "HV03-028", + "indicator": "on_art_below_1" + }, + { + "label": "Currently on ART - 1 to 9yrs", + "ref": "HV03-029", + "indicator": "on_art_1_to_9" + }, + { + "label": "Currently on ART - 10 to 14yrs(M)", + "ref": "HV03-030", + "indicator": "on_art_males_10_to_14" + }, + { + "label": "Currently on ART - 10 to 14yrs(F)", + "ref": "HV03-031", + "indicator": "on_art_females_10_to_14" + }, + { + "label": "Currently on ART - 15 to 19yrs(M)", + "ref": "HV03-032", + "indicator": "on_art_males_15_to_19" + }, + { + "label": "Currently on ART - 15 to 19yrs(F)", + "ref": "HV03-033", + "indicator": "on_art_females_15_to_19" + }, + { + "label": "Currently on ART - 20 to 24yrs(M)", + "ref": "HV03-034", + "indicator": "on_art_males_20_to_24" + }, + { + "label": "Currently on ART - 20 to 24yrs(F)", + "ref": "HV03-035", + "indicator": "on_art_females_20_to_24" + }, + { + "label": "Currently on ART - 25yrs and older(M)", + "ref": "HV03-036", + "indicator": "on_art_males_25_and_older" + }, + { + "label": "Currently on ART - 25yrs and older(F)", + "ref": "HV03-037", + "indicator": "on_art_females_25_and_older" + }, + { + "label": "Total currently on ART (Sum HV03-028 to HV03-037)", + "ref": "HV03-038", + "indicator": "on_art_total" + }, + { + "label": "Currently on ART - key population", + "ref": "HV03-039", + "indicator": "" + } + ] + }, + { + "sectionTitle": "3.5 Survival and Retention on ART at 12 months", + "indicators": [ + { + "label": "On ART at 12 months", + "ref": "HV03-040", + "indicator": "total_on_therapy_at_12_months" + }, + { + "label": "ART Net Cohort at 12 months", + "ref": "HV03-041", + "indicator": "art_net_cohort_at_12_months" + }, + { + "label": "Viral load less than 1000 at 12 months", + "ref": "HV03-042", + "indicator": "virally_suppressed_in_past_year" + }, + { + "label": "Viral load results at 12 months", + "ref": "HV03-043", + "indicator": "viral_load_resulted_in_past_year" + } + ] + }, + { + "sectionTitle": "3.6 On Cotrimoxazole Prophylaxis (within 2 months)", + "indicators": [ + { + "label": "On CTX - Below 1yr", + "ref": "HV03-044", + "indicator": "on_pcp_prophylaxis_below_1" + }, + { + "label": "On CTX - 1 to 9yrs", + "ref": "HV03-045", + "indicator": "on_pcp_prophylaxis_1_to_9" + }, + { + "label": "On CTX - 10 to 14yrs", + "ref": "HV03-046", + "indicator": "on_pcp_prophylaxis_10_to_14" + }, + { + "label": "On CTX - 15 to 19yrs", + "ref": "HV03-047", + "indicator": "on_pcp_prophylaxis_15_to_19" + }, + { + "label": "On CTX - 20 to 24yrs", + "ref": "HV03-048", + "indicator": "on_pcp_prophylaxis_20_to_24" + }, + { + "label": "On CTX - 25yrs and older", + "ref": "HV03-049", + "indicator": "on_pcp_prophylaxis_25_and_older" + }, + { + "label": "Total on CTX (Sum HV03-044 TO HV03-049)", + "ref": "HV03-050", + "indicator": "on_pcp_prophylaxis" + } + ] + }, + { + "sectionTitle": "3.7 Screening", + "indicators": [ + { + "label": "Screened for TB - Below 1yrs(M)", + "ref": "HV03-051", + "indicator": "screened_for_tb_below_1" + }, + { + "label": "Screened for TB - 1 to 9yrs", + "ref": "HV03-052", + "indicator": "screened_for_tb_1_to_9" + }, + { + "label": "Screened for TB - 10 to 14yrs", + "ref": "HV03-053", + "indicator": "screened_for_tb_10_to_14" + }, + { + "label": "Screened for TB - 15 to 19yrs", + "ref": "HV03-054", + "indicator": "screened_for_tb_15_to_19" + }, + { + "label": "Screened for TB - 20 to 24yrs", + "ref": "HV03-055", + "indicator": "screened_for_tb_20_to_24" + }, + { + "label": "Screened for TB - 25yrs & older", + "ref": "HV03-056", + "indicator": "screened_for_tb_25_and_older" + }, + { + "label": "Total Screened for TB (Sum HV03-51 to HV03-56)", + "ref": "HV03-057", + "indicator": "screened_for_tb" + }, + { + "label": "Presumed TB Total ", + "ref": "HV03-058", + "indicator": "" + } + ] + }, + { + "sectionTitle": "3.8 Starting IPT", + "indicators": [ + { + "label": "Starting IPT - Below 1yrs", + "ref": "HV03-059", + "indicator": "newly_started_IPT_below_1" + }, + { + "label": "Starting IPT - 1 to 9yrs", + "ref": "HV03-060", + "indicator": "newly_started_IPT_1_to_9" + }, + { + "label": "Starting IPT - 10 to 14yrs", + "ref": "HV03-061", + "indicator": "newly_started_IPT_10_to_14" + }, + { + "label": "Starting IPT - 15 to 19yrs", + "ref": "HV03-062", + "indicator": "newly_started_IPT_15_to_19" + }, + { + "label": "Starting IPT - 20 to 24yrs", + "ref": "HV03-063", + "indicator": "newly_started_IPT_20_to_24" + }, + { + "label": "Starting IPT - 25yrs and older(F)", + "ref": "HV03-064", + "indicator": "newly_started_IPT_25_and_older" + }, + { + "label": "Total Starting IPT (Sum HV03-059 to HV03-064)", + "ref": "HV03-065", + "indicator": "newly_started_IPT" + }, + { + "label": "Completed IPT 12months ", + "ref": "HV03-066", + "indicator": "completed_12_months_IPT" + } + ] + }, + { + "sectionTitle": "3.9 Nutrition and HIV", + "indicators": [ + { + "label": "Nutrition Assess less than 15yrs", + "ref": "HV03-067", + "indicator": "" + }, + { + "label": "Nutrition Assess greater than 15yrs", + "ref": "HV03-068", + "indicator": "" + }, + { + "label": "Nutrition Assess Total (Sum HV03-067 to HV03-068)", + "ref": "HV03-069", + "indicator": "" + }, + { + "label": "Malnourished less than 15", + "ref": "HV03-070", + "indicator": "" + }, + { + "label": "Malnourished greater than 15", + "ref": "HV03-071", + "indicator": "" + }, + { + "label": "Malnourished Total (Sum HV03-070 to HV03-071)", + "ref": "HV03-072", + "indicator": "" + }, + { + "label": "FBP Provided less than 15", + "ref": "HV03-073", + "indicator": "" + }, + { + "label": "FBP Provided greater than 15", + "ref": "HV03-074", + "indicator": "" + }, + { + "label": "FBP Provided (Sum HV03-073 to HV03-074)", + "ref": "HV03-075", + "indicator": "" + } + ] + }, + { + "sectionTitle": "3.10 HIV in TB Clinic", + "indicators": [ + { + "label": "TB cases New", + "ref": "HV03-076", + "indicator": "started_TB_treatment_within_reporting_period" + }, + { + "label": "TB cases KP", + "ref": "HV03-077", + "indicator": "HIV_patients_newly_enrolled_into_TB_treatment" + }, + { + "label": "TB Cases Tested HIV", + "ref": "HV03-078", + "indicator": "" + }, + { + "label": "TB Known Status (Sum HV03-077 and HV03-078)", + "ref": "HV03-079", + "indicator": "" + }, + { + "label": "TB New HIV Positive", + "ref": "HV03-080", + "indicator": "TB_patients_newly_enrolled_into_HIV_care" + }, + { + "label": "TB TOTAL HIV Positive (Sum HV03-077 and HV03-080)", + "ref": "HV03-081", + "indicator": "newly_identified_HIV_positive_patient_on_TB_treatment" + }, + { + "label": "TB already on HAART", + "ref": "HV03-082", + "indicator": "patients_on_ARV_starting_TB_treatment" + }, + { + "label": "TB starting HAART", + "ref": "HV03-083", + "indicator": "TB_patients_starting_ARV_medication" + }, + { + "label": "TB Total on HAART (Sum HV03-082 and HV03-083)", + "ref": "HV03-084", + "indicator": "newly_identified_TB_patients_on_ARVs" + } + ] + }, + { + "sectionTitle": "3.11 Community Dispensing of ARVs", + "indicators": [ + { + "label": "Community ART current(M)", + "ref": "HV03-085", + "indicator": "community_ART_dispensing_male" + }, + { + "label": "Community ART current(F)", + "ref": "HV03-086", + "indicator": "community_ART_dispensing_female" + } + ] + }, + { + "sectionTitle": "3.12 Family planning & CaCx screen in HIV CCC", + "indicators": [ + { + "label": "Screen CaCx New F18+", + "ref": "HV03-087", + "indicator": "" + }, + { + "label": "Clinical visits F18+", + "ref": "HV03-089", + "indicator": "female_gte_18yo_visits" + }, + { + "label": "On modern FP F15+", + "ref": "HV03-090", + "indicator": "" + } + ] + }, + { + "sectionTitle": "5. Post Exposure Prophylaxis", + "indicators": [ + { + "label": "Exposed Occupational", + "ref": "HV05-01", + "indicator": "hiv_exposed_occupational" + }, + { + "label": "Exposed Other", + "ref": "HV05-02", + "indicator": "hiv_exposed_non_occupational" + }, + { + "label": "Exposed Total (Sum HV05-01 and HV05-02)", + "ref": "HV05-03", + "indicator": "total_hiv_exposed" + }, + { + "label": "PEP Occupational", + "ref": "HV05-04", + "indicator": "started_PEP_occupational" + }, + { + "label": "PEP Other", + "ref": "HV05-05", + "indicator": "started_PEP_non_occupational" + }, + { + "label": "PEP Total (Sum HV05-04 and HV05-05)", + "ref": "HV03-06", + "indicator": "total_started_PEP" + } + ] + } ] diff --git a/service/moh-731/moh-731-legacy.json b/service/moh-731/moh-731-legacy.json index a72161d42..f49ab8b29 100755 --- a/service/moh-731/moh-731-legacy.json +++ b/service/moh-731/moh-731-legacy.json @@ -1,422 +1,422 @@ [ - { - "sectionTitle": "3.1 On Cotrimoxazole Prophylaxis (within 2 months)", - "indicators": [ - { - "label": "HIV Exposed Infants (within 2 months)", - "ref": "HV03-01", - "indicator": "hiv_exposed_infants_below_2_months" - }, - { - "label": "HIV Exposed Infant (Eligible for CTX within 2 months)", - "ref": "HV03-02", - "indicator": "hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below" - }, - { - "label": "On CTX Below 15 yrs(M)", - "ref": "HV03-03", - "indicator": "on_pcp_prophylaxis_males_below_15" - }, - { - "label": "On CTX Below 15 yrs(F)", - "ref": "HV03-04", - "indicator": "on_pcp_prophylaxis_females_below_15" - }, - { - "label": "On CTX 15 yrs and Older(M)", - "ref": "HV03-05", - "indicator": "on_pcp_prophylaxis_males_15_and_above" - }, - { - "label": "On CTX 15 yrs and Older(F)", - "ref": "HV03-06", - "indicator": "on_pcp_prophylaxis_females_15_and_above" - }, - { - "label": "Total on CTX (Sum HV03-03 TO HV03-06)", - "ref": "HV03-07", - "indicator": "on_pcp_prophylaxis" - } - ] - }, - { - "sectionTitle": "3.2 Enrolled in Care", - "indicators": [ - { - "label": "Enrolled in care Below 1yr(M)", - "ref": "HV03-08", - "indicator": "enrolled_in_care_males_lt_one" - }, - { - "label": "Enrolled in care Below 1yr(F)", - "ref": "HV03-08", - "indicator": "enrolled_in_care_females_lt_one" - }, - { - "label": "Enrolled in care Below 15yrs(M)", - "ref": "HV03-09", - "indicator": "enrolled_in_care_males_below_15" - }, - { - "label": "Enrolled in care Below 15yrs(F)", - "ref": "HV03-10", - "indicator": "enrolled_in_care_females_below_15" - }, - { - "label": "Enrolled in care 15yrs & Older(M)", - "ref": "HV03-11", - "indicator": "enrolled_in_care_males_15_and_older" - }, - { - "label": "Enrolled in care 15yrs & Older(F)", - "ref": "HV03-12", - "indicator": "enrolled_in_care_females_15_and_older" - }, - { - "label": "Enrolled in care - Total (Sum HV03-09 to HV03-12)", - "ref": "HV03-13", - "indicator": "enrolled_in_care_total" - } - ] - }, - { - "sectionTitle": "3.3 Currently in Care -(from the total sheet-this month only and from last 2 months)", - "indicators": [ - { - "label": "Currently in care Below 1yr(M)", - "ref": "HV03-14", - "indicator": "currently_in_care_males_lt_one" - }, - { - "label": "Currently in care Below 1yr(F)", - "ref": "HV03-14", - "indicator": "currently_in_care_females_lt_one" - }, - { - "label": "Currently in care Below 15yrs(M)", - "ref": "HV03-15", - "indicator": "currently_in_care_males_below_15" - }, - { - "label": "Currently in care Below 15yrs(F)", - "ref": "HV03-16", - "indicator": "currently_in_care_females_below_15" - }, - { - "label": "Currently in care 15yrs and older(M)", - "ref": "HV03-17", - "indicator": "currently_in_care_males_15_and_older" - }, - { - "label": "Currently in care 15yrs and older(F)", - "ref": "HV03-18", - "indicator": "currently_in_care_females_15_and_older" - }, - { - "label": "Currently in Care-Total (Sum HV03-15 to HV03-18)", - "ref": "HV03-19", - "indicator": "currently_in_care_total" - } - ] - }, - { - "sectionTitle": "3.4 Starting ART", - "indicators": [ - { - "label": "Starting ART -Below 1yr(M)", - "ref": "HV03-20", - "indicator": "starting_art_males_lt_one" - }, - { - "label": "Starting ART -Below 1yr(F)", - "ref": "HV03-20", - "indicator": "starting_art_females_lt_one" - }, - { - "label": "Starting ART -Below 15yrs(M)", - "ref": "HV03-21", - "indicator": "starting_art_males_below_15" - }, - { - "label": "Starting ART -Below 15yrs(F)", - "ref": "HV03-22", - "indicator": "starting_art_females_below_15" - }, - { - "label": "Starting ART -15yr and Older(M)", - "ref": "HV03-23", - "indicator": "starting_art_males_15_and_older" - }, - { - "label": "Starting ART -15yr and Older(F)", - "ref": "HV03-24", - "indicator": "starting_art_females_15_and_older" - }, - { - "label": "Starting on ART -Total (Sum HV03-21 to HV03-24)", - "ref": "HV03-25", - "indicator": "starting_art_total" - }, - { - "label": "Starting -Pregnant", - "ref": "HV03-26", - "indicator": "Starting_Pregnant" - }, - { - "label": "Starting -TB Patient", - "ref": "HV03-27", - "indicator": "starting_art_and_has_tb" - } - ] - }, - { - "sectionTitle": "3.5 Revisits on ART (from the tally sheet -this month only and from last 2 months)", - "indicators": [ - { - "label": "Revisit on ART -Below 1yr(M)", - "ref": "HV03-28", - "indicator": "revisits_on_art_males_lt_one" - }, - { - "label": "Revisit on ART -Below 1yr(F)", - "ref": "HV03-28", - "indicator": "revisits_on_art_females_lt_one" - }, - { - "label": "Revisit on ART -Below 15yrs(M)", - "ref": "HV03-29", - "indicator": "revisits_on_art_males_below_15" - }, - { - "label": "Revisit on ART -Below 15yrs(F)", - "ref": "HV03-30", - "indicator": "revisits_on_art_females_below_15" - }, - { - "label": "Revisit on ART -15yrs and older(M)", - "ref": "HV03-31", - "indicator": "revisits_on_art_males_15_and_older" - }, - { - "label": "Revisit on ART -15yrs and older(F)", - "ref": "HV03-32", - "indicator": "revisits_on_art_females_15_and_older" - }, - { - "label": "Total Revisit on ART (Sum HV03-29 to HV03-32)", - "ref": "HV03-33", - "indicator": "revisits_on_art_total" - } - ] - }, - { - "sectionTitle": "3.6 Currently on ART [ALL] - (Add 3.4 and 3.5 e.g HV03-34=HV03-20+HV03-28)", - "indicators": [ - { - "label": "Currently on ART - Below 1yr(M)", - "ref": "HV03-34", - "indicator": "on_art_males_lt_one" - }, - { - "label": "Currently on ART - Below 1yr(F)", - "ref": "HV03-34", - "indicator": "on_art_females_lt_one" - }, - { - "label": "Currently on ART - Below 15 yrs(M)", - "ref": "HV03-35", - "indicator": "on_art_males_below_15" - }, - { - "label": "Currently on ART - Below 15 yrs(F)", - "ref": "HV03-36", - "indicator": "on_art_females_below_15" - }, - { - "label": "Currently on ART -15yr and older(M)", - "ref": "HV03-37", - "indicator": "on_art_males_15_and_older" - }, - { - "label": "Currently on ART -15yr and older(F)", - "ref": "HV03-38", - "indicator": "on_art_females_15_and_older" - }, - { - "label": "Total currently on ART (Sum HV03-35 to HV03-38)", - "ref": "HV03-39", - "indicator": "on_art_total" - } - ] - }, - { - "sectionTitle": "3.7 Cumulative Ever on ART", - "indicators": [ - { - "label": "Ever on ART - Below 15yrs(M)", - "ref": "HV03-40", - "indicator": "ever_on_art_males_below_15" - }, - { - "label": "Ever on ART - Below 15yrs(F)", - "ref": "HV03-41", - "indicator": "ever_on_art_females_below_15" - }, - { - "label": "Ever on ART - 15yrs & older(M)", - "ref": "HV03-42", - "indicator": "ever_on_art_males_15_and_older" - }, - { - "label": "Ever on ART - 15yrs & older(F)", - "ref": "HV03-43", - "indicator": "ever_on_art_females_15_and_older" - }, - { - "label": "Total Ever on ART (Sum HV03-40 to HV03-43)", - "ref": "HV03-44", - "indicator": "ever_on_art" - } - ] - }, - { - "sectionTitle": "3.8 Survival and Retention on ART at 12 months", - "indicators": [ - { - "label": "ART Net Cohort at 12 months", - "ref": "HV03-45", - "indicator": "art_net_cohort_at_12_months" - }, - { - "label": "On Original 1st Line at 12 months", - "ref": "HV03-46", - "indicator": "on_original_first_line" - }, - { - "label": "On alternative 1st Line at 12 months", - "ref": "HV03-47", - "indicator": "on_alternative_first_line" - }, - { - "label": "On 2nd Line (or higher) at 12 months", - "ref": "HV03-48", - "indicator": "on_second_line_or_higher" - }, - { - "label": "Total on therapy at 12 months (Sum HV03-46 to HV03-48)", - "ref": "HV03-49", - "indicator": "total_on_therapy_at_12_months" - } - ] - }, - { - "sectionTitle": "3.9 Screening", - "indicators": [ - { - "label": "Screened for TB -Below 15yrs(M)", - "ref": "HV03-50", - "indicator": "screened_for_tb_males_below_15" - }, - { - "label": "Screened for TB -Below 15yrs(F)", - "ref": "HV03-51", - "indicator": "screened_for_tb_females_below_15" - }, - { - "label": "Screened for TB -15yrs & older(M)", - "ref": "HV03-52", - "indicator": "screened_for_tb_males_15_and_older" - }, - { - "label": "Screened for TB -15yrs & older(F)", - "ref": "HV03-53", - "indicator": "screened_for_tb_females_15_and_older" - }, - { - "label": "Total Screened for TB (Sum HV03-50 to HV03-53)", - "ref": "HV03-54", - "indicator": "screened_for_tb" - }, - { - "label": "Screened for cervical cancer (F 18 years and older)", - "ref": "HV03-55", - "indicator": "Screened_for_cervical_cancer" - } - ] - }, - { - "sectionTitle": "3.10 Prevention with Positives", - "indicators": [ - { - "label": "Modern contraceptive methods", - "ref": "HV09-04", - "indicator": "using_modern_contracept_method" - }, - { - "label": "Provided with condoms", - "ref": "HV09-05", - "indicator": "condoms_provided" - } - ] - }, - { - "sectionTitle": "3.11 HIV Care Visits", - "indicators": [ - { - "label": "Females (18 years and older)", - "ref": "HV03-70", - "indicator": "female_gte_18yo_visits" - }, - { - "label": "Scheduled", - "ref": "HV03-71", - "indicator": "scheduled_visits" - }, - { - "label": "Unscheduled", - "ref": "HV03-72", - "indicator": "unscheduled_visits" - }, - { - "label": "Total HIV Care visit", - "ref": "HV03-73", - "indicator": "total_visits" - } - ] - }, - { - "sectionTitle": "5. Post Exposure Prophylaxis", - "indicators": [ - { - "label": "Exposed Occupational", - "ref": "HV05-01", - "indicator": "hiv_exposed_occupational" - }, - { - "label": "Exposed Other", - "ref": "HV05-02", - "indicator": "hiv_exposed_non_occupational" - }, - { - "label": "Exposed Total (Sum HV05-01 and HV05-02)", - "ref": "HV05-03", - "indicator": "total_hiv_exposed" - }, - { - "label": "PEP Occupational", - "ref": "HV05-04", - "indicator": "started_PEP_occupational" - }, - { - "label": "PEP Other", - "ref": "HV05-05", - "indicator": "started_PEP_non_occupational" - }, - { - "label": "PEP Total (Sum HV05-04 and HV05-05)", - "ref": "HV03-06", - "indicator": "total_started_PEP" - } - ] - } + { + "sectionTitle": "3.1 On Cotrimoxazole Prophylaxis (within 2 months)", + "indicators": [ + { + "label": "HIV Exposed Infants (within 2 months)", + "ref": "HV03-01", + "indicator": "hiv_exposed_infants_below_2_months" + }, + { + "label": "HIV Exposed Infant (Eligible for CTX within 2 months)", + "ref": "HV03-02", + "indicator": "hiv_exposed_infants_on_pcp_prophylaxis_2_months_and_below" + }, + { + "label": "On CTX Below 15 yrs(M)", + "ref": "HV03-03", + "indicator": "on_pcp_prophylaxis_males_below_15" + }, + { + "label": "On CTX Below 15 yrs(F)", + "ref": "HV03-04", + "indicator": "on_pcp_prophylaxis_females_below_15" + }, + { + "label": "On CTX 15 yrs and Older(M)", + "ref": "HV03-05", + "indicator": "on_pcp_prophylaxis_males_15_and_above" + }, + { + "label": "On CTX 15 yrs and Older(F)", + "ref": "HV03-06", + "indicator": "on_pcp_prophylaxis_females_15_and_above" + }, + { + "label": "Total on CTX (Sum HV03-03 TO HV03-06)", + "ref": "HV03-07", + "indicator": "on_pcp_prophylaxis" + } + ] + }, + { + "sectionTitle": "3.2 Enrolled in Care", + "indicators": [ + { + "label": "Enrolled in care Below 1yr(M)", + "ref": "HV03-08", + "indicator": "enrolled_in_care_males_lt_one" + }, + { + "label": "Enrolled in care Below 1yr(F)", + "ref": "HV03-08", + "indicator": "enrolled_in_care_females_lt_one" + }, + { + "label": "Enrolled in care Below 15yrs(M)", + "ref": "HV03-09", + "indicator": "enrolled_in_care_males_below_15" + }, + { + "label": "Enrolled in care Below 15yrs(F)", + "ref": "HV03-10", + "indicator": "enrolled_in_care_females_below_15" + }, + { + "label": "Enrolled in care 15yrs & Older(M)", + "ref": "HV03-11", + "indicator": "enrolled_in_care_males_15_and_older" + }, + { + "label": "Enrolled in care 15yrs & Older(F)", + "ref": "HV03-12", + "indicator": "enrolled_in_care_females_15_and_older" + }, + { + "label": "Enrolled in care - Total (Sum HV03-09 to HV03-12)", + "ref": "HV03-13", + "indicator": "enrolled_in_care_total" + } + ] + }, + { + "sectionTitle": "3.3 Currently in Care -(from the total sheet-this month only and from last 2 months)", + "indicators": [ + { + "label": "Currently in care Below 1yr(M)", + "ref": "HV03-14", + "indicator": "currently_in_care_males_lt_one" + }, + { + "label": "Currently in care Below 1yr(F)", + "ref": "HV03-14", + "indicator": "currently_in_care_females_lt_one" + }, + { + "label": "Currently in care Below 15yrs(M)", + "ref": "HV03-15", + "indicator": "currently_in_care_males_below_15" + }, + { + "label": "Currently in care Below 15yrs(F)", + "ref": "HV03-16", + "indicator": "currently_in_care_females_below_15" + }, + { + "label": "Currently in care 15yrs and older(M)", + "ref": "HV03-17", + "indicator": "currently_in_care_males_15_and_older" + }, + { + "label": "Currently in care 15yrs and older(F)", + "ref": "HV03-18", + "indicator": "currently_in_care_females_15_and_older" + }, + { + "label": "Currently in Care-Total (Sum HV03-15 to HV03-18)", + "ref": "HV03-19", + "indicator": "currently_in_care_total" + } + ] + }, + { + "sectionTitle": "3.4 Starting ART", + "indicators": [ + { + "label": "Starting ART -Below 1yr(M)", + "ref": "HV03-20", + "indicator": "starting_art_males_lt_one" + }, + { + "label": "Starting ART -Below 1yr(F)", + "ref": "HV03-20", + "indicator": "starting_art_females_lt_one" + }, + { + "label": "Starting ART -Below 15yrs(M)", + "ref": "HV03-21", + "indicator": "starting_art_males_below_15" + }, + { + "label": "Starting ART -Below 15yrs(F)", + "ref": "HV03-22", + "indicator": "starting_art_females_below_15" + }, + { + "label": "Starting ART -15yr and Older(M)", + "ref": "HV03-23", + "indicator": "starting_art_males_15_and_older" + }, + { + "label": "Starting ART -15yr and Older(F)", + "ref": "HV03-24", + "indicator": "starting_art_females_15_and_older" + }, + { + "label": "Starting on ART -Total (Sum HV03-21 to HV03-24)", + "ref": "HV03-25", + "indicator": "starting_art_total" + }, + { + "label": "Starting -Pregnant", + "ref": "HV03-26", + "indicator": "Starting_Pregnant" + }, + { + "label": "Starting -TB Patient", + "ref": "HV03-27", + "indicator": "starting_art_and_has_tb" + } + ] + }, + { + "sectionTitle": "3.5 Revisits on ART (from the tally sheet -this month only and from last 2 months)", + "indicators": [ + { + "label": "Revisit on ART -Below 1yr(M)", + "ref": "HV03-28", + "indicator": "revisits_on_art_males_lt_one" + }, + { + "label": "Revisit on ART -Below 1yr(F)", + "ref": "HV03-28", + "indicator": "revisits_on_art_females_lt_one" + }, + { + "label": "Revisit on ART -Below 15yrs(M)", + "ref": "HV03-29", + "indicator": "revisits_on_art_males_below_15" + }, + { + "label": "Revisit on ART -Below 15yrs(F)", + "ref": "HV03-30", + "indicator": "revisits_on_art_females_below_15" + }, + { + "label": "Revisit on ART -15yrs and older(M)", + "ref": "HV03-31", + "indicator": "revisits_on_art_males_15_and_older" + }, + { + "label": "Revisit on ART -15yrs and older(F)", + "ref": "HV03-32", + "indicator": "revisits_on_art_females_15_and_older" + }, + { + "label": "Total Revisit on ART (Sum HV03-29 to HV03-32)", + "ref": "HV03-33", + "indicator": "revisits_on_art_total" + } + ] + }, + { + "sectionTitle": "3.6 Currently on ART [ALL] - (Add 3.4 and 3.5 e.g HV03-34=HV03-20+HV03-28)", + "indicators": [ + { + "label": "Currently on ART - Below 1yr(M)", + "ref": "HV03-34", + "indicator": "on_art_males_lt_one" + }, + { + "label": "Currently on ART - Below 1yr(F)", + "ref": "HV03-34", + "indicator": "on_art_females_lt_one" + }, + { + "label": "Currently on ART - Below 15 yrs(M)", + "ref": "HV03-35", + "indicator": "on_art_males_below_15" + }, + { + "label": "Currently on ART - Below 15 yrs(F)", + "ref": "HV03-36", + "indicator": "on_art_females_below_15" + }, + { + "label": "Currently on ART -15yr and older(M)", + "ref": "HV03-37", + "indicator": "on_art_males_15_and_older" + }, + { + "label": "Currently on ART -15yr and older(F)", + "ref": "HV03-38", + "indicator": "on_art_females_15_and_older" + }, + { + "label": "Total currently on ART (Sum HV03-35 to HV03-38)", + "ref": "HV03-39", + "indicator": "on_art_total" + } + ] + }, + { + "sectionTitle": "3.7 Cumulative Ever on ART", + "indicators": [ + { + "label": "Ever on ART - Below 15yrs(M)", + "ref": "HV03-40", + "indicator": "ever_on_art_males_below_15" + }, + { + "label": "Ever on ART - Below 15yrs(F)", + "ref": "HV03-41", + "indicator": "ever_on_art_females_below_15" + }, + { + "label": "Ever on ART - 15yrs & older(M)", + "ref": "HV03-42", + "indicator": "ever_on_art_males_15_and_older" + }, + { + "label": "Ever on ART - 15yrs & older(F)", + "ref": "HV03-43", + "indicator": "ever_on_art_females_15_and_older" + }, + { + "label": "Total Ever on ART (Sum HV03-40 to HV03-43)", + "ref": "HV03-44", + "indicator": "ever_on_art" + } + ] + }, + { + "sectionTitle": "3.8 Survival and Retention on ART at 12 months", + "indicators": [ + { + "label": "ART Net Cohort at 12 months", + "ref": "HV03-45", + "indicator": "art_net_cohort_at_12_months" + }, + { + "label": "On Original 1st Line at 12 months", + "ref": "HV03-46", + "indicator": "on_original_first_line" + }, + { + "label": "On alternative 1st Line at 12 months", + "ref": "HV03-47", + "indicator": "on_alternative_first_line" + }, + { + "label": "On 2nd Line (or higher) at 12 months", + "ref": "HV03-48", + "indicator": "on_second_line_or_higher" + }, + { + "label": "Total on therapy at 12 months (Sum HV03-46 to HV03-48)", + "ref": "HV03-49", + "indicator": "total_on_therapy_at_12_months" + } + ] + }, + { + "sectionTitle": "3.9 Screening", + "indicators": [ + { + "label": "Screened for TB -Below 15yrs(M)", + "ref": "HV03-50", + "indicator": "screened_for_tb_males_below_15" + }, + { + "label": "Screened for TB -Below 15yrs(F)", + "ref": "HV03-51", + "indicator": "screened_for_tb_females_below_15" + }, + { + "label": "Screened for TB -15yrs & older(M)", + "ref": "HV03-52", + "indicator": "screened_for_tb_males_15_and_older" + }, + { + "label": "Screened for TB -15yrs & older(F)", + "ref": "HV03-53", + "indicator": "screened_for_tb_females_15_and_older" + }, + { + "label": "Total Screened for TB (Sum HV03-50 to HV03-53)", + "ref": "HV03-54", + "indicator": "screened_for_tb" + }, + { + "label": "Screened for cervical cancer (F 18 years and older)", + "ref": "HV03-55", + "indicator": "Screened_for_cervical_cancer" + } + ] + }, + { + "sectionTitle": "3.10 Prevention with Positives", + "indicators": [ + { + "label": "Modern contraceptive methods", + "ref": "HV09-04", + "indicator": "using_modern_contracept_method" + }, + { + "label": "Provided with condoms", + "ref": "HV09-05", + "indicator": "condoms_provided" + } + ] + }, + { + "sectionTitle": "3.11 HIV Care Visits", + "indicators": [ + { + "label": "Females (18 years and older)", + "ref": "HV03-70", + "indicator": "female_gte_18yo_visits" + }, + { + "label": "Scheduled", + "ref": "HV03-71", + "indicator": "scheduled_visits" + }, + { + "label": "Unscheduled", + "ref": "HV03-72", + "indicator": "unscheduled_visits" + }, + { + "label": "Total HIV Care visit", + "ref": "HV03-73", + "indicator": "total_visits" + } + ] + }, + { + "sectionTitle": "5. Post Exposure Prophylaxis", + "indicators": [ + { + "label": "Exposed Occupational", + "ref": "HV05-01", + "indicator": "hiv_exposed_occupational" + }, + { + "label": "Exposed Other", + "ref": "HV05-02", + "indicator": "hiv_exposed_non_occupational" + }, + { + "label": "Exposed Total (Sum HV05-01 and HV05-02)", + "ref": "HV05-03", + "indicator": "total_hiv_exposed" + }, + { + "label": "PEP Occupational", + "ref": "HV05-04", + "indicator": "started_PEP_occupational" + }, + { + "label": "PEP Other", + "ref": "HV05-05", + "indicator": "started_PEP_non_occupational" + }, + { + "label": "PEP Total (Sum HV05-04 and HV05-05)", + "ref": "HV03-06", + "indicator": "total_started_PEP" + } + ] + } ] diff --git a/service/moh-731/moh-731.service.js b/service/moh-731/moh-731.service.js index 19b65c592..6a2ddf26a 100755 --- a/service/moh-731/moh-731.service.js +++ b/service/moh-731/moh-731.service.js @@ -1,74 +1,78 @@ const dao = require('../../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); const moh731VlegacSectionDefinitions = require('../../service/moh-731/moh-731-legacy'); const moh731V2017SectionDefinitions = require('../../service/moh-731/moh-731-2017'); export class Moh731Service { + getAggregateReport(reportParams) { + return new Promise(function (resolve, reject) { + reportParams.requestParams.isAggregated === true + ? (reportParams.groupBy = '') + : (reportParams.groupBy = 'groupByLocation'); + Promise.join(dao.runReport(reportParams), (results) => { + // get sect + if (reportParams.reportName === 'MOH-731-report') { + results.sectionDefinitions = moh731VlegacSectionDefinitions; + } else if (reportParams.reportName === 'MOH-731-report-2017') { + results.sectionDefinitions = moh731V2017SectionDefinitions; + } - getAggregateReport(reportParams) { - return new Promise(function (resolve, reject) { - reportParams.requestParams.isAggregated === true ? reportParams.groupBy = '' : - reportParams.groupBy = 'groupByLocation'; - Promise.join(dao.runReport(reportParams), - (results) => { - // get sect - if (reportParams.reportName === 'MOH-731-report') { - results.sectionDefinitions = moh731VlegacSectionDefinitions; - } else if (reportParams.reportName === 'MOH-731-report-2017') { - results.sectionDefinitions = moh731V2017SectionDefinitions; - } + resolve(results); + }).catch((errors) => { + reject(errors); + }); + }); + } - resolve(results); - }).catch((errors) => { - reject(errors); - }); - }); - } - - getPatientListReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - Promise.join(dao.getPatientListReport(reportParams), - self.resolveLocationUuidsToName(reportParams.locationUuids), - (results, locations) => { - if (reportParams.reportName === 'MOH-731-report') { - results.indicators = self.getIndicatorSectionDefinitions(reportParams.indicator, - moh731VlegacSectionDefinitions); - } else if (reportParams.reportName === 'MOH-731-report-2017') { - results.indicators = self.getIndicatorSectionDefinitions(reportParams.indicator, - moh731V2017SectionDefinitions); - } - results.locations = locations; - resolve(results); - }).catch((errors) => { - reject(errors); - }); - }); - } - - resolveLocationUuidsToName(uuids) { - return new Promise(function (resolve, reject) { - // resolve location name - dao.resolveLocationUuidsToName(uuids.split(','), function (loc) { - resolve(loc); - }); - }); - } + getPatientListReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + Promise.join( + dao.getPatientListReport(reportParams), + self.resolveLocationUuidsToName(reportParams.locationUuids), + (results, locations) => { + if (reportParams.reportName === 'MOH-731-report') { + results.indicators = self.getIndicatorSectionDefinitions( + reportParams.indicator, + moh731VlegacSectionDefinitions + ); + } else if (reportParams.reportName === 'MOH-731-report-2017') { + results.indicators = self.getIndicatorSectionDefinitions( + reportParams.indicator, + moh731V2017SectionDefinitions + ); + } + results.locations = locations; + resolve(results); + } + ).catch((errors) => { + reject(errors); + }); + }); + } + resolveLocationUuidsToName(uuids) { + return new Promise(function (resolve, reject) { + // resolve location name + dao.resolveLocationUuidsToName(uuids.split(','), function (loc) { + resolve(loc); + }); + }); + } - getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { - let results = []; - _.each(requestIndicators.split(','), function (requestIndicator) { - _.each(sectionDefinitions, function (sectionDefinition) { - _.each(sectionDefinition.indicators, function (indicator) { - if (indicator.indicator === requestIndicator) { - results.push(indicator); - } - }); - }); + getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { + let results = []; + _.each(requestIndicators.split(','), function (requestIndicator) { + _.each(sectionDefinitions, function (sectionDefinition) { + _.each(sectionDefinition.indicators, function (indicator) { + if (indicator.indicator === requestIndicator) { + results.push(indicator); + } }); - return results; - } + }); + }); + return results; + } } diff --git a/service/monthly-schedule-service.js b/service/monthly-schedule-service.js index 1843eb4dc..18dc45c2b 100755 --- a/service/monthly-schedule-service.js +++ b/service/monthly-schedule-service.js @@ -1,120 +1,135 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report'; -import { - throws -} from 'assert'; +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { throws } from 'assert'; export class MonthlyScheduleService { + getMonthlyScheduled(reportParams) { + //let attendedParams = Object.assign(reportParams, { reportName: 'attended' }); + // let scheduledParams = Object.assign(reportParams, { reportName: 'scheduled' }); + let self = this; + return new Promise(function (resolve, reject) { + Promise.join( + self.getAttended(reportParams), + self.getScheduled(reportParams), + self.getHasNotReturned(reportParams), + (attended, scheduled, hasNotReturned) => { + let attendedResponse = self.buildAttendedResponse( + attended.results.results + ); + let scheduledResponse = self.buildScheduledResponse( + scheduled.results.results + ); + let hasNotReturnedResponse = self.buildHasnoReturnedResponse( + hasNotReturned.results.results + ); + let combinedResponse = attendedResponse + .concat(scheduledResponse) + .concat(hasNotReturnedResponse); + let grouped = _.groupBy(combinedResponse, (row) => { + return row.date; + }); + let results = _.chain(combinedResponse) + .groupBy('date') + .map(function (v, i) { + return { + date: i, + count: _.map(v, 'count').reduce(function (acc, x) { + for (let key in x) acc[key] = x[key]; + return acc; + }, {}) + }; + }) + .value(); + resolve({ + reports: { + attended: attended, + scheduled: scheduled, + hasNotReturned: hasNotReturned + }, + results: results + }); + } + ).catch((errors) => { + reject(errors); + }); + }); + } - getMonthlyScheduled(reportParams) { - //let attendedParams = Object.assign(reportParams, { reportName: 'attended' }); - // let scheduledParams = Object.assign(reportParams, { reportName: 'scheduled' }); - let self = this; - return new Promise(function (resolve, reject) { - Promise.join(self.getAttended(reportParams), self.getScheduled(reportParams), self.getHasNotReturned(reportParams), - (attended, scheduled, hasNotReturned) => { - let attendedResponse = self.buildAttendedResponse(attended.results.results); - let scheduledResponse = self.buildScheduledResponse(scheduled.results.results); - let hasNotReturnedResponse = self.buildHasnoReturnedResponse(hasNotReturned.results.results); - let combinedResponse = attendedResponse.concat(scheduledResponse).concat(hasNotReturnedResponse); - let grouped = _.groupBy(combinedResponse, (row) => { - return row.date; - }); - let results = _.chain(combinedResponse).groupBy("date").map(function (v, i) { - return { - date: i, - count: _.map(v, 'count').reduce(function (acc, x) { - for (let key in x) acc[key] = x[key]; - return acc; - }, {}) - } - }).value(); - resolve({ - reports:{ - attended: attended, - scheduled: scheduled, - hasNotReturned: hasNotReturned - }, - results: results - }); - }).catch((errors) => { - reject(errors); - }); - }); - } - - getAttended(reportParams) { - let report = new BaseMysqlReport('dailyAttendanceAggregate', reportParams); - return report.generateReport(); - } - - getScheduled(reportParams) { - let report = new BaseMysqlReport('dailyAppointmentsAggregate', reportParams); - return report.generateReport(); - } + getAttended(reportParams) { + let report = new BaseMysqlReport('dailyAttendanceAggregate', reportParams); + return report.generateReport(); + } - getHasNotReturned(reportParams) { - let report = new BaseMysqlReport('dailyHasNotReturnedAggregate', reportParams); - return report.generateReport(); - } + getScheduled(reportParams) { + let report = new BaseMysqlReport( + 'dailyAppointmentsAggregate', + reportParams + ); + return report.generateReport(); + } - buildAttendedResponse(payload) { - try { - let data = payload.map(function (row) { + getHasNotReturned(reportParams) { + let report = new BaseMysqlReport( + 'dailyHasNotReturnedAggregate', + reportParams + ); + return report.generateReport(); + } - let utc = Moment.utc(row.attended_date).utcOffset(+3).toDate(); - return { - count: { - attended: row.attended, - }, - date: Moment(utc).local().format('YYYY-MM-DD') - } - }); - return data; - } catch (error) { - console.error(error); - throw error; - } + buildAttendedResponse(payload) { + try { + let data = payload.map(function (row) { + let utc = Moment.utc(row.attended_date) + .utcOffset(+3) + .toDate(); + return { + count: { + attended: row.attended + }, + date: Moment(utc).local().format('YYYY-MM-DD') + }; + }); + return data; + } catch (error) { + console.error(error); + throw error; } + } - buildScheduledResponse(payload) { - try { - let data = payload.map(function (row) { - return { - count: { - scheduled: row.scheduled - }, - date: row.scheduled_date - } - }); - return data; - } catch (error) { - console.error(error); - throw error; - } + buildScheduledResponse(payload) { + try { + let data = payload.map(function (row) { + return { + count: { + scheduled: row.scheduled + }, + date: row.scheduled_date + }; + }); + return data; + } catch (error) { + console.error(error); + throw error; } + } - buildHasnoReturnedResponse(payload) { - try { - - let data = payload.map(function (row) { - return { - count: { - has_not_returned: row.has_not_returned - }, - date: row.d - } - }); - return data; - - } catch (error) { - console.error(error); - throw error; - } + buildHasnoReturnedResponse(payload) { + try { + let data = payload.map(function (row) { + return { + count: { + has_not_returned: row.has_not_returned + }, + date: row.d + }; + }); + return data; + } catch (error) { + console.error(error); + throw error; } -} \ No newline at end of file + } +} diff --git a/service/notes.service.js b/service/notes.service.js index 752ca1f90..7007a12e9 100755 --- a/service/notes.service.js +++ b/service/notes.service.js @@ -1,374 +1,394 @@ -(function() { - 'use strict'; - - var dao = require('../etl-dao'); - var _ = require('underscore'); - var moment = require('moment'); - var utils = require('./utils.js'); - var math = require('math'); - - var DEFAULT_NO_NOTES = 40; - var TB_PROPHY_PERIOD = 6; // In months. - var CONCEPT_UUIDS = { - CUR_TB_TX_DETAILED: 'a8afdb8c-1350-11df-a1f1-0026b9348838', - CUR_TB_TX: 'a899e444-1350-11df-a1f1-0026b9348838', - TB_TX_DRUG_STARTED_DETAILED: 'a89fe6f0-1350-11df-a1f1-0026b9348838', - TB_TX_PLAN: 'a89c1fd4-1350-11df-a1f1-0026b9348838', - CC_HPI: 'a89ffbf4-1350-11df-a1f1-0026b9348838', - ASSESSMENT: '23f710cc-7f9c-4255-9b6b-c3e240215dba', - TB_PROPHY_PLAN: 'a89c1cfa-1350-11df-a1f1-0026b9348838', - OTHER_ASSESSMENT: '5e4dc798-2cce-4a1a-97e9-bcf22d64b07c' - }; - - var encOrder = { - 2: 1, // ADULTRETURN - 1: 10, // ADULTINITIAL - 4: 1, // PEDSRETURN - 3: 10, // PEDSINITIAL - 110: 20, // TRIAGE - 99999: 30, // Special Lab encounter code - 21: 40, // OUTREACHFIELDFU - 17: 50, // ECSTABLE - 117: 1, // RESISTANCECLINIC - other: 100 // Any other encounter - }; - - var generateNotes = function(encounters, hivSummaries, vitals, endDate) { - - // Make endDate today if not specified - if (endDate) { - if (typeof endDate === 'string') { - try { - endDate = Date.parse(endDate); - } catch (error) { - console.log(error); - } - } - } else { - endDate = moment(); +(function () { + 'use strict'; + + var dao = require('../etl-dao'); + var _ = require('underscore'); + var moment = require('moment'); + var utils = require('./utils.js'); + var math = require('math'); + + var DEFAULT_NO_NOTES = 40; + var TB_PROPHY_PERIOD = 6; // In months. + var CONCEPT_UUIDS = { + CUR_TB_TX_DETAILED: 'a8afdb8c-1350-11df-a1f1-0026b9348838', + CUR_TB_TX: 'a899e444-1350-11df-a1f1-0026b9348838', + TB_TX_DRUG_STARTED_DETAILED: 'a89fe6f0-1350-11df-a1f1-0026b9348838', + TB_TX_PLAN: 'a89c1fd4-1350-11df-a1f1-0026b9348838', + CC_HPI: 'a89ffbf4-1350-11df-a1f1-0026b9348838', + ASSESSMENT: '23f710cc-7f9c-4255-9b6b-c3e240215dba', + TB_PROPHY_PLAN: 'a89c1cfa-1350-11df-a1f1-0026b9348838', + OTHER_ASSESSMENT: '5e4dc798-2cce-4a1a-97e9-bcf22d64b07c' + }; + + var encOrder = { + 2: 1, // ADULTRETURN + 1: 10, // ADULTINITIAL + 4: 1, // PEDSRETURN + 3: 10, // PEDSINITIAL + 110: 20, // TRIAGE + 99999: 30, // Special Lab encounter code + 21: 40, // OUTREACHFIELDFU + 17: 50, // ECSTABLE + 117: 1, // RESISTANCECLINIC + other: 100 // Any other encounter + }; + + var generateNotes = function (encounters, hivSummaries, vitals, endDate) { + // Make endDate today if not specified + if (endDate) { + if (typeof endDate === 'string') { + try { + endDate = Date.parse(endDate); + } catch (error) { + console.log(error); } + } + } else { + endDate = moment(); + } - // Set startIndex to 0 if not passed - var startIndex = startIndex || 0; - - // Limit to DEFAULT_NO_NOTES notes if not specified - // (i.e DEFAULT_NO_NOTES encounters going backward) - var limit = limit || DEFAULT_NO_NOTES; - - if (!hivSummaries || _.isEmpty(hivSummaries)) { - throw new Error('No summaries returned'); + // Set startIndex to 0 if not passed + var startIndex = startIndex || 0; + + // Limit to DEFAULT_NO_NOTES notes if not specified + // (i.e DEFAULT_NO_NOTES encounters going backward) + var limit = limit || DEFAULT_NO_NOTES; + + if (!hivSummaries || _.isEmpty(hivSummaries)) { + throw new Error('No summaries returned'); + } else { + // TODO: Need to determine whether it is wise to fail if others are + // not available as well. + var hivModels = hivSummaries; + + // Group the summaries based on date + var summaryDateGrouped = {}; + _.each(hivModels, function (model) { + var key = moment(model.encounter_datetime).format('MMM_DD_YYYY'); + model.ordering = encOrder[model.encounter_type] || encOrder.other; + if (Array.isArray(summaryDateGrouped[key])) { + summaryDateGrouped[key].push(model); } else { - // TODO: Need to determine whether it is wise to fail if others are - // not available as well. - var hivModels = hivSummaries; - - // Group the summaries based on date - var summaryDateGrouped = {}; - _.each(hivModels, function(model) { - var key = moment(model.encounter_datetime).format('MMM_DD_YYYY'); - model.ordering = encOrder[model.encounter_type] || encOrder.other; - if (Array.isArray(summaryDateGrouped[key])) { - summaryDateGrouped[key].push(model); - } else { - summaryDateGrouped[key] = [model]; - } - }); - - // Sort the groups according to ordering column - _.each(summaryDateGrouped, function(group) { - group.sort(function compare(x, y) { - return x.ordering - y.ordering; - }); - }); - - // Now pick the most preferred encounter in every group. - var massagedHivModels = _.map(summaryDateGrouped, function(group) { - return _.first(group); - }); - - // Deal with vitals. - var vitalDateGrouped = {}; - if (vitals && !_.isEmpty(vitals)) { - var vitalModels = vitals; - - // Create a date grouped representation - - _.each(vitalModels, function(model) { - var key = moment(model.encounter_datetime).format('MMM_DD_YYYY'); - vitalDateGrouped[key] = model; - }); - } - - // Deal with encounters - var encDateGrouped = {}; - if (encounters && !_.isEmpty(encounters)) { - // Group encounters by date - _.each(encounters, function(encounter) { - var key = moment(encounter.encounterDatetime).format('MMM_DD_YYYY'); - if (Array.isArray(encDateGrouped[key])) { - encDateGrouped[key].push(encounter); - } else { - encDateGrouped[key] = [encounter]; - } - }); - } - - // Generate notes for each Hiv summary date. - var notes = []; - for (var dateKey in summaryDateGrouped) { - var note = generateNote(_.first(summaryDateGrouped[dateKey]), - vitalDateGrouped[dateKey], encDateGrouped[dateKey]); - notes.push(note); - } - return notes; + summaryDateGrouped[key] = [model]; } - } - - /** - * This method will try to generate note for available data, i.e it won't - * fail because one of the expected data object is null - */ - function generateNote(hivSummary, vitals, encounters) { - - var noInfo = ''; - var note = { - visitDate: hivSummary.encounter_datetime, - scheduled: hivSummary.scheduled_visit, - providers: [], - lastViralLoad: { - value: hivSummary.vl_1, - date: hivSummary.vl_1_date, - }, - lastCD4Count: { - value: hivSummary.cd4_1, - date: hivSummary.cd4_1_date - }, - artRegimen: { - curArvMeds: noInfo, - curArvLine: noInfo, - startDate: noInfo - }, - tbProphylaxisPlan: { - plan: noInfo, - startDate: noInfo, - estimatedEndDate: noInfo - }, - ccHpi: [], - assessment: [], - otherAssessment: [], - vitals: { - weight: noInfo, - height: noInfo, - bmi: noInfo, - temperature: noInfo, - oxygenSaturation: noInfo, - systolicBp: noInfo, - diastolicBp: noInfo, - pulse: noInfo - }, - rtcDate: hivSummary.rtc_date - }; + }); - if (vitals && !_.isEmpty(vitals)) { - // Calculate BMI - var bmi = noInfo; - try { - bmi = math.round(utils.calculateBMI(vitals.weight, vitals.height), 1); - } catch (err) { - // Do nothing - } - - note.vitals = { - weight: vitals.weight, - height: vitals.height, - bmi: bmi, - temperature: vitals.temp, - oxygenSaturation: vitals.oxygen_sat, - systolicBp: vitals.systolic_bp || '', - diastolicBp: vitals.diastolic_bp || '', - pulse: vitals.pulse - }; - } + // Sort the groups according to ordering column + _.each(summaryDateGrouped, function (group) { + group.sort(function compare(x, y) { + return x.ordering - y.ordering; + }); + }); - //Get the providers & regimens - if (Array.isArray(encounters) && !_.isEmpty(encounters)) { - note.providers = _getProviders(encounters); - - // Get CC/HPI & Assessment - note.ccHpi = _findTextObsValue(encounters, CONCEPT_UUIDS.CC_HPI, - __findObsWithGivenConcept); - - // Sort ccHpi per obsDatetime - note.ccHpi.sort(function(ccHpi1, ccHpi2) { - return ccHpi1 ? moment(ccHpi1.obsDatetime).diff(ccHpi2.obsDatetime) : null; - }); - - note.assessment = _findTextObsValue(encounters, CONCEPT_UUIDS.ASSESSMENT, - __findObsWithGivenConcept); - - // Sort assessment - note.assessment.sort(function(ass1, ass2) { - return moment(ass1.obsDatetime).diff(ass2.obsDatetime); - }); - note.otherAssessment = _findTextObsValue(encounters, CONCEPT_UUIDS.OTHER_ASSESSMENT, - __findObsWithGivenConcept); - // Sort assessment - note.otherAssessment.sort(function(ass1, ass2) { - return moment(ass1.obsDatetime).diff(ass2.obsDatetime); - }); - - // Get TB prophylaxis - note.tbProphylaxisPlan = _constructTBProphylaxisPlan(encounters, hivSummary, - __findObsWithGivenConcept); - } else { - console.log('encounters array is null or empty'); - } + // Now pick the most preferred encounter in every group. + var massagedHivModels = _.map(summaryDateGrouped, function (group) { + return _.first(group); + }); - // Get ART regimen - if (!_.isEmpty(hivSummary.cur_arv_meds)) { - // Just use the stuff from Etl - note.artRegimen = { - curArvMeds: hivSummary.cur_arv_meds, - curArvLine: hivSummary.cur_arv_line, - arvStartDate: hivSummary.arv_start_date - }; - } else { - // TODO: Try getting it from encounters. - } + // Deal with vitals. + var vitalDateGrouped = {}; + if (vitals && !_.isEmpty(vitals)) { + var vitalModels = vitals; - return note; - } + // Create a date grouped representation - function _getProviders(openmrsEncounters) { - var providers = []; - _.each(openmrsEncounters, function(encModel) { - var encounterType = encModel.encounterType || {}; - if (encModel.encounterProviders) { - var multipleProviderPerEncounter = - __getProvidersFromEncounterProviders(encModel.encounterProviders, - encounterType); - Array.prototype.push.apply(providers, multipleProviderPerEncounter); - } else { - // most likely defined as provider - var providerObject = encModel.provider || {}; // Staying on safe - var provider = { - uuid: providerObject.uuid || '', - name: providerObject.display || '', - encounterType: encounterType.display || '' - }; - if (providerObject.person) { - provider.name = providerObject.person.display || provider.name; - } - providers.push(provider); - } + _.each(vitalModels, function (model) { + var key = moment(model.encounter_datetime).format('MMM_DD_YYYY'); + vitalDateGrouped[key] = model; }); - - return _.uniq(providers, false, function(provider) { - return provider.uuid + provider.encounterType; + } + + // Deal with encounters + var encDateGrouped = {}; + if (encounters && !_.isEmpty(encounters)) { + // Group encounters by date + _.each(encounters, function (encounter) { + var key = moment(encounter.encounterDatetime).format('MMM_DD_YYYY'); + if (Array.isArray(encDateGrouped[key])) { + encDateGrouped[key].push(encounter); + } else { + encDateGrouped[key] = [encounter]; + } }); + } + + // Generate notes for each Hiv summary date. + var notes = []; + for (var dateKey in summaryDateGrouped) { + var note = generateNote( + _.first(summaryDateGrouped[dateKey]), + vitalDateGrouped[dateKey], + encDateGrouped[dateKey] + ); + notes.push(note); + } + return notes; + } + }; + + /** + * This method will try to generate note for available data, i.e it won't + * fail because one of the expected data object is null + */ + function generateNote(hivSummary, vitals, encounters) { + var noInfo = ''; + var note = { + visitDate: hivSummary.encounter_datetime, + scheduled: hivSummary.scheduled_visit, + providers: [], + lastViralLoad: { + value: hivSummary.vl_1, + date: hivSummary.vl_1_date + }, + lastCD4Count: { + value: hivSummary.cd4_1, + date: hivSummary.cd4_1_date + }, + artRegimen: { + curArvMeds: noInfo, + curArvLine: noInfo, + startDate: noInfo + }, + tbProphylaxisPlan: { + plan: noInfo, + startDate: noInfo, + estimatedEndDate: noInfo + }, + ccHpi: [], + assessment: [], + otherAssessment: [], + vitals: { + weight: noInfo, + height: noInfo, + bmi: noInfo, + temperature: noInfo, + oxygenSaturation: noInfo, + systolicBp: noInfo, + diastolicBp: noInfo, + pulse: noInfo + }, + rtcDate: hivSummary.rtc_date + }; - // ****This function is defined within _getProviders function - function __getProvidersFromEncounterProviders(encProviders, encType) { - var _providers = []; - _.each(encProviders, function(encProvider) { - var provider = encProvider.provider; - var providerRep = { - uuid: provider.uuid || '', - name: provider.display || '', - encounterType: encType.display || '' - }; - if (provider.person) { - //Update provider name - providerRep.name = provider.person.display || providerRep.name; - } - _providers.push(providerRep); - }); - return _providers; - } + if (vitals && !_.isEmpty(vitals)) { + // Calculate BMI + var bmi = noInfo; + try { + bmi = math.round(utils.calculateBMI(vitals.weight, vitals.height), 1); + } catch (err) { + // Do nothing + } + + note.vitals = { + weight: vitals.weight, + height: vitals.height, + bmi: bmi, + temperature: vitals.temp, + oxygenSaturation: vitals.oxygen_sat, + systolicBp: vitals.systolic_bp || '', + diastolicBp: vitals.diastolic_bp || '', + pulse: vitals.pulse + }; } - /* - * TODO: Make this recursive to be able to search deeper than one level - */ - function __findObsWithGivenConcept(obsArray, conceptUuid, grouper) { - var grouper = grouper || false; - var found = null; - if (grouper) { - found = []; - _.each(obsArray, function(obs) { - if (obs.groupMembers !== null && obs.concept !== null && obs.concept.uuid === conceptUuid) { - found.push(obs); - } - }); - } else { - // Non grouper concepts - found = _.find(obsArray, function(obs) { - return (obs.concept !== null && obs.concept.uuid === conceptUuid); - }); - } - return found; + //Get the providers & regimens + if (Array.isArray(encounters) && !_.isEmpty(encounters)) { + note.providers = _getProviders(encounters); + + // Get CC/HPI & Assessment + note.ccHpi = _findTextObsValue( + encounters, + CONCEPT_UUIDS.CC_HPI, + __findObsWithGivenConcept + ); + + // Sort ccHpi per obsDatetime + note.ccHpi.sort(function (ccHpi1, ccHpi2) { + return ccHpi1 + ? moment(ccHpi1.obsDatetime).diff(ccHpi2.obsDatetime) + : null; + }); + + note.assessment = _findTextObsValue( + encounters, + CONCEPT_UUIDS.ASSESSMENT, + __findObsWithGivenConcept + ); + + // Sort assessment + note.assessment.sort(function (ass1, ass2) { + return moment(ass1.obsDatetime).diff(ass2.obsDatetime); + }); + note.otherAssessment = _findTextObsValue( + encounters, + CONCEPT_UUIDS.OTHER_ASSESSMENT, + __findObsWithGivenConcept + ); + // Sort assessment + note.otherAssessment.sort(function (ass1, ass2) { + return moment(ass1.obsDatetime).diff(ass2.obsDatetime); + }); + + // Get TB prophylaxis + note.tbProphylaxisPlan = _constructTBProphylaxisPlan( + encounters, + hivSummary, + __findObsWithGivenConcept + ); + } else { + console.log('encounters array is null or empty'); } - function _findTextObsValue(encArray, conceptUuid, obsfinder) { - var values = []; - - _.each(encArray, function(enc) { - var ret = obsfinder(enc.obs, conceptUuid); - if (ret !== null && !_.isEmpty(ret)) { - var value = { - obsDatetime: ret.obsDatetime || enc.encounterDatetime, - encounterType: enc.encounterType.display || '', - value: ret.value - }; - values.push(value); - } - }); - return values; + // Get ART regimen + if (!_.isEmpty(hivSummary.cur_arv_meds)) { + // Just use the stuff from Etl + note.artRegimen = { + curArvMeds: hivSummary.cur_arv_meds, + curArvLine: hivSummary.cur_arv_line, + arvStartDate: hivSummary.arv_start_date + }; + } else { + // TODO: Try getting it from encounters. } - /** - * Algorithm: - * -> Check for existence of tb prophylaxis plan, if found and plan is - * continue or start then report and fetch start date. - * -> if plan is stop then see calculate the duration the patient was on - * prophylaxis and fetch reason if available. - * -> if it is to change the fetch the reasone. - */ - function _constructTBProphylaxisPlan(encArray, hivSummary, obsfinder) { - // Find plan. - var tbProphy = { - plan: 'Not available', - estimatedEndDate: 'Unknown', + return note; + } + + function _getProviders(openmrsEncounters) { + var providers = []; + _.each(openmrsEncounters, function (encModel) { + var encounterType = encModel.encounterType || {}; + if (encModel.encounterProviders) { + var multipleProviderPerEncounter = __getProvidersFromEncounterProviders( + encModel.encounterProviders, + encounterType + ); + Array.prototype.push.apply(providers, multipleProviderPerEncounter); + } else { + // most likely defined as provider + var providerObject = encModel.provider || {}; // Staying on safe + var provider = { + uuid: providerObject.uuid || '', + name: providerObject.display || '', + encounterType: encounterType.display || '' }; - var planConceptUuid = CONCEPT_UUIDS.TB_PROPHY_PLAN; - var found = null; + if (providerObject.person) { + provider.name = providerObject.person.display || provider.name; + } + providers.push(provider); + } + }); + + return _.uniq(providers, false, function (provider) { + return provider.uuid + provider.encounterType; + }); + + // ****This function is defined within _getProviders function + function __getProvidersFromEncounterProviders(encProviders, encType) { + var _providers = []; + _.each(encProviders, function (encProvider) { + var provider = encProvider.provider; + var providerRep = { + uuid: provider.uuid || '', + name: provider.display || '', + encounterType: encType.display || '' + }; + if (provider.person) { + //Update provider name + providerRep.name = provider.person.display || providerRep.name; + } + _providers.push(providerRep); + }); + return _providers; + } + } + + /* + * TODO: Make this recursive to be able to search deeper than one level + */ + function __findObsWithGivenConcept(obsArray, conceptUuid, grouper) { + var grouper = grouper || false; + var found = null; + if (grouper) { + found = []; + _.each(obsArray, function (obs) { + if ( + obs.groupMembers !== null && + obs.concept !== null && + obs.concept.uuid === conceptUuid + ) { + found.push(obs); + } + }); + } else { + // Non grouper concepts + found = _.find(obsArray, function (obs) { + return obs.concept !== null && obs.concept.uuid === conceptUuid; + }); + } + return found; + } + + function _findTextObsValue(encArray, conceptUuid, obsfinder) { + var values = []; + + _.each(encArray, function (enc) { + var ret = obsfinder(enc.obs, conceptUuid); + if (ret !== null && !_.isEmpty(ret)) { + var value = { + obsDatetime: ret.obsDatetime || enc.encounterDatetime, + encounterType: enc.encounterType.display || '', + value: ret.value + }; + values.push(value); + } + }); + return values; + } + + /** + * Algorithm: + * -> Check for existence of tb prophylaxis plan, if found and plan is + * continue or start then report and fetch start date. + * -> if plan is stop then see calculate the duration the patient was on + * prophylaxis and fetch reason if available. + * -> if it is to change the fetch the reasone. + */ + function _constructTBProphylaxisPlan(encArray, hivSummary, obsfinder) { + // Find plan. + var tbProphy = { + plan: 'Not available', + estimatedEndDate: 'Unknown' + }; + var planConceptUuid = CONCEPT_UUIDS.TB_PROPHY_PLAN; + var found = null; - _.find(encArray, function(enc) { - found = obsfinder(enc.obs, planConceptUuid); - return found !== null && !_.isEmpty(found); - }); + _.find(encArray, function (enc) { + found = obsfinder(enc.obs, planConceptUuid); + return found !== null && !_.isEmpty(found); + }); - if (found) { - tbProphy.plan = found.value.display; - } + if (found) { + tbProphy.plan = found.value.display; + } - // Calculate estimated end date of plan (6 months after starting) - var tempDate = moment(hivSummary.tb_prophylaxis_start_date); - if (tempDate.isValid()) { - tbProphy.startDate = hivSummary.tb_prophylaxis_start_date; - tbProphy.estimatedEndDate = - moment(hivSummary.tb_prophylaxis_start_date) - .add(TB_PROPHY_PERIOD, 'months') - .toDate().toISOString(); - } else { - tbProphy.startDate = 'Not available'; - tbProphy.estimatedEndDate = 'N/A'; - } - return tbProphy; + // Calculate estimated end date of plan (6 months after starting) + var tempDate = moment(hivSummary.tb_prophylaxis_start_date); + if (tempDate.isValid()) { + tbProphy.startDate = hivSummary.tb_prophylaxis_start_date; + tbProphy.estimatedEndDate = moment(hivSummary.tb_prophylaxis_start_date) + .add(TB_PROPHY_PERIOD, 'months') + .toDate() + .toISOString(); + } else { + tbProphy.startDate = 'Not available'; + tbProphy.estimatedEndDate = 'N/A'; } + return tbProphy; + } - module.exports = { - generateNote: generateNote, - generateNotes: generateNotes - }; + module.exports = { + generateNote: generateNote, + generateNotes: generateNotes + }; })(); diff --git a/service/oncology/patient-oncology-summary-service.js b/service/oncology/patient-oncology-summary-service.js index 9846dd172..13e2468d2 100644 --- a/service/oncology/patient-oncology-summary-service.js +++ b/service/oncology/patient-oncology-summary-service.js @@ -1,15 +1,15 @@ -var db = require("../../etl-db"); +var db = require('../../etl-db'); function getOncMeds(request, medsFormat, encounterId) { let queryParts = {}; var patientUuid = request.uuid; var programUuid = request.programUuid; - if (medsFormat === "summary") { + if (medsFormat === 'summary') { queryParts = { - columns: "t1.value_coded", - table: "amrs.obs", + columns: 't1.value_coded', + table: 'amrs.obs', where: [ - "t2.uuid = ? and t1.concept_id in ? and t1.encounter_id = ? and t1.voided = ?", + 't2.uuid = ? and t1.concept_id in ? and t1.encounter_id = ? and t1.voided = ?', patientUuid, [9918], encounterId, @@ -17,21 +17,21 @@ function getOncMeds(request, medsFormat, encounterId) { ], order: [ { - column: "t1.obs_group_id", + column: 't1.obs_group_id', asc: false } ], - joins: [["amrs.person", "t2", "t2.person_id=t1.person_id"]], + joins: [['amrs.person', 't2', 't2.person_id=t1.person_id']], offset: request.startIndex, limit: request.limit }; } else { queryParts = { columns: - "t1.concept_id, t1.value_coded, t1.value_numeric, t1.obs_group_id, t1.encounter_id, t1.obs_datetime", - table: "amrs.obs", + 't1.concept_id, t1.value_coded, t1.value_numeric, t1.obs_group_id, t1.encounter_id, t1.obs_datetime', + table: 'amrs.obs', where: [ - "t2.uuid = ? and t5.programuuid = ? and t1.concept_id in ? and t1.voided = ?", + 't2.uuid = ? and t5.programuuid = ? and t1.concept_id in ? and t1.voided = ?', patientUuid, programUuid, [9918, 8723, 1896, 7463, 1899, 9869], @@ -39,17 +39,17 @@ function getOncMeds(request, medsFormat, encounterId) { ], order: [ { - column: "t1.obs_group_id", + column: 't1.obs_group_id', asc: false } ], joins: [ - ["amrs.person", "t2", "t2.person_id = t1.person_id"], - ["amrs.patient_program", "t3", "t3.patient_id ``= t2.person_id"] + ['amrs.person', 't2', 't2.person_id = t1.person_id'], + ['amrs.patient_program', 't3', 't3.patient_id ``= t2.person_id'] ], leftOuterJoins: [ [ - "(SELECT program_id, uuid as `programuuid` FROM amrs.program ) `t5` ON (t3.program_id = t5.program_id)" + '(SELECT program_id, uuid as `programuuid` FROM amrs.program ) `t5` ON (t3.program_id = t5.program_id)' ] ], offset: request.startIndex, @@ -61,7 +61,7 @@ function getOncMeds(request, medsFormat, encounterId) { function generateMedsDataSet(data) { let meds = []; - const groupBy = key => array => + const groupBy = (key) => (array) => array.reduce((objectsByKeyValue, obj) => { const value = obj[key]; objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj); @@ -69,15 +69,15 @@ function generateMedsDataSet(data) { }, {}); //Group medical history obs by the group if (data) { - const groupByEncounter = groupBy("encounter_id"); + const groupByEncounter = groupBy('encounter_id'); const encounterData = groupByEncounter(data); - _.each(encounterData, function(concepts) { + _.each(encounterData, function (concepts) { let oncMeds = {}; - const i = groupBy("obs_group_id"); - oncMeds.treatment_plan = _.filter(concepts, function(o) { + const i = groupBy('obs_group_id'); + oncMeds.treatment_plan = _.filter(concepts, function (o) { return o.concept_id === 9869; }); - _.remove(concepts, function(e) { + _.remove(concepts, function (e) { return e.obs_group_id == null; }); let drug; @@ -94,16 +94,16 @@ function generateMedsDataSet(data) { function getPatientOncologyDiagnosis(request) { let patientUuid = request.uuid; let queryParts = { - columns: "cancer_type, cancer_subtype, diagnosis_date", + columns: 'cancer_type, cancer_subtype, diagnosis_date', order: [ { - column: "encounter_id", + column: 'encounter_id', asc: false } ], - joins: [["amrs.person", "t2", "t2.person_id = t1.person_id"]], - table: "etl.flat_onc_patient_history", - where: ["t2.uuid = ?", patientUuid], + joins: [['amrs.person', 't2', 't2.person_id = t1.person_id']], + table: 'etl.flat_onc_patient_history', + where: ['t2.uuid = ?', patientUuid], offset: request.startIndex, limit: request.limit }; @@ -118,25 +118,25 @@ function getOncologyIntegratedProgramSnapshot(request) { "t1.encounter_id, t1.encounter_datetime, t6.encounter_type_name, REPLACE(t3.name, 'Oncology ', '') AS `visit_name`, t5.name AS location, t6.breast_exam_findings, t6.via_test_result, t6.hiv_status, t6.prior_via_test_result, t6.prior_via_test_result_date", order: [ { - column: "encounter_datetime", + column: 'encounter_datetime', asc: false } ], - group: ["t1.visit_id"], + group: ['t1.visit_id'], joins: [ - ["amrs.visit", "t2", "t2.visit_id = t1.visit_id"], - ["amrs.visit_type", "t3", "t3.visit_type_id = t2.visit_type_id"], - ["amrs.person", "t4", "t4.person_id = t1.patient_id"], - ["amrs.location", "t5", "t5.location_id = t1.location_id"], + ['amrs.visit', 't2', 't2.visit_id = t1.visit_id'], + ['amrs.visit_type', 't3', 't3.visit_type_id = t2.visit_type_id'], + ['amrs.person', 't4', 't4.person_id = t1.patient_id'], + ['amrs.location', 't5', 't5.location_id = t1.location_id'], [ - "etl.flat_onc_patient_history", - "t6", - "t6.encounter_id = t1.encounter_id" + 'etl.flat_onc_patient_history', + 't6', + 't6.encounter_id = t1.encounter_id' ] ], - table: "amrs.encounter", + table: 'amrs.encounter', where: [ - "t4.uuid = ? and t2.visit_type_id in ? and t1.voided = ?", + 't4.uuid = ? and t2.visit_type_id in ? and t1.voided = ?', patientUuid, [5, 6, 70, 72, 71], 0 diff --git a/service/openmrs-rest/encounter.js b/service/openmrs-rest/encounter.js index f762147a5..8e42da08c 100755 --- a/service/openmrs-rest/encounter.js +++ b/service/openmrs-rest/encounter.js @@ -1,67 +1,82 @@ -(function(){ +(function () { var rp = require('request-promise'); var _ = require('underscore'); var Promise = require('bluebird'); - var config = require("../../conf/config"); + var config = require('../../conf/config'); var requestConfig = require('../../request-config'); - - var openmrsProtocal = config.openmrs.https? 'https': 'http'; + + var openmrsProtocal = config.openmrs.https ? 'https' : 'http'; var appName = config.openmrs.applicationName || 'amrs'; - var openmrsBase = openmrsProtocal + '://' + config.openmrs.host + ':' - + config.openmrs.port + '/' + appName; - + var openmrsBase = + openmrsProtocal + + '://' + + config.openmrs.host + + ':' + + config.openmrs.port + + '/' + + appName; + function getPatientEncounters(params) { - if(_.isUndefined(params)) { + if (_.isUndefined(params)) { throw new Error('At least one argument should be passed'); } - - var _customDefaultRep = 'custom:(uuid,encounterDatetime,' + + + var _customDefaultRep = + 'custom:(uuid,encounterDatetime,' + 'patient:(uuid,uuid),form:(uuid,name),location:ref,encounterType:ref,' + 'encounterProviders:(provider:full,encounterRole:ref),' + 'obs:(uuid,obsDatetime,concept:(uuid,name:(uuid,name)),value:ref,' + 'groupMembers:(uuid,concept:(uuid,name:(uuid,name)),obsDatetime,value:ref)))'; - - var endpoint = '/ws/rest/v1/encounter'; - - // Create request param object - var reqParams = {} - + + var endpoint = '/ws/rest/v1/encounter'; + + // Create request param object + var reqParams = {}; + if (!_.isUndefined(params) && typeof params === 'string') { - var patientUuid = params; - reqParams = { - patient: patientUuid, - v: _customDefaultRep, - openmrsBaseUrl: openmrsBase - }; + var patientUuid = params; + reqParams = { + patient: patientUuid, + v: _customDefaultRep, + openmrsBaseUrl: openmrsBase + }; } else { - if(_.isObject(params) && !_.isFunction(params) && !_.isArray(params)) { + if (_.isObject(params) && !_.isFunction(params) && !_.isArray(params)) { var v = params.rep || params.v; reqParams = { - patient: params.patientUuid, - v: v || _customDefaultRep, - openmrsBaseUrl: params.openmrsBaseUrl || openmrsBase + patient: params.patientUuid, + v: v || _customDefaultRep, + openmrsBaseUrl: params.openmrsBaseUrl || openmrsBase }; } else { // Invalid object type passed - throw new Error('Error! function requires a string uuid or a '+ - 'parameter map passed, passed ' + params); - } - } - - return new Promise(function(resolve, reject){ - requestConfig.getRequestPromise({ - patient: reqParams.patient, - v: reqParams.v - }, reqParams.openmrsBaseUrl + endpoint) - .then(function(data) { - resolve(data.results); - }).catch(function(err) { - reject(err); - }); + throw new Error( + 'Error! function requires a string uuid or a ' + + 'parameter map passed, passed ' + + params + ); + } + } + + return new Promise(function (resolve, reject) { + requestConfig + .getRequestPromise( + { + patient: reqParams.patient, + v: reqParams.v + }, + reqParams.openmrsBaseUrl + endpoint + ) + .then(function (data) { + resolve(data.results); + }) + .catch(function (err) { + reject(err); + }); }); } - + module.exports = { getPatientEncounters: getPatientEncounters - } -})(); + }; +})(); diff --git a/service/openmrs-rest/obs.service.js b/service/openmrs-rest/obs.service.js index a270aea94..d2f64b5ae 100755 --- a/service/openmrs-rest/obs.service.js +++ b/service/openmrs-rest/obs.service.js @@ -1,7 +1,7 @@ /*jshint -W003, -W097, -W117, -W026 */ 'use strict'; var Promise = require('bluebird'); -var encounterService = require('../../service/openmrs-rest/encounter.js') +var encounterService = require('../../service/openmrs-rest/encounter.js'); var db = require('../../etl-db'); var _ = require('underscore'); var reportFactory = require('../../etl-factory'); @@ -14,14 +14,20 @@ var rp = require('../../request-config'); var config = require('../../conf/config'); var moment = require('moment'); var eidRestFormatter = require('../../eid-rest-formatter'); -module.exports = function () { +module.exports = (function () { function getRestResource(path) { - var protocol = config.openmrs.https ? 'https' :'http'; - var link = protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + path; + var protocol = config.openmrs.https ? 'https' : 'http'; + var link = + protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + path; return link; } function getPatientIdentifiers(patientUuId) { - var uri = getRestResource('/' + config.openmrs.applicationName + '/ws/rest/v1/patient/' + patientUuId); + var uri = getRestResource( + '/' + + config.openmrs.applicationName + + '/ws/rest/v1/patient/' + + patientUuId + ); var queryString = { v: 'full' }; @@ -37,20 +43,23 @@ module.exports = function () { .then(function (response) { var patientIdentifiers = { identifiers: [] - } + }; _.each(response.identifiers, function (identifier) { //exclude Old AMPATH Medical Record Number identifierType // if (identifier.identifierType.uuid != "58a46a32-1359-11df-a1f1-0026b9348838") { - patientIdentifiers.identifiers.push(identifier.identifier); - var hasALetterRegEx = /[a-z]/i; - if (hasALetterRegEx.test(identifier.identifier)) { - var indexOfFirstLetter = identifier.identifier.match(/[a-z]/i).index; - var identifierWithSpace = identifier.identifier.substr(0, indexOfFirstLetter) + - ' ' + identifier.identifier.substr(indexOfFirstLetter); - patientIdentifiers.identifiers.push(identifierWithSpace); - } + patientIdentifiers.identifiers.push(identifier.identifier); + var hasALetterRegEx = /[a-z]/i; + if (hasALetterRegEx.test(identifier.identifier)) { + var indexOfFirstLetter = identifier.identifier.match(/[a-z]/i) + .index; + var identifierWithSpace = + identifier.identifier.substr(0, indexOfFirstLetter) + + ' ' + + identifier.identifier.substr(indexOfFirstLetter); + patientIdentifiers.identifiers.push(identifierWithSpace); + } // } - }) + }); resolve(patientIdentifiers); }) .catch(function (error) { @@ -61,12 +70,14 @@ module.exports = function () { } function getPatientTestObsByConceptUuId(conceptUuId, patientUuId) { var patientObs = []; - var uri = getRestResource('/' + config.openmrs.applicationName + '/ws/rest/v1/obs'); + var uri = getRestResource( + '/' + config.openmrs.applicationName + '/ws/rest/v1/obs' + ); var queryString = { patient: patientUuId, concept: conceptUuId, v: 'full' - } + }; return new Promise(function (resolve, reject) { rp.getRequestPromise(queryString, uri) .then(function (response) { @@ -77,23 +88,27 @@ module.exports = function () { }) .catch(function (error) { reject(error); - }) - }) + }); + }); } function getAmrsPatientObsByDate(conceptUuId, patientUuId) { var todaysDate = moment(new Date()).format('YYYY-MM-DD'); var patientObs = []; - var uri = getRestResource('/' + config.openmrs.applicationName + '/ws/rest/v1/obs'); + var uri = getRestResource( + '/' + config.openmrs.applicationName + '/ws/rest/v1/obs' + ); var queryString = { patient: patientUuId, concept: conceptUuId, v: 'full' - } + }; return new Promise(function (resolve, reject) { rp.getRequestPromise(queryString, uri) .then(function (response) { _.each(response.results, function (data) { - var obsDateCreated = moment(new Date(data.auditInfo.dateCreated)).format('YYYY-MM-DD'); + var obsDateCreated = moment( + new Date(data.auditInfo.dateCreated) + ).format('YYYY-MM-DD'); if (obsDateCreated == todaysDate) { patientObs.push(data); } @@ -102,59 +117,66 @@ module.exports = function () { }) .catch(function (error) { reject(error); - console.error("error getAmrsPatientObsByDate++++++++++++++++++++++++++++++++++++++", error); - }) - }) + console.error( + 'error getAmrsPatientObsByDate++++++++++++++++++++++++++++++++++++++', + error + ); + }); + }); } function getPatientAllTestObsByPatientUuId(patientUuId) { var allPatientObs = { obs: [] - } + }; var labConcepts = { concepts: [ - { "conceptId": 657, "uuid": "a896cce6-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 9238, "uuid": "457c741d-8f71-4829-b59d-594e0a618892" }, - { "conceptId": 1238, "uuid": "a89b5856-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 856, "uuid": "a8982474-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 1030, "uuid": "a898fe80-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 730, "uuid": "a8970a26-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 5497, "uuid": "a8a8bb18-1350-11df-a1f1-0026b9348838" } + { conceptId: 657, uuid: 'a896cce6-1350-11df-a1f1-0026b9348838' }, + { conceptId: 9238, uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, + { conceptId: 1238, uuid: 'a89b5856-1350-11df-a1f1-0026b9348838' }, + { conceptId: 856, uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + { conceptId: 1030, uuid: 'a898fe80-1350-11df-a1f1-0026b9348838' }, + { conceptId: 730, uuid: 'a8970a26-1350-11df-a1f1-0026b9348838' }, + { conceptId: 5497, uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838' } ] - } + }; var promiseArray = []; return new Promise(function (resolve, reject) { _.each(labConcepts.concepts, function (testObject) { var labConceptUuId = testObject.uuid; - var result = getPatientTestObsByConceptUuId(labConceptUuId, patientUuId); + var result = getPatientTestObsByConceptUuId( + labConceptUuId, + patientUuId + ); promiseArray.push(result); }); - Promise.all(promiseArray).then(function (response) { - var concatenatedArray = [].concat.apply([], response); - resolve(concatenatedArray); - }) + Promise.all(promiseArray) + .then(function (response) { + var concatenatedArray = [].concat.apply([], response); + resolve(concatenatedArray); + }) .catch(function (error) { reject(error); - }) + }); }); } function getPatientTodaysTestObsByPatientUuId(patientUuId) { var allPatientObs = { obs: [] - } + }; var labConcepts = { concepts: [ - { "conceptId": 657, "uuid": "a896cce6-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 9238, "uuid": "457c741d-8f71-4829-b59d-594e0a618892" }, - { "conceptId": 1238, "uuid": "a89b5856-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 856, "uuid": "a8982474-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 1030, "uuid": "a898fe80-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 730, "uuid": "a8970a26-1350-11df-a1f1-0026b9348838" }, - { "conceptId": 5497, "uuid": "a8a8bb18-1350-11df-a1f1-0026b9348838" } + { conceptId: 657, uuid: 'a896cce6-1350-11df-a1f1-0026b9348838' }, + { conceptId: 9238, uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, + { conceptId: 1238, uuid: 'a89b5856-1350-11df-a1f1-0026b9348838' }, + { conceptId: 856, uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + { conceptId: 1030, uuid: 'a898fe80-1350-11df-a1f1-0026b9348838' }, + { conceptId: 730, uuid: 'a8970a26-1350-11df-a1f1-0026b9348838' }, + { conceptId: 5497, uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838' } ] - } + }; var promiseArray = []; return new Promise(function (resolve, reject) { _.each(labConcepts.concepts, function (testObject) { @@ -163,17 +185,20 @@ module.exports = function () { promiseArray.push(result); }); - Promise.all(promiseArray).then(function (response) { - var concatenatedArray = [].concat.apply([], response); - resolve(concatenatedArray); - }) + Promise.all(promiseArray) + .then(function (response) { + var concatenatedArray = [].concat.apply([], response); + resolve(concatenatedArray); + }) .catch(function (error) { reject(error); - }) + }); }); } function postObsToAMRS(payload, patientUuId) { - var uri = getRestResource('/' + config.openmrs.applicationName + '/ws/rest/v1/obs'); + var uri = getRestResource( + '/' + config.openmrs.applicationName + '/ws/rest/v1/obs' + ); return new Promise(function (resolve, reject) { rp.postRequestPromise(payload, uri) .then(function (response) { @@ -181,7 +206,7 @@ module.exports = function () { }) .catch(function (error) { reject(error); - }) + }); }); } function postAllObsToAMRS(payload, patientUuId) { @@ -195,18 +220,29 @@ module.exports = function () { if (viralLoadPayload != undefined) { var valid = eidRestFormatter.checkStatusOfViralLoad(viralLoadPayload); if (valid == 1) { - promisesViralLoadlAll.push(generateAndPostLabObsPayload(viralLoadPayload, - patientUuId, eidRestFormatter.convertViralLoadPayloadToRestConsumableObs)); - - } - else if (valid == 0) { - promisesViralLoadlAll.push(generateAndPostLabObsPayload(viralLoadPayload, - patientUuId, eidRestFormatter.convertViralLoadWithLessThanToRestConsumableObs)); - - } - else if (valid == 2) { - promisesViralLoadlAll.push(generateAndPostLabObsPayload(viralLoadPayload, - patientUuId, eidRestFormatter.convertViralLoadExceptionToRestConsumableObs)); + promisesViralLoadlAll.push( + generateAndPostLabObsPayload( + viralLoadPayload, + patientUuId, + eidRestFormatter.convertViralLoadPayloadToRestConsumableObs + ) + ); + } else if (valid == 0) { + promisesViralLoadlAll.push( + generateAndPostLabObsPayload( + viralLoadPayload, + patientUuId, + eidRestFormatter.convertViralLoadWithLessThanToRestConsumableObs + ) + ); + } else if (valid == 2) { + promisesViralLoadlAll.push( + generateAndPostLabObsPayload( + viralLoadPayload, + patientUuId, + eidRestFormatter.convertViralLoadExceptionToRestConsumableObs + ) + ); } } }); @@ -214,17 +250,33 @@ module.exports = function () { if (payload.cd4Panel.length > 0) { _.each(payload.cd4Panel, function (cd4Payload) { if (cd4Payload != undefined) { - var cd4PanelHasValidData = eidRestFormatter.cd4PanelHasValidData(cd4Payload); - var cd4PanelHasErrors = eidRestFormatter.cd4PanelHasErrors(cd4Payload); + var cd4PanelHasValidData = eidRestFormatter.cd4PanelHasValidData( + cd4Payload + ); + var cd4PanelHasErrors = eidRestFormatter.cd4PanelHasErrors( + cd4Payload + ); if (cd4PanelHasValidData) { var cd4Data = eidRestFormatter.generateCd4ValidData(cd4Payload); - promisesCd4All.push(generateAndPostLabObsPayload(cd4Data, - patientUuId, eidRestFormatter.convertCD4PayloadTORestConsumableObs)); + promisesCd4All.push( + generateAndPostLabObsPayload( + cd4Data, + patientUuId, + eidRestFormatter.convertCD4PayloadTORestConsumableObs + ) + ); } if (cd4PanelHasErrors) { - var cd4Exceptions = eidRestFormatter.generateCd4Exceptions(cd4Payload); - promisesCd4All.push(generateAndPostLabObsPayload(cd4Exceptions, - patientUuId, eidRestFormatter.convertCD4ExceptionTORestConsumableObs)); + var cd4Exceptions = eidRestFormatter.generateCd4Exceptions( + cd4Payload + ); + promisesCd4All.push( + generateAndPostLabObsPayload( + cd4Exceptions, + patientUuId, + eidRestFormatter.convertCD4ExceptionTORestConsumableObs + ) + ); } } }); @@ -233,8 +285,11 @@ module.exports = function () { _.each(payload.pcr, function (pcrPayload) { if (pcrPayload != undefined) { promisesDnaPcrAll.push( - generateAndPostLabObsPayload(pcrPayload, - patientUuId, eidRestFormatter.convertDNAPCRPayloadTORestConsumableObs) + generateAndPostLabObsPayload( + pcrPayload, + patientUuId, + eidRestFormatter.convertDNAPCRPayloadTORestConsumableObs + ) ); } }); @@ -242,7 +297,7 @@ module.exports = function () { return new Promise(function (resolve, reject) { Promise.all(promisesViralLoadlAll, promisesCd4All, promisesDnaPcrAll) .then(function (response) { - resolve(response) + resolve(response); }) .catch(function (error) { reject(error); @@ -264,7 +319,7 @@ module.exports = function () { }) .catch(function (error) { reject(error); - }) + }); }); } @@ -277,5 +332,5 @@ module.exports = function () { postObsToAMRS: postObsToAMRS, getAmrsPatientObsByDate: getAmrsPatientObsByDate, getPatientTodaysTestObsByPatientUuId: getPatientTodaysTestObsByPatientUuId - } -} (); + }; +})(); diff --git a/service/openmrs-rest/patient.service.js b/service/openmrs-rest/patient.service.js index 97c0bbf23..08b2d12f9 100755 --- a/service/openmrs-rest/patient.service.js +++ b/service/openmrs-rest/patient.service.js @@ -1,113 +1,122 @@ (function () { - var rp = require('request-promise'); - var _ = require('underscore'); - var Promise = require('bluebird'); - var config = require("../../conf/config"); - var requestConfig = require('../../request-config'); - - var openmrsProtocal = config.openmrs.https ? 'https' : 'http'; - var appName = config.openmrs.applicationName || 'amrs'; - var openmrsBase = openmrsProtocal + '://' + config.openmrs.host + ':' - + config.openmrs.port + '/' + appName; - - var serviceDefinition = { - getPatientByUuid: getPatientByUuid, - getPatientByIdentifier: getPatientByIdentifier, - getPatientUuidsByIdentifiers: getPatientUuidsByIdentifiers + var rp = require('request-promise'); + var _ = require('underscore'); + var Promise = require('bluebird'); + var config = require('../../conf/config'); + var requestConfig = require('../../request-config'); + + var openmrsProtocal = config.openmrs.https ? 'https' : 'http'; + var appName = config.openmrs.applicationName || 'amrs'; + var openmrsBase = + openmrsProtocal + + '://' + + config.openmrs.host + + ':' + + config.openmrs.port + + '/' + + appName; + + var serviceDefinition = { + getPatientByUuid: getPatientByUuid, + getPatientByIdentifier: getPatientByIdentifier, + getPatientUuidsByIdentifiers: getPatientUuidsByIdentifiers + }; + + function getPatientByUuid(patientUuid, params) { + var endPoint = '/ws/rest/v1/patient/' + patientUuid; + + var requestParam = { + v: params.rep || 'default' }; - function getPatientByUuid(patientUuid, params) { - var endPoint = '/ws/rest/v1/patient/' + patientUuid; - - var requestParam = { - v: params.rep || 'default' - }; - - var url = (params.openmrsBaseUrl || openmrsBase) + endPoint; + var url = (params.openmrsBaseUrl || openmrsBase) + endPoint; - return new Promise(function (resolve, reject) { - requestConfig.getRequestPromise(requestParam, url) - .then(function (data) { - resolve(data); - }) - .catch(function (err) { - reject(err); - }); + return new Promise(function (resolve, reject) { + requestConfig + .getRequestPromise(requestParam, url) + .then(function (data) { + resolve(data); + }) + .catch(function (err) { + reject(err); }); + }); + } - } - - function getPatientByIdentifier(params) { - var endPoint = '/ws/rest/v1/patient'; + function getPatientByIdentifier(params) { + var endPoint = '/ws/rest/v1/patient'; - var requestParam = { - q: params.q, - v: params.rep || 'default' - }; + var requestParam = { + q: params.q, + v: params.rep || 'default' + }; - var url = (params.openmrsBaseUrl || openmrsBase) + endPoint; + var url = (params.openmrsBaseUrl || openmrsBase) + endPoint; + return new Promise(function (resolve, reject) { + requestConfig + .getRequestPromise(requestParam, url) + .then(function (data) { + resolve(data.results); + }) + .catch(function (err) { + reject(err); + }); + }); + } + + function getPatientUuidsByIdentifiers(identifiersArray, baseUrl) { + var results = []; + return Promise.reduce( + identifiersArray, + function (previous, identifier) { return new Promise(function (resolve, reject) { - requestConfig.getRequestPromise(requestParam, url) - .then(function (data) { - resolve(data.results); - }) - .catch(function (err) { - reject(err); - }); + _getPatientUuidByIdentifier(identifier, baseUrl) + .then(function (value) { + console.error( + identifier + ' ' + value.patientUuid + ' reduced to', + results.length + ); + if (value.patientUuid) { + results.push(value); + } + resolve(results); + }) + .catch(function (error) { + resolve(results); + }); }); - } - - function getPatientUuidsByIdentifiers(identifiersArray, baseUrl) { - var results = []; - return Promise.reduce(identifiersArray, function (previous, identifier) { - return new Promise(function (resolve, reject) { - _getPatientUuidByIdentifier(identifier, baseUrl) - .then(function (value) { - console.error(identifier + ' ' + value.patientUuid + ' reduced to', results.length); - if(value.patientUuid){ - results.push(value); - } - resolve(results); - }) - .catch(function (error) { - resolve(results); - }); + }, + 0 + ); + } + + function _getPatientUuidByIdentifier(identifier, baseUrl) { + var param = { + q: identifier, + openmrsBaseUrl: baseUrl + }; + return new Promise(function (resolve, reject) { + getPatientByIdentifier(param) + .then(function (response) { + if (Array.isArray(response)) { + resolve({ + identifier: identifier, + patientUuid: response.length > 0 ? response[0].uuid : '' }); - }, 0); - } - - - function _getPatientUuidByIdentifier(identifier, baseUrl) { - var param = { - q: identifier, - openmrsBaseUrl: baseUrl - }; - return new Promise(function (resolve, reject) { - getPatientByIdentifier(param) - .then(function (response) { - if (Array.isArray(response)) { - resolve( - { - identifier: identifier, - patientUuid: response.length > 0 ? response[0].uuid : '' - } - ); - } else { - throw ('Invalid response', response); - } - }) - .catch(function (error) { - console.error('getPatientByIdentifier error', error); - resolve({ - identifier: identifier, - hasError: true - }); - }); - + } else { + throw ('Invalid response', response); + } + }) + .catch(function (error) { + console.error('getPatientByIdentifier error', error); + resolve({ + identifier: identifier, + hasError: true + }); }); - } + }); + } - module.exports = serviceDefinition; + module.exports = serviceDefinition; })(); - diff --git a/service/openmrs-rest/program.service.js b/service/openmrs-rest/program.service.js index 9a029c20e..762c3fc16 100755 --- a/service/openmrs-rest/program.service.js +++ b/service/openmrs-rest/program.service.js @@ -1,59 +1,68 @@ var rp = require('request-promise'); var _ = require('underscore'); var Promise = require('bluebird'); -var config = require("../../conf/config"); +var config = require('../../conf/config'); var requestConfig = require('../../request-config'); var openmrsProtocal = config.openmrs.https ? 'https' : 'http'; var appName = config.openmrs.applicationName || 'amrs'; -var openmrsBase = openmrsProtocal + '://' + config.openmrs.host + ':' + config.openmrs.port + '/' + appName; +var openmrsBase = + openmrsProtocal + + '://' + + config.openmrs.host + + ':' + + config.openmrs.port + + '/' + + appName; var serviceDefinition = { - getProgramEnrollmentByUuid: getProgramEnrollmentByUuid, - getProgramEnrollmentByPatientUuid: getProgramEnrollmentByPatientUuid + getProgramEnrollmentByUuid: getProgramEnrollmentByUuid, + getProgramEnrollmentByPatientUuid: getProgramEnrollmentByPatientUuid }; module.exports = serviceDefinition; function getProgramEnrollmentByUuid(enrollmentUuid, params) { - var endPoint = '/ws/rest/v1/programenrollment/' + enrollmentUuid; + var endPoint = '/ws/rest/v1/programenrollment/' + enrollmentUuid; - var requestParam = { - v: params.rep || undefined - }; + var requestParam = { + v: params.rep || undefined + }; - var url = (params.openmrsBaseUrl || openmrsBase) + endPoint; - - return new Promise(function (resolve, reject) { - requestConfig.getRequestPromise(requestParam, url) - .then(function (data) { - resolve(data); - }) - .catch(function (err) { - reject(err); - }); - }); + var url = (params.openmrsBaseUrl || openmrsBase) + endPoint; + return new Promise(function (resolve, reject) { + requestConfig + .getRequestPromise(requestParam, url) + .then(function (data) { + resolve(data); + }) + .catch(function (err) { + reject(err); + }); + }); } function getProgramEnrollmentByPatientUuid(patientUuid, params) { - var endPoint = '/ws/rest/v1/programenrollment'; - var v = 'custom:(uuid,display,voided,dateEnrolled,dateCompleted,program:(uuid))'; - - var requestParam = { - v: v, - patient: patientUuid - }; - - var url = (params.openmrsBaseUrl || openmrsBase) + endPoint; - - return new Promise(function (resolve, reject) { - requestConfig.getRequestPromise(requestParam, url) - .then(function (data) { - resolve(data); - }) - .catch(function (err) { - reject(err); - }); - }); + var endPoint = '/ws/rest/v1/programenrollment'; + var v = + 'custom:(uuid,display,voided,dateEnrolled,dateCompleted,program:(uuid))'; + + var requestParam = { + v: v, + patient: patientUuid + }; + + var url = (params.openmrsBaseUrl || openmrsBase) + endPoint; + + return new Promise(function (resolve, reject) { + requestConfig + .getRequestPromise(requestParam, url) + .then(function (data) { + resolve(data); + }) + .catch(function (err) { + reject(err); + }); + }); } diff --git a/service/patient-care-cascade-report.service.js b/service/patient-care-cascade-report.service.js index 3e5580ea4..aa63ec247 100755 --- a/service/patient-care-cascade-report.service.js +++ b/service/patient-care-cascade-report.service.js @@ -1,31 +1,28 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); export class patientCareCascadeService { - - getAggregateReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - Promise.join(dao.runReport(reportParams), - (results) => { - resolve(results); - //TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - }); - } - getPatientListReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - //TODO: Do some pre processing - Promise.join(dao.getPatientListReport(reportParams), - (results) => { - resolve(results); - }).catch((errors) => { - reject(errors); - }); - }); - } -} \ No newline at end of file + getAggregateReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + Promise.join(dao.runReport(reportParams), (results) => { + resolve(results); + //TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + }); + } + getPatientListReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + //TODO: Do some pre processing + Promise.join(dao.getPatientListReport(reportParams), (results) => { + resolve(results); + }).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/patient-gain-loses.service.js b/service/patient-gain-loses.service.js index d48439457..8d340ca8e 100644 --- a/service/patient-gain-loses.service.js +++ b/service/patient-gain-loses.service.js @@ -1,23 +1,25 @@ -import { BaseMysqlReport } from "../app/reporting-framework/base-mysql.report"; -import { PatientlistMysqlReport } from "../app/reporting-framework/patientlist-mysql.report"; +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; -const _ = require("lodash"); -const Promise = require("bluebird"); +const _ = require('lodash'); +const Promise = require('bluebird'); const helpers = require('../etl-helpers'); export class PatientGainLosesService { - getAggregateReport(reportParams) { return new Promise((resolve, reject) => { - let report = new BaseMysqlReport("patientGainLoseAggregate", reportParams.requestParams); + let report = new BaseMysqlReport( + 'patientGainLoseAggregate', + reportParams.requestParams + ); - Promise.join(report.generateReport(), results => { + Promise.join(report.generateReport(), (results) => { let result = results.results.results; results.size = result ? result.length : 0; results.result = result; - delete results["results"]; + delete results['results']; resolve(results); - }).catch(errors => { + }).catch((errors) => { reject(errors); }); }); @@ -25,30 +27,31 @@ export class PatientGainLosesService { getPatientListReport(reportParams) { let indicators = reportParams.indicators - ? reportParams.indicators.split(",") + ? reportParams.indicators.split(',') : []; let report = new PatientlistMysqlReport( - "patientGainLoseAggregate", + 'patientGainLoseAggregate', reportParams ); return new Promise(function (resolve, reject) { - Promise.join(report.generatePatientListReport(indicators), - (results) => { - results.results.results.forEach((element) => { - if (element.cur_meds) { - element.cur_meds = helpers.getARVNames(element.cur_meds); - } - if (element.arv_first_regimen) { - element.arv_first_regimen = helpers.getARVNames(element.arv_first_regimen); - } - }) - resolve(results); - }).catch((errors) => { - console.error('Error', errors); - reject(errors); + Promise.join(report.generatePatientListReport(indicators), (results) => { + results.results.results.forEach((element) => { + if (element.cur_meds) { + element.cur_meds = helpers.getARVNames(element.cur_meds); + } + if (element.arv_first_regimen) { + element.arv_first_regimen = helpers.getARVNames( + element.arv_first_regimen + ); + } }); + resolve(results); + }).catch((errors) => { + console.error('Error', errors); + reject(errors); + }); }); } } diff --git a/service/patient-list-compare.service.js b/service/patient-list-compare.service.js index 6e08396ad..326893e5c 100755 --- a/service/patient-list-compare.service.js +++ b/service/patient-list-compare.service.js @@ -1,178 +1,183 @@ 'use strict'; var _ = require('underscore'); -var - Promise = require('bluebird'); +var Promise = require('bluebird'); var db = require('../etl-db'); var serviceDef = { - fullPatientListComparison: fullPatientListComparison, - comparePatientLists: comparePatientLists, - generateComparisonStats: generateComparisonStats, - getAllResultsForHandler: getAllResultsForHandler, - fetchAndCompareList: fetchAndCompareList, - resolvePersonIds: resolvePersonIds, - toArrayOfPatientObjects: toArrayOfPatientObjects + fullPatientListComparison: fullPatientListComparison, + comparePatientLists: comparePatientLists, + generateComparisonStats: generateComparisonStats, + getAllResultsForHandler: getAllResultsForHandler, + fetchAndCompareList: fetchAndCompareList, + resolvePersonIds: resolvePersonIds, + toArrayOfPatientObjects: toArrayOfPatientObjects }; module.exports = serviceDef; function fetchAndCompareList(patientList, requestObject, handler) { - if (typeof patientList[0] === 'number' || - typeof patientList[0] === 'string') { - patientList = toArrayOfPatientObjects(patientList); - } - return new Promise(function (resolve, reject) { - getAllResultsForHandler(requestObject, handler) - .then(function (response) { - var compared = fullPatientListComparison(patientList, response.result); - - if (compared.summaryStats.totalIncoming !== 0) - compared.summaryStats.pocIncomingRatio = (compared.summaryStats.totalPoc / compared.summaryStats.totalIncoming); - - if (compared.onlyIncoming.length > 0) { - resolvePersonIds(_getPersonids(compared.onlyIncoming)) - .then(function (results) { - compared.onlyIncoming = results.result; - resolve(compared); - }) - .catch(function (error) { - console.error('Error resolving patient_ids', error); - resolve(compared); - }); - } else { - resolve(compared); - } + if ( + typeof patientList[0] === 'number' || + typeof patientList[0] === 'string' + ) { + patientList = toArrayOfPatientObjects(patientList); + } + return new Promise(function (resolve, reject) { + getAllResultsForHandler(requestObject, handler) + .then(function (response) { + var compared = fullPatientListComparison(patientList, response.result); + + if (compared.summaryStats.totalIncoming !== 0) + compared.summaryStats.pocIncomingRatio = + compared.summaryStats.totalPoc / + compared.summaryStats.totalIncoming; + + if (compared.onlyIncoming.length > 0) { + resolvePersonIds(_getPersonids(compared.onlyIncoming)) + .then(function (results) { + compared.onlyIncoming = results.result; + resolve(compared); }) .catch(function (error) { - reject(error); + console.error('Error resolving patient_ids', error); + resolve(compared); }); - }); + } else { + resolve(compared); + } + }) + .catch(function (error) { + reject(error); + }); + }); } function fullPatientListComparison(incoming, poc) { - var comparison = comparePatientLists(incoming, poc); - generateComparisonStats(comparison, incoming, poc); - return comparison; + var comparison = comparePatientLists(incoming, poc); + generateComparisonStats(comparison, incoming, poc); + return comparison; } function comparePatientLists(incoming, poc) { - var comparison = { - both: [], - onlyPoc: [], - onlyIncoming: [] - }; - - for (var i = 0; i < incoming.length; i++) { - var inItem = incoming[i]; - var foundPoc = null; - for (var j = 0; j < poc.length; j++) { - if (inItem.person_id === poc[j].person_id) { - foundPoc = poc[j]; - break; - } - } - - if (foundPoc !== null) { - comparison.both.push(foundPoc); - } else { - comparison.onlyIncoming.push(inItem); - } + var comparison = { + both: [], + onlyPoc: [], + onlyIncoming: [] + }; + + for (var i = 0; i < incoming.length; i++) { + var inItem = incoming[i]; + var foundPoc = null; + for (var j = 0; j < poc.length; j++) { + if (inItem.person_id === poc[j].person_id) { + foundPoc = poc[j]; + break; + } } - for (var i = 0; i < poc.length; i++) { - var pocItem = poc[i]; - var foundIncoming = null; - for (var j = 0; j < incoming.length; j++) { - if (pocItem.person_id === incoming[j].person_id) { - foundIncoming = poc[j]; - break; - } - } + if (foundPoc !== null) { + comparison.both.push(foundPoc); + } else { + comparison.onlyIncoming.push(inItem); + } + } + + for (var i = 0; i < poc.length; i++) { + var pocItem = poc[i]; + var foundIncoming = null; + for (var j = 0; j < incoming.length; j++) { + if (pocItem.person_id === incoming[j].person_id) { + foundIncoming = poc[j]; + break; + } + } - if (foundIncoming === null) { - comparison.onlyPoc.push(pocItem); - } + if (foundIncoming === null) { + comparison.onlyPoc.push(pocItem); } + } - return comparison; + return comparison; } function generateComparisonStats(comparisonResults, incoming, poc) { - comparisonResults.summaryStats = {}; - comparisonResults.summaryStats.totalPoc = poc.length; - comparisonResults.summaryStats.totalIncoming = incoming.length; - comparisonResults.summaryStats.totalBoth = comparisonResults.both.length; - comparisonResults.summaryStats.totalOnlyPoc = comparisonResults.onlyPoc.length; - comparisonResults.summaryStats.totalOnlyIncoming = comparisonResults.onlyIncoming.length; + comparisonResults.summaryStats = {}; + comparisonResults.summaryStats.totalPoc = poc.length; + comparisonResults.summaryStats.totalIncoming = incoming.length; + comparisonResults.summaryStats.totalBoth = comparisonResults.both.length; + comparisonResults.summaryStats.totalOnlyPoc = + comparisonResults.onlyPoc.length; + comparisonResults.summaryStats.totalOnlyIncoming = + comparisonResults.onlyIncoming.length; } function getAllResultsForHandler(requestObject, handler) { - requestObject.query.startIndex = 0; - requestObject.query.limit = 1000000; - - return new Promise(function (resolve, reject) { - handler(requestObject, function (results) { - // TODO: check for error on the returned results - resolve(results); - }); + requestObject.query.startIndex = 0; + requestObject.query.limit = 1000000; + + return new Promise(function (resolve, reject) { + handler(requestObject, function (results) { + // TODO: check for error on the returned results + resolve(results); }); + }); } function _getPersonids(patientList) { - var patients = []; - _.each(patientList, function (patient) { - patients.push(patient.person_id); - }); - return patients; + var patients = []; + _.each(patientList, function (patient) { + patients.push(patient.person_id); + }); + return patients; } function toArrayOfPatientObjects(patientsIdArray) { - var patientObjects = []; - - _.each(patientsIdArray, function (id) { - patientObjects.push({ - person_id: id - }); + var patientObjects = []; + _.each(patientsIdArray, function (id) { + patientObjects.push({ + person_id: id }); - return patientObjects; + }); + return patientObjects; } function resolvePersonIds(personIdsArray) { - var list = ''; - - if (Array.isArray(personIdsArray)) { - list = JSON.stringify(personIdsArray); - } else { - list = personIdsArray; - } - - list = list.replace('[', "").replace(']', ""); - - var sql = "select t1.person_id, t1.uuid as patient_uuid, t4.patient_id, t1.gender," + - " t1.birthdate, extract(year from (from_days(datediff(now(), t1.birthdate)))) as age," + - "concat(COALESCE(t2.given_name,''),' ',COALESCE(t2.middle_name,''),' ',COALESCE(t2.family_name,''))" + - "as person_name, group_concat(distinct t3.identifier separator ', ') as identifiers FROM amrs.person `t1`" + - "INNER JOIN amrs.person_name `t2` ON (t1.person_id = t2.person_id and (t2.voided is null || t2.voided = 0))" + - "LEFT OUTER JOIN amrs.patient `t4` ON (t1.person_id = t4.patient_id)" + - "LEFT OUTER JOIN amrs.patient_identifier `t3` ON (t1.person_id = t3.patient_id)" + - "WHERE t1.person_id in (?) GROUP BY t1.person_id"; - - sql = sql.replace('?', list); - - var queryObject = { - query: sql, - sqlParams: [] - } - - return new Promise(function (resolve, reject) { - db.queryReportServer(queryObject, function (response) { - if (response.error) { - reject(response); - } else { - resolve(response); - } - }); + var list = ''; + + if (Array.isArray(personIdsArray)) { + list = JSON.stringify(personIdsArray); + } else { + list = personIdsArray; + } + + list = list.replace('[', '').replace(']', ''); + + var sql = + 'select t1.person_id, t1.uuid as patient_uuid, t4.patient_id, t1.gender,' + + ' t1.birthdate, extract(year from (from_days(datediff(now(), t1.birthdate)))) as age,' + + "concat(COALESCE(t2.given_name,''),' ',COALESCE(t2.middle_name,''),' ',COALESCE(t2.family_name,''))" + + "as person_name, group_concat(distinct t3.identifier separator ', ') as identifiers FROM amrs.person `t1`" + + 'INNER JOIN amrs.person_name `t2` ON (t1.person_id = t2.person_id and (t2.voided is null || t2.voided = 0))' + + 'LEFT OUTER JOIN amrs.patient `t4` ON (t1.person_id = t4.patient_id)' + + 'LEFT OUTER JOIN amrs.patient_identifier `t3` ON (t1.person_id = t3.patient_id)' + + 'WHERE t1.person_id in (?) GROUP BY t1.person_id'; + + sql = sql.replace('?', list); + + var queryObject = { + query: sql, + sqlParams: [] + }; + + return new Promise(function (resolve, reject) { + db.queryReportServer(queryObject, function (response) { + if (response.error) { + reject(response); + } else { + resolve(response); + } }); -} \ No newline at end of file + }); +} diff --git a/service/patient-medical-history.service.js b/service/patient-medical-history.service.js index 0207a4525..933c52228 100644 --- a/service/patient-medical-history.service.js +++ b/service/patient-medical-history.service.js @@ -1,38 +1,37 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report' +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; var processors = require('../etl-processors.js'); -export class PatientMedicalHistoryService extends BaseMysqlReport{ +export class PatientMedicalHistoryService extends BaseMysqlReport { + constructor(reportName, params) { + super(reportName, params); + } + generateReport(additionalParams) { + const that = this; + let indicators = ['previous_regimen', 'current_regimen']; + return new Promise((resolve, reject) => { + super + .generateReport(additionalParams) + .then((results) => { + results.size = results ? results.results.results.length : 0; + results.result = results ? results.results.results : []; - constructor(reportName, params) { - super(reportName, params) - } - generateReport(additionalParams) { - const that = this; - let indicators =[ 'previous_regimen', 'current_regimen' ]; - return new Promise((resolve, reject) => { - super.generateReport(additionalParams) - .then((results) => { - results.size=results?results.results.results.length:0; - results.result=results?results.results.results:[]; + delete results['results']; + var pd = processors.findChanges(indicators, results, ''); + var pd2 = processors.convertConceptIdToName(indicators, results, ''); - delete results['results']; - var pd= processors.findChanges(indicators,results,'') ; - var pd2= processors.convertConceptIdToName(indicators,results,'') ; - - - resolve(results); - }) - .catch((error) => { - console.error('Patient Medical History Report generation error: ', error); - reject(error); - }); + resolve(results); + }) + .catch((error) => { + console.error( + 'Patient Medical History Report generation error: ', + error + ); + reject(error); }); - } - + }); + } } diff --git a/service/patient-medication-history.service.js b/service/patient-medication-history.service.js index 226028c51..767867a5b 100755 --- a/service/patient-medication-history.service.js +++ b/service/patient-medication-history.service.js @@ -1,24 +1,19 @@ - const _ = require('lodash'); export class patientMedicationHistService { - - processMedicationHistory(data) { - var revisedResults=[]; - _.each(data.result, function (result) { - try{ - if(result && result.current_regimen===result.previous_regimen){ - // do not include medication data when current and previous regimen are same - }else{ - revisedResults.push(result) - } - - } catch(error){ - console.log(error) - } - - }); - data.result=revisedResults; - return data; - } - + processMedicationHistory(data) { + var revisedResults = []; + _.each(data.result, function (result) { + try { + if (result && result.current_regimen === result.previous_regimen) { + // do not include medication data when current and previous regimen are same + } else { + revisedResults.push(result); + } + } catch (error) { + console.log(error); + } + }); + data.result = revisedResults; + return data; + } } diff --git a/service/patient-monthly-status-history.js b/service/patient-monthly-status-history.js index 7ea8dcfbd..6017915df 100755 --- a/service/patient-monthly-status-history.js +++ b/service/patient-monthly-status-history.js @@ -1,23 +1,28 @@ -const Promise = require("bluebird"); +const Promise = require('bluebird'); const db = require('../etl-db'); export class PatientMonthlyStatusHistory { - resolvePersonId(personUuid) { - let query = "Select * from amrs.person where uuid = ? limit 1" - let params = [personUuid]; - return new Promise(function (resolve, reject) { - db.queryReportServer({ query: query, sqlParams: params }, (result) => { - resolve(result); - }) - }); - } - getPatientMonthlyStatusHistory(personUuid, startDate, endDate) { - - - return this.resolvePersonId(personUuid).then((person => { - if (person.result && person.result.length > 0) { - let personId = person.result[0].person_id; - let params = [startDate, endDate, personId, startDate, endDate, personId]; - let query = `SELECT p1 AS person_id, + resolvePersonId(personUuid) { + let query = 'Select * from amrs.person where uuid = ? limit 1'; + let params = [personUuid]; + return new Promise(function (resolve, reject) { + db.queryReportServer({ query: query, sqlParams: params }, (result) => { + resolve(result); + }); + }); + } + getPatientMonthlyStatusHistory(personUuid, startDate, endDate) { + return this.resolvePersonId(personUuid).then((person) => { + if (person.result && person.result.length > 0) { + let personId = person.result[0].person_id; + let params = [ + startDate, + endDate, + personId, + startDate, + endDate, + personId + ]; + let query = `SELECT p1 AS person_id, Date_format(e2, '%d-%m-%Y') AS most_recent_clinical_encounter, l3.name AS location, @@ -492,19 +497,20 @@ FROM (SELECT t1.person_id AS p1, ON l3.location_id = l2 JOIN amrs.encounter_type AS et1 ON et1.encounter_type_id = encounter_type; - ` - return new Promise(function (resolve, reject) { - db.queryReportServer({ query: query, sqlParams: params }, (result) => { - resolve(result); - }) - }); - } else { - return new Promise(function (resolve, reject) { - reject({ error: 'Could not resolve patient id' }); - }) - } - })) - + `; + return new Promise(function (resolve, reject) { + db.queryReportServer( + { query: query, sqlParams: params }, + (result) => { + resolve(result); + } + ); + }); + } else { + return new Promise(function (resolve, reject) { + reject({ error: 'Could not resolve patient id' }); + }); } - -} \ No newline at end of file + }); + } +} diff --git a/service/patient-oncology-summary-service.js b/service/patient-oncology-summary-service.js index 3d4cb154c..475fe68d7 100644 --- a/service/patient-oncology-summary-service.js +++ b/service/patient-oncology-summary-service.js @@ -1,98 +1,120 @@ var db = require('../etl-db'); function getOncMeds(request, medsFormat, encounterId) { - let queryParts = {}; - var patientUuid = request.uuid; - var programUuid = request.programUuid; - if (medsFormat == 'summary') { - queryParts = { - columns: "t1.value_coded", - table: "amrs.obs", - where: ["t2.uuid = ? and t1.concept_id in ? and t1.encounter_id = ? and t1.voided = ?", patientUuid, [9918], encounterId, 0], - order: [{ - column: 't1.obs_group_id', - asc: false - }], - joins: [ - ['amrs.person', 't2', 't2.person_id=t1.person_id'], - ], - offset: request.startIndex, - limit: request.limit - }; - } else { - queryParts = { - columns: "t1.concept_id, t1.value_coded, t1.value_numeric, t1.obs_group_id, t1.encounter_id, t1.obs_datetime", - table: "amrs.obs", - where: ["t2.uuid = ? and t5.programuuid = ? and t1.concept_id in ? and t1.voided = ?", patientUuid, programUuid, [9918, 8723, 1896, 7463, 1899, 9869], 0], - order: [{ - column: 't1.obs_group_id', - asc: false - }], - joins: [ - ['amrs.person', 't2', 't2.person_id=t1.person_id'], - ['amrs.patient_program', 't3', 't3.patient_id=t2.person_id'] - ], - leftOuterJoins: [ - ['(SELECT program_id, uuid as `programuuid` FROM amrs.program ) `t5` ON (t3.program_id = t5.program_id)'] - ], - offset: request.startIndex, - limit: request.limit - }; - } + let queryParts = {}; + var patientUuid = request.uuid; + var programUuid = request.programUuid; + if (medsFormat == 'summary') { + queryParts = { + columns: 't1.value_coded', + table: 'amrs.obs', + where: [ + 't2.uuid = ? and t1.concept_id in ? and t1.encounter_id = ? and t1.voided = ?', + patientUuid, + [9918], + encounterId, + 0 + ], + order: [ + { + column: 't1.obs_group_id', + asc: false + } + ], + joins: [['amrs.person', 't2', 't2.person_id=t1.person_id']], + offset: request.startIndex, + limit: request.limit + }; + } else { + queryParts = { + columns: + 't1.concept_id, t1.value_coded, t1.value_numeric, t1.obs_group_id, t1.encounter_id, t1.obs_datetime', + table: 'amrs.obs', + where: [ + 't2.uuid = ? and t5.programuuid = ? and t1.concept_id in ? and t1.voided = ?', + patientUuid, + programUuid, + [9918, 8723, 1896, 7463, 1899, 9869], + 0 + ], + order: [ + { + column: 't1.obs_group_id', + asc: false + } + ], + joins: [ + ['amrs.person', 't2', 't2.person_id=t1.person_id'], + ['amrs.patient_program', 't3', 't3.patient_id=t2.person_id'] + ], + leftOuterJoins: [ + [ + '(SELECT program_id, uuid as `programuuid` FROM amrs.program ) `t5` ON (t3.program_id = t5.program_id)' + ] + ], + offset: request.startIndex, + limit: request.limit + }; + } - return db.queryDb(queryParts) + return db.queryDb(queryParts); } function generateMedsDataSet(data) { - let meds = []; - const groupBy = key => array => - array.reduce((objectsByKeyValue, obj) => { - const value = obj[key]; - objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj); - return objectsByKeyValue; - }, {}); - //Group medical history obs by the group - if (data) { - const groupByEncounter = groupBy('encounter_id'); - const encounterData = groupByEncounter(data); - _.each(encounterData, function (concepts) { - let oncMeds = {}; - const i = groupBy('obs_group_id'); - let plan = _.filter(concepts, function (o) { - return o.concept_id === 9869 - }); - oncMeds.treatment_plan = plan; - _.remove(concepts, function (e) { - return e.obs_group_id == null; - }); - let drug; - drug = i(concepts); - if (!_.isEmpty(drug)) { - oncMeds.drugs = drug; - meds.push(oncMeds); - } - }) - } - return meds; + let meds = []; + const groupBy = (key) => (array) => + array.reduce((objectsByKeyValue, obj) => { + const value = obj[key]; + objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj); + return objectsByKeyValue; + }, {}); + //Group medical history obs by the group + if (data) { + const groupByEncounter = groupBy('encounter_id'); + const encounterData = groupByEncounter(data); + _.each(encounterData, function (concepts) { + let oncMeds = {}; + const i = groupBy('obs_group_id'); + let plan = _.filter(concepts, function (o) { + return o.concept_id === 9869; + }); + oncMeds.treatment_plan = plan; + _.remove(concepts, function (e) { + return e.obs_group_id == null; + }); + let drug; + drug = i(concepts); + if (!_.isEmpty(drug)) { + oncMeds.drugs = drug; + meds.push(oncMeds); + } + }); + } + return meds; } function getPatientOncologyDiagnosis(request) { - let patientUuid = request.uuid; - let queryParts = { - columns: "*", - order: [{ - column: 'encounter_id', - asc: false - }], - joins: [ - ['amrs.person', 't2', 't2.person_id=t1.person_id'] - ], - table: "amrs.obs", - where: ["t2.uuid = ? and t1.concept_id in ? and t1.voided = ?", patientUuid, [9841, 9871, 6536, 9844, 6551, 9846, 6540, 9843], 0], - offset: request.startIndex, - limit: request.limit - }; - return db.queryDb(queryParts); + let patientUuid = request.uuid; + let queryParts = { + columns: '*', + order: [ + { + column: 'encounter_id', + asc: false + } + ], + joins: [['amrs.person', 't2', 't2.person_id=t1.person_id']], + table: 'amrs.obs', + where: [ + 't2.uuid = ? and t1.concept_id in ? and t1.voided = ?', + patientUuid, + [9841, 9871, 6536, 9844, 6551, 9846, 6540, 9843], + 0 + ], + offset: request.startIndex, + limit: request.limit + }; + return db.queryDb(queryParts); } -export {generateMedsDataSet, getOncMeds, getPatientOncologyDiagnosis} +export { generateMedsDataSet, getOncMeds, getPatientOncologyDiagnosis }; diff --git a/service/patient-peer-referral.service.js b/service/patient-peer-referral.service.js index 9085c1af6..dd738e5a6 100644 --- a/service/patient-peer-referral.service.js +++ b/service/patient-peer-referral.service.js @@ -1,73 +1,75 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report' -import { - PatientlistMysqlReport -} from '../app/reporting-framework/patientlist-mysql.report' -import { - PatientReferralAggregateService -} from './patient-referral-aggregate.service' +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; +import { PatientReferralAggregateService } from './patient-referral-aggregate.service'; export class PatientReferralService { + getAggregateReport(reportParams) { + reportParams.locationUuids = reportParams.locationUuids + ? reportParams.locationUuids.replace(/,/g, "','") + : null; + reportParams.programUuids = reportParams.programUuids + ? reportParams.programUuids.replace(/,/g, "','") + : null; + // notificationStatus param can either be ALL or null + // notificationStatus param with ALL is used to get all patients irrespective of notification status + // if notificationStatus is not provided : only patients notification with null notification status are included + reportParams.notificationStatus = reportParams.notificationStatus + ? null + : 'null'; + let self = this; + return new Promise(function (resolve, reject) { + reportParams.groupBy = 'groupByLocation,groupByProgram'; + reportParams.countBy = 'num_persons'; + let report = new PatientReferralAggregateService( + 'referralAggregate', + reportParams + ); + Promise.join(report.generateReport(reportParams), (results) => { + // TODO Do some post processing + results = results.results; + resolve(results); + }).catch((errors) => { + reject(errors); + }); + }); + } + getPatientListReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + reportParams.groupBy = 'groupByPerson'; + //TODO: Do some pre processing + Promise.join(dao.runReport(reportParams), (results) => { + resolve(results); + }).catch((errors) => { + reject(errors); + }); + }); + } - getAggregateReport(reportParams) { - reportParams.locationUuids = reportParams.locationUuids ? reportParams.locationUuids.replace(/,/g, "','") : null; - reportParams.programUuids = reportParams.programUuids ? reportParams.programUuids.replace(/,/g, "','") : null; - // notificationStatus param can either be ALL or null - // notificationStatus param with ALL is used to get all patients irrespective of notification status - // if notificationStatus is not provided : only patients notification with null notification status are included - reportParams.notificationStatus = reportParams.notificationStatus ? null : 'null'; - let self = this; - return new Promise(function (resolve, reject) { - reportParams.groupBy = 'groupByLocation,groupByProgram'; - reportParams.countBy = 'num_persons'; - let report = new PatientReferralAggregateService('referralAggregate', reportParams); - Promise.join(report.generateReport(reportParams), - (results) => { - // TODO Do some post processing - results = results.results; - resolve(results); - }).catch((errors) => { - reject(errors); - }); - }); - } - - getPatientListReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - reportParams.groupBy = 'groupByPerson'; - //TODO: Do some pre processing - Promise.join(dao.runReport(reportParams), - (results) => { - resolve(results); - }).catch((errors) => { - reject(errors); - }); - }); - } - - getPatientListReport2(reportParams) { - // let self = this; - return new Promise(function (resolve, reject) { - reportParams.groupBy = 'groupByPerson'; - reportParams.notificationStatus = reportParams.notificationStatus ? null : 'null'; - let report = new PatientlistMysqlReport('referralAggregate', reportParams); - Promise.join(report.generatePatientListReport([]), - (results) => { - // results.result = results.results.results; - let data = results; - data.result = results.results.results; - // let data = results.results.results; - resolve(data); - }) - .catch((errors) => { - reject(errors); - }); - }); - } + getPatientListReport2(reportParams) { + // let self = this; + return new Promise(function (resolve, reject) { + reportParams.groupBy = 'groupByPerson'; + reportParams.notificationStatus = reportParams.notificationStatus + ? null + : 'null'; + let report = new PatientlistMysqlReport( + 'referralAggregate', + reportParams + ); + Promise.join(report.generatePatientListReport([]), (results) => { + // results.result = results.results.results; + let data = results; + data.result = results.results.results; + // let data = results.results.results; + resolve(data); + }).catch((errors) => { + reject(errors); + }); + }); + } } diff --git a/service/patient-referral-aggregate.service.js b/service/patient-referral-aggregate.service.js index 7ef4eb78b..69d835b5c 100755 --- a/service/patient-referral-aggregate.service.js +++ b/service/patient-referral-aggregate.service.js @@ -1,31 +1,31 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report' +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; var processors = require('../etl-processors.js'); -export class PatientReferralAggregateService extends BaseMysqlReport{ +export class PatientReferralAggregateService extends BaseMysqlReport { + constructor(reportName, params) { + super(reportName, params); + } + generateReport(additionalParams) { + const that = this; + return new Promise((resolve, reject) => { + super + .generateReport(additionalParams) + .then((results) => { + var pd = processors.processPatientReferral([], results.results, ''); - constructor(reportName, params) { - super(reportName, params) - } - generateReport(additionalParams) { - const that = this; - return new Promise((resolve, reject) => { - super.generateReport(additionalParams) - .then((results) => { - var pd= processors.processPatientReferral([],results.results,'') ; - - resolve(results); - }) - .catch((error) => { - console.error('Patient Referral Aggregate Report generation error: ', error); - reject(error); - }); + resolve(results); + }) + .catch((error) => { + console.error( + 'Patient Referral Aggregate Report generation error: ', + error + ); + reject(error); }); - } - + }); + } } diff --git a/service/patient-referral.service.js b/service/patient-referral.service.js index 37d2c0c6a..731881368 100755 --- a/service/patient-referral.service.js +++ b/service/patient-referral.service.js @@ -1,9 +1,9 @@ -import { PatientlistMysqlReport } from "../app/reporting-framework/patientlist-mysql.report"; -import { PatientReferralAggregateService } from "./patient-referral-aggregate.service"; -import { titleCase } from "../etl-helpers"; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; +import { PatientReferralAggregateService } from './patient-referral-aggregate.service'; +import { titleCase } from '../etl-helpers'; -const dao = require("../etl-dao"); -const Promise = require("bluebird"); +const dao = require('../etl-dao'); +const Promise = require('bluebird'); export class PatientReferralService { getAggregateReport(reportParams) { @@ -15,12 +15,12 @@ export class PatientReferralService { : null; reportParams.notificationStatus = reportParams.notificationStatus ? null - : "null"; + : 'null'; return new Promise(function (resolve, reject) { - reportParams.groupBy = "groupByLocation,groupByProgram"; - reportParams.countBy = "num_persons"; + reportParams.groupBy = 'groupByLocation,groupByProgram'; + reportParams.countBy = 'num_persons'; let report = new PatientReferralAggregateService( - "referralAggregate", + 'referralAggregate', reportParams ); Promise.join(report.generateReport(reportParams), (results) => { @@ -34,7 +34,7 @@ export class PatientReferralService { getPatientListReport(reportParams) { return new Promise(function (resolve, reject) { - reportParams.groupBy = "groupByPerson"; + reportParams.groupBy = 'groupByPerson'; Promise.join(dao.runReport(reportParams), (results) => { resolve(results); }).catch((errors) => { @@ -45,10 +45,10 @@ export class PatientReferralService { getReferralPatientListReport(reportParams) { return new Promise(function (resolve, reject) { - reportParams.groupBy = "groupByPerson"; + reportParams.groupBy = 'groupByPerson'; reportParams.notificationStatus = reportParams.notificationStatus ? null - : "null"; + : 'null'; let reportName = reportParams.reportName; let report = new PatientlistMysqlReport(reportName, reportParams); @@ -74,12 +74,12 @@ export class PatientReferralService { getPeerNavigatorReferralPatientList(reportParams) { return new Promise(function (resolve, reject) { - reportParams.groupBy = "groupByPerson"; + reportParams.groupBy = 'groupByPerson'; reportParams.notificationStatus = reportParams.notificationStatus ? null - : "null"; + : 'null'; let report = new PatientlistMysqlReport( - "referral-patient-peer-navigator-list", + 'referral-patient-peer-navigator-list', reportParams ); Promise.join(report.generatePatientListReport([]), (results) => { diff --git a/service/patient-register-report.service.js b/service/patient-register-report.service.js index c1de0546a..3f8eed7ef 100755 --- a/service/patient-register-report.service.js +++ b/service/patient-register-report.service.js @@ -1,20 +1,18 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); export class PatientRegisterReportService { - - getAggregateReport(reportParams) { - let self = this; - return new Promise(function (resolve, reject) { - reportParams.groupBy = 'groupByEncounter'; - Promise.join(dao.runReport(reportParams), - (results) => { - resolve(results); - //TODO Do some post processing - }).catch((errors) => { - reject(errors); - }); - }); - } -} \ No newline at end of file + getAggregateReport(reportParams) { + let self = this; + return new Promise(function (resolve, reject) { + reportParams.groupBy = 'groupByEncounter'; + Promise.join(dao.runReport(reportParams), (results) => { + resolve(results); + //TODO Do some post processing + }).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/patient-reminder.service.js b/service/patient-reminder.service.js index 7758af6a7..23029dde3 100755 --- a/service/patient-reminder.service.js +++ b/service/patient-reminder.service.js @@ -1,265 +1,320 @@ 'use strict'; -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); var serviceDef = { - generateReminders: generateReminders, - viralLoadReminders: viralLoadReminders, - newViralLoadPresent: newViralLoadPresent, - viralLoadErrors: viralLoadErrors, - pendingViralOrder: pendingViralOrder, - inhReminders: inhReminders + generateReminders: generateReminders, + viralLoadReminders: viralLoadReminders, + newViralLoadPresent: newViralLoadPresent, + viralLoadErrors: viralLoadErrors, + pendingViralOrder: pendingViralOrder, + inhReminders: inhReminders }; module.exports = serviceDef; - function viralLoadReminders(data) { - - let reminders = []; - - let labMessage = 'Last viral load: none'; - if (data.last_vl_date) { - labMessage = 'Last viral load: ' + transformZeroVl(data.viral_load) + ' on ' + - '(' + Moment(data.last_vl_date).format('DD-MM-YYYY') + ')' + ' ' + - data.months_since_last_vl_date + ' months ago.'; - } + let reminders = []; - let isAdult = checkAge(new Date(data.birth_date)); - - if (!isAdult && data.months_since_last_vl_date >= 6) { - reminders.push({ - message: 'Patient requires viral load. Patients who are between 0-24 years old ' + - 'require a viral load test every 6 months. ' + labMessage, - title: 'Viral Load Reminder', - type: 'danger', - display: { - banner: true, - toast: true - } - }); - } else if (isAdult && data.needs_vl_coded === 2 && data.months_since_last_vl_date >= 6 ) { - reminders.push({ - message: 'Patient requires viral load. Patients older than 25 years and newly on ART require ' + - 'a viral load test every 6 months. ' + labMessage, - title: 'Viral Load Reminder', - type: 'danger', - display: { - banner: true, - toast: true - } - }); - } else if (isAdult && data.needs_vl_coded === 3 && data.months_since_last_vl_date >= 12) { - reminders.push({ - message: 'Patient requires viral load. Patients older than 25 years and on ART > 1 year require ' + - 'a viral load test every year. ' + labMessage, - title: 'Viral Load Reminder', - type: 'danger', - display: { - banner: true, - toast: true - } - }); - } - else if (data.needs_vl_coded === 4) { - reminders.push({ - message: 'Patient requires viral load. A pregnant or breastfeeding patient with vl > 400 requires ' + - 'a viral load test every 3 months. ' + labMessage, - title: 'Viral Load Reminder', - type: 'danger', - display: { - banner: true, - toast: true - } - }); - } - else if (data.needs_vl_coded === 5) { - reminders.push({ - message: 'Patient requires viral load. A pregnant or breastfeeding patient with vl<= 400 requires ' + - 'a viral load test every 6 months. ' + labMessage, - title: 'Viral Load Reminder', - type: 'danger', - display: { - banner: true, - toast: true - } - }); - } + let labMessage = 'Last viral load: none'; + if (data.last_vl_date) { + labMessage = + 'Last viral load: ' + + transformZeroVl(data.viral_load) + + ' on ' + + '(' + + Moment(data.last_vl_date).format('DD-MM-YYYY') + + ')' + + ' ' + + data.months_since_last_vl_date + + ' months ago.'; + } + + let isAdult = checkAge(new Date(data.birth_date)); + + if (!isAdult && data.months_since_last_vl_date >= 6) { + reminders.push({ + message: + 'Patient requires viral load. Patients who are between 0-24 years old ' + + 'require a viral load test every 6 months. ' + + labMessage, + title: 'Viral Load Reminder', + type: 'danger', + display: { + banner: true, + toast: true + } + }); + } else if ( + isAdult && + data.needs_vl_coded === 2 && + data.months_since_last_vl_date >= 6 + ) { + reminders.push({ + message: + 'Patient requires viral load. Patients older than 25 years and newly on ART require ' + + 'a viral load test every 6 months. ' + + labMessage, + title: 'Viral Load Reminder', + type: 'danger', + display: { + banner: true, + toast: true + } + }); + } else if ( + isAdult && + data.needs_vl_coded === 3 && + data.months_since_last_vl_date >= 12 + ) { + reminders.push({ + message: + 'Patient requires viral load. Patients older than 25 years and on ART > 1 year require ' + + 'a viral load test every year. ' + + labMessage, + title: 'Viral Load Reminder', + type: 'danger', + display: { + banner: true, + toast: true + } + }); + } else if (data.needs_vl_coded === 4) { + reminders.push({ + message: + 'Patient requires viral load. A pregnant or breastfeeding patient with vl > 400 requires ' + + 'a viral load test every 3 months. ' + + labMessage, + title: 'Viral Load Reminder', + type: 'danger', + display: { + banner: true, + toast: true + } + }); + } else if (data.needs_vl_coded === 5) { + reminders.push({ + message: + 'Patient requires viral load. A pregnant or breastfeeding patient with vl<= 400 requires ' + + 'a viral load test every 6 months. ' + + labMessage, + title: 'Viral Load Reminder', + type: 'danger', + display: { + banner: true, + toast: true + } + }); + } - return reminders; + return reminders; } function checkAge(dateString) { - let today = new Date(); - let birthDate = new Date(dateString); - let age = today.getFullYear() - birthDate.getFullYear(); - let m = today.getMonth() - birthDate.getMonth(); - if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { - age--; - } - isInfant(dateString); - if (age <= 24) { - return false; - } else { - return true; - } + let today = new Date(); + let birthDate = new Date(dateString); + let age = today.getFullYear() - birthDate.getFullYear(); + let m = today.getMonth() - birthDate.getMonth(); + if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { + age--; + } + isInfant(dateString); + if (age <= 24) { + return false; + } else { + return true; + } } function isInfant(dateString) { - let months = Moment().diff(dateString, 'months'); + let months = Moment().diff(dateString, 'months'); } -function qualifiesDifferenciatedReminders(data){ - - let reminders = []; - let diffMessage = ''; - if (data.qualifies_differenciated_care) { - diffMessage = 'Last viral load: ' + transformZeroVl(data.viral_load) + ' on ' + - '(' + Moment(data.last_vl_date).format('DD-MM-YYYY') + ')' + ' ' + - data.months_since_last_vl_date + ' months ago.'; - } +function qualifiesDifferenciatedReminders(data) { + let reminders = []; + let diffMessage = ''; + if (data.qualifies_differenciated_care) { + diffMessage = + 'Last viral load: ' + + transformZeroVl(data.viral_load) + + ' on ' + + '(' + + Moment(data.last_vl_date).format('DD-MM-YYYY') + + ')' + + ' ' + + data.months_since_last_vl_date + + ' months ago.'; + } - if (data.qualifies_differenciated_care && data.is_postnatal === 0 && data.is_pregnant === 0 && data.qualifies_enhanced === 0) { - reminders.push({ - message: 'Patient qualifies for differentiated care. Viral load is <= 400 and age >= 20. ' + diffMessage, - title: 'Differentiated Care Reminder', - type: 'warning', - display: { - banner: true, - toast: true - }, - auto_register: '334c9e98-173f-4454-a8ce-f80b20b7fdf0' - }); - - } else { - console.info.call('No Differenciated Care Reminder For Selected Patient' + data.qualifies_differenciated_care); - } - - return reminders; + if ( + data.qualifies_differenciated_care && + data.is_postnatal === 0 && + data.is_pregnant === 0 && + data.qualifies_enhanced === 0 + ) { + reminders.push({ + message: + 'Patient qualifies for differentiated care. Viral load is <= 400 and age >= 20. ' + + diffMessage, + title: 'Differentiated Care Reminder', + type: 'warning', + display: { + banner: true, + toast: true + }, + auto_register: '334c9e98-173f-4454-a8ce-f80b20b7fdf0' + }); + } else { + console.info.call( + 'No Differenciated Care Reminder For Selected Patient' + + data.qualifies_differenciated_care + ); + } + return reminders; } - function inhReminders(data) { - let reminders = []; - try{ - if (data.is_on_inh_treatment && data.inh_treatment_days_remaining > 30 && - data.inh_treatment_days_remaining < 150) { - - reminders.push({ - message: 'Patient started INH treatment on (' + - - Moment(data.ipt_start_date).format('DD-MM-YYYY') + '). ' + - 'Expected to end on (' + - Moment(data.ipt_completion_date).format('DD-MM-YYYY') + '). ' - + data.inh_treatment_days_remaining + - ' days remaining.', - title: 'INH Treatment Reminder', - type: 'danger', - display: { - banner: true, - toast: true - } - }); + let reminders = []; + try { + if ( + data.is_on_inh_treatment && + data.inh_treatment_days_remaining > 30 && + data.inh_treatment_days_remaining < 150 + ) { + reminders.push({ + message: + 'Patient started INH treatment on (' + + Moment(data.ipt_start_date).format('DD-MM-YYYY') + + '). ' + + 'Expected to end on (' + + Moment(data.ipt_completion_date).format('DD-MM-YYYY') + + '). ' + + data.inh_treatment_days_remaining + + ' days remaining.', + title: 'INH Treatment Reminder', + type: 'danger', + display: { + banner: true, + toast: true } - } catch(e){ - console.log(e); + }); } - // INH Treatment Reminder - last mont - if (data.is_on_inh_treatment && data.inh_treatment_days_remaining <= 30 && - data.inh_treatment_days_remaining > 0) { - reminders.push({ - message: 'Patient has been on INH treatment for the last 5 months, expected to end on (' + - Moment(data.ipt_completion_date).format('DD-MM-YYYY') + ') ', - title: 'INH Treatment Reminder', - type: 'danger', - display: { - banner: true, - toast: true - } - }); - } - return reminders; + } catch (e) { + console.log(e); + } + // INH Treatment Reminder - last mont + if ( + data.is_on_inh_treatment && + data.inh_treatment_days_remaining <= 30 && + data.inh_treatment_days_remaining > 0 + ) { + reminders.push({ + message: + 'Patient has been on INH treatment for the last 5 months, expected to end on (' + + Moment(data.ipt_completion_date).format('DD-MM-YYYY') + + ') ', + title: 'INH Treatment Reminder', + type: 'danger', + display: { + banner: true, + toast: true + } + }); + } + return reminders; } - function viralLoadErrors(data) { - let reminders = []; - if (data.ordered_vl_has_error === 1) { - reminders.push({ - message: 'Viral load test that was ordered on: (' + - Moment(data.vl_error_order_date).format('DD-MM-YYYY') + ') ' + - 'resulted to an error. Please re-order.', - title: 'Lab Error Reminder', - type: 'danger', - display: { - banner: true, - toast: true - } - }); - } - return reminders; + let reminders = []; + if (data.ordered_vl_has_error === 1) { + reminders.push({ + message: + 'Viral load test that was ordered on: (' + + Moment(data.vl_error_order_date).format('DD-MM-YYYY') + + ') ' + + 'resulted to an error. Please re-order.', + title: 'Lab Error Reminder', + type: 'danger', + display: { + banner: true, + toast: true + } + }); + } + return reminders; } function pendingViralOrder(data) { - let reminders = []; - if (data.overdue_vl_lab_order > 0) { - reminders.push({ - message: 'No result reported for patient\'s viral load test drawn on (' + - Moment(data.vl_order_date).format('DD-MM-YYYY') + ') days ago' + - ' Please follow up with lab or redraw new specimen.', - title: 'Overdue Viral Load Order', - type: 'danger', - display: { - banner: true, - toast: true - } - }); - } - return reminders; + let reminders = []; + if (data.overdue_vl_lab_order > 0) { + reminders.push({ + message: + "No result reported for patient's viral load test drawn on (" + + Moment(data.vl_order_date).format('DD-MM-YYYY') + + ') days ago' + + ' Please follow up with lab or redraw new specimen.', + title: 'Overdue Viral Load Order', + type: 'danger', + display: { + banner: true, + toast: true + } + }); + } + return reminders; } function newViralLoadPresent(data) { - let reminders = []; - if (data.new_viral_load_present) { - reminders.push({ - message: 'New viral load result: ' + transformZeroVl(data.viral_load) + ' (collected on ' + - Moment(data.last_vl_date).format('DD-MM-YYYY') + ').', - title: 'New Viral Load present', - type: 'success', - display: { - banner: true, - toast: true - } - }); - } - return reminders; + let reminders = []; + if (data.new_viral_load_present) { + reminders.push({ + message: + 'New viral load result: ' + + transformZeroVl(data.viral_load) + + ' (collected on ' + + Moment(data.last_vl_date).format('DD-MM-YYYY') + + ').', + title: 'New Viral Load present', + type: 'success', + display: { + banner: true, + toast: true + } + }); + } + return reminders; } function pendingViralLoadLabResult(eidResults) { - // console.log('EID Results', eidResults); - let incompleteResult = eidResults.find((result)=>{ - if(result){ - if(result.sample_status){ - return result.sample_status === 'Incomplete'; - } - }else{ - console.error('EID Result undefined error', result); - } - }); + // console.log('EID Results', eidResults); + let incompleteResult = eidResults.find((result) => { + if (result) { + if (result.sample_status) { + return result.sample_status === 'Incomplete'; + } + } else { + console.error('EID Result undefined error', result); + } + }); let reminders = []; //let data = _.last(eidResults.viralLoad); if (incompleteResult) { let dateSplit = incompleteResult.date_collected.split('-'); let dateCollected = Moment(incompleteResult.date_collected); reminders.push({ - message: 'Patient lab Order No.' + incompleteResult.order_number + ' is currently being processed. Sample' + - ' collected on ' + dateCollected.format('DD-MM-YYYY') + ').', - title : 'Pending Lab Order Result', - type : 'info', + message: + 'Patient lab Order No.' + + incompleteResult.order_number + + ' is currently being processed. Sample' + + ' collected on ' + + dateCollected.format('DD-MM-YYYY') + + ').', + title: 'Pending Lab Order Result', + type: 'info', display: { banner: true, - toast : true + toast: true } }); } @@ -267,180 +322,190 @@ function pendingViralLoadLabResult(eidResults) { } function qualifiesEnhancedReminders(data) { - let reminders = []; - - switch (data.qualifies_enhanced) { - case 1: - reminders.push({ - message: 'The Patient’s viral load is greater than 400. Patients with viral load greater than 400 should be enrolled in the Viremia Program.', - title: 'Viremia Program', - type: 'warning', - display: { - banner: true, - toast: true - }, - auto_register: 'c4246ff0-b081-460c-bcc5-b0678012659e' - }); - break; - case 2: - reminders.push({ - message: 'The patient is eligible to return to the Standard HIV Program.', - title: 'Viremia Program', - type: 'warning', - display: { - banner: true, - toast: true - } - }); - break; - case 3: - reminders.push({ - message: 'Patient requires 3 months repeat VL', - title: 'Viremia Program', - type: 'warning', - display: { - banner: true, - toast: true - } - }); - break; - default: - console.info.call('No Viremia Program Reminder For Selected Patient' + data.qualifies_enhanced); - - } - - return reminders; - -} + let reminders = []; -function dnaReminder(data) { - let reminders = []; - - if (data.is_infant === 1) { - switch (data.dna_pcr_reminder) { - case 1: - reminders.push({ - message: 'HIV Exposed Infants require a DNA/PCR test at the age of 0-6 weeks.', - title: 'DNA/PCR Reminder', - type: 'warning', - display: { - banner: true, - toast: true - } - }); - break; - case 2: - reminders.push({ - message: 'HIV Exposed Infants require a DNA/PCR test at the age of 6 months.', - title: 'DNA/PCR Reminder', - type: 'warning', - display: { - banner: true, - toast: true - } - }); - break; - case 3: - reminders.push({ - message: 'HIV Exposed Infants require a DNA/PCR test at the age of 12 months.', - title: 'DNA/PCR Reminder', - type: 'warning', - display: { - banner: true, - toast: true - } - }); - break; - case 4: - reminders.push({ - message: 'HIV Exposed Infants require an Antibody test at the age of 18-24 months.', - title: 'DNA/PCR Reminder', - type: 'warning', - display: { - banner: true, - toast: true - } - }); - break; - default: - console.info.call('No DNA/PCR Reminder For Selected Patient' + data.qna_pcr_reminder); + switch (data.qualifies_enhanced) { + case 1: + reminders.push({ + message: + 'The Patient’s viral load is greater than 400. Patients with viral load greater than 400 should be enrolled in the Viremia Program.', + title: 'Viremia Program', + type: 'warning', + display: { + banner: true, + toast: true + }, + auto_register: 'c4246ff0-b081-460c-bcc5-b0678012659e' + }); + break; + case 2: + reminders.push({ + message: + 'The patient is eligible to return to the Standard HIV Program.', + title: 'Viremia Program', + type: 'warning', + display: { + banner: true, + toast: true } - - } - - return reminders; + }); + break; + case 3: + reminders.push({ + message: 'Patient requires 3 months repeat VL', + title: 'Viremia Program', + type: 'warning', + display: { + banner: true, + toast: true + } + }); + break; + default: + console.info.call( + 'No Viremia Program Reminder For Selected Patient' + + data.qualifies_enhanced + ); + } + return reminders; } -function dstReminders(data) { - // console.log('dstRemindersdata', data); +function dnaReminder(data) { + let reminders = []; - let reminders = []; - if (data.has_dst_result === 1) { + if (data.is_infant === 1) { + switch (data.dna_pcr_reminder) { + case 1: + reminders.push({ + message: + 'HIV Exposed Infants require a DNA/PCR test at the age of 0-6 weeks.', + title: 'DNA/PCR Reminder', + type: 'warning', + display: { + banner: true, + toast: true + } + }); + break; + case 2: + reminders.push({ + message: + 'HIV Exposed Infants require a DNA/PCR test at the age of 6 months.', + title: 'DNA/PCR Reminder', + type: 'warning', + display: { + banner: true, + toast: true + } + }); + break; + case 3: + reminders.push({ + message: + 'HIV Exposed Infants require a DNA/PCR test at the age of 12 months.', + title: 'DNA/PCR Reminder', + type: 'warning', + display: { + banner: true, + toast: true + } + }); + break; + case 4: reminders.push({ - message: 'New DRT/DST Image result : (collected on ' + - Moment(data.test_date).format('DD-MM-YYYY') + ').', - title: 'DRT/DST Reminders', - type: 'success', - display: { - banner: true, - toast: true - } + message: + 'HIV Exposed Infants require an Antibody test at the age of 18-24 months.', + title: 'DNA/PCR Reminder', + type: 'warning', + display: { + banner: true, + toast: true + } }); + break; + default: + console.info.call( + 'No DNA/PCR Reminder For Selected Patient' + data.qna_pcr_reminder + ); } - return reminders; + } + return reminders; } -function geneXpertReminders(data) { +function dstReminders(data) { + // console.log('dstRemindersdata', data); - let reminders = []; - if (data.has_gene_xpert_result === 1) { - reminders.push({ - message: 'New GeneXpert Image result : (collected on ' + - Moment(data.test_date).format('DD-MM-YYYY') + ').', - title: 'GeneXpert Reminders', - type: 'success', - display: { - banner: true, - toast: true - } - }); - } - return reminders; + let reminders = []; + if (data.has_dst_result === 1) { + reminders.push({ + message: + 'New DRT/DST Image result : (collected on ' + + Moment(data.test_date).format('DD-MM-YYYY') + + ').', + title: 'DRT/DST Reminders', + type: 'success', + display: { + banner: true, + toast: true + } + }); + } + return reminders; +} +function geneXpertReminders(data) { + let reminders = []; + if (data.has_gene_xpert_result === 1) { + reminders.push({ + message: + 'New GeneXpert Image result : (collected on ' + + Moment(data.test_date).format('DD-MM-YYYY') + + ').', + title: 'GeneXpert Reminders', + type: 'success', + display: { + banner: true, + toast: true + } + }); + } + return reminders; } -function getIptCompletionReminder(data){ - let reminders = []; +function getIptCompletionReminder(data) { + let reminders = []; - if (data.not_completed_ipt) { - reminders.push({ - message: 'Patient started IPT on ' + Moment(data.ipt_start_date).format('DD-MM-YYYY') +' and was supposed to be completed on '+ Moment(data.ipt_start_date).add(6, 'months').format('DD-MM-YYYY'), - title: 'IPT Completion Reminder', - type: 'warning', - display: { - banner: true, - toast: true - } - }); - - } else { - console.info.call('No IPT Completion Reminder For Selected Patient'); - } - - return reminders; + if (data.not_completed_ipt) { + reminders.push({ + message: + 'Patient started IPT on ' + + Moment(data.ipt_start_date).format('DD-MM-YYYY') + + ' and was supposed to be completed on ' + + Moment(data.ipt_start_date).add(6, 'months').format('DD-MM-YYYY'), + title: 'IPT Completion Reminder', + type: 'warning', + display: { + banner: true, + toast: true + } + }); + } else { + console.info.call('No IPT Completion Reminder For Selected Patient'); + } + return reminders; } function generateReminders(etlResults, eidResults) { let reminders = []; let patientReminder; - if (etlResults && etlResults.length > 0 ) { - patientReminder = { - person_id: etlResults[0].person_id, - person_uuid: etlResults[0].person_uuid - }; + if (etlResults && etlResults.length > 0) { + patientReminder = { + person_id: etlResults[0].person_id, + person_uuid: etlResults[0].person_uuid + }; } let data = etlResults[0]; @@ -448,7 +513,9 @@ function generateReminders(etlResults, eidResults) { let vl_Errors = viralLoadErrors(data); let pending_vl_orders = pendingViralOrder(data); let pending_vl_lab_result = pendingViralLoadLabResult(eidResults); - let qualifies_differenciated_care_reminders = qualifiesDifferenciatedReminders(data); + let qualifies_differenciated_care_reminders = qualifiesDifferenciatedReminders( + data + ); let inh_reminders = inhReminders(data); let vl_reminders = viralLoadReminders(data); let qualifies_enhanced = qualifiesEnhancedReminders(data); @@ -457,7 +524,7 @@ function generateReminders(etlResults, eidResults) { let gene_xpert_result = geneXpertReminders(data); let not_completed_ipt = getIptCompletionReminder(data); let currentReminder = []; - if(pending_vl_lab_result.length> 0) { + if (pending_vl_lab_result.length > 0) { currentReminder = pending_vl_lab_result.concat(inh_reminders); } else { currentReminder = new_vl.concat( @@ -470,23 +537,22 @@ function generateReminders(etlResults, eidResults) { dna_pcr_reminder, dst_result, gene_xpert_result, - not_completed_ipt); + not_completed_ipt + ); } - + reminders = reminders.concat(currentReminder); - + patientReminder.reminders = reminders; return patientReminder; } -function transformZeroVl(vl){ - - // VL OF Zero to be shown as LDL - - if(vl === 0 || vl === '0'){ - return 'LDL'; - }else{ - return vl; - } +function transformZeroVl(vl) { + // VL OF Zero to be shown as LDL + if (vl === 0 || vl === '0') { + return 'LDL'; + } else { + return vl; + } } diff --git a/service/patient-status-change-tracker-service.js b/service/patient-status-change-tracker-service.js index a4be4d993..113ec97cf 100755 --- a/service/patient-status-change-tracker-service.js +++ b/service/patient-status-change-tracker-service.js @@ -1,235 +1,237 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); const underscore = require('underscore'); -const indicatorsKeys = ['active_return', 'new_enrollment', 'transfer_in', 'LTFU', 'transfer_out', 'dead', 'HIV_negative', - 'self_disengaged', 'self_transfer_out']; +const indicatorsKeys = [ + 'active_return', + 'new_enrollment', + 'transfer_in', + 'LTFU', + 'transfer_out', + 'dead', + 'HIV_negative', + 'self_disengaged', + 'self_transfer_out' +]; import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; -import { - PatientlistMysqlReport -} from '../app/reporting-framework/patientlist-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; export class PatientStatusChangeTrackerService { - - getAggregateReport(reportParams) { - // reportParams.requestParams - switch (reportParams.requestParams.analysis || 'none') { - case 'cumulativeAnalysis': - return this.getCumulativeAggregateAnalysis(reportParams); - break; - case 'monthlyAnalysis': - return this.getMonthlyAggregateAnalysis(reportParams); - break; - case 'cohortAnalysis': - return this.getCohortAggregateAnalysis(reportParams); - break; - default: - return this.getCumulativeAggregateAnalysis(reportParams); - } + getAggregateReport(reportParams) { + // reportParams.requestParams + switch (reportParams.requestParams.analysis || 'none') { + case 'cumulativeAnalysis': + return this.getCumulativeAggregateAnalysis(reportParams); + break; + case 'monthlyAnalysis': + return this.getMonthlyAggregateAnalysis(reportParams); + break; + case 'cohortAnalysis': + return this.getCohortAggregateAnalysis(reportParams); + break; + default: + return this.getCumulativeAggregateAnalysis(reportParams); } - - getCumulativeAggregateAnalysis(reportParams) { - return new Promise((resolve, reject) => { - Promise.all([ - this.getCumulativeAggregates(reportParams), - ]).then((data) => { - data = this.runPostProcessing(data[0]); - data.analysis = reportParams.requestParams.analysis; - resolve(data); - }).catch((e) => { - console.log('Error, ', e); - reject(e); - - }); + } + + getCumulativeAggregateAnalysis(reportParams) { + return new Promise((resolve, reject) => { + Promise.all([this.getCumulativeAggregates(reportParams)]) + .then((data) => { + data = this.runPostProcessing(data[0]); + data.analysis = reportParams.requestParams.analysis; + resolve(data); + }) + .catch((e) => { + console.log('Error, ', e); + reject(e); }); - } - - - getMonthlyAggregateAnalysis(reportParams) { - return new Promise((resolve, reject) => { - Promise.all([ - this.getCumulativeAggregates(reportParams), - this.getMonthlyChangeAggregates(reportParams.requestParams) - ]).then((data) => { - let results = this.groupResultsByReportingMonth(data); - results.analysis = reportParams.requestParams.analysis; - results = this.runPostProcessing(results); - resolve(results); - }).catch((e) => { - console.log('Error, ', e); - reject(e); - - }); - }); - } - - getCohortAggregateAnalysis(reportParams) { - return new Promise((resolve, reject) => { - Promise.all([ - this.getMonthlyChangeAggregates(reportParams.requestParams) - ]).then((data) => { - resolve(data[0]); - }).catch((e) => { - console.log('Error, ', e); - reject(e); - - }); + }); + } + + getMonthlyAggregateAnalysis(reportParams) { + return new Promise((resolve, reject) => { + Promise.all([ + this.getCumulativeAggregates(reportParams), + this.getMonthlyChangeAggregates(reportParams.requestParams) + ]) + .then((data) => { + let results = this.groupResultsByReportingMonth(data); + results.analysis = reportParams.requestParams.analysis; + results = this.runPostProcessing(results); + resolve(results); + }) + .catch((e) => { + console.log('Error, ', e); + reject(e); }); - } - - - groupResultsByReportingMonth(data) { - let cumulativeAggr = data[0]; - let monthlyChangeAggr = data[1]; - cumulativeAggr.sql2 = monthlyChangeAggr.sql; - - _.each(cumulativeAggr.result, (cumulativeRow, i) => { - _.each(monthlyChangeAggr.result, (monthlyRow, j) => { - if (cumulativeRow.reporting_month === monthlyRow.reporting_month) { - cumulativeRow[monthlyRow.indicator] = monthlyRow.counts; - } - - }); - - // clean data by adding missing indicators and negations - _.each(indicatorsKeys, (key, j) => { - _.each(indicatorsKeys, (key2, i) => { - if (!cumulativeRow[key + '_to_' + key2]) cumulativeRow[key + '_to_' + key2] = 0; - }); - }); + }); + } + + getCohortAggregateAnalysis(reportParams) { + return new Promise((resolve, reject) => { + Promise.all([this.getMonthlyChangeAggregates(reportParams.requestParams)]) + .then((data) => { + resolve(data[0]); + }) + .catch((e) => { + console.log('Error, ', e); + reject(e); }); - return cumulativeAggr; - } - - - getPatientListReport(reportParams) { - reportParams['reportName'] = 'patient-status-change-tracker-report'; - let derivedIndicators = this.getDerivedIndicators(); - return new Promise((resolve, reject) => { - // check if it is a derived indicator - if (underscore.contains(derivedIndicators, reportParams.indicator)) { - let start = new Date(); - dao.getPatientCareStatusPatientListQuery(reportParams, - (results) => { - if (results.error) { - console.log(results.error); - reject(results); - } else { - results.duration = (new Date() - start) / 1000; - resolve(results); - } - - } - ); - } else { - let self = this; - let indicators = reportParams.indicator.split(','); - let locations = reportParams.locations.split(','); - reportParams.locations = locations; - console.log('Params', reportParams); - let report = new PatientlistMysqlReport('patintChangeStatusTrackerAggregate', reportParams); - try { - Promise.join(report.generatePatientListReport(indicators), - (result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - }).catch((errors) => { - console.log(errors) - reject(errors); - }); - } catch (error) { - console.log(error) - reject(error); - } - } - - }); - } - - // getPatientListReport(reportParams) { - // let self = this; - // let indicators = reportParams.indicator.split(','); - // let locations = reportParams.locations.split(','); - - // reportParams.locations = locations; - // console.log('Params', reportParams); - // let report = new PatientlistMysqlReport('patintChangeStatusTrackerAggregate', reportParams); - // return new Promise(function (resolve, reject) { - // try { - // Promise.join(report.generatePatientListReport(indicators), - // (result) => { - // let returnedResult = {}; - // returnedResult.schemas = result.schemas; - // returnedResult.sqlQuery = result.sqlQuery; - // returnedResult.result = result.results.results; - // resolve(returnedResult); - // }).catch((errors) => { - // console.log(errors) - // reject(errors); - // }); - // } catch (error) { - // console.log(error) - // reject(error); - // } - // }); - - // } + }); + } + + groupResultsByReportingMonth(data) { + let cumulativeAggr = data[0]; + let monthlyChangeAggr = data[1]; + cumulativeAggr.sql2 = monthlyChangeAggr.sql; + + _.each(cumulativeAggr.result, (cumulativeRow, i) => { + _.each(monthlyChangeAggr.result, (monthlyRow, j) => { + if (cumulativeRow.reporting_month === monthlyRow.reporting_month) { + cumulativeRow[monthlyRow.indicator] = monthlyRow.counts; + } + }); - getCumulativeAggregates(reportParams) { - return new Promise((resolve, reject) => { - reportParams.groupBy = 'groupByEndDate'; - let start = new Date(); - let report = new BaseMysqlReport("patintChangeStatusTrackerAggregate", reportParams.requestParams); - report.generateReport() - .then((results) => { - results.duration = (new Date() - start) / 1000; - results.size = results ? results.results.results.length : 0; - results.result = results ? results.results.results : []; - delete results['results']; - resolve(results); - } - ).catch((errors) => { - console.log(errors); - reject(errors); - }); + // clean data by adding missing indicators and negations + _.each(indicatorsKeys, (key, j) => { + _.each(indicatorsKeys, (key2, i) => { + if (!cumulativeRow[key + '_to_' + key2]) + cumulativeRow[key + '_to_' + key2] = 0; }); - } - - getMonthlyChangeAggregates(reportParams) { - return new Promise((resolve, reject) => { - reportParams.whereClause = ''; - let start = new Date(); - dao.getPatientCareStatusAggregatesQuery(reportParams, - (results) => { - if (results.error) { - reject(results); - } else { - results.duration = (new Date() - start) / 1000; - resolve(results); - } - - } - ); + }); + }); + return cumulativeAggr; + } + + getPatientListReport(reportParams) { + reportParams['reportName'] = 'patient-status-change-tracker-report'; + let derivedIndicators = this.getDerivedIndicators(); + return new Promise((resolve, reject) => { + // check if it is a derived indicator + if (underscore.contains(derivedIndicators, reportParams.indicator)) { + let start = new Date(); + dao.getPatientCareStatusPatientListQuery(reportParams, (results) => { + if (results.error) { + console.log(results.error); + reject(results); + } else { + results.duration = (new Date() - start) / 1000; + resolve(results); + } }); - } - - getDerivedIndicators() { - let indicators = []; - _.each(indicatorsKeys, (key, j) => { - _.each(indicatorsKeys, (key2, i) => { - indicators.push(key + '_to_' + key2); - }); + } else { + let self = this; + let indicators = reportParams.indicator.split(','); + let locations = reportParams.locations.split(','); + reportParams.locations = locations; + console.log('Params', reportParams); + let report = new PatientlistMysqlReport( + 'patintChangeStatusTrackerAggregate', + reportParams + ); + try { + Promise.join( + report.generatePatientListReport(indicators), + (result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + } + ).catch((errors) => { + console.log(errors); + reject(errors); + }); + } catch (error) { + console.log(error); + reject(error); + } + } + }); + } + + // getPatientListReport(reportParams) { + // let self = this; + // let indicators = reportParams.indicator.split(','); + // let locations = reportParams.locations.split(','); + + // reportParams.locations = locations; + // console.log('Params', reportParams); + // let report = new PatientlistMysqlReport('patintChangeStatusTrackerAggregate', reportParams); + // return new Promise(function (resolve, reject) { + // try { + // Promise.join(report.generatePatientListReport(indicators), + // (result) => { + // let returnedResult = {}; + // returnedResult.schemas = result.schemas; + // returnedResult.sqlQuery = result.sqlQuery; + // returnedResult.result = result.results.results; + // resolve(returnedResult); + // }).catch((errors) => { + // console.log(errors) + // reject(errors); + // }); + // } catch (error) { + // console.log(error) + // reject(error); + // } + // }); + + // } + + getCumulativeAggregates(reportParams) { + return new Promise((resolve, reject) => { + reportParams.groupBy = 'groupByEndDate'; + let start = new Date(); + let report = new BaseMysqlReport( + 'patintChangeStatusTrackerAggregate', + reportParams.requestParams + ); + report + .generateReport() + .then((results) => { + results.duration = (new Date() - start) / 1000; + results.size = results ? results.results.results.length : 0; + results.result = results ? results.results.results : []; + delete results['results']; + resolve(results); + }) + .catch((errors) => { + console.log(errors); + reject(errors); }); - return indicators; - - } - - runPostProcessing(results) { - return results; - } - + }); + } + + getMonthlyChangeAggregates(reportParams) { + return new Promise((resolve, reject) => { + reportParams.whereClause = ''; + let start = new Date(); + dao.getPatientCareStatusAggregatesQuery(reportParams, (results) => { + if (results.error) { + reject(results); + } else { + results.duration = (new Date() - start) / 1000; + resolve(results); + } + }); + }); + } + + getDerivedIndicators() { + let indicators = []; + _.each(indicatorsKeys, (key, j) => { + _.each(indicatorsKeys, (key2, i) => { + indicators.push(key + '_to_' + key2); + }); + }); + return indicators; + } + + runPostProcessing(results) { + return results; + } } diff --git a/service/patients-requiring-viral-load.service.js b/service/patients-requiring-viral-load.service.js index 2a6403b83..088560c44 100755 --- a/service/patients-requiring-viral-load.service.js +++ b/service/patients-requiring-viral-load.service.js @@ -1,56 +1,54 @@ const dao = require('../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const Moment = require('moment'); const _ = require('lodash'); -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report'; -import { - PatientlistMysqlReport -} from '../app/reporting-framework/patientlist-mysql.report'; +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; export class patientsRequiringVLService { - - getAggregateReport(reportParams) { - console.log('Getting agg') - let self = this; - let report = new BaseMysqlReport('labsReportAggregate', reportParams); - return new Promise(function (resolve, reject) { - try { - Promise.join(report.generateReport(), - (result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - //TODO Do some post processing - }).catch((errors) => { - console.error(errors); - reject(errors); - }); - } catch (error) { - console.error(errors); - } - + getAggregateReport(reportParams) { + console.log('Getting agg'); + let self = this; + let report = new BaseMysqlReport('labsReportAggregate', reportParams); + return new Promise(function (resolve, reject) { + try { + Promise.join(report.generateReport(), (result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + //TODO Do some post processing + }).catch((errors) => { + console.error(errors); + reject(errors); }); - } - getPatientListReport(reportParams) { - let self = this; - let locations = reportParams.locationUuids.split(','); - reportParams.locationUuids = locations; - return new Promise(function (resolve, reject) { - let report = new PatientlistMysqlReport('labsReportAggregate', reportParams) - //TODO: Do some pre processing - Promise.join(report.generatePatientListReport(['needs_vl_in_period']), - (result) => { - let returnedResult = {}; - returnedResult.schemas = result.schemas; - returnedResult.sqlQuery = result.sqlQuery; - returnedResult.result = result.results.results; - resolve(returnedResult); - }).catch((errors) => { - reject(errors); - }); - }); - } -} \ No newline at end of file + } catch (error) { + console.error(errors); + } + }); + } + getPatientListReport(reportParams) { + let self = this; + let locations = reportParams.locationUuids.split(','); + reportParams.locationUuids = locations; + return new Promise(function (resolve, reject) { + let report = new PatientlistMysqlReport( + 'labsReportAggregate', + reportParams + ); + //TODO: Do some pre processing + Promise.join( + report.generatePatientListReport(['needs_vl_in_period']), + (result) => { + let returnedResult = {}; + returnedResult.schemas = result.schemas; + returnedResult.sqlQuery = result.sqlQuery; + returnedResult.result = result.results.results; + resolve(returnedResult); + } + ).catch((errors) => { + reject(errors); + }); + }); + } +} diff --git a/service/prep-indicator-definitions.json b/service/prep-indicator-definitions.json index 15b1aa86e..1d4a57161 100644 --- a/service/prep-indicator-definitions.json +++ b/service/prep-indicator-definitions.json @@ -1,94 +1,94 @@ [ - { - "sectionTitle": "", - "indicators": [ - { - "label": "Location", - "indicator": "location" - } - ] - }, - { - "sectionTitle": "PrEP this month", - "indicators": [ - { - "label": "Active on PrEP", - "indicator": "active_on_prep_this_month" - }, - { - "label": "Newly Enrolled in PrEP", - "indicator": "enrolled_in_prep_this_month" - }, - { - "label": "Discontinued from PrEP", - "indicator": "prep_discontinued_this_month" - }, - { - "label": "Cumulative Discontinued from PrEP", - "indicator": "cumulative_prep_discontinued_this_month" - }, - { - "label": "PrEP LTFUs this month", - "indicator": "prep_ltfu_this_month" - }, - { - "label": "Cumulative PrEP LTFUs", - "indicator": "cumulative_prep_ltfu_this_month" - }, - { - "label": "Turned Positive this month", - "indicator": "turned_positive_this_month" - }, - { - "label": "Cumulative Turned Positive this month", - "indicator": "cumulative_turned_positive_this_month" - }, - { - "label": "HIV Rapid tests done this month", - "indicator": "has_hiv_rapid_test_this_month" - } - ] - }, - { - "sectionTitle": "Active on PrEP by Population Type", - "indicators": [ - { - "label": "Discordant Population", - "indicator": "dc__population_type__discordant__active_on_prep_this_month" - }, - { - "label": "Key Population", - "indicator": "dc__population_type__key__active_on_prep_this_month" - }, - { - "label": "General Population", - "indicator": "general_pop_active" - }, - { - "label": "Priority Population", - "indicator": "dc__population_type__priority__active_on_prep_this_month" - } - ] - }, - { - "sectionTitle": "Pregnancy and Breastfeeding", - "indicators": [ - { - "label": "Active & Pregnant", - "indicator": "dc__is_pregnant__is_pregnant__active_on_prep_this_month" - }, - { - "label": "Newly Enrolled & Pregnant", - "indicator": "dc__newly_enrolled_pregnant__is_pregnant__enrolled_in_prep_this_month" - }, - { - "label": "Active & BreastFeeding", - "indicator": "dc__is_breastfeeding__is_breastfeeding__active_on_prep_this_month" - }, - { - "label": "Newly Enrolled & BreastFeeding", - "indicator": "dc__newly_enrolled_breastfeeding__is_breastfeeding__enrolled_in_prep_this_month" - } - ] - } -] \ No newline at end of file + { + "sectionTitle": "", + "indicators": [ + { + "label": "Location", + "indicator": "location" + } + ] + }, + { + "sectionTitle": "PrEP this month", + "indicators": [ + { + "label": "Active on PrEP", + "indicator": "active_on_prep_this_month" + }, + { + "label": "Newly Enrolled in PrEP", + "indicator": "enrolled_in_prep_this_month" + }, + { + "label": "Discontinued from PrEP", + "indicator": "prep_discontinued_this_month" + }, + { + "label": "Cumulative Discontinued from PrEP", + "indicator": "cumulative_prep_discontinued_this_month" + }, + { + "label": "PrEP LTFUs this month", + "indicator": "prep_ltfu_this_month" + }, + { + "label": "Cumulative PrEP LTFUs", + "indicator": "cumulative_prep_ltfu_this_month" + }, + { + "label": "Turned Positive this month", + "indicator": "turned_positive_this_month" + }, + { + "label": "Cumulative Turned Positive this month", + "indicator": "cumulative_turned_positive_this_month" + }, + { + "label": "HIV Rapid tests done this month", + "indicator": "has_hiv_rapid_test_this_month" + } + ] + }, + { + "sectionTitle": "Active on PrEP by Population Type", + "indicators": [ + { + "label": "Discordant Population", + "indicator": "dc__population_type__discordant__active_on_prep_this_month" + }, + { + "label": "Key Population", + "indicator": "dc__population_type__key__active_on_prep_this_month" + }, + { + "label": "General Population", + "indicator": "general_pop_active" + }, + { + "label": "Priority Population", + "indicator": "dc__population_type__priority__active_on_prep_this_month" + } + ] + }, + { + "sectionTitle": "Pregnancy and Breastfeeding", + "indicators": [ + { + "label": "Active & Pregnant", + "indicator": "dc__is_pregnant__is_pregnant__active_on_prep_this_month" + }, + { + "label": "Newly Enrolled & Pregnant", + "indicator": "dc__newly_enrolled_pregnant__is_pregnant__enrolled_in_prep_this_month" + }, + { + "label": "Active & BreastFeeding", + "indicator": "dc__is_breastfeeding__is_breastfeeding__active_on_prep_this_month" + }, + { + "label": "Newly Enrolled & BreastFeeding", + "indicator": "dc__newly_enrolled_breastfeeding__is_breastfeeding__enrolled_in_prep_this_month" + } + ] + } +] diff --git a/service/prep-monthly-summary.service.js b/service/prep-monthly-summary.service.js index a783425e9..abfa9734f 100644 --- a/service/prep-monthly-summary.service.js +++ b/service/prep-monthly-summary.service.js @@ -1,110 +1,119 @@ -const Promise = require("bluebird"); +const Promise = require('bluebird'); const _ = require('lodash'); -import { - MultiDatasetPatientlistReport -} from '../app/reporting-framework/multi-dataset-patientlist.report.js'; +import { MultiDatasetPatientlistReport } from '../app/reporting-framework/multi-dataset-patientlist.report.js'; import ReportProcessorHelpersService from '../app/reporting-framework/report-processor-helpers.service'; const indicatorDefinitions = require('./prep-indicator-definitions.json'); var etlHelpers = require('../etl-helpers'); export class PrepMonthlySummaryService extends MultiDatasetPatientlistReport { - - constructor(reportName, params) { - if (params.isAggregated) { - params.excludeParam = ['location_id']; - params.joinColumnParam = 'join_location'; - } - - super(reportName, params) + constructor(reportName, params) { + if (params.isAggregated) { + params.excludeParam = ['location_id']; + params.joinColumnParam = 'join_location'; } - getAggregateReport(reportParams) { - const that = this; - return new Promise((resolve, reject) => { - super.generateReport(reportParams) - .then((results) => { - if (reportParams && reportParams.type === 'patient-list') { - resolve(results); - } else { - let finalResult = [] - const reportProcessorHelpersService = new ReportProcessorHelpersService(); - for (let result of results) { - if (result.report && result.report.reportSchemas && result.report.reportSchemas.main && - result.report.reportSchemas.main.transFormDirectives.joinColumn) { - finalResult = reportProcessorHelpersService - .joinDataSets(that.params[result.report.reportSchemas.main.transFormDirectives.joinColumnParam] || - result.report.reportSchemas.main.transFormDirectives.joinColumn, - finalResult, result.results.results.results); - - } - } - resolve({ - queriesAndSchemas: results, - result: finalResult, - sectionDefinitions: indicatorDefinitions, - indicatorDefinitions: [] - }); - - } - }) - .catch((error) => { - console.error('prep monthly report generation error: ', error); - reject(error); - }); + super(reportName, params); + } + getAggregateReport(reportParams) { + const that = this; + return new Promise((resolve, reject) => { + super + .generateReport(reportParams) + .then((results) => { + if (reportParams && reportParams.type === 'patient-list') { + resolve(results); + } else { + let finalResult = []; + const reportProcessorHelpersService = new ReportProcessorHelpersService(); + for (let result of results) { + if ( + result.report && + result.report.reportSchemas && + result.report.reportSchemas.main && + result.report.reportSchemas.main.transFormDirectives.joinColumn + ) { + finalResult = reportProcessorHelpersService.joinDataSets( + that.params[ + result.report.reportSchemas.main.transFormDirectives + .joinColumnParam + ] || + result.report.reportSchemas.main.transFormDirectives + .joinColumn, + finalResult, + result.results.results.results + ); + } + } + resolve({ + queriesAndSchemas: results, + result: finalResult, + sectionDefinitions: indicatorDefinitions, + indicatorDefinitions: [] + }); + } + }) + .catch((error) => { + console.error('prep monthly report generation error: ', error); + reject(error); }); - } - - generatePatientList(indicators) { - let self = this; - return new Promise((resolve, reject) => { - super.generatePatientListReport(indicators) - .then((results) => { - let indicatorLabels = self.getIndicatorSectionDefinitions(results.indicators, - indicatorDefinitions); - - results.indicators = indicatorLabels; + }); + } - if (results.result.length > 0) { - _.each(results.result, (item) => { - item.cur_prep_meds_names = etlHelpers.getARVNames(item.cur_prep_meds_names); - }); - } + generatePatientList(indicators) { + let self = this; + return new Promise((resolve, reject) => { + super + .generatePatientListReport(indicators) + .then((results) => { + let indicatorLabels = self.getIndicatorSectionDefinitions( + results.indicators, + indicatorDefinitions + ); - self.resolveLocationUuidsToName(self.params.locationUuids) - .then((locations) => { - results.locations = locations; - resolve(results); - }) - .catch((err) => { - resolve(results); - }); + results.indicators = indicatorLabels; - }) - .catch((err) => { - reject(results); - }); - - }); - } + if (results.result.length > 0) { + _.each(results.result, (item) => { + item.cur_prep_meds_names = etlHelpers.getARVNames( + item.cur_prep_meds_names + ); + }); + } - getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { - let results = []; - _.each(requestIndicators, function (requestIndicator) { - _.each(sectionDefinitions, function (sectionDefinition) { - _.each(sectionDefinition.indicators, function (indicator) { - if (indicator.indicator === requestIndicator) { - results.push(indicator); - } - }); + self + .resolveLocationUuidsToName(self.params.locationUuids) + .then((locations) => { + results.locations = locations; + resolve(results); + }) + .catch((err) => { + resolve(results); }); + }) + .catch((err) => { + reject(results); }); - return results; - } + }); + } - resolveLocationUuidsToName(uuids) { - return new Promise((resolve, reject) => { - dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { - resolve(loc); - }); + getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { + let results = []; + _.each(requestIndicators, function (requestIndicator) { + _.each(sectionDefinitions, function (sectionDefinition) { + _.each(sectionDefinition.indicators, function (indicator) { + if (indicator.indicator === requestIndicator) { + results.push(indicator); + } }); - } -} \ No newline at end of file + }); + }); + return results; + } + + resolveLocationUuidsToName(uuids) { + return new Promise((resolve, reject) => { + dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { + resolve(loc); + }); + }); + } +} diff --git a/service/radilogy-imaging.service.js b/service/radilogy-imaging.service.js index 93512020a..fb74edd42 100644 --- a/service/radilogy-imaging.service.js +++ b/service/radilogy-imaging.service.js @@ -1,10 +1,9 @@ /*jshint -W003, -W097, -W117, -W026 */ 'use strict'; -var - Promise = require('bluebird') - , config = require('../conf/config') - , curl = require('curlrequest'); +var Promise = require('bluebird'), + config = require('../conf/config'), + curl = require('curlrequest'); var rp = require('request-promise'); var _ = require('lodash'); var connection = require('../dao/connection/mysql-connection-service'); @@ -12,164 +11,159 @@ var authorizer = require('../authorization/etl-authorizer'); var squel = require('squel'); var definition = { - - getImagingResultsByPatientIdentifier:getImagingResultsByPatientIdentifier, - getRequestPromise:getRequestPromise, - getPatientImagesByPatientIdentifier:getPatientImagesByPatientIdentifier, - constructWadoUrl:constructWadoUrl, - postRadiologyImagingComments:postRadiologyImagingComments, - getAllPatientImages:getAllPatientImages - + getImagingResultsByPatientIdentifier: getImagingResultsByPatientIdentifier, + getRequestPromise: getRequestPromise, + getPatientImagesByPatientIdentifier: getPatientImagesByPatientIdentifier, + constructWadoUrl: constructWadoUrl, + postRadiologyImagingComments: postRadiologyImagingComments, + getAllPatientImages: getAllPatientImages }; var authorizationHeader = ''; module.exports = definition; -var wado ={}; - +var wado = {}; function getImagingResultsByPatientIdentifier(queryString) { - var resource = getRefpacsServerUrl(); - // resource.url = resource.url + '/' + queryString.id; - // console.log('CASE 111111'); - return getRequestPromise(queryString, resource); + var resource = getRefpacsServerUrl(); + // resource.url = resource.url + '/' + queryString.id; + // console.log('CASE 111111'); + return getRequestPromise(queryString, resource); } function getAllPatientImages(queryString) { - var resource = getRefpacsImagingStudyUrl(); - // console.log('CASE 2222222'); - return getRequestPromise(queryString, resource); - + var resource = getRefpacsImagingStudyUrl(); + // console.log('CASE 2222222'); + return getRequestPromise(queryString, resource); } -function getRequestPromise(queryString,resource) { - console.log('resource.apiKey',resource.apiKey); - console.log('resource.url',resource.url); - var options = { - uri: resource.url, - qs:queryString, - headers: { - 'User-Agent': 'Request-Promise', - 'authorization': authorizationHeader, - 'x-api-key': resource.apiKey - }, - json: true, - rejectUnauthorized: false, - requestCert: true - }; - var ret = rp(options); - return ret; +function getRequestPromise(queryString, resource) { + console.log('resource.apiKey', resource.apiKey); + console.log('resource.url', resource.url); + var options = { + uri: resource.url, + qs: queryString, + headers: { + 'User-Agent': 'Request-Promise', + authorization: authorizationHeader, + 'x-api-key': resource.apiKey + }, + json: true, + rejectUnauthorized: false, + requestCert: true + }; + var ret = rp(options); + return ret; } function getRefpacsServerUrl() { - var serverConfig = config.refpacs.locations[0]; - return { - url: serverConfig.host + config.refpacs.generalPath, - apiKey: serverConfig.apiKey - }; + var serverConfig = config.refpacs.locations[0]; + return { + url: serverConfig.host + config.refpacs.generalPath, + apiKey: serverConfig.apiKey + }; } function getRefpacsImagingStudyUrl() { - var serverConfigs = config.refpacs.locations[0]; - return { - url: serverConfigs.host + config.refpacs.imagesPath, - apiKey: serverConfigs.apiKey - }; + var serverConfigs = config.refpacs.locations[0]; + return { + url: serverConfigs.host + config.refpacs.imagesPath, + apiKey: serverConfigs.apiKey + }; } function postRadiologyImagingComments(payload) { - return new Promise(function (resolve, reject) { - connection.getServerConnection() - .then(function (conn) { - - var query = squel.insert() - .into('etl.radiology_comments') - .set('encounter_id', payload.encounterId) - .set('comments', payload.comments) - .set('thumbs', payload.thumbs) - .set('date_created', squel.fval('NOW()')) - .set('creator', getCurrentUserIdSquel()) - .set('voided', 0) - .toString(); - - conn.query(query, {}, function (err, rows, fields) { - console.log('rows',rows); - if (err) { - console.error(err); - reject('Error updating resource'); - } - else { - - resolve(rows); - - } - conn.release(); - }); - }) - .catch(function (err) { - reject('Error establishing connection to MySql Server'); - }); - -}); + return new Promise(function (resolve, reject) { + connection + .getServerConnection() + .then(function (conn) { + var query = squel + .insert() + .into('etl.radiology_comments') + .set('encounter_id', payload.encounterId) + .set('comments', payload.comments) + .set('thumbs', payload.thumbs) + .set('date_created', squel.fval('NOW()')) + .set('creator', getCurrentUserIdSquel()) + .set('voided', 0) + .toString(); + + conn.query(query, {}, function (err, rows, fields) { + console.log('rows', rows); + if (err) { + console.error(err); + reject('Error updating resource'); + } else { + resolve(rows); + } + conn.release(); + }); + }) + .catch(function (err) { + reject('Error establishing connection to MySql Server'); + }); + }); } - function getPatientImagesByPatientIdentifier(queryString) { - - var resource = getRefpacsImagingStudyUrl(); - resource.url = resource.url + '/' + queryString.id; - // console.log('CASE 3333333'); - return getRequestPromise(null, resource); + var resource = getRefpacsImagingStudyUrl(); + resource.url = resource.url + '/' + queryString.id; + // console.log('CASE 3333333'); + return getRequestPromise(null, resource); } function constructWadoUrl(load) { - - return new Promise(function (resolve, reject) { - try { - // console.log('Response', JSON.stringify(load)); - var studyUID; - var objectUID; - var seriesUID; - if (Array.isArray(load.series) && load.series.length > 0 ) { - studyUID = _.trimStart(load.uid, 'urn:oid:'); - objectUID = _.trimStart(load.series[0].instance[0].uid, 'urn:oid:'); - seriesUID = _.trimStart(load.series[0].uid, 'urn:oid:'); - } else if (Array.isArray(load.entry) && load.entry.length > 0 ) { - // console.log('Radiology load:',load.entry[0].resource); - // studyUID = _.trimStart(load.uid, 'urn:oid:'); - // studyUID = load.entry[0].resource.id; - // objectUID = _.trimStart(load.entry[0].resource.series[0].instance[0].uid, 'urn:oid:'); - // seriesUID = _.trimStart(load.entry[0].resource.series[0].uid, 'urn:oid:'); - throw new Error('Request to Radiology could be incorrect'); - } else { - throw new Error('Unknown Response from Radiology'); - } - var res = getImagesFromWado(studyUID,objectUID,seriesUID); - resolve(res); - } catch(err) { - console.log('An Error occured while accessing radiology server', err); - reject(err); - } - - }); + return new Promise(function (resolve, reject) { + try { + // console.log('Response', JSON.stringify(load)); + var studyUID; + var objectUID; + var seriesUID; + if (Array.isArray(load.series) && load.series.length > 0) { + studyUID = _.trimStart(load.uid, 'urn:oid:'); + objectUID = _.trimStart(load.series[0].instance[0].uid, 'urn:oid:'); + seriesUID = _.trimStart(load.series[0].uid, 'urn:oid:'); + } else if (Array.isArray(load.entry) && load.entry.length > 0) { + // console.log('Radiology load:',load.entry[0].resource); + // studyUID = _.trimStart(load.uid, 'urn:oid:'); + // studyUID = load.entry[0].resource.id; + // objectUID = _.trimStart(load.entry[0].resource.series[0].instance[0].uid, 'urn:oid:'); + // seriesUID = _.trimStart(load.entry[0].resource.series[0].uid, 'urn:oid:'); + throw new Error('Request to Radiology could be incorrect'); + } else { + throw new Error('Unknown Response from Radiology'); + } + var res = getImagesFromWado(studyUID, objectUID, seriesUID); + resolve(res); + } catch (err) { + console.log('An Error occured while accessing radiology server', err); + reject(err); + } + }); } function getCorrespondingImages(results) { - - console.log('results corresponding', results); - wado =results; - return results; - - + console.log('results corresponding', results); + wado = results; + return results; } -function getImagesFromWado(studyUID,objectUID,seriesUID) { - var serverConfigs = config.refpacs.imageHost; - var addr = serverConfigs + '/wado?requestType=WADO'; - var url = addr +'&studyUID=' +studyUID +'&objectUID=' +objectUID +'&seriesUID=' +seriesUID; - console.log('url---->>>>',url); - - return url +function getImagesFromWado(studyUID, objectUID, seriesUID) { + var serverConfigs = config.refpacs.imageHost; + var addr = serverConfigs + '/wado?requestType=WADO'; + var url = + addr + + '&studyUID=' + + studyUID + + '&objectUID=' + + objectUID + + '&seriesUID=' + + seriesUID; + console.log('url---->>>>', url); + + return url; } - function getCurrentUserIdSquel() { - return squel.select().field('MAX(user_id)') - .from('amrs.users').where('uuid = ?', authorizer.getUser().uuid); -} \ No newline at end of file + return squel + .select() + .field('MAX(user_id)') + .from('amrs.users') + .where('uuid = ?', authorizer.getUser().uuid); +} diff --git a/service/retention-appointment-tracing-service.js b/service/retention-appointment-tracing-service.js index 46db28446..2035b75f4 100644 --- a/service/retention-appointment-tracing-service.js +++ b/service/retention-appointment-tracing-service.js @@ -1,95 +1,93 @@ -const Promise = require("bluebird"); +const Promise = require('bluebird'); const _ = require('lodash'); var helpers = require('../etl-helpers'); -import { - MultiDatasetPatientlistReport -} from '../app/reporting-framework/multi-dataset-patientlist.report.js'; +import { MultiDatasetPatientlistReport } from '../app/reporting-framework/multi-dataset-patientlist.report.js'; import ReportProcessorHelpersService from '../app/reporting-framework/report-processor-helpers.service'; -import { - BaseMysqlReport -} from '../app/reporting-framework/base-mysql.report'; -import { - PatientlistMysqlReport -} from '../app/reporting-framework/patientlist-mysql.report'; +import { BaseMysqlReport } from '../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../app/reporting-framework/patientlist-mysql.report'; import * as retentionIndicators from '../app/reporting-framework/hiv/retention-adherence-indicators.json'; -const retentionSectionDefs = require('../app/reporting-framework/hiv/retention-report.json') +const retentionSectionDefs = require('../app/reporting-framework/hiv/retention-report.json'); export class RetentionAppointmentTracingService extends MultiDatasetPatientlistReport { + constructor(reportName, params) { + super(reportName, params); + } - constructor(reportName, params) { - super(reportName, params) - } - - generateReport(additionalParams) { - const that = this; - return new Promise((resolve, reject) => { - super.generateReport(additionalParams) - .then((results) => { - if (additionalParams && additionalParams.type === 'patient-list') { - resolve(results); - } else { - - let finalResult = [] - const reportProcessorHelpersService = new ReportProcessorHelpersService(); - for (let result of results) { - if (result.report && result.report.reportSchemas && result.report.reportSchemas.main && - result.report.reportSchemas.main.transFormDirectives.joinColumn) { - finalResult = reportProcessorHelpersService - .joinDataSets(that.params[result.report.reportSchemas.main.transFormDirectives.joinColumnParam] || - result.report.reportSchemas.main.transFormDirectives.joinColumn, - finalResult, result.results.results.results); - - } - } - - resolve({ - queriesAndSchemas: results, - result: finalResult, - sectionDefinitions:retentionSectionDefs, - indicatorDefinitions: [] - }); - } - }) - .catch((error) => { - console.error('Retention generation error: ', error); - reject(error); - }); - - }); - } - - getPatientListReport(reportParams) { - let self = this; - return new Promise((resolve, reject) => { - super.generatePatientListReport(indicators) - .then((results) => { - self.resolveLocationUuidsToName(self.params.locationUuids) - .then((locations) => { - results.locations = locations; - resolve(results); - }) - .catch((err) => { - resolve(results); - }); - - }) - .catch((err) => { - console.error('MOH patient list generation error', err); - reject(err); - }); - }); - } - - getIndicatorDefinitions(){ - return new Promise((resolve, reject) => { - - if(retentionIndicators['indicators']){ - resolve(retentionIndicators['indicators']); - }else{ - reject('Error: Retention Indicators not found'); + generateReport(additionalParams) { + const that = this; + return new Promise((resolve, reject) => { + super + .generateReport(additionalParams) + .then((results) => { + if (additionalParams && additionalParams.type === 'patient-list') { + resolve(results); + } else { + let finalResult = []; + const reportProcessorHelpersService = new ReportProcessorHelpersService(); + for (let result of results) { + if ( + result.report && + result.report.reportSchemas && + result.report.reportSchemas.main && + result.report.reportSchemas.main.transFormDirectives.joinColumn + ) { + finalResult = reportProcessorHelpersService.joinDataSets( + that.params[ + result.report.reportSchemas.main.transFormDirectives + .joinColumnParam + ] || + result.report.reportSchemas.main.transFormDirectives + .joinColumn, + finalResult, + result.results.results.results + ); + } } + resolve({ + queriesAndSchemas: results, + result: finalResult, + sectionDefinitions: retentionSectionDefs, + indicatorDefinitions: [] + }); + } }) + .catch((error) => { + console.error('Retention generation error: ', error); + reject(error); + }); + }); + } - } + getPatientListReport(reportParams) { + let self = this; + return new Promise((resolve, reject) => { + super + .generatePatientListReport(indicators) + .then((results) => { + self + .resolveLocationUuidsToName(self.params.locationUuids) + .then((locations) => { + results.locations = locations; + resolve(results); + }) + .catch((err) => { + resolve(results); + }); + }) + .catch((err) => { + console.error('MOH patient list generation error', err); + reject(err); + }); + }); + } -} \ No newline at end of file + getIndicatorDefinitions() { + return new Promise((resolve, reject) => { + if (retentionIndicators['indicators']) { + resolve(retentionIndicators['indicators']); + } else { + reject('Error: Retention Indicators not found'); + } + }); + } +} diff --git a/service/slack-service.js b/service/slack-service.js index 40bf8a83e..d46e0c42a 100755 --- a/service/slack-service.js +++ b/service/slack-service.js @@ -1,150 +1,167 @@ -const config = require('../conf/config') -const Promise = require("bluebird"); +const config = require('../conf/config'); +const Promise = require('bluebird'); const rp = require('request-promise'); export class SlackService { + getBaseUrl() { + var host = config.slackserver.host; + var port = config.slackserver.port; - getBaseUrl(){ - var host = config.slackserver.host; - var port = config.slackserver.port; + return host + ':' + port; + } + //post and get from a poc + postFeedbackToPoc(message) { + var url = this.getBaseUrl() + '/posttopoc'; + var options = { + method: 'POST', + uri: url, + body: { + name: message.name, + location: message.location, + phone: message.phone, + department: message.department, + message: message.message + }, + json: true + }; - return host + ':' + port; - } - //post and get from a poc - postFeedbackToPoc(message) { - var url = this.getBaseUrl() + '/posttopoc'; - var options = { - method: 'POST', - uri: url, - body: { - name: message.name, - location: message.location, - phone: message.phone, - department:message.department, - message: message.message - }, - json: true - }; - - return new Promise(function (resolve, reject) { - rp(options) - .then(function(parsedBody) { - resolve({ status: 'okay' }); - }).catch(function(err) { - console.log('Error:', err); - resolve({ status: err }); - }); + return new Promise(function (resolve, reject) { + rp(options) + .then(function (parsedBody) { + resolve({ status: 'okay' }); + }) + .catch(function (err) { + console.log('Error:', err); + resolve({ status: err }); }); - - } - getPocMessages(count, oldest) { - var geturl = this.getBaseUrl() + '/pocfeedback/' + count + '/' + oldest; - - return new Promise(function(resolve, reject) { - rp(geturl) - .then(function(data) { - resolve(data); - }).catch(function(err) { - console.log(err); - reject(err); - }); + }); + } + getPocMessages(count, oldest) { + var geturl = this.getBaseUrl() + '/pocfeedback/' + count + '/' + oldest; + + return new Promise(function (resolve, reject) { + rp(geturl) + .then(function (data) { + resolve(data); + }) + .catch(function (err) { + console.log(err); + reject(err); }); - } - postToChannels(message, channel) { - var url = this.getBaseUrl() + '/posttochannel'; - var options = { - method: 'POST', - uri: url, - body: { - name: message.name, - location: message.location, - phone: message.phone, - department:message.department, - message: message.message, - channel: channel - }, - json: true - }; - - return new Promise(function (resolve, reject) { - rp(options) - .then(function(parsedBody) { - resolve({ status: 'okay' }); - }).catch(function(err) { - console.log('Error:', err); - resolve({ status: err }); - }); + }); + } + postToChannels(message, channel) { + var url = this.getBaseUrl() + '/posttochannel'; + var options = { + method: 'POST', + uri: url, + body: { + name: message.name, + location: message.location, + phone: message.phone, + department: message.department, + message: message.message, + channel: channel + }, + json: true + }; + + return new Promise(function (resolve, reject) { + rp(options) + .then(function (parsedBody) { + resolve({ status: 'okay' }); + }) + .catch(function (err) { + console.log('Error:', err); + resolve({ status: err }); }); - - } - postToGroups(message, group) { - var url = this.getBaseUrl() + '/posttogroup'; - var options = { - method: 'POST', - uri: url, - body: { - name: message.name, - location: message.location, - phone: message.phone, - department:message.department, - message: message.message, - group: group - }, - json: true - }; - - return new Promise(function (resolve, reject) { - rp(options) - .then(function(parsedBody) { - resolve({ status: 'okay' }); - }).catch(function(err) { - console.log('Error:', err); - resolve({ status: err }); - }); + }); + } + postToGroups(message, group) { + var url = this.getBaseUrl() + '/posttogroup'; + var options = { + method: 'POST', + uri: url, + body: { + name: message.name, + location: message.location, + phone: message.phone, + department: message.department, + message: message.message, + group: group + }, + json: true + }; + + return new Promise(function (resolve, reject) { + rp(options) + .then(function (parsedBody) { + resolve({ status: 'okay' }); + }) + .catch(function (err) { + console.log('Error:', err); + resolve({ status: err }); }); - - } - getChannelMessages(count, oldest) { - var geturl = this.getBaseUrl() + '/channel-slackmessages/' + count + '/' + oldest; - - return new Promise(function(resolve, reject) { - rp(geturl) - .then(function(data) { - resolve(data); - }).catch(function(err) { - console.log(err); - reject(err); - }); + }); + } + getChannelMessages(count, oldest) { + var geturl = + this.getBaseUrl() + '/channel-slackmessages/' + count + '/' + oldest; + + return new Promise(function (resolve, reject) { + rp(geturl) + .then(function (data) { + resolve(data); + }) + .catch(function (err) { + console.log(err); + reject(err); }); - } + }); + } + + //get from particular group and channel + getFromChannel(channelname, count, oldest) { + var geturl = + this.getBaseUrl() + + '/channel-slackmessages/' + + channelname + + '/' + + count + + '/' + + oldest; - //get from particular group and channel - getFromChannel(channelname, count, oldest) { - var geturl = this.getBaseUrl() + '/channel-slackmessages/' + channelname + '/' + count + '/' + oldest; - - return new Promise(function(resolve, reject) { - rp(geturl) - .then(function(data) { - resolve(data); - }).catch(function(err) { - console.log(err); - reject(err); - }); + return new Promise(function (resolve, reject) { + rp(geturl) + .then(function (data) { + resolve(data); + }) + .catch(function (err) { + console.log(err); + reject(err); }); - } + }); + } + + getFromGroup(groupname, count, oldest) { + var geturl = + this.getBaseUrl() + + '/group-slackmessages/' + + groupname + + '/' + + count + + '/' + + oldest; - getFromGroup(groupname, count, oldest) { - var geturl = this.getBaseUrl() + '/group-slackmessages/' + groupname + '/' + count + '/' + oldest; - - return new Promise(function(resolve, reject) { - rp(geturl) - .then(function(data) { - resolve(data); - }).catch(function(err) { - console.log(err); - reject(err); - }); + return new Promise(function (resolve, reject) { + rp(geturl) + .then(function (data) { + resolve(data); + }) + .catch(function (err) { + console.log(err); + reject(err); }); - } - -} \ No newline at end of file + }); + } +} diff --git a/service/surge-reports/surge-daily-report-service.js b/service/surge-reports/surge-daily-report-service.js index 2c205fd46..5b9541065 100644 --- a/service/surge-reports/surge-daily-report-service.js +++ b/service/surge-reports/surge-daily-report-service.js @@ -1,63 +1,65 @@ const Promise = require('bluebird'); -import { - BaseMysqlReport -} from '../../app/reporting-framework/base-mysql.report'; -import { - PatientlistMysqlReport -} from '../../app/reporting-framework/patientlist-mysql.report'; +import { BaseMysqlReport } from '../../app/reporting-framework/base-mysql.report'; +import { PatientlistMysqlReport } from '../../app/reporting-framework/patientlist-mysql.report'; const reportSections = require('../../service/surge-reports/surge-daily-report.json'); var helpers = require('../../etl-helpers'); export class SurgeDailyReportService { - getAggregateReport(reportParams) { - if (reportParams.locationUuids) { - let locationUuids = reportParams.locationUuids ? reportParams.locationUuids.split(',') : []; - reportParams.locationUuids = locationUuids; - - } - return new Promise(function (resolve, reject) { - let report = new BaseMysqlReport('surgeDailyReport', reportParams); - Promise.join(report.generateReport(), - (results) => { - let result = results.results.results; - results.size = result ? result.length : 0; - results.result = result; - results.sectionDefinitions = reportSections; - delete results['results']; - resolve(results); - }).catch((errors) => { - console.error('Error', errors); - reject(errors); - }); - }); + getAggregateReport(reportParams) { + if (reportParams.locationUuids) { + let locationUuids = reportParams.locationUuids + ? reportParams.locationUuids.split(',') + : []; + reportParams.locationUuids = locationUuids; } + return new Promise(function (resolve, reject) { + let report = new BaseMysqlReport('surgeDailyReport', reportParams); + Promise.join(report.generateReport(), (results) => { + let result = results.results.results; + results.size = result ? result.length : 0; + results.result = result; + results.sectionDefinitions = reportSections; + delete results['results']; + resolve(results); + }).catch((errors) => { + console.error('Error', errors); + reject(errors); + }); + }); + } - getPatientListReport(reportParams) { - let indicators = reportParams.indicators ? reportParams.indicators.split(',') : []; - if (reportParams.locationUuids) { - let locationUuids = reportParams.locationUuids ? reportParams.locationUuids.split(',') : []; - reportParams.locationUuids = locationUuids; - - } - let report = new PatientlistMysqlReport('surgeDailyReport', reportParams); - return new Promise(function (resolve, reject) { - Promise.join(report.generatePatientListReport(indicators), - (results) => { - results.results.results.forEach((element) => { - if (element.arv_first_regimen_names) { - element.arv_first_regimen_names = helpers.getARVNames(element.arv_first_regimen_names); - } - if (element.cur_arv_meds_names) { - element.cur_arv_meds_names = helpers.getARVNames(element.cur_arv_meds_names); - } - if (element.cur_meds) { - element.cur_meds = helpers.getARVNames(element.cur_meds); - } - }) - resolve(results); - }).catch((errors) => { - console.error('Error', errors); - reject(errors); - }); - }); + getPatientListReport(reportParams) { + let indicators = reportParams.indicators + ? reportParams.indicators.split(',') + : []; + if (reportParams.locationUuids) { + let locationUuids = reportParams.locationUuids + ? reportParams.locationUuids.split(',') + : []; + reportParams.locationUuids = locationUuids; } -} \ No newline at end of file + let report = new PatientlistMysqlReport('surgeDailyReport', reportParams); + return new Promise(function (resolve, reject) { + Promise.join(report.generatePatientListReport(indicators), (results) => { + results.results.results.forEach((element) => { + if (element.arv_first_regimen_names) { + element.arv_first_regimen_names = helpers.getARVNames( + element.arv_first_regimen_names + ); + } + if (element.cur_arv_meds_names) { + element.cur_arv_meds_names = helpers.getARVNames( + element.cur_arv_meds_names + ); + } + if (element.cur_meds) { + element.cur_meds = helpers.getARVNames(element.cur_meds); + } + }); + resolve(results); + }).catch((errors) => { + console.error('Error', errors); + reject(errors); + }); + }); + } +} diff --git a/service/surge-reports/surge-daily-report.json b/service/surge-reports/surge-daily-report.json index b7fe49ea1..20eadd2b3 100644 --- a/service/surge-reports/surge-daily-report.json +++ b/service/surge-reports/surge-daily-report.json @@ -1,261 +1,261 @@ [ - { - "sectionTitle": "", - "indicators": [ - { - "label": "Locations", - "indicator": "location" - } - ] - }, - { - "sectionTitle": "Visits", - "indicators": [ - { - "label": "visits today", - "description": "All visits today", - "indicator": "visit_today" - }, - { - "label": "Scheduled today", - "description": "Patients scheduled today", - "indicator": "appointment_today" - }, - { - "label": "Honored visit", - "description": "scheduled patients who came for visits today", - "indicator": "scheduled_visit_today" - }, - { - "label": "Unscheduled early", - "description": "Patients who came earlier than their rtc date", - "indicator": "early_appointment_today" - }, - { - "label": "Unscheduled late", - "description": "Patients who came after their rtc date", - "indicator": "late_appointment_today" - }, - { - "label": "Missed appointments", - "description": "Patients who missed their appointments today", - "indicator": "missed_appointment_today" - } - ] - }, - { - "sectionTitle": "Client Disengagements", - "indicators": [ - { - "label": "All defaulters as of today", - "description": "All defaulters as of today", - "indicator": "defaulters_today" - }, - { - "label": "People who became LTFU today", - "description": "People who became LTFU today", - "indicator": "newly_ltfu_today" - }, - { - "label": "Peole reported dead today", - "description": "Peole reported dead today", - "indicator": "dead_today" - } - ] - }, - { - "sectionTitle": "LTFU Outcomes today(Surge LTFUs)", - "indicators": [ - { - "label": "Total Otcomes", - "description": "surge LTFUs brought back, transfered out or those who are confirmed dead today", - "indicator": "ltfu_outcome_total_today" - }, - { - "label": "Brought To Care ", - "description": "Surge LTFUs who were brought back to care today", - "indicator": "ltfu_active_today" - }, - { - "label": "Reported transfered out", - "description": "Surge LTFUs that have been transfered to another clinic today", - "indicator": "ltfu_transfer_out_today" - }, - { - "label": "Reported dead", - "description": "Surge LTFUs that are confirmed dead today", - "indicator": "ltfu_death_today" - } - ] - }, - { - "sectionTitle": "Viral Load today", - "indicators": [ - { - "label": "Active and Eligible for VL", - "description": "Active and Eligible for VL this week", - "indicator": "due_for_vl_today_active" - }, - { - "label": "Scheduled and Eligible for VL", - "description": "Sheduled and Due for VL", - "indicator": "scheduled_today_and_due_for_vl" - }, - { - "label": "Unsheduled and Eligible for VL", - "description": "Unsheduled and Due for VL", - "indicator": "unscheduled_today_and_due_for_vl" - }, - { - "label": "Eligible for VL with VL order", - "description": "Eligible for VL with VL order", - "indicator": "due_for_vl_today_has_vl_order" - }, - { - "label": "Eligible for VL without VL order", - "description": "Eligible for VL without VL order", - "indicator": "due_for_vl_today_dont_have_order" - }, - { - "label": "VL resulted this week", - "description": "VL resulted this week", - "indicator": "has_vl_today" - }, - { - "label": "Has VL and Suppressed cumulative (<400 copies)", - "description": "Has VL and Suppressed cumulative", - "indicator": "is_suppressed_active" - }, - { - "label": "Has VL and Unsuppressed cumulative (>400 copies)", - "description": "Has VL and Unsuppressed cumulative", - "indicator": "is_unsuppressed_active" - } - ] - }, - { - "sectionTitle": "Differentiated Care(DC)", - "indicators": [ - { - "label": "Active on DC as of this week", - "description": "Active on DC as of this week", - "indicator": "on_dc_today" - }, - { - "label": "DC eligible total (on DC and those not on DC)", - "description": "DC eligible as of this week", - "indicator": "elligible_total" - }, - { - "label": "DC eligible and on dc", - "description": "DC eligible as of this week", - "indicator": "eligible_and_on_dc" - }, - { - "label": "DC eligible and not dc", - "description": "DC eligible as of this week", - "indicator": "eligible_not_on_dc" - }, - { - "label": "DC eligible and not on dc scheduled", - "description": "DC eligible as of this week", - "indicator": "eligible_not_on_dc_and_appointment_today" - }, - { - "label": "DC eligible and not on dc unscheduled", - "description": "DC eligible as of this week", - "indicator": "eligible_not_on_dc_and_unscheduled_today" - }, - { - "label": "DC eligible and on dc scheduled", - "description": "DC eligible as of this week", - "indicator": "eligible_and_on_dc_and_appointment_today" - }, - { - "label": "DC eligible and on dc unscheduled", - "description": "DC eligible as of this week", - "indicator": "eligible_and_on_dc_and_unscheduled_today" - }, - { - "label": "Enrolled to DC this week", - "description": "Enrolled to DC this week", - "indicator": "started_dc_today" - } - ] - }, - { - "sectionTitle": "ART", - "indicators": [ - { - "label": "Enrolled today", - "description": "enrolled today", - "indicator": "enrolled_today" - }, - { - "label": "Started ART today", - "description": "Started ART today", - "indicator": "started_art_today" - }, - { - "label": "ART revisit today", - "description": "ART revisit today", - "indicator": "art_revisit_today" - }, - { - "label": "Transfer in today", - "description": "Transfer in today", - "indicator": "transfer_in_today" - }, - { - "label": "Transfer out today", - "description": "Transfer out today", - "indicator": "transfer_out_today" - } - ] - }, - { - "sectionTitle": "Second Visit for New on ART (TX_SV)", - "indicators": [ - { - "label": "Scheduled second visit", - "description": "Scheduled second visit", - "indicator": "tx2_appointment_today" - }, - { - "label": "Honored Second visit", - "description": "Honored Second visit", - "indicator": "tx2_appointment_honored" - }, - { - "label": "ART second visit today", - "description": "ART second visit today", - "indicator": "tx2_visit_today" - }, - { - "label": "Unscheduled second visit today", - "description": "Unscheduled second visit today", - "indicator": "tx2_unscheduled_today" - }, - { - "label": "Missed ART second visit today", - "description": "Missed ART second visit ", - "indicator": "tx2_appointment_missed" - } - ] - }, - { - "sectionTitle": "Interventions", - "indicators": [ - { - "label": "Total interventions", - "description": "Pinterventions", - "indicator": "interventions" - }, - { - "label": "Intervention done today", - "description": "intervention done today", - "indicator": "intervention_done_today" - } - ] - } -] \ No newline at end of file + { + "sectionTitle": "", + "indicators": [ + { + "label": "Locations", + "indicator": "location" + } + ] + }, + { + "sectionTitle": "Visits", + "indicators": [ + { + "label": "visits today", + "description": "All visits today", + "indicator": "visit_today" + }, + { + "label": "Scheduled today", + "description": "Patients scheduled today", + "indicator": "appointment_today" + }, + { + "label": "Honored visit", + "description": "scheduled patients who came for visits today", + "indicator": "scheduled_visit_today" + }, + { + "label": "Unscheduled early", + "description": "Patients who came earlier than their rtc date", + "indicator": "early_appointment_today" + }, + { + "label": "Unscheduled late", + "description": "Patients who came after their rtc date", + "indicator": "late_appointment_today" + }, + { + "label": "Missed appointments", + "description": "Patients who missed their appointments today", + "indicator": "missed_appointment_today" + } + ] + }, + { + "sectionTitle": "Client Disengagements", + "indicators": [ + { + "label": "All defaulters as of today", + "description": "All defaulters as of today", + "indicator": "defaulters_today" + }, + { + "label": "People who became LTFU today", + "description": "People who became LTFU today", + "indicator": "newly_ltfu_today" + }, + { + "label": "Peole reported dead today", + "description": "Peole reported dead today", + "indicator": "dead_today" + } + ] + }, + { + "sectionTitle": "LTFU Outcomes today(Surge LTFUs)", + "indicators": [ + { + "label": "Total Otcomes", + "description": "surge LTFUs brought back, transfered out or those who are confirmed dead today", + "indicator": "ltfu_outcome_total_today" + }, + { + "label": "Brought To Care ", + "description": "Surge LTFUs who were brought back to care today", + "indicator": "ltfu_active_today" + }, + { + "label": "Reported transfered out", + "description": "Surge LTFUs that have been transfered to another clinic today", + "indicator": "ltfu_transfer_out_today" + }, + { + "label": "Reported dead", + "description": "Surge LTFUs that are confirmed dead today", + "indicator": "ltfu_death_today" + } + ] + }, + { + "sectionTitle": "Viral Load today", + "indicators": [ + { + "label": "Active and Eligible for VL", + "description": "Active and Eligible for VL this week", + "indicator": "due_for_vl_today_active" + }, + { + "label": "Scheduled and Eligible for VL", + "description": "Sheduled and Due for VL", + "indicator": "scheduled_today_and_due_for_vl" + }, + { + "label": "Unsheduled and Eligible for VL", + "description": "Unsheduled and Due for VL", + "indicator": "unscheduled_today_and_due_for_vl" + }, + { + "label": "Eligible for VL with VL order", + "description": "Eligible for VL with VL order", + "indicator": "due_for_vl_today_has_vl_order" + }, + { + "label": "Eligible for VL without VL order", + "description": "Eligible for VL without VL order", + "indicator": "due_for_vl_today_dont_have_order" + }, + { + "label": "VL resulted this week", + "description": "VL resulted this week", + "indicator": "has_vl_today" + }, + { + "label": "Has VL and Suppressed cumulative (<400 copies)", + "description": "Has VL and Suppressed cumulative", + "indicator": "is_suppressed_active" + }, + { + "label": "Has VL and Unsuppressed cumulative (>400 copies)", + "description": "Has VL and Unsuppressed cumulative", + "indicator": "is_unsuppressed_active" + } + ] + }, + { + "sectionTitle": "Differentiated Care(DC)", + "indicators": [ + { + "label": "Active on DC as of this week", + "description": "Active on DC as of this week", + "indicator": "on_dc_today" + }, + { + "label": "DC eligible total (on DC and those not on DC)", + "description": "DC eligible as of this week", + "indicator": "elligible_total" + }, + { + "label": "DC eligible and on dc", + "description": "DC eligible as of this week", + "indicator": "eligible_and_on_dc" + }, + { + "label": "DC eligible and not dc", + "description": "DC eligible as of this week", + "indicator": "eligible_not_on_dc" + }, + { + "label": "DC eligible and not on dc scheduled", + "description": "DC eligible as of this week", + "indicator": "eligible_not_on_dc_and_appointment_today" + }, + { + "label": "DC eligible and not on dc unscheduled", + "description": "DC eligible as of this week", + "indicator": "eligible_not_on_dc_and_unscheduled_today" + }, + { + "label": "DC eligible and on dc scheduled", + "description": "DC eligible as of this week", + "indicator": "eligible_and_on_dc_and_appointment_today" + }, + { + "label": "DC eligible and on dc unscheduled", + "description": "DC eligible as of this week", + "indicator": "eligible_and_on_dc_and_unscheduled_today" + }, + { + "label": "Enrolled to DC this week", + "description": "Enrolled to DC this week", + "indicator": "started_dc_today" + } + ] + }, + { + "sectionTitle": "ART", + "indicators": [ + { + "label": "Enrolled today", + "description": "enrolled today", + "indicator": "enrolled_today" + }, + { + "label": "Started ART today", + "description": "Started ART today", + "indicator": "started_art_today" + }, + { + "label": "ART revisit today", + "description": "ART revisit today", + "indicator": "art_revisit_today" + }, + { + "label": "Transfer in today", + "description": "Transfer in today", + "indicator": "transfer_in_today" + }, + { + "label": "Transfer out today", + "description": "Transfer out today", + "indicator": "transfer_out_today" + } + ] + }, + { + "sectionTitle": "Second Visit for New on ART (TX_SV)", + "indicators": [ + { + "label": "Scheduled second visit", + "description": "Scheduled second visit", + "indicator": "tx2_appointment_today" + }, + { + "label": "Honored Second visit", + "description": "Honored Second visit", + "indicator": "tx2_appointment_honored" + }, + { + "label": "ART second visit today", + "description": "ART second visit today", + "indicator": "tx2_visit_today" + }, + { + "label": "Unscheduled second visit today", + "description": "Unscheduled second visit today", + "indicator": "tx2_unscheduled_today" + }, + { + "label": "Missed ART second visit today", + "description": "Missed ART second visit ", + "indicator": "tx2_appointment_missed" + } + ] + }, + { + "sectionTitle": "Interventions", + "indicators": [ + { + "label": "Total interventions", + "description": "Pinterventions", + "indicator": "interventions" + }, + { + "label": "Intervention done today", + "description": "intervention done today", + "indicator": "intervention_done_today" + } + ] + } +] diff --git a/service/surge-reports/surge-indicators-config.json b/service/surge-reports/surge-indicators-config.json index b425171b4..8ef734d7a 100644 --- a/service/surge-reports/surge-indicators-config.json +++ b/service/surge-reports/surge-indicators-config.json @@ -1,95 +1,93 @@ { - "reportSchemas": [ - { - "reportName" : "surgeReport", - "indicators": [ - "visit_this_week", - "scheduled_this_week", - "on_schedule_this_week", - "unscheduled_this_week", - "early_appointment_this_week", - "late_appointment_this_week", - "missed_appointment_this_week", - "defaulted", - "surge_ltfu_and_still_ltfu", - "is_ltfu_after_may", - "surge_ltfu_and_ltfu_after_may", - "newly_ltfu_this_week", - "due_for_vl_has_vl_order_unscheduled", - "due_for_vl_dont_have_order_unscheduled", - "defaulter_to_active_this_week", - "missed_to_active_this_week", - "has_vl_this_week_and_suppressed", - "has_vl_this_week_and_unsuppressed", - "due_for_vl_has_vl_order_scheduled", - "due_for_vl_dont_have_order_scheduled", - "elligible_total_revised", - "tx2_scheduled_this_week_but_came_early", - "cumulative_dead", - "is_ltfu_after_may_total", - "dead_this_week", - "ltfu_cumulative_outcomes_total", - "ltfu_cumulative_outcomes_active", - "ltfu_cumulative_outcomes_transfer_out", - "ltfu_cumulative_outcomes_death", - "ltfu_active_this_week", - "ltfu_transfer_out_this_week", - "ltfu_death_this_week", - "old_ltfus_to_active", - "old_ltfus_to_active_this_week", - "overdue_for_vl_active", - "scheduled_this_week_and_due_for_vl", - "unscheduled_this_week_and_due_for_vl", - "due_for_vl_has_vl_order", - "due_for_vl_dont_have_order", - "has_vl_this_week", - "is_suppressed", - "is_un_suppressed", - "active_on_dc", - "elligible_total", - "eligible_and_on_dc", - "eligible_not_on_dc", - "eligible_not_on_dc_and_scheduled_this_week", - "eligible_not_on_dc_and_unscheduled_this_week", - "eligible_and_on_dc_and_scheduled_this_week", - "eligible_and_on_dc_and_unscheduled_this_week", - "started_dc_this_week", - "enrolled_this_week", - "started_art_this_week", - "art_revisit_this_week", - "transfer_in_this_week", - "transfer_out_this_week", - "tx2_scheduled_this_week", - "tx2_scheduled_honored", - "tx2_visit_this_week", - "tx2_unscheduled_this_week", - "missed_tx2_visit_this_week", - "interventions", - "intervention_done_this_week", - "med_surge_ltfus_cumulative", - "med_surge_ltfus_outcomes", - "med_surge_ltfu_and_med_ltfu_after_may", - "med_defaulters", - "newly_med_ltfu_this_week", - "all_ltfus" - ] - }, - { - "reportName" : "prepReport", - "indicators": [ - "active_on_prep_this_week", - "enrolled_in_prep_this_week", - "prep_ltfu_this_week", - "prep_discontinued_this_week", - "prep_defaulter_this_week", - "prev_on_prep_and_turned_positive" - ] - }, - { - "reportName" : "surgeBaselineReport", - "indicators": [ - "is_ltfu_surge_baseline" - ] - } - ] -} \ No newline at end of file + "reportSchemas": [ + { + "reportName": "surgeReport", + "indicators": [ + "visit_this_week", + "scheduled_this_week", + "on_schedule_this_week", + "unscheduled_this_week", + "early_appointment_this_week", + "late_appointment_this_week", + "missed_appointment_this_week", + "defaulted", + "surge_ltfu_and_still_ltfu", + "is_ltfu_after_may", + "surge_ltfu_and_ltfu_after_may", + "newly_ltfu_this_week", + "due_for_vl_has_vl_order_unscheduled", + "due_for_vl_dont_have_order_unscheduled", + "defaulter_to_active_this_week", + "missed_to_active_this_week", + "has_vl_this_week_and_suppressed", + "has_vl_this_week_and_unsuppressed", + "due_for_vl_has_vl_order_scheduled", + "due_for_vl_dont_have_order_scheduled", + "elligible_total_revised", + "tx2_scheduled_this_week_but_came_early", + "cumulative_dead", + "is_ltfu_after_may_total", + "dead_this_week", + "ltfu_cumulative_outcomes_total", + "ltfu_cumulative_outcomes_active", + "ltfu_cumulative_outcomes_transfer_out", + "ltfu_cumulative_outcomes_death", + "ltfu_active_this_week", + "ltfu_transfer_out_this_week", + "ltfu_death_this_week", + "old_ltfus_to_active", + "old_ltfus_to_active_this_week", + "overdue_for_vl_active", + "scheduled_this_week_and_due_for_vl", + "unscheduled_this_week_and_due_for_vl", + "due_for_vl_has_vl_order", + "due_for_vl_dont_have_order", + "has_vl_this_week", + "is_suppressed", + "is_un_suppressed", + "active_on_dc", + "elligible_total", + "eligible_and_on_dc", + "eligible_not_on_dc", + "eligible_not_on_dc_and_scheduled_this_week", + "eligible_not_on_dc_and_unscheduled_this_week", + "eligible_and_on_dc_and_scheduled_this_week", + "eligible_and_on_dc_and_unscheduled_this_week", + "started_dc_this_week", + "enrolled_this_week", + "started_art_this_week", + "art_revisit_this_week", + "transfer_in_this_week", + "transfer_out_this_week", + "tx2_scheduled_this_week", + "tx2_scheduled_honored", + "tx2_visit_this_week", + "tx2_unscheduled_this_week", + "missed_tx2_visit_this_week", + "interventions", + "intervention_done_this_week", + "med_surge_ltfus_cumulative", + "med_surge_ltfus_outcomes", + "med_surge_ltfu_and_med_ltfu_after_may", + "med_defaulters", + "newly_med_ltfu_this_week", + "all_ltfus" + ] + }, + { + "reportName": "prepReport", + "indicators": [ + "active_on_prep_this_week", + "enrolled_in_prep_this_week", + "prep_ltfu_this_week", + "prep_discontinued_this_week", + "prep_defaulter_this_week", + "prev_on_prep_and_turned_positive" + ] + }, + { + "reportName": "surgeBaselineReport", + "indicators": ["is_ltfu_surge_baseline"] + } + ] +} diff --git a/service/surge-reports/surge-multi-dataset-patientlist.report.js b/service/surge-reports/surge-multi-dataset-patientlist.report.js index abe2d00e5..977832487 100644 --- a/service/surge-reports/surge-multi-dataset-patientlist.report.js +++ b/service/surge-reports/surge-multi-dataset-patientlist.report.js @@ -2,37 +2,41 @@ import { Promise } from 'bluebird'; import { MultiDatasetReport } from '../../app/reporting-framework/multi-dataset.report'; export class SurgeMultiDatasetPatientlistReport extends MultiDatasetReport { - - constructor(reportName, params) { - super(reportName, params); - } - generatePatientListReport(indicators) { - let additionalParams = { - type: 'patient-list', - indicators: indicators - }; - let that = this; - return new Promise((resolve, reject) => { - this.generateReport(additionalParams). - then((results) => { - for (let i = 0; i < results.length; i++) { - if (results[i].results && results[i].results.results && results[i].results.results.results) { - resolve({ - result: results[i].results.results.results, - queriesAndSchemas: results[i], - indicators: indicators, - size: that.params.limit, - startIndex: that.params.startIndex, - allResults: results - }); - break; - } - } - reject('Patientlist error:', results); - }).catch((err) => { - console.error('Patientlist Error', err); - reject(err); - }); + constructor(reportName, params) { + super(reportName, params); + } + generatePatientListReport(indicators) { + let additionalParams = { + type: 'patient-list', + indicators: indicators + }; + let that = this; + return new Promise((resolve, reject) => { + this.generateReport(additionalParams) + .then((results) => { + for (let i = 0; i < results.length; i++) { + if ( + results[i].results && + results[i].results.results && + results[i].results.results.results + ) { + resolve({ + result: results[i].results.results.results, + queriesAndSchemas: results[i], + indicators: indicators, + size: that.params.limit, + startIndex: that.params.startIndex, + allResults: results + }); + break; + } + } + reject('Patientlist error:', results); + }) + .catch((err) => { + console.error('Patientlist Error', err); + reject(err); }); - } + }); + } } diff --git a/service/surge-reports/surge-report.json b/service/surge-reports/surge-report.json index 99185bf78..53efe97b7 100644 --- a/service/surge-reports/surge-report.json +++ b/service/surge-reports/surge-report.json @@ -1,386 +1,386 @@ [ - { - "sectionTitle": "", - "indicators": [ - { - "label": "Locations", - "indicator": "location" - } - ] - }, - { - "sectionTitle": "Visits", - "indicators": [ - { - "label": "Visit this week", - "description": "All patients who came for visits this week including scheduled and unscheduled", - "indicator": "visit_this_week" - }, - { - "label": "Scheduled this week", - "description": "Patients scheduled this week", - "indicator": "scheduled_this_week" - }, - { - "label": "Honored visit", - "description": "Patients scheduled this week and came for their visit", - "indicator": "on_schedule_this_week" - }, - { - "label": "Unscheduled early", - "description": "Patients who came this week for their visit which earlier than the week of their rtc", - "indicator": "early_appointment_this_week" - }, - { - "label": "Unscheduled late", - "description": "Patients who came this week for their visit which later than the week of their rtc", - "indicator": "late_appointment_this_week" - }, - { - "label": "Transfer in this week", - "description": "Transfer in this week", - "indicator": "transfer_in_this_week" - }, - { - "label": "Transfer out this week", - "description": "Transfer out this week", - "indicator": "transfer_out_this_week" - } - ] - }, - { - "sectionTitle": "Client Disengagements", - "indicators": [ - { - "label": "Cumulative LTFUs (All LTFUs)", - "description": "All patients who have missed their rtc more than 28 days", - "indicator": "all_ltfus" - }, - { - "label": "Cumulative Surge LTFUs (LTFUs as from 30th Sep 2019)", - "description": "All patients who became LTFUs as from 30th Sep 2019 including those who have been resolved", - "indicator": "is_ltfu_after_may_total" - }, - { - "label": "Target to bring back this week (LTFUs as from 30th Sep 2019 not yet resolved)", - "description": "All patients who became LTFUs as from 30th Sep 2019 and have not been resolved", - "indicator": "is_ltfu_after_may" - }, - { - "label": "Cumulative Medication refill LTFUs(Missed medication pickup rtc for more that 28 days)", - "description": "All patients who have missed their medication pickup rtc for more that 28 days as from 30th September 2019 to now, including those with outcomes already", - "indicator": "med_surge_ltfus_cumulative" - }, - { - "label": "Medication refill LTFUs not yet resolved", - "description": "All patients who have missed their medication pickup rtc for more that 28 days as from 30th September 2019 to now and have not been resolved yet", - "indicator": "med_surge_ltfu_and_med_ltfu_after_may" - }, - { - "label": "Missed appintments this week (0 - 4 days)", - "description": "Patients who missed their appointments this week ", - "indicator": "missed_appointment_this_week" - }, - { - "label": "Last week missed that have returned", - "description": "All patients who had missed their appointments last week and have returned this week", - "indicator": "missed_to_active_this_week" - }, - { - "label": "All Defaulters as of this week (5 - 28 days)", - "description": "Patients who have missed their rtc date between 5 and 28 days", - "indicator": "defaulted" - }, - { - "label": "Last week defaulters that have returned", - "description": "All patients who were defaulters by last week and have returned this week", - "indicator": "defaulter_to_active_this_week" - }, - { - "label": "Medication refill Defaulters as of this week (Missed medication pickup rtc 5 - 28 days)", - "description": "Patients who have missed their medication pickup rtc date between 5 and 28 days", - "indicator": "med_defaulters" - }, - { - "label": "LTFUs this week (patients who bacame LTFU this week)", - "description": "Patients who became LTFU this week", - "indicator": "newly_ltfu_this_week" - }, - { - "label": "Medication refill LTFUs this week(Missed medication pickup rtc date more than 28 days this week)", - "description": "Patients who have missed their medication pickup rtc date for more than 28 days this week", - "indicator": "newly_med_ltfu_this_week" - }, - { - "label": "All dead patients after may", - "description": "All dead patients afetr may 12th", - "indicator": "cumulative_dead" - }, - { - "label": "Dead this week", - "description": "All patients who died this week", - "indicator": "dead_this_week" - } - ] - }, - { - "sectionTitle": "LTFU Outcomes this week(Surge LTFUs)", - "indicators": [ - { - "label": "Brought back to care", - "description": "Patients in the target to bring back this week and have been brought back this week", - "indicator": "ltfu_active_this_week" - }, - { - "label": "Reported self transfered", - "description": "Patients in the target to bring back this week and have been reported self transfered this week", - "indicator": "ltfu_transfer_out_this_week" - }, - { - "label": "Reported dead", - "description": "Patients in the target to bring back this week and have been reported dead this week", - "indicator": "ltfu_death_this_week" - }, - { - "label": "Medication refill brought back this week", - "description": "Medication refill LTFUs that have been brought back this week", - "indicator": "med_surge_ltfus_outcomes_this_week" - } - ] - }, - { - "sectionTitle": "LTFU cumulative outcome(Surge LTFUs)", - "indicators": [ - { - "label": "Cumulative Outcomes (brought back, self transfers and dead)", - "description": "surge LTFUs brought back, transfered out or those who are confirmed dead", - "indicator": "ltfu_cumulative_outcomes_total" - }, - { - "label": "Brought back to care cumulative", - "description": "Total Surge LTFUs who were brought back to care", - "indicator": "ltfu_cumulative_outcomes_active" - }, - { - "label": "Reported self transfered cumulative", - "description": "Total Surge LTFUs that have been reported self transfered", - "indicator": "ltfu_cumulative_outcomes_transfer_out" - }, - { - "label": "Reported dead cumulative", - "description": "Total Surge LTFUs that have been confirmed dead", - "indicator": "ltfu_cumulative_outcomes_death" - }, - { - "label": "Cumulative medication refill brought back", - "description": "All medication refill LTFUs that have been brought back", - "indicator": "med_surge_ltfus_outcomes" - } - ] - }, - { - "sectionTitle": "LTFU Outcomes (clients lost before october 2019)", - "indicators": [ - { - "label": "Returnees cumulative", - "description": "Patients who were LTFU before october 2019 and have returned", - "indicator": "old_ltfus_to_active" - }, - { - "label": "Returnees this week", - "description": "Patients who were LTFU before october 2019 and have returned this week", - "indicator": "old_ltfus_to_active_this_week" - } - ] - }, - { - "sectionTitle": "Viral Load", - "indicators": [ - { - "label": "Active and Due for VL as of this week", - "description": "Patients overdue for VL", - "indicator": "overdue_for_vl_active" - }, - { - "label": "Scheduled and Due for VL ", - "description": "Sheduled this week and overdue for VL", - "indicator": "scheduled_this_week_and_due_for_vl" - }, - { - "label": "Scheduled and Due for VL with order", - "description": "Sheduled this week, overdue for VL and have VL order", - "indicator": "due_for_vl_has_vl_order_scheduled" - }, - { - "label": "Scheduled and Due for VL without order", - "description": "Sheduled this week, overdue for VL and don't have VL order", - "indicator": "due_for_vl_dont_have_order_scheduled" - }, - { - "label": "Due for VL and not scheduled this week", - "description": "Overdue for VL but RTC date not this week", - "indicator": "unscheduled_this_week_and_due_for_vl" - }, - { - "label": "Due for VL and not scheduled this week with VL order", - "description": "Overdue for VL, RTC date not this week, have VL order", - "indicator": "due_for_vl_has_vl_order_unscheduled" - }, - { - "label": "Due for VL and not scheduled this week without VL order", - "description": "Overdue for VL, RTC date not this week, without VL order", - "indicator": "due_for_vl_dont_have_order_unscheduled" - }, - { - "label": "VL resulted ", - "description": "All patients who have VL results", - "indicator": "has_vl_this_week" - }, - { - "label": "VL resulted and suppressed", - "description": "VL resulted this week and suppressed (<400 copies)", - "indicator": "has_vl_this_week_and_suppressed" - }, - { - "label": "VL resulted and not suppressed", - "description": "VL resulted this week and unsuppressed (>400 copies)", - "indicator": "has_vl_this_week_and_unsuppressed" - }, - { - "label": "Has VL and Suppressed cumulative(<400 copies)", - "description": "All active patients who are suppressed", - "indicator": "is_suppressed" - }, - { - "label": "Has VL and Unsuppressed cumulative(>400 copies)", - "description": "All active patients who are unsuppressed", - "indicator": "is_un_suppressed" - } - ] - }, - { - "sectionTitle": "Differentiated Care(DC)", - "indicators": [ - { - "label": "Total eligible for DC", - "description": "Includes both patients on DC and still eligible and those eligible but not yet enrolled to DC", - "indicator": "elligible_total" - }, - { - "label": "DC eligible and not on DC", - "description": "All patients eligible for DC but not on DC", - "indicator": "eligible_not_on_dc" - }, - { - "label": "Active on DC as of this week", - "description": "Active on DC as of this week", - "indicator": "active_on_dc" - }, - { - "label": "Enrolled to DC this week", - "description": "Enrolled to DC this week", - "indicator": "started_dc_this_week" - }, - { - "label": "DC eligible and not on DC with RTC this week", - "description": "DC eligible and not on dc with RTC this week", - "indicator": "eligible_not_on_dc_and_scheduled_this_week" - }, - { - "label": "DC eligible and not on DC and RTC not this week", - "description": "DC eligible and not on dc whose RTC is not this week", - "indicator": "eligible_not_on_dc_and_unscheduled_this_week" - } - ] - }, - { - "sectionTitle": "ART", - "indicators": [ - { - "label": "Enrolled this week", - "description": "Enrolled this week", - "indicator": "enrolled_this_week" - }, - { - "label": "Started ART this week", - "description": "Started ART this week", - "indicator": "started_art_this_week" - }, - { - "label": "ART revisit this week", - "description": "ART revisit this week", - "indicator": "art_revisit_this_week" - } - ] - }, - { - "sectionTitle": "Second Visit for New on ART (TX_SV)", - "indicators": [ - { - "label": "Scheduled second visit", - "description": "Scheduled second visit", - "indicator": "tx2_scheduled_this_week" - }, - { - "label": "Scheduled second visit but came earlier", - "description": "Scheduled second visit but came earlier", - "indicator": "tx2_scheduled_this_week_but_came_early" - }, - { - "label": "Honored Second visit", - "description": "Honored Second visit.", - "indicator": "tx2_scheduled_honored" - }, - { - "label": "UnScheduled second visit", - "description": "UnScheduled second visit", - "indicator": "tx2_unscheduled_this_week" - }, - { - "label": "Total ART second visits this week", - "description": "ART second visit this week", - "indicator": "tx2_visit_this_week" - }, - { - "label": "Missed ART second visit this week", - "description": "Missed ART second visit this week", - "indicator": "missed_tx2_visit_this_week" - } - ] - }, - { - "sectionTitle": "Prevention", - "indicators": [ - { - "label": "Active on prep as of week", - "description": "Active on prep as of this week", - "indicator": "active_on_prep_this_week" - }, - { - "label": "Enrolled in prep this week", - "description": "Enrolled in prep this week", - "indicator": "enrolled_in_prep_this_week" - }, - { - "label": "Prep LTFU as of week", - "description": "Prep LTFU as of this week", - "indicator": "prep_ltfu_this_week" - }, - { - "label": "Prep discontinued this week", - "description": "Prep discontinued this week", - "indicator": "prep_discontinued_this_week" - }, - { - "label": "Prep defaulter as of week", - "description": "Prep defaulters as of this week", - "indicator": "prep_defaulter_this_week" - }, - { - "label": "Prep discounted and turned HIV positive this week", - "description": "Previous on Prep and turned positive this week", - "indicator": "prev_on_prep_and_turned_positive" - } - ] - } -] \ No newline at end of file + { + "sectionTitle": "", + "indicators": [ + { + "label": "Locations", + "indicator": "location" + } + ] + }, + { + "sectionTitle": "Visits", + "indicators": [ + { + "label": "Visit this week", + "description": "All patients who came for visits this week including scheduled and unscheduled", + "indicator": "visit_this_week" + }, + { + "label": "Scheduled this week", + "description": "Patients scheduled this week", + "indicator": "scheduled_this_week" + }, + { + "label": "Honored visit", + "description": "Patients scheduled this week and came for their visit", + "indicator": "on_schedule_this_week" + }, + { + "label": "Unscheduled early", + "description": "Patients who came this week for their visit which earlier than the week of their rtc", + "indicator": "early_appointment_this_week" + }, + { + "label": "Unscheduled late", + "description": "Patients who came this week for their visit which later than the week of their rtc", + "indicator": "late_appointment_this_week" + }, + { + "label": "Transfer in this week", + "description": "Transfer in this week", + "indicator": "transfer_in_this_week" + }, + { + "label": "Transfer out this week", + "description": "Transfer out this week", + "indicator": "transfer_out_this_week" + } + ] + }, + { + "sectionTitle": "Client Disengagements", + "indicators": [ + { + "label": "Cumulative LTFUs (All LTFUs)", + "description": "All patients who have missed their rtc more than 28 days", + "indicator": "all_ltfus" + }, + { + "label": "Cumulative Surge LTFUs (LTFUs as from 30th Sep 2019)", + "description": "All patients who became LTFUs as from 30th Sep 2019 including those who have been resolved", + "indicator": "is_ltfu_after_may_total" + }, + { + "label": "Target to bring back this week (LTFUs as from 30th Sep 2019 not yet resolved)", + "description": "All patients who became LTFUs as from 30th Sep 2019 and have not been resolved", + "indicator": "is_ltfu_after_may" + }, + { + "label": "Cumulative Medication refill LTFUs(Missed medication pickup rtc for more that 28 days)", + "description": "All patients who have missed their medication pickup rtc for more that 28 days as from 30th September 2019 to now, including those with outcomes already", + "indicator": "med_surge_ltfus_cumulative" + }, + { + "label": "Medication refill LTFUs not yet resolved", + "description": "All patients who have missed their medication pickup rtc for more that 28 days as from 30th September 2019 to now and have not been resolved yet", + "indicator": "med_surge_ltfu_and_med_ltfu_after_may" + }, + { + "label": "Missed appintments this week (0 - 4 days)", + "description": "Patients who missed their appointments this week ", + "indicator": "missed_appointment_this_week" + }, + { + "label": "Last week missed that have returned", + "description": "All patients who had missed their appointments last week and have returned this week", + "indicator": "missed_to_active_this_week" + }, + { + "label": "All Defaulters as of this week (5 - 28 days)", + "description": "Patients who have missed their rtc date between 5 and 28 days", + "indicator": "defaulted" + }, + { + "label": "Last week defaulters that have returned", + "description": "All patients who were defaulters by last week and have returned this week", + "indicator": "defaulter_to_active_this_week" + }, + { + "label": "Medication refill Defaulters as of this week (Missed medication pickup rtc 5 - 28 days)", + "description": "Patients who have missed their medication pickup rtc date between 5 and 28 days", + "indicator": "med_defaulters" + }, + { + "label": "LTFUs this week (patients who bacame LTFU this week)", + "description": "Patients who became LTFU this week", + "indicator": "newly_ltfu_this_week" + }, + { + "label": "Medication refill LTFUs this week(Missed medication pickup rtc date more than 28 days this week)", + "description": "Patients who have missed their medication pickup rtc date for more than 28 days this week", + "indicator": "newly_med_ltfu_this_week" + }, + { + "label": "All dead patients after may", + "description": "All dead patients afetr may 12th", + "indicator": "cumulative_dead" + }, + { + "label": "Dead this week", + "description": "All patients who died this week", + "indicator": "dead_this_week" + } + ] + }, + { + "sectionTitle": "LTFU Outcomes this week(Surge LTFUs)", + "indicators": [ + { + "label": "Brought back to care", + "description": "Patients in the target to bring back this week and have been brought back this week", + "indicator": "ltfu_active_this_week" + }, + { + "label": "Reported self transfered", + "description": "Patients in the target to bring back this week and have been reported self transfered this week", + "indicator": "ltfu_transfer_out_this_week" + }, + { + "label": "Reported dead", + "description": "Patients in the target to bring back this week and have been reported dead this week", + "indicator": "ltfu_death_this_week" + }, + { + "label": "Medication refill brought back this week", + "description": "Medication refill LTFUs that have been brought back this week", + "indicator": "med_surge_ltfus_outcomes_this_week" + } + ] + }, + { + "sectionTitle": "LTFU cumulative outcome(Surge LTFUs)", + "indicators": [ + { + "label": "Cumulative Outcomes (brought back, self transfers and dead)", + "description": "surge LTFUs brought back, transfered out or those who are confirmed dead", + "indicator": "ltfu_cumulative_outcomes_total" + }, + { + "label": "Brought back to care cumulative", + "description": "Total Surge LTFUs who were brought back to care", + "indicator": "ltfu_cumulative_outcomes_active" + }, + { + "label": "Reported self transfered cumulative", + "description": "Total Surge LTFUs that have been reported self transfered", + "indicator": "ltfu_cumulative_outcomes_transfer_out" + }, + { + "label": "Reported dead cumulative", + "description": "Total Surge LTFUs that have been confirmed dead", + "indicator": "ltfu_cumulative_outcomes_death" + }, + { + "label": "Cumulative medication refill brought back", + "description": "All medication refill LTFUs that have been brought back", + "indicator": "med_surge_ltfus_outcomes" + } + ] + }, + { + "sectionTitle": "LTFU Outcomes (clients lost before october 2019)", + "indicators": [ + { + "label": "Returnees cumulative", + "description": "Patients who were LTFU before october 2019 and have returned", + "indicator": "old_ltfus_to_active" + }, + { + "label": "Returnees this week", + "description": "Patients who were LTFU before october 2019 and have returned this week", + "indicator": "old_ltfus_to_active_this_week" + } + ] + }, + { + "sectionTitle": "Viral Load", + "indicators": [ + { + "label": "Active and Due for VL as of this week", + "description": "Patients overdue for VL", + "indicator": "overdue_for_vl_active" + }, + { + "label": "Scheduled and Due for VL ", + "description": "Sheduled this week and overdue for VL", + "indicator": "scheduled_this_week_and_due_for_vl" + }, + { + "label": "Scheduled and Due for VL with order", + "description": "Sheduled this week, overdue for VL and have VL order", + "indicator": "due_for_vl_has_vl_order_scheduled" + }, + { + "label": "Scheduled and Due for VL without order", + "description": "Sheduled this week, overdue for VL and don't have VL order", + "indicator": "due_for_vl_dont_have_order_scheduled" + }, + { + "label": "Due for VL and not scheduled this week", + "description": "Overdue for VL but RTC date not this week", + "indicator": "unscheduled_this_week_and_due_for_vl" + }, + { + "label": "Due for VL and not scheduled this week with VL order", + "description": "Overdue for VL, RTC date not this week, have VL order", + "indicator": "due_for_vl_has_vl_order_unscheduled" + }, + { + "label": "Due for VL and not scheduled this week without VL order", + "description": "Overdue for VL, RTC date not this week, without VL order", + "indicator": "due_for_vl_dont_have_order_unscheduled" + }, + { + "label": "VL resulted ", + "description": "All patients who have VL results", + "indicator": "has_vl_this_week" + }, + { + "label": "VL resulted and suppressed", + "description": "VL resulted this week and suppressed (<400 copies)", + "indicator": "has_vl_this_week_and_suppressed" + }, + { + "label": "VL resulted and not suppressed", + "description": "VL resulted this week and unsuppressed (>400 copies)", + "indicator": "has_vl_this_week_and_unsuppressed" + }, + { + "label": "Has VL and Suppressed cumulative(<400 copies)", + "description": "All active patients who are suppressed", + "indicator": "is_suppressed" + }, + { + "label": "Has VL and Unsuppressed cumulative(>400 copies)", + "description": "All active patients who are unsuppressed", + "indicator": "is_un_suppressed" + } + ] + }, + { + "sectionTitle": "Differentiated Care(DC)", + "indicators": [ + { + "label": "Total eligible for DC", + "description": "Includes both patients on DC and still eligible and those eligible but not yet enrolled to DC", + "indicator": "elligible_total" + }, + { + "label": "DC eligible and not on DC", + "description": "All patients eligible for DC but not on DC", + "indicator": "eligible_not_on_dc" + }, + { + "label": "Active on DC as of this week", + "description": "Active on DC as of this week", + "indicator": "active_on_dc" + }, + { + "label": "Enrolled to DC this week", + "description": "Enrolled to DC this week", + "indicator": "started_dc_this_week" + }, + { + "label": "DC eligible and not on DC with RTC this week", + "description": "DC eligible and not on dc with RTC this week", + "indicator": "eligible_not_on_dc_and_scheduled_this_week" + }, + { + "label": "DC eligible and not on DC and RTC not this week", + "description": "DC eligible and not on dc whose RTC is not this week", + "indicator": "eligible_not_on_dc_and_unscheduled_this_week" + } + ] + }, + { + "sectionTitle": "ART", + "indicators": [ + { + "label": "Enrolled this week", + "description": "Enrolled this week", + "indicator": "enrolled_this_week" + }, + { + "label": "Started ART this week", + "description": "Started ART this week", + "indicator": "started_art_this_week" + }, + { + "label": "ART revisit this week", + "description": "ART revisit this week", + "indicator": "art_revisit_this_week" + } + ] + }, + { + "sectionTitle": "Second Visit for New on ART (TX_SV)", + "indicators": [ + { + "label": "Scheduled second visit", + "description": "Scheduled second visit", + "indicator": "tx2_scheduled_this_week" + }, + { + "label": "Scheduled second visit but came earlier", + "description": "Scheduled second visit but came earlier", + "indicator": "tx2_scheduled_this_week_but_came_early" + }, + { + "label": "Honored Second visit", + "description": "Honored Second visit.", + "indicator": "tx2_scheduled_honored" + }, + { + "label": "UnScheduled second visit", + "description": "UnScheduled second visit", + "indicator": "tx2_unscheduled_this_week" + }, + { + "label": "Total ART second visits this week", + "description": "ART second visit this week", + "indicator": "tx2_visit_this_week" + }, + { + "label": "Missed ART second visit this week", + "description": "Missed ART second visit this week", + "indicator": "missed_tx2_visit_this_week" + } + ] + }, + { + "sectionTitle": "Prevention", + "indicators": [ + { + "label": "Active on prep as of week", + "description": "Active on prep as of this week", + "indicator": "active_on_prep_this_week" + }, + { + "label": "Enrolled in prep this week", + "description": "Enrolled in prep this week", + "indicator": "enrolled_in_prep_this_week" + }, + { + "label": "Prep LTFU as of week", + "description": "Prep LTFU as of this week", + "indicator": "prep_ltfu_this_week" + }, + { + "label": "Prep discontinued this week", + "description": "Prep discontinued this week", + "indicator": "prep_discontinued_this_week" + }, + { + "label": "Prep defaulter as of week", + "description": "Prep defaulters as of this week", + "indicator": "prep_defaulter_this_week" + }, + { + "label": "Prep discounted and turned HIV positive this week", + "description": "Previous on Prep and turned positive this week", + "indicator": "prev_on_prep_and_turned_positive" + } + ] + } +] diff --git a/service/surge-reports/surge-report.service.js b/service/surge-reports/surge-report.service.js index c4beaee2e..0ceca3b4c 100644 --- a/service/surge-reports/surge-report.service.js +++ b/service/surge-reports/surge-report.service.js @@ -1,134 +1,154 @@ -import ReportProcessorHelpersService from "../../app/reporting-framework/report-processor-helpers.service"; -import { SurgeMultiDatasetPatientlistReport } from "./surge-multi-dataset-patientlist.report"; -import { PatientlistMysqlReport } from "../../app/reporting-framework/patientlist-mysql.report"; +import ReportProcessorHelpersService from '../../app/reporting-framework/report-processor-helpers.service'; +import { SurgeMultiDatasetPatientlistReport } from './surge-multi-dataset-patientlist.report'; +import { PatientlistMysqlReport } from '../../app/reporting-framework/patientlist-mysql.report'; import moment from 'moment'; const helpers = require('../../etl-helpers'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); const _ = require('lodash'); const surgeSectionDefinitions = require('./surge-report.json'); const surgeSchemaReportMap = require('./surge-indicators-config.json'); export class SurgeService extends SurgeMultiDatasetPatientlistReport { - - constructor(reportName, params) { - super(reportName, params) - } - - generateReport(additionalParams) { - const that = this; - that.determineSurgeReportSourceTables(this.params.year_week); - return new Promise((resolve, reject) => { - super.generateReport(additionalParams) - .then((results) => { - if (additionalParams && additionalParams.type === 'patient-list') { - resolve(results); - } else { - - let finalResult = [] - const reportProcessorHelpersService = new ReportProcessorHelpersService(); - for (let result of results) { - if (result.report && result.report.reportSchemas && result.report.reportSchemas.main && - result.report.reportSchemas.main.transFormDirectives.joinColumn) { - finalResult = reportProcessorHelpersService - .joinDataSets(that.params[result.report.reportSchemas.main.transFormDirectives.joinColumnParam] || - result.report.reportSchemas.main.transFormDirectives.joinColumn, - finalResult, result.results.results.results); - - } - } - - resolve({ - queriesAndSchemas: results, - result: finalResult, - sectionDefinitions: surgeSectionDefinitions, - indicatorDefinitions: [] - }); - } - }) - .catch((error) => { - console.error('Surge Report generation error: ', error); - reject(error); - }); - - }); - } - - getPatientListReport(reportParams) { - const that = this; - reportParams.surgeWeeklyDatasetSource = that.determineSurgeReportSourceTables(reportParams.year_week); - let indicators = reportParams.indicators ? reportParams.indicators.split(',') : []; - if (reportParams.locationUuids) { - let locationUuids = reportParams.locationUuids ? reportParams.locationUuids.split(',') : []; - reportParams.locationUuids = locationUuids; - - } - let report = new PatientlistMysqlReport(that.whichReportSchema(reportParams.indicators), reportParams); - return new Promise(function (resolve, reject) { - Promise.join(report.generatePatientListReport(indicators), - (results) => { - results.results.results.forEach((element) => { - if (element.cur_meds) { - element.cur_meds = helpers.getARVNames(element.cur_meds); - } - if (element.arv_first_regimen) { - element.arv_first_regimen = helpers.getARVNames(element.arv_first_regimen); - } - }) - resolve(results); - }).catch((errors) => { - console.error('Error', errors); - reject(errors); - }); + constructor(reportName, params) { + super(reportName, params); + } + + generateReport(additionalParams) { + const that = this; + that.determineSurgeReportSourceTables(this.params.year_week); + return new Promise((resolve, reject) => { + super + .generateReport(additionalParams) + .then((results) => { + if (additionalParams && additionalParams.type === 'patient-list') { + resolve(results); + } else { + let finalResult = []; + const reportProcessorHelpersService = new ReportProcessorHelpersService(); + for (let result of results) { + if ( + result.report && + result.report.reportSchemas && + result.report.reportSchemas.main && + result.report.reportSchemas.main.transFormDirectives.joinColumn + ) { + finalResult = reportProcessorHelpersService.joinDataSets( + that.params[ + result.report.reportSchemas.main.transFormDirectives + .joinColumnParam + ] || + result.report.reportSchemas.main.transFormDirectives + .joinColumn, + finalResult, + result.results.results.results + ); + } + } + + resolve({ + queriesAndSchemas: results, + result: finalResult, + sectionDefinitions: surgeSectionDefinitions, + indicatorDefinitions: [] + }); + } + }) + .catch((error) => { + console.error('Surge Report generation error: ', error); + reject(error); }); + }); + } + + getPatientListReport(reportParams) { + const that = this; + reportParams.surgeWeeklyDatasetSource = that.determineSurgeReportSourceTables( + reportParams.year_week + ); + let indicators = reportParams.indicators + ? reportParams.indicators.split(',') + : []; + if (reportParams.locationUuids) { + let locationUuids = reportParams.locationUuids + ? reportParams.locationUuids.split(',') + : []; + reportParams.locationUuids = locationUuids; } - - - generatePatientListReport(indicators) { - let self = this; - reportParams.surgeWeeklyDatasetSource = self.determineSurgeReportSourceTables(reportParams.year_week); - return new Promise((resolve, reject) => { - super.generatePatientListReport(indicators) - .then((results) => { - results.sections = surgeSectionDefinitions; - self.resolveLocationUuidsToName(self.params.locationUuids) - .then((locations) => { - results.locations = locations; - resolve(results); - }) - .catch((err) => { - resolve(results); - }); - - }) - .catch((err) => { - console.error('Surge patient list generation error', err); - reject(err); - }); + let report = new PatientlistMysqlReport( + that.whichReportSchema(reportParams.indicators), + reportParams + ); + return new Promise(function (resolve, reject) { + Promise.join(report.generatePatientListReport(indicators), (results) => { + results.results.results.forEach((element) => { + if (element.cur_meds) { + element.cur_meds = helpers.getARVNames(element.cur_meds); + } + if (element.arv_first_regimen) { + element.arv_first_regimen = helpers.getARVNames( + element.arv_first_regimen + ); + } }); - } - - resolveLocationUuidsToName(uuids) { - return new Promise((resolve, reject) => { - dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { - resolve(loc); + resolve(results); + }).catch((errors) => { + console.error('Error', errors); + reject(errors); + }); + }); + } + + generatePatientListReport(indicators) { + let self = this; + reportParams.surgeWeeklyDatasetSource = self.determineSurgeReportSourceTables( + reportParams.year_week + ); + return new Promise((resolve, reject) => { + super + .generatePatientListReport(indicators) + .then((results) => { + results.sections = surgeSectionDefinitions; + self + .resolveLocationUuidsToName(self.params.locationUuids) + .then((locations) => { + results.locations = locations; + resolve(results); + }) + .catch((err) => { + resolve(results); }); + }) + .catch((err) => { + console.error('Surge patient list generation error', err); + reject(err); }); + }); + } + + resolveLocationUuidsToName(uuids) { + return new Promise((resolve, reject) => { + dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { + resolve(loc); + }); + }); + } + + whichReportSchema(indicator) { + let report = _.find(surgeSchemaReportMap.reportSchemas, (schema) => { + return _.includes(schema.indicators, indicator); + }); + return report ? report.reportName : 'Indicator not found'; + } + + determineSurgeReportSourceTables(yearWeek) { + const self = this; + if (yearWeek.slice(4) >= moment().week() - 1) { + return (self.params.surgeWeeklyDatasetSource = + 'etl.surge_weekly_report_dataset'); + } else { + return (self.params.surgeWeeklyDatasetSource = + 'etl.surge_weekly_report_dataset_frozen'); } - - whichReportSchema(indicator) { - let report = _.find(surgeSchemaReportMap.reportSchemas, (schema) => { - return _.includes(schema.indicators, indicator); - }); - return report ? report.reportName : 'Indicator not found'; - } - - determineSurgeReportSourceTables(yearWeek) { - const self = this; - if (yearWeek.slice(4) >= moment().week() - 1) { - return self.params.surgeWeeklyDatasetSource = "etl.surge_weekly_report_dataset"; - } else { - return self.params.surgeWeeklyDatasetSource = "etl.surge_weekly_report_dataset_frozen"; - } - } -} \ No newline at end of file + } +} diff --git a/service/surge-reports/surge-service.js b/service/surge-reports/surge-service.js index ac6bc47a7..1a17bd0ea 100644 --- a/service/surge-reports/surge-service.js +++ b/service/surge-reports/surge-service.js @@ -6,105 +6,117 @@ const surgeDefs = require('./surge-report.json'); const dao = require('../../etl-dao'); export class SurgeReportService extends MultiDatasetPatientlistReport { - constructor(reportName, params) { - if (params.isAggregated) { - params.excludeParam = ['location_id']; - params.joinColumnParam = 'join_location'; - } - console.log('creating new surge report service') - super(reportName, params) + constructor(reportName, params) { + if (params.isAggregated) { + params.excludeParam = ['location_id']; + params.joinColumnParam = 'join_location'; } + console.log('creating new surge report service'); + super(reportName, params); + } - generateReport(additionalParams) { - const that = this; - return new Promise((resolve, reject) => { - console.log('Params:::', that.params); - super.generateReport(additionalParams) - .then((results) => { - if (additionalParams && additionalParams.type === 'patient-list') { - resolve(results); - } else { + generateReport(additionalParams) { + const that = this; + return new Promise((resolve, reject) => { + console.log('Params:::', that.params); + super + .generateReport(additionalParams) + .then((results) => { + if (additionalParams && additionalParams.type === 'patient-list') { + resolve(results); + } else { + let finalResult = []; + const reportProcessorHelpersService = new ReportProcessorHelpersService(); + for (let result of results) { + if ( + result.report && + result.report.reportSchemas && + result.report.reportSchemas.main && + result.report.reportSchemas.main.transFormDirectives.joinColumn + ) { + finalResult = reportProcessorHelpersService.joinDataSets( + that.params[ + result.report.reportSchemas.main.transFormDirectives + .joinColumnParam + ] || + result.report.reportSchemas.main.transFormDirectives + .joinColumn, + finalResult, + result.results.results.results + ); + } + } - let finalResult = [] - const reportProcessorHelpersService = new ReportProcessorHelpersService(); - for (let result of results) { - if (result.report && result.report.reportSchemas && result.report.reportSchemas.main && - result.report.reportSchemas.main.transFormDirectives.joinColumn) { - finalResult = reportProcessorHelpersService - .joinDataSets(that.params[result.report.reportSchemas.main.transFormDirectives.joinColumnParam] || - result.report.reportSchemas.main.transFormDirectives.joinColumn, - finalResult, result.results.results.results); - - } - } - - if(this.params && this.params.isAggregated === true) { - finalResult[0].location = 'Multiple Locations...'; - } - resolve({ - queriesAndSchemas: results, - result: finalResult, - sectionDefinitions: surgeDefs, - indicatorDefinitions: [] - }); - } - }) - .catch((error) => { - console.error('Surge Report generation error: ', error); - reject(error); - }); + if (this.params && this.params.isAggregated === true) { + finalResult[0].location = 'Multiple Locations...'; + } + resolve({ + queriesAndSchemas: results, + result: finalResult, + sectionDefinitions: surgeDefs, + indicatorDefinitions: [] + }); + } + }) + .catch((error) => { + console.error('Surge Report generation error: ', error); + reject(error); }); - } - - generatePatientListReport(indicators) { - let self = this; - let surgeRepDefs = surgeDefs; - return new Promise((resolve, reject) => { - super.generatePatientListReport(indicators) - .then((results) => { - let indicatorLabels = self.getIndicatorSectionDefinitions(results.indicators, - surgeRepDefs); - - results.indicators = indicatorLabels; + }); + } - self.resolveLocationUuidsToName(self.params.locationUuids) - .then((locations) => { - results.locations = locations; - resolve(results); - }) - .catch((err) => { - resolve(results); - }); + generatePatientListReport(indicators) { + let self = this; + let surgeRepDefs = surgeDefs; + return new Promise((resolve, reject) => { + super + .generatePatientListReport(indicators) + .then((results) => { + let indicatorLabels = self.getIndicatorSectionDefinitions( + results.indicators, + surgeRepDefs + ); - }) - .catch((err) => { - console.error('Surge patient list generation error', err); - reject(err); - }); - }); - } + results.indicators = indicatorLabels; - getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { - let results = []; - _.each(requestIndicators, function (requestIndicator) { - _.each(sectionDefinitions, function (sectionDefinition) { - _.each(sectionDefinition.indicators, function (indicator) { - if (indicator.indicator === requestIndicator) { - // console.log('Found indicator', requestIndicator); - results.push(indicator); - } - }); + self + .resolveLocationUuidsToName(self.params.locationUuids) + .then((locations) => { + results.locations = locations; + resolve(results); + }) + .catch((err) => { + resolve(results); }); + }) + .catch((err) => { + console.error('Surge patient list generation error', err); + reject(err); }); - return results; - } + }); + } - resolveLocationUuidsToName(uuids) { - return new Promise((resolve, reject) => { - // resolve location name - dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { - resolve(loc); - }); + getIndicatorSectionDefinitions(requestIndicators, sectionDefinitions) { + let results = []; + _.each(requestIndicators, function (requestIndicator) { + _.each(sectionDefinitions, function (sectionDefinition) { + _.each(sectionDefinition.indicators, function (indicator) { + if (indicator.indicator === requestIndicator) { + // console.log('Found indicator', requestIndicator); + results.push(indicator); + } }); - } -} \ No newline at end of file + }); + }); + return results; + } + + resolveLocationUuidsToName(uuids) { + return new Promise((resolve, reject) => { + // resolve location name + dao.resolveLocationUuidsToName(uuids.split(','), (loc) => { + resolve(loc); + }); + }); + } +} diff --git a/service/utils.js b/service/utils.js index f89d31344..efdad8eac 100755 --- a/service/utils.js +++ b/service/utils.js @@ -1,17 +1,16 @@ -(function(){ +(function () { 'use strict'; var _ = require('underscore'); - + function calculateBMI(weight, height) { - if(_.isUndefined(weight) || _.isUndefined(height)) { + if (_.isUndefined(weight) || _.isUndefined(height)) { throw new Error('Please provide both weight and height'); } - - return (weight / (height / 100 * height / 100)); + + return weight / (((height / 100) * height) / 100); } - + module.exports = { calculateBMI: calculateBMI }; - })(); diff --git a/test/authorization/etl-authorizer.test.js b/test/authorization/etl-authorizer.test.js index 529277954..b11c1668b 100755 --- a/test/authorization/etl-authorizer.test.js +++ b/test/authorization/etl-authorizer.test.js @@ -18,65 +18,63 @@ global.assert = chai.assert; var baseUrl = 'http://localhost:8002'; chai.use(sinonChai); -describe('ETL-AUTHORIZER TESTS', function() { +describe('ETL-AUTHORIZER TESTS', function () { + //var stub; + var userSample; + beforeEach(function (done) { + //stub = sinon.stub(db, 'queryServer_test'); + userSample = userMocks.getMockedUser(); + etlAuthorizer.setUser(userSample); + done(); + }); - //var stub; - var userSample; - beforeEach(function(done) { - //stub = sinon.stub(db, 'queryServer_test'); - userSample = userMocks.getMockedUser(); - etlAuthorizer.setUser(userSample); - done(); - }); + afterEach(function () { + //stub.restore(); + etlAuthorizer.setUser(undefined); + }); - afterEach(function() { - //stub.restore(); - etlAuthorizer.setUser(undefined); - }); - - it('should inject user mocks', - function(){ - expect(userMocks).to.be.defined; - expect(userSample).to.be.defined; - }); - - it('should set user when setUser is called', - function(){ - etlAuthorizer.setUser(userSample); - expect(etlAuthorizer.getUser()).to.deep.equal(userSample); - }); - - it('should return true when a user has a certain privilege' + - ' and hasPrivilege is invoked ', - function(){ - var toFind = userSample.privileges[2].display; - var hasPrivilege = etlAuthorizer.hasPrivilege(toFind); - expect(hasPrivilege).to.be.true; - }); - - it('should always return true when a user is a super user' + - ' and hasPrivilege is invoked ', - function(){ - - var userWithSuperUserRole = userMocks.getMockedUser(); - - //add super user role - var superUserRole = { - uuid:'some-uuid', - display: 'System Developer' //this is a super user role - }; - - userWithSuperUserRole.roles.push(superUserRole); - - //make privileges empty as is the case with super user roles - userWithSuperUserRole.privileges = []; - - //set the user - etlAuthorizer.setUser(userWithSuperUserRole); - - var hasPrivilege = etlAuthorizer.hasPrivilege('some random feature'); - expect(hasPrivilege).to.be.true; - }); - - -}); \ No newline at end of file + it('should inject user mocks', function () { + expect(userMocks).to.be.defined; + expect(userSample).to.be.defined; + }); + + it('should set user when setUser is called', function () { + etlAuthorizer.setUser(userSample); + expect(etlAuthorizer.getUser()).to.deep.equal(userSample); + }); + + it( + 'should return true when a user has a certain privilege' + + ' and hasPrivilege is invoked ', + function () { + var toFind = userSample.privileges[2].display; + var hasPrivilege = etlAuthorizer.hasPrivilege(toFind); + expect(hasPrivilege).to.be.true; + } + ); + + it( + 'should always return true when a user is a super user' + + ' and hasPrivilege is invoked ', + function () { + var userWithSuperUserRole = userMocks.getMockedUser(); + + //add super user role + var superUserRole = { + uuid: 'some-uuid', + display: 'System Developer' //this is a super user role + }; + + userWithSuperUserRole.roles.push(superUserRole); + + //make privileges empty as is the case with super user roles + userWithSuperUserRole.privileges = []; + + //set the user + etlAuthorizer.setUser(userWithSuperUserRole); + + var hasPrivilege = etlAuthorizer.hasPrivilege('some random feature'); + expect(hasPrivilege).to.be.true; + } + ); +}); diff --git a/test/authorization/location-authorizer.plugin.test.js b/test/authorization/location-authorizer.plugin.test.js index a3f83a10f..5d946b6e5 100755 --- a/test/authorization/location-authorizer.plugin.test.js +++ b/test/authorization/location-authorizer.plugin.test.js @@ -9,308 +9,357 @@ var Plugin = require(libpath + '/location-authorizer.plugin.js'); // Declare internals var internals = {}; -function NOOP() { -} +function NOOP() {} /** * This is a test for hapi js plugin that extends the route end points to allow * location based authorization. */ describe('openmrsLocationAuthorizer', function () { + var plugin = { + name: 'openmrsLocationAuthorizer', + version: '0.0.0', + register: Plugin.register, + path: libpath + }; - var plugin = { - name: 'openmrsLocationAuthorizer', - version: '0.0.0', - register: Plugin.register, - path: libpath - }; - - it('does not interfere with handlers throwing exceptions', function (done) { - var server = new Hapi.Server(); - server.connection(); - server.route({ - method: 'GET', path: '/', config: { - handler: function (request, reply) { - throw new Error("uncaught exception test"); - } - } - }); - server.register(plugin, {}, function (err) { - server.start(function (err) { - server.inject({method: 'GET', url: '/'}, function (res) { - internals.asyncCheck(function () { - expect(res.statusCode).to.equal(500); - server.stop(NOOP); - }, done); - }); - }); - }); + it('does not interfere with handlers throwing exceptions', function (done) { + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + handler: function (request, reply) { + throw new Error('uncaught exception test'); + } + } }); - - it('makes sure that openmrsLocationAuthorizer can be enabled only for secured routes', function (done) { - var server = new Hapi.Server(0); - server.connection(); - server.route({ - method: 'GET', path: '/', config: { - plugins: {'openmrsLocationAuthorizer': {locationParameter: [{type: 'params', name: 'uuid'}]}}, - handler: function (request, reply) { - reply("TEST"); - } - } - }); - server.register(plugin, {}, function (err) { - server.start(function (err) { - expect(err).to.not.be.undefined; - expect(err).to.match(/openmrsLocationAuthorizer can be enabled only for secured route/); - server.stop(NOOP); // Make sure the server is stopped - done(); - }); + server.register(plugin, {}, function (err) { + server.start(function (err) { + server.inject({ method: 'GET', url: '/' }, function (res) { + internals.asyncCheck(function () { + expect(res.statusCode).to.equal(500); + server.stop(NOOP); + }, done); }); + }); }); + }); - it('should allow openmrsLocationAuthorizer for routes secured in the route config', function (done) { - var server = new Hapi.Server(0); - server.connection(); - server.auth.scheme('custom', internals.authSchema); - server.auth.strategy('default', 'custom', false, {}); - server.route({ - method: 'GET', path: '/', config: { - auth: 'default', - plugins: {'openmrsLocationAuthorizer': {locationParameter: [{type: 'params', name: 'uuid'}]}}, - handler: function (request, reply) { - reply("TEST"); - } - } - }); - server.register(plugin, {}, function (err) { - server.start(function (err) { - expect(err).to.be.undefined; - server.stop(NOOP); // Make sure the server is stopped - done(); - }); - }); + it('makes sure that openmrsLocationAuthorizer can be enabled only for secured routes', function (done) { + var server = new Hapi.Server(0); + server.connection(); + server.route({ + method: 'GET', + path: '/', + config: { + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [{ type: 'params', name: 'uuid' }] + } + }, + handler: function (request, reply) { + reply('TEST'); + } + } }); + server.register(plugin, {}, function (err) { + server.start(function (err) { + expect(err).to.not.be.undefined; + expect(err).to.match( + /openmrsLocationAuthorizer can be enabled only for secured route/ + ); + server.stop(NOOP); // Make sure the server is stopped + done(); + }); + }); + }); - it('should allow openmrsLocationAuthorizer for routes secured globally with authentication', function (done) { - var server = new Hapi.Server(0); - server.connection(); - server.auth.scheme('custom', internals.authSchema); - server.auth.strategy('default', 'custom', false, {}); - server.auth.default('default'); - server.route({ - method: 'GET', path: '/', config: { - plugins: {'openmrsLocationAuthorizer': {locationParameter: [{type: 'params', name: 'uuid'}]}}, - handler: function (request, reply) { - reply("TEST"); - } - } - }); - server.register(plugin, {}, function (err) { - server.start(function (err) { - expect(err).to.be.undefined; - server.stop(NOOP); // Make sure the server is stopped - done(); - }); - }); + it('should allow openmrsLocationAuthorizer for routes secured in the route config', function (done) { + var server = new Hapi.Server(0); + server.connection(); + server.auth.scheme('custom', internals.authSchema); + server.auth.strategy('default', 'custom', false, {}); + server.route({ + method: 'GET', + path: '/', + config: { + auth: 'default', + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [{ type: 'params', name: 'uuid' }] + } + }, + handler: function (request, reply) { + reply('TEST'); + } + } + }); + server.register(plugin, {}, function (err) { + server.start(function (err) { + expect(err).to.be.undefined; + server.stop(NOOP); // Make sure the server is stopped + done(); + }); }); + }); - it('should allow openmrsLocationAuthorizer for routes secured globally with authentication and blacklisting routes' + - ' to require authorization', function (done) { - var server = new Hapi.Server(0); - server.connection({ - routes: { - plugins: { - openmrsLocationAuthorizer: {locationParameter: [{type: 'params', name: 'uuid'}]} - } - } - }); - server.auth.scheme('custom', internals.authSchema); - server.auth.strategy('default', 'custom', false, {}); - server.auth.default('default'); - server.route({ - method: 'GET', path: '/', config: { - //plugins: {'openmrsLocationAuthorizer': {locationParameter: [{ type: 'params',name: 'uuid' }]}}, - handler: function (request, reply) { - reply("TEST"); - } - } - }); - server.register(plugin, {}, function (err) { - server.start(function (err) { - expect(err).to.be.undefined; - server.stop(NOOP); // Make sure the server is stopped - done(); - }); - }); + it('should allow openmrsLocationAuthorizer for routes secured globally with authentication', function (done) { + var server = new Hapi.Server(0); + server.connection(); + server.auth.scheme('custom', internals.authSchema); + server.auth.strategy('default', 'custom', false, {}); + server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + config: { + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [{ type: 'params', name: 'uuid' }] + } + }, + handler: function (request, reply) { + reply('TEST'); + } + } }); + server.register(plugin, {}, function (err) { + server.start(function (err) { + expect(err).to.be.undefined; + server.stop(NOOP); // Make sure the server is stopped + done(); + }); + }); + }); - it('should error with global authentication not set and blacklisting routes to require authorization', function (done) { - var server = new Hapi.Server(0); - server.connection({ - routes: { - plugins: { - openmrsLocationAuthorizer: {locationParameter: [{type: 'params', name: 'uuid'}]} - } - } - }); - //server.auth.scheme('custom', internals.authSchema); - //server.auth.strategy('default', 'custom', false, {}); - //server.auth.default('default'); - server.route({ - method: 'GET', path: '/', config: { - //plugins: {'openmrsLocationAuthorizer': {locationParameter: [{ type: 'params',name: 'uuid' }]}}, - handler: function (request, reply) { - reply("TEST"); - } + it( + 'should allow openmrsLocationAuthorizer for routes secured globally with authentication and blacklisting routes' + + ' to require authorization', + function (done) { + var server = new Hapi.Server(0); + server.connection({ + routes: { + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [{ type: 'params', name: 'uuid' }] } + } + } + }); + server.auth.scheme('custom', internals.authSchema); + server.auth.strategy('default', 'custom', false, {}); + server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + config: { + //plugins: {'openmrsLocationAuthorizer': {locationParameter: [{ type: 'params',name: 'uuid' }]}}, + handler: function (request, reply) { + reply('TEST'); + } + } + }); + server.register(plugin, {}, function (err) { + server.start(function (err) { + expect(err).to.be.undefined; + server.stop(NOOP); // Make sure the server is stopped + done(); }); - server.register(plugin, {}, function (err) { - server.start(function (err) { - expect(err).to.not.be.undefined; - expect(err).to.match(/openmrsLocationAuthorizer can be enabled only for secured route/); - server.stop(NOOP); // Make sure the server is stopped - done(); - }); - }); + }); + } + ); + + it('should error with global authentication not set and blacklisting routes to require authorization', function (done) { + var server = new Hapi.Server(0); + server.connection({ + routes: { + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [{ type: 'params', name: 'uuid' }] + } + } + } }); + //server.auth.scheme('custom', internals.authSchema); + //server.auth.strategy('default', 'custom', false, {}); + //server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + config: { + //plugins: {'openmrsLocationAuthorizer': {locationParameter: [{ type: 'params',name: 'uuid' }]}}, + handler: function (request, reply) { + reply('TEST'); + } + } + }); + server.register(plugin, {}, function (err) { + server.start(function (err) { + expect(err).to.not.be.undefined; + expect(err).to.match( + /openmrsLocationAuthorizer can be enabled only for secured route/ + ); + server.stop(NOOP); // Make sure the server is stopped + done(); + }); + }); + }); - it('should not error with global authentication set, blacklisting routes to require authorization, and disabling ' + - 'authentication and authorization for a specific route', function (done) { + it( + 'should not error with global authentication set, blacklisting routes to require authorization, and disabling ' + + 'authentication and authorization for a specific route', + function (done) { + var plugin = { + name: 'openmrsLocationAuthorizer', + version: '0.0.0', + register: Plugin.register, + path: libpath, + options: { + roles: false + } + }; - var plugin = { - name: 'openmrsLocationAuthorizer', - version: '0.0.0', - register: Plugin.register, - path: libpath, - options: { - roles: false + var server = new Hapi.Server(0); + server.connection({ + routes: { + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [{ type: 'params', name: 'uuid' }] } - }; + } + } + }); - var server = new Hapi.Server(0); - server.connection({ - routes: { - plugins: { - openmrsLocationAuthorizer: {locationParameter: [{type: 'params', name: 'uuid'}]} - } - } - }); + server.auth.scheme('custom', internals.authSchema); + server.auth.strategy('default', 'custom', false, {}); + server.auth.default('default'); - server.auth.scheme('custom', internals.authSchema); - server.auth.strategy('default', 'custom', false, {}); - server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + config: { + auth: false, + plugins: { openmrsLocationAuthorizer: false }, + handler: function (request, reply) { + reply('TEST'); + } + } + }); - server.route({ - method: 'GET', path: '/', config: { - auth: false, - plugins: {'openmrsLocationAuthorizer': false}, - handler: function (request, reply) { - reply("TEST"); - } - } + server.register(plugin, {}, function (err) { + server.inject({ method: 'GET', url: '/' }, function (res) { + internals.asyncCheck(function () { + expect(res.statusCode).to.equal(200); + }, done); }); + }); + } + ); - server.register(plugin, {}, function (err) { - server.inject({method: 'GET', url: '/'}, function (res) { - internals.asyncCheck(function () { - expect(res.statusCode).to.equal(200); - }, done); - }); - }); + it('should error with global auth set but auth false on route', function (done) { + var server = new Hapi.Server(0); + server.connection(); + server.auth.scheme('custom', internals.authSchema); + server.auth.strategy('default', 'custom', false, {}); + server.auth.default('default'); + server.route({ + method: 'GET', + path: '/', + config: { + auth: false, + plugins: { + openmrsLocationAuthorizer: { + locationParameter: [{ type: 'params', name: 'uuid' }] + } + }, + handler: function (request, reply) { + reply('TEST'); + } + } }); - - it('should error with global auth set but auth false on route', function (done) { - var server = new Hapi.Server(0); - server.connection(); - server.auth.scheme('custom', internals.authSchema); - server.auth.strategy('default', 'custom', false, {}); - server.auth.default('default'); - server.route({ - method: 'GET', path: '/', config: { - auth: false, - plugins: {'openmrsLocationAuthorizer': {locationParameter: [{type: 'params', name: 'uuid'}]}}, - handler: function (request, reply) { - reply("TEST"); - } - } - }); - server.register(plugin, {}, function (err) { - server.start(function (err) { - expect(err).to.not.be.undefined; - server.stop(NOOP); // Make sure the server is stopped - done(); - }); - }); + server.register(plugin, {}, function (err) { + server.start(function (err) { + expect(err).to.not.be.undefined; + server.stop(NOOP); // Make sure the server is stopped + done(); + }); }); + }); - it('ignores routes without openmrsLocationAuthorizer instructions', function (done) { - var server = new Hapi.Server(); - server.connection(); - server.route({ - method: 'GET', path: '/', handler: function (request, reply) { - reply("TEST"); - } - }); - server.register(plugin, {}, function (err) { - - server.inject('/', function (res) { - - expect(res.payload).to.equal("TEST"); - done(); - }); - }); + it('ignores routes without openmrsLocationAuthorizer instructions', function (done) { + var server = new Hapi.Server(); + server.connection(); + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + reply('TEST'); + } + }); + server.register(plugin, {}, function (err) { + server.inject('/', function (res) { + expect(res.payload).to.equal('TEST'); + done(); + }); }); + }); - it('Validates the openmrsLocationAuthorizer plugin options are optional', function (done) { - var server = new Hapi.Server(0); - server.connection(); - server.auth.scheme('custom', internals.authSchema); - server.auth.strategy('default', 'custom', true, {}); - server.route({ - method: 'GET', path: '/', config: { - auth: 'default', - plugins: {'openmrsLocationAuthorizer': {bla: 'USER'}}, - handler: function (request, reply) { - reply("TEST"); - } - } - }); + it('Validates the openmrsLocationAuthorizer plugin options are optional', function (done) { + var server = new Hapi.Server(0); + server.connection(); + server.auth.scheme('custom', internals.authSchema); + server.auth.strategy('default', 'custom', true, {}); + server.route({ + method: 'GET', + path: '/', + config: { + auth: 'default', + plugins: { openmrsLocationAuthorizer: { bla: 'USER' } }, + handler: function (request, reply) { + reply('TEST'); + } + } + }); - var plugin = { - name: 'openmrsLocationAuthorizer', - version: '0.0.0', - register: Plugin.register, - path: libpath - }; + var plugin = { + name: 'openmrsLocationAuthorizer', + version: '0.0.0', + register: Plugin.register, + path: libpath + }; - server.register(plugin, {}, function (err) { - expect(err).to.be.undefined; - done(); - }); + server.register(plugin, {}, function (err) { + expect(err).to.be.undefined; + done(); }); + }); }); internals.authSchema = function () { + var scheme = { + authenticate: function (request, reply) { + return reply({ + username: 'asafdav', + locationParameter: [{ type: 'params', name: 'uuid' }] + }); + }, + payload: function (request, reply) { + return reply(request.auth.credentials.payload); + }, + response: function (request, reply) { + return reply(); + } + }; - var scheme = { - authenticate: function (request, reply) { - return reply({username: "asafdav", locationParameter: [{type: 'params', name: 'uuid'}]}); - }, - payload: function (request, reply) { - return reply(request.auth.credentials.payload); - }, - response: function (request, reply) { - return reply(); - } - }; - - return scheme; + return scheme; }; internals.asyncCheck = function (f, done) { - try { - f(); - done(); - } catch (e) { - done(e); - } -} + try { + f(); + done(); + } catch (e) { + done(e); + } +}; diff --git a/test/dao.test.js b/test/dao.test.js index 21a4be360..55c90f5b4 100755 --- a/test/dao.test.js +++ b/test/dao.test.js @@ -22,9 +22,7 @@ var baseUrl = 'http://localhost:8002'; chai.use(sinonChai); describe('ETL-SERVER TESTS', function () { - describe('Testing DAO', function () { - // example showing how to use a stub to fake a method var stub; beforeEach(function (done) { @@ -38,76 +36,74 @@ describe('ETL-SERVER TESTS', function () { stub.restore(); }); - it('should create the right query parts object when getPatient is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getPatient(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - //get patient always fetched data from etl.flat_hiv_summary - expect(queryParts.table).to.equal('etl.flat_hiv_summary'); - // if fields is null output all columns - expect(queryParts.columns).to.equal('*'); - - expect(queryParts.where).to.include(options.params.uuid); + it('should create the right query parts object when getPatient is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getPatient(options, function (res) { + // console.log('body2 ++', res); + done(); }); - it('should create the right fields property when getPatient is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: ['a', 'b', 'c'], - startIndex: null, - limit: null - } - }; - - dao.getPatient(options, function (res) { - // console.log('bodyxx ++', res); - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('array'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + //get patient always fetched data from etl.flat_hiv_summary + expect(queryParts.table).to.equal('etl.flat_hiv_summary'); + // if fields is null output all columns + expect(queryParts.columns).to.equal('*'); + + expect(queryParts.where).to.include(options.params.uuid); + }); + + it('should create the right fields property when getPatient is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: ['a', 'b', 'c'], + startIndex: null, + limit: null + } + }; + + dao.getPatient(options, function (res) { + // console.log('bodyxx ++', res); + done(); }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('array'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); }); // describe('Tests for /etl/custom_data Endpoint', function() { diff --git a/test/dao/analytics/analytics-dao.test.js b/test/dao/analytics/analytics-dao.test.js index 77a53e276..7bd6d2b80 100755 --- a/test/dao/analytics/analytics-dao.test.js +++ b/test/dao/analytics/analytics-dao.test.js @@ -21,97 +21,97 @@ global.assert = chai.assert; chai.use(sinonChai); describe('ANALYTICS LEVEL ETL-SERVER TESTS', function () { + describe('Testing etl-dao layer', function () { + // example showing how to use a stub to fake a method + var stub; + beforeEach(function (done) { + stub = sinon.stub(db, 'queryServer_test'); + + // .yieldsTo(1, null, { result:mockData.getPatientMockData() }); + done(); + }); - describe('Testing etl-dao layer', function () { - - // example showing how to use a stub to fake a method - var stub; - beforeEach(function (done) { - stub = sinon.stub(db, 'queryServer_test'); - - // .yieldsTo(1, null, { result:mockData.getPatientMockData() }); - done(); - }); - - afterEach(function () { - stub.restore(); - }); - - it('should create the right query parts object when getHivSummaryData is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null, - joins: [['a', 't2'], ['c', 'd']], - - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getHivSummaryData(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_hiv_summary'); - expect(queryParts.where).to.include("date(encounter_datetime) >= ? and date(encounter_datetime) <= ?"); - expect(queryParts.joins).to.be.an('array'); - expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.location'); - expect(queryParts.joins).to.have.deep.property('[0][1]', 't2'); - expect(queryParts.joins).to.have.deep.property('[0][2]', 't1.location_uuid = t2.uuid'); - expect(queryParts.joins).to.have.deep.property('[1][0]', 'amrs.person'); - expect(queryParts.joins).to.have.deep.property('[1][1]', 't3'); - - }); - - it('should create the right fields property when getHivSummaryData is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - locations: '124' - }, - query: { - order: null, - fields: "a,b,c", - startIndex: null, - limit: null - } - }; - - dao.getHivSummaryData(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('string'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); - }); + afterEach(function () { + stub.restore(); + }); + it('should create the right query parts object when getHivSummaryData is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null, + joins: [ + ['a', 't2'], + ['c', 'd'] + ] + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getHivSummaryData(options, function (res) { + // console.log('body2 ++', res); + done(); + }); + + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_hiv_summary'); + expect(queryParts.where).to.include( + 'date(encounter_datetime) >= ? and date(encounter_datetime) <= ?' + ); + expect(queryParts.joins).to.be.an('array'); + expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.location'); + expect(queryParts.joins).to.have.deep.property('[0][1]', 't2'); + expect(queryParts.joins).to.have.deep.property( + '[0][2]', + 't1.location_uuid = t2.uuid' + ); + expect(queryParts.joins).to.have.deep.property('[1][0]', 'amrs.person'); + expect(queryParts.joins).to.have.deep.property('[1][1]', 't3'); }); + it('should create the right fields property when getHivSummaryData is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + locations: '124' + }, + query: { + order: null, + fields: 'a,b,c', + startIndex: null, + limit: null + } + }; + + dao.getHivSummaryData(options, function (res) { + done(); + }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('string'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); + }); }); diff --git a/test/dao/clinic/clinic-dao.test.js b/test/dao/clinic/clinic-dao.test.js index c8219521e..899ec09b9 100755 --- a/test/dao/clinic/clinic-dao.test.js +++ b/test/dao/clinic/clinic-dao.test.js @@ -21,9 +21,7 @@ global.assert = chai.assert; chai.use(sinonChai); describe('CLINIC LEVEL ETL-SERVER TESTS', function () { - describe('Testing etl-dao layer', function () { - // example showing how to use a stub to fake a method var stub; beforeEach(function (done) { @@ -38,617 +36,621 @@ describe('CLINIC LEVEL ETL-SERVER TESTS', function () { }); // - it('should create the right query parts object when getClinicHivSummayIndicators is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getClinicHivSummayIndicators(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.hiv_summary_indicators'); - // if fields is null output all columns - expect(queryParts.columns).to.equal('*'); - - expect(queryParts.where).to.include(options.params.uuid); - }); - - it('should create the right fields property when getClinicHivSummayIndicators is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: ['a', 'b', 'c'], - startIndex: null, - limit: null - } - }; - - dao.getClinicHivSummayIndicators(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('array'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); - }); - - - it('should create the right query parts object when getClinicDefaulterList is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getClinicDefaulterList(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_defaulters'); - // if fields is null output all columns - console.log('Log', JSON.stringify(queryParts.columns)) - expect(queryParts.columns[0]).to.equal('*'); - expect(queryParts.columns[1]).to.equal('extract(year from (from_days(datediff(now(),t3.birthdate)))) as age'); - expect(queryParts.where).to.include(options.params.uuid); - }); - - it('should create the right fields property when getClinicDefaulterList is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: ['a', 'b', 'c'], - startIndex: null, - limit: null - } - }; - - dao.getClinicDefaulterList(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('array'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); - }); - - it('should create the right query parts object when getHasNotReturned is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null, - joins: [['a'], ['b'], ['c']] - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getHasNotReturned(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_hiv_summary'); - // if fields is null output default given columns - expect(queryParts.columns).to.equal('t1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers'); - expect(queryParts.where).to.include('t1.location_uuid = ? and date(t1.rtc_date) between ? and ? and next_clinical_datetime_hiv is null'); - expect(queryParts.joins).to.be.an('array'); - //expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.person_name'); - // expect(queryParts.joins).to.have.deep.property('[0][1]', 't3'); - - expect(queryParts.group).to.be.an('array'); - expect(queryParts.group).to.include('person_id'); - assert.equal(queryParts.group.length, 1); - - }); - - it('should create the right fields property when getHasNotReturned is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: ['a', 'b', 'c'], - startIndex: null, - limit: null - } - }; - - dao.getHasNotReturned(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('array'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); - }); - - it('should create the right query parts object when getClinicMonthlyAppointmentSchedule is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null, - group: [] - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getClinicMonthlyAppointmentSchedule(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_hiv_summary'); - expect(queryParts.where).to.include(options.params.uuid); - expect(queryParts.group).to.be.an('array'); - - expect(queryParts.group).to.include('rtc_date'); - assert.equal(queryParts.group.length, 1); - - - }); - - it('should create the right fields property when getClinicMonthlyAppointmentSchedule is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: "a,b,c", - startIndex: null, - limit: null, - group: [] - } - }; - - dao.getClinicMonthlyAppointmentSchedule(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('string'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); - }); - it('should create the right query parts object when getClinicMonthlyVisits is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123', - startDate: "2015-08-03T21:00:00.000Z" - - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null, - group: [] - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getClinicMonthlyVisits(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_hiv_summary'); - expect(queryParts.where).to.include(options.params.uuid, options.params.startDate); - - - }); - - it('should create the right fields property when getClinicMonthlyVisits is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: ['a', 'b', 'c'], - startIndex: null, - limit: null, - group: [] - } - }; - - dao.getClinicMonthlyVisits(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('array'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); - expect(queryParts.group).to.be.an('array'); - expect(queryParts.group).to.include('encounter_datetime'); - assert.equal(queryParts.group.length, 1); - }); - - it('should create the right query parts object when getClinicEncounterData is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null, - joins: [['a', 't2'], ['c', 'd']], - group: [] - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getClinicEncounterData(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_hiv_summary'); - expect(queryParts.where).to.include(options.params.uuid); - // if fields is null output all columns - expect(queryParts.columns).to.equal("t1.*,t2.gender,round(datediff(t1.encounter_datetime,t2.birthdate)/365) as age,group_concat(identifier) as identifiers"); - expect(queryParts.joins).to.be.an('array'); - expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.person'); - expect(queryParts.joins).to.have.deep.property('[0][1]', 't2'); - expect(queryParts.joins).to.have.deep.property('[0][2]', 't1.person_id = t2.person_id'); - expect(queryParts.joins).to.have.deep.property('[1][0]', 'amrs.patient_identifier'); - expect(queryParts.joins).to.have.deep.property('[1][1]', 't3'); - - - - - }); - - it('should create the right fields property when getClinicEncounterData is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: "a,b,c", - startIndex: null, - limit: null, - joins: [['a', 't2'], ['c', 'd']], - group: [] - } - }; - - dao.getClinicEncounterData(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('string'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); - expect(queryParts.group).to.be.an('array'); - expect(queryParts.group).to.include('encounter_id'); - expect(queryParts.group).to.include('person_id'); - assert.equal(queryParts.group.length, 2); - - - }); - - it('should create the right query parts object when getClinicAppointmentSchedule is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null, - joins: [['a', 't2'], ['c', 'd']], - group: ['a'] - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getClinicAppointmentSchedule(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_hiv_summary'); - expect(queryParts.where).to.include(options.params.uuid); - // if fields is null output all columns - expect(queryParts.columns).to.equal("t1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers"); - expect(queryParts.joins).to.be.an('array'); - expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.person_name'); - expect(queryParts.joins).to.have.deep.property('[0][1]', 't3'); - - expect(queryParts.group).to.be.an('array'); - expect(queryParts.group).to.include('person_id'); - assert.equal(queryParts.group.length, 1); - - - }); - - it('should create the right fields property when getClinicAppointmentSchedule is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: "a,b,c", - startIndex: null, - limit: null - } - }; - - dao.getClinicAppointmentSchedule(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('string'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); - }); - - it('should create the right query parts object when getClinicDailyVisits is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null, - joins: [['a', 't2'], ['c', 'd']], - group: ['a'] - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getClinicDailyVisits(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_hiv_summary'); - expect(queryParts.where).to.include(options.params.uuid); - // if fields is null output all columns - expect(queryParts.columns).to.equal("t1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers"); - expect(queryParts.joins).to.be.an('array'); - expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.person_name'); - expect(queryParts.joins).to.have.deep.property('[0][1]', 't3'); - - expect(queryParts.group).to.be.an('array'); - expect(queryParts.group).to.include('person_id'); - assert.equal(queryParts.group.length, 1); - - - }); - - it('should create the right fields property when getClinicDailyVisits is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: "a,b,c", - startIndex: null, - limit: null - } - }; - - dao.getClinicDailyVisits(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - - expect(queryParts.columns).to.be.an('string'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); + it('should create the right query parts object when getClinicHivSummayIndicators is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getClinicHivSummayIndicators(options, function (res) { + // console.log('body2 ++', res); + done(); }); - }); + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.hiv_summary_indicators'); + // if fields is null output all columns + expect(queryParts.columns).to.equal('*'); + + expect(queryParts.where).to.include(options.params.uuid); + }); + + it('should create the right fields property when getClinicHivSummayIndicators is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: ['a', 'b', 'c'], + startIndex: null, + limit: null + } + }; + + dao.getClinicHivSummayIndicators(options, function (res) { + done(); + }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('array'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); + + it('should create the right query parts object when getClinicDefaulterList is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getClinicDefaulterList(options, function (res) { + // console.log('body2 ++', res); + done(); + }); + + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_defaulters'); + // if fields is null output all columns + console.log('Log', JSON.stringify(queryParts.columns)); + expect(queryParts.columns[0]).to.equal('*'); + expect(queryParts.columns[1]).to.equal( + 'extract(year from (from_days(datediff(now(),t3.birthdate)))) as age' + ); + expect(queryParts.where).to.include(options.params.uuid); + }); + + it('should create the right fields property when getClinicDefaulterList is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: ['a', 'b', 'c'], + startIndex: null, + limit: null + } + }; + + dao.getClinicDefaulterList(options, function (res) { + done(); + }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('array'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); + + it('should create the right query parts object when getHasNotReturned is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null, + joins: [['a'], ['b'], ['c']] + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getHasNotReturned(options, function (res) { + // console.log('body2 ++', res); + done(); + }); + + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_hiv_summary'); + // if fields is null output default given columns + expect(queryParts.columns).to.equal( + 't1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers' + ); + expect(queryParts.where).to.include( + 't1.location_uuid = ? and date(t1.rtc_date) between ? and ? and next_clinical_datetime_hiv is null' + ); + expect(queryParts.joins).to.be.an('array'); + //expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.person_name'); + // expect(queryParts.joins).to.have.deep.property('[0][1]', 't3'); + + expect(queryParts.group).to.be.an('array'); + expect(queryParts.group).to.include('person_id'); + assert.equal(queryParts.group.length, 1); + }); + + it('should create the right fields property when getHasNotReturned is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: ['a', 'b', 'c'], + startIndex: null, + limit: null + } + }; + + dao.getHasNotReturned(options, function (res) { + done(); + }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('array'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); + + it('should create the right query parts object when getClinicMonthlyAppointmentSchedule is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null, + group: [] + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getClinicMonthlyAppointmentSchedule(options, function (res) { + // console.log('body2 ++', res); + done(); + }); + + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_hiv_summary'); + expect(queryParts.where).to.include(options.params.uuid); + expect(queryParts.group).to.be.an('array'); + + expect(queryParts.group).to.include('rtc_date'); + assert.equal(queryParts.group.length, 1); + }); + + it('should create the right fields property when getClinicMonthlyAppointmentSchedule is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: 'a,b,c', + startIndex: null, + limit: null, + group: [] + } + }; + + dao.getClinicMonthlyAppointmentSchedule(options, function (res) { + done(); + }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.columns).to.be.an('string'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); + it('should create the right query parts object when getClinicMonthlyVisits is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123', + startDate: '2015-08-03T21:00:00.000Z' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null, + group: [] + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getClinicMonthlyVisits(options, function (res) { + // console.log('body2 ++', res); + done(); + }); + + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_hiv_summary'); + expect(queryParts.where).to.include( + options.params.uuid, + options.params.startDate + ); + }); + + it('should create the right fields property when getClinicMonthlyVisits is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: ['a', 'b', 'c'], + startIndex: null, + limit: null, + group: [] + } + }; + + dao.getClinicMonthlyVisits(options, function (res) { + done(); + }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('array'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + expect(queryParts.group).to.be.an('array'); + expect(queryParts.group).to.include('encounter_datetime'); + assert.equal(queryParts.group.length, 1); + }); + + it('should create the right query parts object when getClinicEncounterData is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null, + joins: [ + ['a', 't2'], + ['c', 'd'] + ], + group: [] + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getClinicEncounterData(options, function (res) { + // console.log('body2 ++', res); + done(); + }); + + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_hiv_summary'); + expect(queryParts.where).to.include(options.params.uuid); + // if fields is null output all columns + expect(queryParts.columns).to.equal( + 't1.*,t2.gender,round(datediff(t1.encounter_datetime,t2.birthdate)/365) as age,group_concat(identifier) as identifiers' + ); + expect(queryParts.joins).to.be.an('array'); + expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.person'); + expect(queryParts.joins).to.have.deep.property('[0][1]', 't2'); + expect(queryParts.joins).to.have.deep.property( + '[0][2]', + 't1.person_id = t2.person_id' + ); + expect(queryParts.joins).to.have.deep.property( + '[1][0]', + 'amrs.patient_identifier' + ); + expect(queryParts.joins).to.have.deep.property('[1][1]', 't3'); + }); + + it('should create the right fields property when getClinicEncounterData is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: 'a,b,c', + startIndex: null, + limit: null, + joins: [ + ['a', 't2'], + ['c', 'd'] + ], + group: [] + } + }; + + dao.getClinicEncounterData(options, function (res) { + done(); + }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('string'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + expect(queryParts.group).to.be.an('array'); + expect(queryParts.group).to.include('encounter_id'); + expect(queryParts.group).to.include('person_id'); + assert.equal(queryParts.group.length, 2); + }); + + it('should create the right query parts object when getClinicAppointmentSchedule is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null, + joins: [ + ['a', 't2'], + ['c', 'd'] + ], + group: ['a'] + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getClinicAppointmentSchedule(options, function (res) { + // console.log('body2 ++', res); + done(); + }); + + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_hiv_summary'); + expect(queryParts.where).to.include(options.params.uuid); + // if fields is null output all columns + expect(queryParts.columns).to.equal( + 't1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers' + ); + expect(queryParts.joins).to.be.an('array'); + expect(queryParts.joins).to.have.deep.property( + '[0][0]', + 'amrs.person_name' + ); + expect(queryParts.joins).to.have.deep.property('[0][1]', 't3'); + + expect(queryParts.group).to.be.an('array'); + expect(queryParts.group).to.include('person_id'); + assert.equal(queryParts.group.length, 1); + }); + + it('should create the right fields property when getClinicAppointmentSchedule is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: 'a,b,c', + startIndex: null, + limit: null + } + }; + + dao.getClinicAppointmentSchedule(options, function (res) { + done(); + }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('string'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); + + it('should create the right query parts object when getClinicDailyVisits is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null, + joins: [ + ['a', 't2'], + ['c', 'd'] + ], + group: ['a'] + } + }; + + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + + dao.getClinicDailyVisits(options, function (res) { + // console.log('body2 ++', res); + done(); + }); + + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_hiv_summary'); + expect(queryParts.where).to.include(options.params.uuid); + // if fields is null output all columns + expect(queryParts.columns).to.equal( + 't1.*,t3.given_name,t3.middle_name,t3.family_name,group_concat(identifier) as identifiers' + ); + expect(queryParts.joins).to.be.an('array'); + expect(queryParts.joins).to.have.deep.property( + '[0][0]', + 'amrs.person_name' + ); + expect(queryParts.joins).to.have.deep.property('[0][1]', 't3'); + + expect(queryParts.group).to.be.an('array'); + expect(queryParts.group).to.include('person_id'); + assert.equal(queryParts.group.length, 1); + }); + + it('should create the right fields property when getClinicDailyVisits is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: 'a,b,c', + startIndex: null, + limit: null + } + }; + + dao.getClinicDailyVisits(options, function (res) { + done(); + }); + + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('string'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); + }); }); diff --git a/test/dao/lab-cohorts/lab-cohorts-dao.js b/test/dao/lab-cohorts/lab-cohorts-dao.js index 33aa722cb..16d88303c 100755 --- a/test/dao/lab-cohorts/lab-cohorts-dao.js +++ b/test/dao/lab-cohorts/lab-cohorts-dao.js @@ -18,9 +18,7 @@ global.assert = chai.assert; chai.use(sinonChai); describe('LAB COHORTS ETL-SERVER TESTS', function () { - describe('Testing etl-dao layer', function () { - // example showing how to use a stub to fake a method var stub; beforeEach(function (done) { @@ -35,31 +33,29 @@ describe('LAB COHORTS ETL-SERVER TESTS', function () { stub.restore(); }); - it('should create the right query parts object when loadLabCohorts is called', - function (done) { - - stub.resolves({ - startIndex: 0, - size: 1, - result: [] - }); - var options = { - query: { - startDate: '2016-01-08', - endDate: '2016-08-08', - limit: 10000, - offset: 0 - } - }; - - dao.loadLabCohorts(options, function (res) { - done(); - }); - - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('amrs.patient'); - expect(queryParts.columns[0]).to.equal('distinct pe.uuid'); - expect(queryParts.limit).to.equal(10000); //max limit + it('should create the right query parts object when loadLabCohorts is called', function (done) { + stub.resolves({ + startIndex: 0, + size: 1, + result: [] + }); + var options = { + query: { + startDate: '2016-01-08', + endDate: '2016-08-08', + limit: 10000, + offset: 0 + } + }; + + dao.loadLabCohorts(options, function (res) { + done(); }); + + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('amrs.patient'); + expect(queryParts.columns[0]).to.equal('distinct pe.uuid'); + expect(queryParts.limit).to.equal(10000); //max limit + }); }); }); diff --git a/test/dao/patient/etl-patient-hiv-summary-dao.test.js b/test/dao/patient/etl-patient-hiv-summary-dao.test.js index 2588d3352..953bbb19b 100755 --- a/test/dao/patient/etl-patient-hiv-summary-dao.test.js +++ b/test/dao/patient/etl-patient-hiv-summary-dao.test.js @@ -18,66 +18,62 @@ global.assert = chai.assert; var baseUrl = 'http://localhost:8002'; chai.use(sinonChai); - describe('ETL PATIENT HIV SUMMARY DAO:', function () { + beforeEach(function (done) { + done(); + }); - beforeEach(function (done) { - done(); - }); - - afterEach(function () { - }); - - it('should load dao', - function () { - expect(dao).to.be.defined; - expect(db).to.be.defined; - }); - - it('should fetch hiv summary records for a patient by patient uuid', - function (done) { - // params: patientUuid, clinicalOnly, startIndex, limit, params object - //params object include sortOrder, - // should return a promise - var expectedQueryObj = { - columns: '*', - table: 'etl.flat_hiv_summary', - where: ['uuid = ? AND is_clinical_encounter = true', 'patient uuid'], - order: [{ - column: 'encounter_datetime', - asc: false - }], - offset: 0, - limit: 100 - }; + afterEach(function () {}); - var mockOutput = { - result: [], - size: 0, - sql: 'SELECT * FROM etl.flat_hiv_summary `t1` WHERE (uuid = ?) ORDER BY encounter_datetime DESC LIMIT 100', - sqlParams: ['patient uuid'], - startIndex: '0' - }; - var stub = sinon.stub(db, 'queryDb', - function (queryObject) { - expect(queryObject).to.deep.equal(expectedQueryObj); - return new Promise(function (success, error) { - success(mockOutput); - }) - }); + it('should load dao', function () { + expect(dao).to.be.defined; + expect(db).to.be.defined; + }); - dao.getPatientHivSummary('patient uuid', true, {}, 0, 100) - .then(function (results) { - expect(results).to.deep.equal(mockOutput); - done(); - stub.restore(); - }) - .catch(function (error) { - stub.restore(); - expect(true).to.be.false; - done(); - }); + it('should fetch hiv summary records for a patient by patient uuid', function (done) { + // params: patientUuid, clinicalOnly, startIndex, limit, params object + //params object include sortOrder, + // should return a promise + var expectedQueryObj = { + columns: '*', + table: 'etl.flat_hiv_summary', + where: ['uuid = ? AND is_clinical_encounter = true', 'patient uuid'], + order: [ + { + column: 'encounter_datetime', + asc: false + } + ], + offset: 0, + limit: 100 + }; - }); + var mockOutput = { + result: [], + size: 0, + sql: + 'SELECT * FROM etl.flat_hiv_summary `t1` WHERE (uuid = ?) ORDER BY encounter_datetime DESC LIMIT 100', + sqlParams: ['patient uuid'], + startIndex: '0' + }; + var stub = sinon.stub(db, 'queryDb', function (queryObject) { + expect(queryObject).to.deep.equal(expectedQueryObj); + return new Promise(function (success, error) { + success(mockOutput); + }); + }); -}); \ No newline at end of file + dao + .getPatientHivSummary('patient uuid', true, {}, 0, 100) + .then(function (results) { + expect(results).to.deep.equal(mockOutput); + done(); + stub.restore(); + }) + .catch(function (error) { + stub.restore(); + expect(true).to.be.false; + done(); + }); + }); +}); diff --git a/test/dao/patient/patient-dao.test.js b/test/dao/patient/patient-dao.test.js index c990ddae2..41ee501f6 100755 --- a/test/dao/patient/patient-dao.test.js +++ b/test/dao/patient/patient-dao.test.js @@ -25,10 +25,7 @@ global.assert = chai.assert; chai.use(sinonChai); describe('PATIENT LEVEL ETL-SERVER TESTS', function () { - - describe('Testing etl-dao layer', function () { - // example showing how to use a stub to fake a method var stub; var queryDbStub; @@ -46,569 +43,588 @@ describe('PATIENT LEVEL ETL-SERVER TESTS', function () { queryDbStub.restore(); }); - it('should create the right query parts object when getPatient is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getPatient(options, function (res) { - // console.log('body2 ++', res); - done(); - }); + it('should create the right query parts object when getPatient is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null + } + }; - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - //get patient always fetched data from etl.flat_hiv_summary - expect(queryParts.table).to.equal('etl.flat_hiv_summary'); - // if fields is null output all columns - expect(queryParts.columns).to.equal('*'); + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - expect(queryParts.where).to.include(options.params.uuid); + dao.getPatient(options, function (res) { + // console.log('body2 ++', res); + done(); }); - it('should create the right fields property when getPatient is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: ['a', 'b', 'c'], - startIndex: null, - limit: null - } - }; + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + //get patient always fetched data from etl.flat_hiv_summary + expect(queryParts.table).to.equal('etl.flat_hiv_summary'); + // if fields is null output all columns + expect(queryParts.columns).to.equal('*'); - dao.getPatient(options, function (res) { - // console.log('bodyxx ++', res); - done(); - }); + expect(queryParts.where).to.include(options.params.uuid); + }); - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; + it('should create the right fields property when getPatient is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: ['a', 'b', 'c'], + startIndex: null, + limit: null + } + }; - expect(queryParts.columns).to.be.an('array'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); + dao.getPatient(options, function (res) { + // console.log('bodyxx ++', res); + done(); }); - it('should create the right query parts object when getPatientData is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null - } - }; + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + expect(queryParts.columns).to.be.an('array'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); - dao.getPatientData(options, function (res) { - // console.log('body2 ++', res); - done(); - }); + it('should create the right query parts object when getPatientData is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null + } + }; - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_labs_and_imaging'); - // if fields is null output all columns - expect(queryParts.columns).to.equal('t1.*, t2.cur_arv_meds'); + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - expect(queryParts.where).to.include(options.params.uuid); + dao.getPatientData(options, function (res) { + // console.log('body2 ++', res); + done(); }); - it('should create the right fields property when getPatientData is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: "a,b,c", - startIndex: null, - limit: null - } - }; + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_labs_and_imaging'); + // if fields is null output all columns + expect(queryParts.columns).to.equal('t1.*, t2.cur_arv_meds'); - dao.getPatientData(options, function (res) { - done(); - }); + expect(queryParts.where).to.include(options.params.uuid); + }); - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; + it('should create the right fields property when getPatientData is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: 'a,b,c', + startIndex: null, + limit: null + } + }; - expect(queryParts.columns).to.be.an('string'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); + dao.getPatientData(options, function (res) { + done(); }); - it('should create the right query parts object when getPatientVitals is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - queryDbStub.resolves({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null - } - }; + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + expect(queryParts.columns).to.be.an('string'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); - dao.getPatientVitals(options, function (res) { - // console.log('body2 ++', res); - done(); - }); + it('should create the right query parts object when getPatientVitals is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + queryDbStub.resolves({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null + } + }; - // console.log('body2 ++', stub.args[0][0]); - var queryParts = queryDbStub.args[0][0]; - expect(queryParts.table).to.equal('etl.flat_vitals'); - // if fields is null output all columns - expect(queryParts.columns).to.equal('*'); + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - expect(queryParts.where).to.include(options.params.uuid); + dao.getPatientVitals(options, function (res) { + // console.log('body2 ++', res); + done(); }); - it('should create the right fields property when getPatientVitals is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - queryDbStub.resolves({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: ['a', 'b', 'c'], - startIndex: null, - limit: null - } - }; + // console.log('body2 ++', stub.args[0][0]); + var queryParts = queryDbStub.args[0][0]; + expect(queryParts.table).to.equal('etl.flat_vitals'); + // if fields is null output all columns + expect(queryParts.columns).to.equal('*'); - dao.getPatientVitals(options, function (res) { - done(); - }); + expect(queryParts.where).to.include(options.params.uuid); + }); - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = queryDbStub.args[0][0]; + it('should create the right fields property when getPatientVitals is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + queryDbStub.resolves({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: ['a', 'b', 'c'], + startIndex: null, + limit: null + } + }; - expect(queryParts.columns).to.be.an('array'); - expect(queryParts.columns).to.include('a'); - expect(queryParts.columns).to.include('b'); - expect(queryParts.columns).to.include('c'); + dao.getPatientVitals(options, function (res) { + done(); }); - it('should create the right query parts object when getPatientCountGroupedByLocation is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null, - joins: [['a', 't2'], ['c', 'd']], - group: ['a'] - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - dao.getPatientCountGroupedByLocation(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('amrs.patient'); - // if fields is null output all columns - expect(queryParts.columns).to.equal("t3.location_id,t3.name,count( distinct t1.patient_id) as total"); - expect(queryParts.joins).to.be.an('array'); - expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.encounter'); - expect(queryParts.joins).to.have.deep.property('[0][1]', 't2'); - expect(queryParts.joins).to.have.deep.property('[0][2]', 't1.patient_id = t2.patient_id'); - expect(queryParts.joins).to.have.deep.property('[1][0]', 'amrs.location'); - expect(queryParts.joins).to.have.deep.property('[1][1]', 't3'); - - expect(queryParts.group).to.be.an('array'); - expect(queryParts.group).to.include('t3.uuid,t3.name'); - assert.equal(queryParts.group.length, 1); + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = queryDbStub.args[0][0]; + expect(queryParts.columns).to.be.an('array'); + expect(queryParts.columns).to.include('a'); + expect(queryParts.columns).to.include('b'); + expect(queryParts.columns).to.include('c'); + }); + it('should create the right query parts object when getPatientCountGroupedByLocation is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null, + joins: [ + ['a', 't2'], + ['c', 'd'] + ], + group: ['a'] + } + }; - it('should create the right fields property when getPatientCountGroupedByLocation is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: "a,b,c", - startIndex: null, - limit: null - } - }; - - dao.getPatientCountGroupedByLocation(options, function (res) { - done(); - }); - - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + dao.getPatientCountGroupedByLocation(options, function (res) { + // console.log('body2 ++', res); + done(); + }); - expect(queryParts.columns).to.be.an('string'); - expect(queryParts.columns).to.include('t3.location_id,t3.name,count( distinct t1.patient_id) as total'); + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('amrs.patient'); + // if fields is null output all columns + expect(queryParts.columns).to.equal( + 't3.location_id,t3.name,count( distinct t1.patient_id) as total' + ); + expect(queryParts.joins).to.be.an('array'); + expect(queryParts.joins).to.have.deep.property( + '[0][0]', + 'amrs.encounter' + ); + expect(queryParts.joins).to.have.deep.property('[0][1]', 't2'); + expect(queryParts.joins).to.have.deep.property( + '[0][2]', + 't1.patient_id = t2.patient_id' + ); + expect(queryParts.joins).to.have.deep.property('[1][0]', 'amrs.location'); + expect(queryParts.joins).to.have.deep.property('[1][1]', 't3'); + + expect(queryParts.group).to.be.an('array'); + expect(queryParts.group).to.include('t3.uuid,t3.name'); + assert.equal(queryParts.group.length, 1); + }); + it('should create the right fields property when getPatientCountGroupedByLocation is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() }); - it('should create the right query parts object when getPatientDetailsGroupedByLocation is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '123' - }, - query: { - order: null, - fields: null, - startIndex: null, - limit: null, - joins: [['a', 't2'], ['c', 'd']], - group: ['a'] - } - }; - - // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); - - dao.getPatientDetailsGroupedByLocation(options, function (res) { - // console.log('body2 ++', res); - done(); - }); - - // console.log('body2 ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; - expect(queryParts.table).to.equal('amrs.patient'); - // if fields is null output all columns - expect(queryParts.columns).to.equal("distinct t4.uuid as patientUuid, t1.patient_id, t3.given_name, t3.middle_name, t3.family_name, t4.gender, extract(year from (from_days(datediff(now(),t4.birthdate)))) as age"); - expect(queryParts.joins).to.be.an('array'); - expect(queryParts.joins).to.have.deep.property('[0][0]', 'amrs.encounter'); - expect(queryParts.joins).to.have.deep.property('[0][1]', 't2'); - expect(queryParts.joins).to.have.deep.property('[0][2]', 't1.patient_id = t2.patient_id'); - expect(queryParts.joins).to.have.deep.property('[1][0]', 'amrs.person_name'); - expect(queryParts.joins).to.have.deep.property('[1][1]', 't3'); + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: 'a,b,c', + startIndex: null, + limit: null + } + }; + dao.getPatientCountGroupedByLocation(options, function (res) { + done(); }); - it('should create the right fields property when getPatientDetailsGroupedByLocation is called', - function (done) { - // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); - stub.yields({ - startIndex: 0, - size: 1, - result: mockData.getPatientMockData() - }); - var options = { - params: { - uuid: '124' - }, - query: { - order: null, - fields: "a,b,c", - startIndex: null, - limit: null - } - }; - - dao.getPatientDetailsGroupedByLocation(options, function (res) { - done(); - }); + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; - // console.log('bodyxx ++', stub.args[0][0]); - var queryParts = stub.args[0][0]; + expect(queryParts.columns).to.be.an('string'); + expect(queryParts.columns).to.include( + 't3.location_id,t3.name,count( distinct t1.patient_id) as total' + ); + }); + it('should create the right query parts object when getPatientDetailsGroupedByLocation is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() + }); + var options = { + params: { + uuid: '123' + }, + query: { + order: null, + fields: null, + startIndex: null, + limit: null, + joins: [ + ['a', 't2'], + ['c', 'd'] + ], + group: ['a'] + } + }; - expect(queryParts.columns).to.be.an('string'); - expect(queryParts.columns).to.include('distinct t4.uuid as patientUuid, t1.patient_id, t3.given_name, t3.middle_name, t3.family_name'); + // stub.withArgsWithAsync(options).yieldsTo(mockData.getPatientMockData()); + dao.getPatientDetailsGroupedByLocation(options, function (res) { + // console.log('body2 ++', res); + done(); }); + // console.log('body2 ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + expect(queryParts.table).to.equal('amrs.patient'); + // if fields is null output all columns + expect(queryParts.columns).to.equal( + 'distinct t4.uuid as patientUuid, t1.patient_id, t3.given_name, t3.middle_name, t3.family_name, t4.gender, extract(year from (from_days(datediff(now(),t4.birthdate)))) as age' + ); + expect(queryParts.joins).to.be.an('array'); + expect(queryParts.joins).to.have.deep.property( + '[0][0]', + 'amrs.encounter' + ); + expect(queryParts.joins).to.have.deep.property('[0][1]', 't2'); + expect(queryParts.joins).to.have.deep.property( + '[0][2]', + 't1.patient_id = t2.patient_id' + ); + expect(queryParts.joins).to.have.deep.property( + '[1][0]', + 'amrs.person_name' + ); + expect(queryParts.joins).to.have.deep.property('[1][1]', 't3'); + }); - it('should ensure that convertViralLoadPayloadToRestConsumableObs receives the right input and generates the correct payload', - function (done) { - var expectedInput = { - "PatientID": "value", - "DateCollected": "26-May-2016", - "FinalResult": 0 - } - var patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - var expectedOutput = { - concept: "a8982474-1350-11df-a1f1-0026b9348838", - person: "c6e4e026-3b49-4b64-81de-05cf8bd18594", - obsDatetime: "2016-05-26T00:00:00+03:00", - value: 0 - } - var payload = eidRestFormatter.convertViralLoadPayloadToRestConsumableObs(expectedInput, patientUuId); - payload.then(function (p) { - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("value"); - expect(p).deep.equal(expectedOutput); - done(); - }); - - }); - it('should ensure that convertCD4PayloadTORestConsumableObs receives the right input and generates the correct payload', - function (done) { - var expectedInput = { - "PatientID": "value", - "DateCollected": "26-May-2016", - "AVGCD3percentLymph": 81.49, - "AVGCD3AbsCnt": 1339.69, - "AVGCD3CD4percentLymph": 26.29, - "AVGCD3CD4AbsCnt": 432.28, - "CD45AbsCnt": 1644.03 - } - var patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - var expectedOutput = { - concept: "a896cce6-1350-11df-a1f1-0026b9348838", - person: "c6e4e026-3b49-4b64-81de-05cf8bd18594", - obsDatetime: "2016-05-26T00:00:00+03:00", - groupMembers: [ - { - "concept": "a89c4220-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 81.49, - "obsDatetime": "2016-05-26T00:00:00+03:00" - }, - { - "concept": "a898fcd2-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 1339.69, - "obsDatetime": "2016-05-26T00:00:00+03:00" - }, - { - "concept": "a8970a26-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 26.29, - "obsDatetime": "2016-05-26T00:00:00+03:00" - }, - { - "concept": "a8a8bb18-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 432.28, - "obsDatetime": "2016-05-26T00:00:00+03:00" - }, - { - "concept": "a89c4914-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 1644.03, - "obsDatetime": "2016-05-26T00:00:00+03:00" - } - ] - } - var payload = eidRestFormatter.convertCD4PayloadTORestConsumableObs(expectedInput, patientUuId); - payload.then(function (p) { - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("groupMembers"); - expect(p.groupMembers).to.be.an("array"); - - expect(p).deep.equal(expectedOutput); - done(); - }) + it('should create the right fields property when getPatientDetailsGroupedByLocation is called', function (done) { + // stub.callsArgWithAsync(1, null, { result:mockData.getPatientMockData() }); + stub.yields({ + startIndex: 0, + size: 1, + result: mockData.getPatientMockData() }); - it('should ensure that convertDNAPCRPayloadTORestConsumableObs receives the right input and generates the correct payload', - function (done) { - var expectedInput = { - "PatientID": "value", - "DateCollected": "26-May-2016", - "FinalResult": "NEGATIVE" - } - var patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - var expectedOutput = { - concept: "a898fe80-1350-11df-a1f1-0026b9348838", - person: "c6e4e026-3b49-4b64-81de-05cf8bd18594", - obsDatetime: "2016-05-26T00:00:00+03:00", - value: "a896d2cc-1350-11df-a1f1-0026b9348838" + var options = { + params: { + uuid: '124' + }, + query: { + order: null, + fields: 'a,b,c', + startIndex: null, + limit: null } - var payload = eidRestFormatter.convertDNAPCRPayloadTORestConsumableObs(expectedInput, patientUuId); - payload.then(function (p) { - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("value"); - - expect(p).deep.equal(expectedOutput); - done(); - }) + }; + dao.getPatientDetailsGroupedByLocation(options, function (res) { + done(); }); - it('should ensure that convertDNAPCRPayloadTORestConsumableObs receives the right input and generates the correct payload', - function (done) { - var expectedInput = { - "PatientID": "value", - "DateCollected": "26-May-2016", - "FinalResult": "POSITIVE" - } - var patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - var expectedOutput = { - concept: "a898fe80-1350-11df-a1f1-0026b9348838", - person: "c6e4e026-3b49-4b64-81de-05cf8bd18594", - obsDatetime: "2016-05-26T00:00:00+03:00", - value: "a896f3a6-1350-11df-a1f1-0026b9348838" - } - var payload = eidRestFormatter.convertDNAPCRPayloadTORestConsumableObs(expectedInput, patientUuId); - payload.then(function (p) { - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("value"); - expect(p).deep.equal(expectedOutput); - done(); + // console.log('bodyxx ++', stub.args[0][0]); + var queryParts = stub.args[0][0]; + + expect(queryParts.columns).to.be.an('string'); + expect(queryParts.columns).to.include( + 'distinct t4.uuid as patientUuid, t1.patient_id, t3.given_name, t3.middle_name, t3.family_name' + ); + }); - }) + it('should ensure that convertViralLoadPayloadToRestConsumableObs receives the right input and generates the correct payload', function (done) { + var expectedInput = { + PatientID: 'value', + DateCollected: '26-May-2016', + FinalResult: 0 + }; + var patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + var expectedOutput = { + concept: 'a8982474-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2016-05-26T00:00:00+03:00', + value: 0 + }; + var payload = eidRestFormatter.convertViralLoadPayloadToRestConsumableObs( + expectedInput, + patientUuId + ); + payload.then(function (p) { + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('value'); + expect(p).deep.equal(expectedOutput); + done(); }); - it('should ensure that the convertViralLoadExceptionToRestConsumableObs function generates the right output', - function (done) { - var expectedInput = { - "LabID": "173545", - "PatientID": "2524040", - "ProviderID": "1289-8", - "MFLCode": "15204", - "AMRslocationID": "14", - "AMRslocation": "MTRH Module 3", - "PatientNames": "XXXXXXX", - "DateCollected": "26-May-2016", - "DateReceived": "26-May-2016", - "DateTested": "30-May-2016", - "Result": "4064 ", - "FinalResult": "wewe tu", - "DateDispatched": "08-Jun-2016" - } - var patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - var payload = eidRestFormatter.convertViralLoadExceptionToRestConsumableObs(expectedInput, patientUuId); - payload.then(function (p) { - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("groupMembers"); - expect(p.groupMembers).to.be.an("array"); - done(); - - }); + }); + it('should ensure that convertCD4PayloadTORestConsumableObs receives the right input and generates the correct payload', function (done) { + var expectedInput = { + PatientID: 'value', + DateCollected: '26-May-2016', + AVGCD3percentLymph: 81.49, + AVGCD3AbsCnt: 1339.69, + AVGCD3CD4percentLymph: 26.29, + AVGCD3CD4AbsCnt: 432.28, + CD45AbsCnt: 1644.03 + }; + var patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + var expectedOutput = { + concept: 'a896cce6-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2016-05-26T00:00:00+03:00', + groupMembers: [ + { + concept: 'a89c4220-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 81.49, + obsDatetime: '2016-05-26T00:00:00+03:00' + }, + { + concept: 'a898fcd2-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 1339.69, + obsDatetime: '2016-05-26T00:00:00+03:00' + }, + { + concept: 'a8970a26-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 26.29, + obsDatetime: '2016-05-26T00:00:00+03:00' + }, + { + concept: 'a8a8bb18-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 432.28, + obsDatetime: '2016-05-26T00:00:00+03:00' + }, + { + concept: 'a89c4914-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 1644.03, + obsDatetime: '2016-05-26T00:00:00+03:00' + } + ] + }; + var payload = eidRestFormatter.convertCD4PayloadTORestConsumableObs( + expectedInput, + patientUuId + ); + payload.then(function (p) { + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('groupMembers'); + expect(p.groupMembers).to.be.an('array'); + + expect(p).deep.equal(expectedOutput); + done(); }); - it('should ensure that the convertCD4ExceptionTORestConsumableObs function generates the right output', - function (done) { - var expectedInput = { - "LabID": "6304", - "PatientID": "000981160-5", - "ProviderID": "", - "MFLCode": "15753", - "AMRslocationID": "3", - "AMRslocation": "Turbo", - "PatientNames": "XXXXXXXXXXXXXXXXXXXXXX", - "DateCollected": "02-Jun-2016", - "DateReceived": "06-Jun-2016", - "DateTested": "06-Jun-2016", - "Result": "81.49", - "AVGCD3percentLymph": "Not done", - "AVGCD3AbsCnt": "Not done", - "AVGCD3CD4percentLymph": "Not done", - "AVGCD3CD4AbsCnt": "not done", - "CD45AbsCnt": "not done", - "DateDispatched": "" - } - var patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - var payload = eidRestFormatter.convertCD4ExceptionTORestConsumableObs(expectedInput, patientUuId); - payload.then(function (p) { - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("groupMembers"); - expect(p.groupMembers).to.be.an("array"); - done(); - - }); + }); + it('should ensure that convertDNAPCRPayloadTORestConsumableObs receives the right input and generates the correct payload', function (done) { + var expectedInput = { + PatientID: 'value', + DateCollected: '26-May-2016', + FinalResult: 'NEGATIVE' + }; + var patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + var expectedOutput = { + concept: 'a898fe80-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2016-05-26T00:00:00+03:00', + value: 'a896d2cc-1350-11df-a1f1-0026b9348838' + }; + var payload = eidRestFormatter.convertDNAPCRPayloadTORestConsumableObs( + expectedInput, + patientUuId + ); + payload.then(function (p) { + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('value'); + + expect(p).deep.equal(expectedOutput); + done(); }); - + }); + it('should ensure that convertDNAPCRPayloadTORestConsumableObs receives the right input and generates the correct payload', function (done) { + var expectedInput = { + PatientID: 'value', + DateCollected: '26-May-2016', + FinalResult: 'POSITIVE' + }; + var patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + var expectedOutput = { + concept: 'a898fe80-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2016-05-26T00:00:00+03:00', + value: 'a896f3a6-1350-11df-a1f1-0026b9348838' + }; + var payload = eidRestFormatter.convertDNAPCRPayloadTORestConsumableObs( + expectedInput, + patientUuId + ); + payload.then(function (p) { + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('value'); + + expect(p).deep.equal(expectedOutput); + done(); + }); + }); + it('should ensure that the convertViralLoadExceptionToRestConsumableObs function generates the right output', function (done) { + var expectedInput = { + LabID: '173545', + PatientID: '2524040', + ProviderID: '1289-8', + MFLCode: '15204', + AMRslocationID: '14', + AMRslocation: 'MTRH Module 3', + PatientNames: 'XXXXXXX', + DateCollected: '26-May-2016', + DateReceived: '26-May-2016', + DateTested: '30-May-2016', + Result: '4064 ', + FinalResult: 'wewe tu', + DateDispatched: '08-Jun-2016' + }; + var patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + var payload = eidRestFormatter.convertViralLoadExceptionToRestConsumableObs( + expectedInput, + patientUuId + ); + payload.then(function (p) { + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('groupMembers'); + expect(p.groupMembers).to.be.an('array'); + done(); + }); + }); + it('should ensure that the convertCD4ExceptionTORestConsumableObs function generates the right output', function (done) { + var expectedInput = { + LabID: '6304', + PatientID: '000981160-5', + ProviderID: '', + MFLCode: '15753', + AMRslocationID: '3', + AMRslocation: 'Turbo', + PatientNames: 'XXXXXXXXXXXXXXXXXXXXXX', + DateCollected: '02-Jun-2016', + DateReceived: '06-Jun-2016', + DateTested: '06-Jun-2016', + Result: '81.49', + AVGCD3percentLymph: 'Not done', + AVGCD3AbsCnt: 'Not done', + AVGCD3CD4percentLymph: 'Not done', + AVGCD3CD4AbsCnt: 'not done', + CD45AbsCnt: 'not done', + DateDispatched: '' + }; + var patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + var payload = eidRestFormatter.convertCD4ExceptionTORestConsumableObs( + expectedInput, + patientUuId + ); + payload.then(function (p) { + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('groupMembers'); + expect(p.groupMembers).to.be.an('array'); + done(); + }); + }); }); }); diff --git a/test/database-access/query.service.test.js b/test/database-access/query.service.test.js index b2f4873bd..bb5503e51 100755 --- a/test/database-access/query.service.test.js +++ b/test/database-access/query.service.test.js @@ -1,30 +1,31 @@ import QueryService from '../../app/database-access/query.service'; const chai = require('chai'), - should = chai.should(), - expect = chai.expect, - chaiAsPromised = require('chai-as-promised'), - Mysql = require('mysql'), - sinon = require('sinon'), - Promise = require('bluebird'); - + should = chai.should(), + expect = chai.expect, + chaiAsPromised = require('chai-as-promised'), + Mysql = require('mysql'), + sinon = require('sinon'), + Promise = require('bluebird'); chai.use(chaiAsPromised); describe('Query Service', function () { - const queryService = new QueryService(); - let executeQueryStub; - beforeEach(() => { - executeQueryStub = sinon.stub(queryService, 'executeQuery').resolves(''); - }); - afterEach(() => { - queryService.executeQuery.restore(); - }); - - it('executeQuery should resolve with a promise', (done) => { - queryService.executeQuery('select * from etl.flat_hiv_summary limit 100').then( (result) => { - expect(result).to.equal(''); - }).then(done, done) - }); + const queryService = new QueryService(); + let executeQueryStub; + beforeEach(() => { + executeQueryStub = sinon.stub(queryService, 'executeQuery').resolves(''); + }); + afterEach(() => { + queryService.executeQuery.restore(); + }); -}); \ No newline at end of file + it('executeQuery should resolve with a promise', (done) => { + queryService + .executeQuery('select * from etl.flat_hiv_summary limit 100') + .then((result) => { + expect(result).to.equal(''); + }) + .then(done, done); + }); +}); diff --git a/test/eid-obs-compare.test.js b/test/eid-obs-compare.test.js index 2e56d8fc2..d9cf065db 100755 --- a/test/eid-obs-compare.test.js +++ b/test/eid-obs-compare.test.js @@ -19,677 +19,693 @@ var baseUrl = 'http://localhost:8002'; chai.use(sinonChai); describe('EID-OBS COMPARE TESTS', function () { - - beforeEach(function (done) { - - done(); - }); - - afterEach(function () { - - }); - - it('should load eid-obs-compare module', - function () { - expect(eidObsCompare).to.be.defined; - //expect(userSample).to.be.defined; - }); - - it('should load lab data samples module', - function () { - expect(labDataSamples).to.be.defined; - //expect(userSample).to.be.defined; - }); - - it('should match eid and amrs viral load correctly when isViralLoadEquivalent', - function () { - - //CASE 1: EID result is not an error and is a number - var eidResult = labDataSamples.getEidViralLoad(); - var equivalentObs = labDataSamples.getAmrsViralLoadObs(); - - var isEquivalent = eidObsCompare.isViralLoadEquivalent(eidResult, equivalentObs); - - expect(isEquivalent).to.be.true; - - //CASE 2: EID result is not an error and is not a number - eidResult = { - "LabID": "173545", - "PatientID": "2524040", - "ProviderID": "1289-8", - "MFLCode": "15204", - "AMRslocationID": "14", - "AMRslocation": "MTRH Module 3", - "PatientNames": "XXXXXXX", - "DateCollected": "26-May-2016", - "DateReceived": "26-May-2016", - "DateTested": "30-May-2016", - "Result": "3", - "FinalResult": "<150", - "DateDispatched": "08-Jun-2016" - }; - - equivalentObs = { - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - obsDatetime: '2016-05-26T00:00:00+03:00', - concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, - value: 0 - }; - - var isEquivalent = eidObsCompare.isViralLoadEquivalent(eidResult, equivalentObs); - - expect(isEquivalent).to.be.true; - - //CASE 3: EID result is an error - eidResult = { - "LabID": "173545", - "PatientID": "2524040", - "ProviderID": "1289-8", - "MFLCode": "15204", - "AMRslocationID": "14", - "AMRslocation": "MTRH Module 3", - "PatientNames": "XXXXXXX", - "DateCollected": "26-May-2016", - "DateReceived": "26-May-2016", - "DateTested": "30-May-2016", - "Result": "4064 ", - "FinalResult": "wewe tu", - "DateDispatched": "08-Jun-2016" - }; - equivalentObs = { - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - obsDatetime: '2016-05-26T00:00:00+03:00', - concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, - groupMembers: [ - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-05-26T00:00:00+03:00' - }, - { - concept: 'a8a06fc6-1350-11df-a1f1-0026b9348838', - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: 'wewe tu', - obsDatetime: '2016-05-26T00:00:00+03:00' - } - ] - }; - - isEquivalent = eidObsCompare.isViralLoadEquivalent(eidResult, equivalentObs); - - expect(isEquivalent).to.be.true; - - }); - - it('should match eid and amrs DNA PCR correctly when isDnaPcrEquivalent', - function () { - var eidResult = labDataSamples.getEidDnaPcr(); - var equivalentObs = labDataSamples.getAmrsEidPcrObs(); - - var isEquivalent = eidObsCompare.isDnaPcrEquivalent(eidResult, equivalentObs); - - expect(isEquivalent).to.be.true; - }); - - - it('should match eid and amrs CD4 Panel correctly when isCd4PanelEquivalent', - function () { - //CASE 1 EID result is valid - var eidResult = labDataSamples.getEidCd4Panel(); - var equivalentObs = labDataSamples.getAmrsCd4PanelObs(); - - var isEquivalent = eidObsCompare.isCd4PanelEquivalent(eidResult, equivalentObs); - - expect(isEquivalent).to.be.true; - - //CASE 2 EID result is an error - eidResult = { - "LabID": "6304", - "PatientID": "000981160-5", - "ProviderID": "", - "MFLCode": "15753", - "AMRslocationID": "3", - "AMRslocation": "Turbo", - "PatientNames": "XXXXXXXXXXXXXXXXXXXXXX", - "DateCollected": "02-Jun-2016", - "DateReceived": "06-Jun-2016", - "DateTested": "06-Jun-2016", - "Result": "81.49", - "AVGCD3percentLymph": "Not done", - "AVGCD3AbsCnt": "Not done", - "AVGCD3CD4percentLymph": "Not done", - "AVGCD3CD4AbsCnt": "not done", - "CD45AbsCnt": "not done", - "DateDispatched": "" - }; - - equivalentObs = { - concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - obsDatetime: '2016-06-02T00:00:00+03:00', - groupMembers: [ - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a89c4220-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a8970a26-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: 'a89c4914-1350-11df-a1f1-0026b9348838', - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - } - ] - }; - - isEquivalent = eidObsCompare.isCd4PanelEquivalent(eidResult, equivalentObs); - - expect(isEquivalent).to.be.true; - - }); - - it('should locate a given eid result in an array of obs correctly when findEquivalentObject', - function () { - var arrayOfObs = [ - { - concept: { uuid: 'concept1' }, - obsDateTime: '2014-01-01' - }, - { - concept: { uuid: 'concept2' }, - obsDateTime: '2013-06-02' - }, - { - concept: { uuid: 'concept3' }, - obsDatetime: '2014-01-04' - }, - { - concept: { uuid: 'concept4' }, - obsDatetime: '2014-01-04' - } - ]; - - var eidResult = { - DateCollected: '2014-01-04' - }; - - var foundObs = - eidObsCompare.findEquivalentObject(eidResult, arrayOfObs, - function (eid, obs) { - return eidObsCompare.conceptDateComparer(eid, obs, 'concept3'); - }); - - expect(foundObs).to.deep.equal(arrayOfObs[2]); - }); - - it('should return all missing EID results when findMissingEidResult', - function () { - var arrayOfObs = [ - { - concept: { uuid: 'concept1' }, - obsDateTime: '2014-01-01' - }, - { - concept: { uuid: 'concept2' }, - obsDateTime: '2013-06-02' - }, - { - concept: { uuid: 'concept3' }, - obsDatetime: '2014-01-04' - }, - { - concept: { uuid: 'concept4' }, - obsDatetime: '2014-01-04' - }, - { - concept: { uuid: 'concept3' }, - obsDatetime: '2016-03-04' - } - ]; - - var eidResults = [ - { - DateCollected: '2014-01-04' - }, - { - DateCollected: '2011-01-04' - }, - { - DateCollected: '2010-01-04' - }, - { - DateCollected: '2016-03-04' - }, - { - DateCollected: '2014-01-23' - }, - ]; - - var foundObs = - eidObsCompare.findMissingEidResults(eidResults, arrayOfObs, - function (eid, obs) { - return eidObsCompare.conceptDateComparer(eid, obs, 'concept3'); - }); - expect(foundObs.length).to.equal(3); - expect(foundObs[0]).to.deep.equal(eidResults[1]); - expect(foundObs[1]).to.deep.equal(eidResults[2]); - expect(foundObs[2]).to.deep.equal(eidResults[4]); - }); - - it('should call correct functions to/and find all eid results when ' + - 'findAllMissingEidResults', - function () { - var eidResults = { - viralLoad: [{ DateCollected: '2016-03-04' }], - pcr: [{ DateCollected: '2015-03-04' }], - cd4Panel: [{ DateCollected: '2014-03-04' }] - }; - var spy = sinon.spy(eidObsCompare, 'findMissingEidResults'); - var results = eidObsCompare.findAllMissingEidResults(eidResults, []); - - console.log('results', results); - expect(spy.calledThrice).to.be.true; //proof that all three tests are compared - - //proof that checked for viral load - expect(spy.firstCall.calledWith(eidResults.viralLoad, [], eidObsCompare.isViralLoadEquivalent)).to.be.true; - - //proof that checked for pcr - expect(spy.secondCall.calledWith(eidResults.pcr, [], eidObsCompare.isDnaPcrEquivalent)).to.be.true; - - //proof that checked for cd4Panel - expect(spy.thirdCall.calledWith(eidResults.cd4Panel, [], eidObsCompare.isCd4PanelEquivalent)).to.be.true; - - //results are as expected - expect(eidResults).to.deep.equal(results); //since we are passing empty obs, then all results are missing - }); - - it('should merge EID results when mergeEidResults', - function () { - var eidResults = [ - { - patientIdentifier: 'id1', - viralLoad: ['val 1', 'val 2'], - pcr: ['val 1', 'val 2', 'val 3'], - cd4Panel: ['val 1', 'val 2', 'val 3'] - }, - { - patientIdentifier: 'id2', - viralLoad: ['val 3', 'val 4'], - pcr: ['val 4', 'val 5', 'val 6'], - cd4Panel: ['val 4', 'val 5', 'val 6'] - } - ]; - - var expectedMergedResults = { - viralLoad: ['val 1', 'val 2', 'val 3', 'val 4'], - pcr: ['val 1', 'val 2', 'val 3', 'val 4', 'val 5', 'val 6'], - cd4Panel: ['val 1', 'val 2', 'val 3', 'val 4', 'val 5', 'val 6'] - }; - - var mergedResult = eidObsCompare.mergeEidResults(eidResults); - - expect(mergedResult).to.deep.equal(expectedMergedResults); - }); - - it('should return correctly when isEidViralLoadError', - function () { - var viralLoadError = { - "LabID": "173545", - "PatientID": "2524040", - "ProviderID": "1289-8", - "MFLCode": "15204", - "AMRslocationID": "14", - "AMRslocation": "MTRH Module 3", - "PatientNames": "XXXXXXX", - "DateCollected": "26-May-2016", - "DateReceived": "26-May-2016", - "DateTested": "30-May-2016", - "Result": "4064 ", - "FinalResult": "wewe tu", - "DateDispatched": "08-Jun-2016" - }; - - expect(eidObsCompare.isEidViralLoadError(viralLoadError)).to.be.true; - }); - - it('should return correctly when isEidCD4PanelError', - function () { - var cd4Error = { - "LabID": "6304", - "PatientID": "000981160-5", - "ProviderID": "", - "MFLCode": "15753", - "AMRslocationID": "3", - "AMRslocation": "Turbo", - "PatientNames": "XXXXXXXXXXXXXXXXXXXXXX", - "DateCollected": "02-Jun-2016", - "DateReceived": "06-Jun-2016", - "DateTested": "06-Jun-2016", - "Result": "81.49", - "AVGCD3percentLymph": "Not done", - "AVGCD3AbsCnt": "Not done", - "AVGCD3CD4percentLymph": "Not done", - "AVGCD3CD4AbsCnt": "not done", - "CD45AbsCnt": "not done", - "DateDispatched": "" - }; - - expect(eidObsCompare.isEidCD4PanelError(cd4Error)).to.be.true; - }); - - it('should return correctly when isObsViralLoadError', - function () { - var viralLoadError = { - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - obsDatetime: '2016-05-26T00:00:00+03:00', - concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, - groupMembers: [ - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-05-26T00:00:00+03:00' - }, - { - concept: { uuid: 'a8a06fc6-1350-11df-a1f1-0026b9348838' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: 'wewe tu', - obsDatetime: '2016-05-26T00:00:00+03:00' - } - ] - }; - - expect(eidObsCompare.isObsViralLoadError(viralLoadError)).to.be.true; - }); - - it('should return correctly when isObsCd4PanelError', - function () { - var cd4Error = { - concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - obsDatetime: '2016-06-02T00:00:00+03:00', - groupMembers: [ - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a89c4220-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a8970a26-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a89c4914-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - }, - { - concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-06-02T00:00:00+03:00' - } - ] - }; - - expect(eidObsCompare.isObsCd4PanelError(cd4Error)).to.be.true; - }); - - - it('should find all conflicting EID and AMRS viral load results', () => { - var eidResults = [ - { - "LabID": "173545", - "PatientID": "2524040", - "ProviderID": "1289-8", - "MFLCode": "15204", - "AMRslocationID": "14", - "AMRslocation": "MTRH Module 3", - "PatientNames": "XXXXXXX", - "DateCollected": "26-May-2016", - "DateReceived": "26-May-2016", - "DateTested": "30-May-2016", - "Result": "3", - "FinalResult": "130", - "DateDispatched": "08-Jun-2016" - }, - { - "LabID": "173545", - "PatientID": "2524040", - "ProviderID": "1289-8", - "MFLCode": "15204", - "AMRslocationID": "14", - "AMRslocation": "MTRH Module 3", - "PatientNames": "XXXXXXX", - "DateCollected": "5-May-2016", - "DateReceived": "26-May-2016", - "DateTested": "30-May-2016", - "Result": "3", - "FinalResult": "<150", - "DateDispatched": "08-Jun-2016" - }, - { - "LabID": "173545", - "PatientID": "2524040", - "ProviderID": "1289-8", - "MFLCode": "15204", - "AMRslocationID": "14", - "AMRslocation": "MTRH Module 3", - "PatientNames": "XXXXXXX", - "DateCollected": "10-May-2016", - "DateReceived": "26-May-2016", - "DateTested": "30-May-2016", - "Result": "Error", - "FinalResult": "Error", - "DateDispatched": "08-Jun-2016" - }, - { - "LabID": "173545", - "PatientID": "2524040", - "ProviderID": "1289-8", - "MFLCode": "15204", - "AMRslocationID": "14", - "AMRslocation": "MTRH Module 3", - "PatientNames": "XXXXXXX", - "DateCollected": "12-May-2016", - "DateReceived": "26-May-2016", - "DateTested": "30-May-2016", - "Result": "78", - "FinalResult": "288", - "DateDispatched": "08-Jun-2016" - } - ]; - - var amrsObs = [ - { - uuid: 'uuid1', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-26T00:00:00+03:00', - concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, - value: 0 - }, - { - uuid: 'uuid2', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-26T00:00:00+03:00', - concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, - value: 130 - }, - { - uuid: 'uuid3', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-05T00:00:00+03:00', - concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, - value: 0 - }, - { - uuid: 'uuid4', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-05T00:00:00+03:00', - concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, - groupMembers: [ - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-05-05T00:00:00+03:00' - }, - { - concept: 'a8a06fc6-1350-11df-a1f1-0026b9348838', - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: 'wewe tu', - obsDatetime: '2016-05-05T00:00:00+03:00' - } - ] - }, - { - uuid: 'uuid5', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-10T00:00:00+03:00', - concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, - value: 0 - }, - { - uuid: 'uuid6', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-10T00:00:00+03:00', - concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, - groupMembers: [ - { - concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, - obsDatetime: '2016-05-10T00:00:00+03:00' - }, - { - concept: 'a8a06fc6-1350-11df-a1f1-0026b9348838', - person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', - value: 'wewe tu', - obsDatetime: '2016-05-10T00:00:00+03:00' - } - ] - }, - { - uuid: 'uuid6', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-10T00:00:00+03:00', - concept: { uuid: 'some other uuid' }, - value: 'some other' - } - ]; - - var conflicting = [ - { - eid: eidResults[0], - obs: [amrsObs[0]] - }, - { - eid: eidResults[1], - obs: [amrsObs[3]] - }, - { - eid: eidResults[2], - obs: [amrsObs[4]] - } - ]; - - var results = - eidObsCompare.findConflictingEidAmrsViralLoadResults(eidResults, amrsObs); - - expect(results).to.deep.equal(conflicting); - - }); - - - + beforeEach(function (done) { + done(); + }); + + afterEach(function () {}); + + it('should load eid-obs-compare module', function () { + expect(eidObsCompare).to.be.defined; + //expect(userSample).to.be.defined; + }); + + it('should load lab data samples module', function () { + expect(labDataSamples).to.be.defined; + //expect(userSample).to.be.defined; + }); + + it('should match eid and amrs viral load correctly when isViralLoadEquivalent', function () { + //CASE 1: EID result is not an error and is a number + var eidResult = labDataSamples.getEidViralLoad(); + var equivalentObs = labDataSamples.getAmrsViralLoadObs(); + + var isEquivalent = eidObsCompare.isViralLoadEquivalent( + eidResult, + equivalentObs + ); + + expect(isEquivalent).to.be.true; + + //CASE 2: EID result is not an error and is not a number + eidResult = { + LabID: '173545', + PatientID: '2524040', + ProviderID: '1289-8', + MFLCode: '15204', + AMRslocationID: '14', + AMRslocation: 'MTRH Module 3', + PatientNames: 'XXXXXXX', + DateCollected: '26-May-2016', + DateReceived: '26-May-2016', + DateTested: '30-May-2016', + Result: '3', + FinalResult: '<150', + DateDispatched: '08-Jun-2016' + }; + + equivalentObs = { + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2016-05-26T00:00:00+03:00', + concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + value: 0 + }; + + var isEquivalent = eidObsCompare.isViralLoadEquivalent( + eidResult, + equivalentObs + ); + + expect(isEquivalent).to.be.true; + + //CASE 3: EID result is an error + eidResult = { + LabID: '173545', + PatientID: '2524040', + ProviderID: '1289-8', + MFLCode: '15204', + AMRslocationID: '14', + AMRslocation: 'MTRH Module 3', + PatientNames: 'XXXXXXX', + DateCollected: '26-May-2016', + DateReceived: '26-May-2016', + DateTested: '30-May-2016', + Result: '4064 ', + FinalResult: 'wewe tu', + DateDispatched: '08-Jun-2016' + }; + equivalentObs = { + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2016-05-26T00:00:00+03:00', + concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, + groupMembers: [ + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-05-26T00:00:00+03:00' + }, + { + concept: 'a8a06fc6-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 'wewe tu', + obsDatetime: '2016-05-26T00:00:00+03:00' + } + ] + }; + + isEquivalent = eidObsCompare.isViralLoadEquivalent( + eidResult, + equivalentObs + ); + + expect(isEquivalent).to.be.true; + }); + + it('should match eid and amrs DNA PCR correctly when isDnaPcrEquivalent', function () { + var eidResult = labDataSamples.getEidDnaPcr(); + var equivalentObs = labDataSamples.getAmrsEidPcrObs(); + + var isEquivalent = eidObsCompare.isDnaPcrEquivalent( + eidResult, + equivalentObs + ); + + expect(isEquivalent).to.be.true; + }); + + it('should match eid and amrs CD4 Panel correctly when isCd4PanelEquivalent', function () { + //CASE 1 EID result is valid + var eidResult = labDataSamples.getEidCd4Panel(); + var equivalentObs = labDataSamples.getAmrsCd4PanelObs(); + + var isEquivalent = eidObsCompare.isCd4PanelEquivalent( + eidResult, + equivalentObs + ); + + expect(isEquivalent).to.be.true; + + //CASE 2 EID result is an error + eidResult = { + LabID: '6304', + PatientID: '000981160-5', + ProviderID: '', + MFLCode: '15753', + AMRslocationID: '3', + AMRslocation: 'Turbo', + PatientNames: 'XXXXXXXXXXXXXXXXXXXXXX', + DateCollected: '02-Jun-2016', + DateReceived: '06-Jun-2016', + DateTested: '06-Jun-2016', + Result: '81.49', + AVGCD3percentLymph: 'Not done', + AVGCD3AbsCnt: 'Not done', + AVGCD3CD4percentLymph: 'Not done', + AVGCD3CD4AbsCnt: 'not done', + CD45AbsCnt: 'not done', + DateDispatched: '' + }; + + equivalentObs = { + concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2016-06-02T00:00:00+03:00', + groupMembers: [ + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a89c4220-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a8970a26-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 'a89c4914-1350-11df-a1f1-0026b9348838', + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + } + ] + }; + + isEquivalent = eidObsCompare.isCd4PanelEquivalent(eidResult, equivalentObs); + + expect(isEquivalent).to.be.true; + }); + + it('should locate a given eid result in an array of obs correctly when findEquivalentObject', function () { + var arrayOfObs = [ + { + concept: { uuid: 'concept1' }, + obsDateTime: '2014-01-01' + }, + { + concept: { uuid: 'concept2' }, + obsDateTime: '2013-06-02' + }, + { + concept: { uuid: 'concept3' }, + obsDatetime: '2014-01-04' + }, + { + concept: { uuid: 'concept4' }, + obsDatetime: '2014-01-04' + } + ]; + + var eidResult = { + DateCollected: '2014-01-04' + }; + + var foundObs = eidObsCompare.findEquivalentObject( + eidResult, + arrayOfObs, + function (eid, obs) { + return eidObsCompare.conceptDateComparer(eid, obs, 'concept3'); + } + ); + + expect(foundObs).to.deep.equal(arrayOfObs[2]); + }); + + it('should return all missing EID results when findMissingEidResult', function () { + var arrayOfObs = [ + { + concept: { uuid: 'concept1' }, + obsDateTime: '2014-01-01' + }, + { + concept: { uuid: 'concept2' }, + obsDateTime: '2013-06-02' + }, + { + concept: { uuid: 'concept3' }, + obsDatetime: '2014-01-04' + }, + { + concept: { uuid: 'concept4' }, + obsDatetime: '2014-01-04' + }, + { + concept: { uuid: 'concept3' }, + obsDatetime: '2016-03-04' + } + ]; + + var eidResults = [ + { + DateCollected: '2014-01-04' + }, + { + DateCollected: '2011-01-04' + }, + { + DateCollected: '2010-01-04' + }, + { + DateCollected: '2016-03-04' + }, + { + DateCollected: '2014-01-23' + } + ]; + + var foundObs = eidObsCompare.findMissingEidResults( + eidResults, + arrayOfObs, + function (eid, obs) { + return eidObsCompare.conceptDateComparer(eid, obs, 'concept3'); + } + ); + expect(foundObs.length).to.equal(3); + expect(foundObs[0]).to.deep.equal(eidResults[1]); + expect(foundObs[1]).to.deep.equal(eidResults[2]); + expect(foundObs[2]).to.deep.equal(eidResults[4]); + }); + + it( + 'should call correct functions to/and find all eid results when ' + + 'findAllMissingEidResults', + function () { + var eidResults = { + viralLoad: [{ DateCollected: '2016-03-04' }], + pcr: [{ DateCollected: '2015-03-04' }], + cd4Panel: [{ DateCollected: '2014-03-04' }] + }; + var spy = sinon.spy(eidObsCompare, 'findMissingEidResults'); + var results = eidObsCompare.findAllMissingEidResults(eidResults, []); + + console.log('results', results); + expect(spy.calledThrice).to.be.true; //proof that all three tests are compared + + //proof that checked for viral load + expect( + spy.firstCall.calledWith( + eidResults.viralLoad, + [], + eidObsCompare.isViralLoadEquivalent + ) + ).to.be.true; + + //proof that checked for pcr + expect( + spy.secondCall.calledWith( + eidResults.pcr, + [], + eidObsCompare.isDnaPcrEquivalent + ) + ).to.be.true; + + //proof that checked for cd4Panel + expect( + spy.thirdCall.calledWith( + eidResults.cd4Panel, + [], + eidObsCompare.isCd4PanelEquivalent + ) + ).to.be.true; + + //results are as expected + expect(eidResults).to.deep.equal(results); //since we are passing empty obs, then all results are missing + } + ); + + it('should merge EID results when mergeEidResults', function () { + var eidResults = [ + { + patientIdentifier: 'id1', + viralLoad: ['val 1', 'val 2'], + pcr: ['val 1', 'val 2', 'val 3'], + cd4Panel: ['val 1', 'val 2', 'val 3'] + }, + { + patientIdentifier: 'id2', + viralLoad: ['val 3', 'val 4'], + pcr: ['val 4', 'val 5', 'val 6'], + cd4Panel: ['val 4', 'val 5', 'val 6'] + } + ]; + + var expectedMergedResults = { + viralLoad: ['val 1', 'val 2', 'val 3', 'val 4'], + pcr: ['val 1', 'val 2', 'val 3', 'val 4', 'val 5', 'val 6'], + cd4Panel: ['val 1', 'val 2', 'val 3', 'val 4', 'val 5', 'val 6'] + }; + + var mergedResult = eidObsCompare.mergeEidResults(eidResults); + + expect(mergedResult).to.deep.equal(expectedMergedResults); + }); + + it('should return correctly when isEidViralLoadError', function () { + var viralLoadError = { + LabID: '173545', + PatientID: '2524040', + ProviderID: '1289-8', + MFLCode: '15204', + AMRslocationID: '14', + AMRslocation: 'MTRH Module 3', + PatientNames: 'XXXXXXX', + DateCollected: '26-May-2016', + DateReceived: '26-May-2016', + DateTested: '30-May-2016', + Result: '4064 ', + FinalResult: 'wewe tu', + DateDispatched: '08-Jun-2016' + }; + + expect(eidObsCompare.isEidViralLoadError(viralLoadError)).to.be.true; + }); + + it('should return correctly when isEidCD4PanelError', function () { + var cd4Error = { + LabID: '6304', + PatientID: '000981160-5', + ProviderID: '', + MFLCode: '15753', + AMRslocationID: '3', + AMRslocation: 'Turbo', + PatientNames: 'XXXXXXXXXXXXXXXXXXXXXX', + DateCollected: '02-Jun-2016', + DateReceived: '06-Jun-2016', + DateTested: '06-Jun-2016', + Result: '81.49', + AVGCD3percentLymph: 'Not done', + AVGCD3AbsCnt: 'Not done', + AVGCD3CD4percentLymph: 'Not done', + AVGCD3CD4AbsCnt: 'not done', + CD45AbsCnt: 'not done', + DateDispatched: '' + }; + + expect(eidObsCompare.isEidCD4PanelError(cd4Error)).to.be.true; + }); + + it('should return correctly when isObsViralLoadError', function () { + var viralLoadError = { + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2016-05-26T00:00:00+03:00', + concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, + groupMembers: [ + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-05-26T00:00:00+03:00' + }, + { + concept: { uuid: 'a8a06fc6-1350-11df-a1f1-0026b9348838' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 'wewe tu', + obsDatetime: '2016-05-26T00:00:00+03:00' + } + ] + }; + + expect(eidObsCompare.isObsViralLoadError(viralLoadError)).to.be.true; + }); + + it('should return correctly when isObsCd4PanelError', function () { + var cd4Error = { + concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2016-06-02T00:00:00+03:00', + groupMembers: [ + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a89c4220-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a8970a26-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a89c4914-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + }, + { + concept: { uuid: '5026a3ee-0612-48bf-b9a3-a2944ddc3e04' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a899ea48-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-06-02T00:00:00+03:00' + } + ] + }; + + expect(eidObsCompare.isObsCd4PanelError(cd4Error)).to.be.true; + }); + + it('should find all conflicting EID and AMRS viral load results', () => { + var eidResults = [ + { + LabID: '173545', + PatientID: '2524040', + ProviderID: '1289-8', + MFLCode: '15204', + AMRslocationID: '14', + AMRslocation: 'MTRH Module 3', + PatientNames: 'XXXXXXX', + DateCollected: '26-May-2016', + DateReceived: '26-May-2016', + DateTested: '30-May-2016', + Result: '3', + FinalResult: '130', + DateDispatched: '08-Jun-2016' + }, + { + LabID: '173545', + PatientID: '2524040', + ProviderID: '1289-8', + MFLCode: '15204', + AMRslocationID: '14', + AMRslocation: 'MTRH Module 3', + PatientNames: 'XXXXXXX', + DateCollected: '5-May-2016', + DateReceived: '26-May-2016', + DateTested: '30-May-2016', + Result: '3', + FinalResult: '<150', + DateDispatched: '08-Jun-2016' + }, + { + LabID: '173545', + PatientID: '2524040', + ProviderID: '1289-8', + MFLCode: '15204', + AMRslocationID: '14', + AMRslocation: 'MTRH Module 3', + PatientNames: 'XXXXXXX', + DateCollected: '10-May-2016', + DateReceived: '26-May-2016', + DateTested: '30-May-2016', + Result: 'Error', + FinalResult: 'Error', + DateDispatched: '08-Jun-2016' + }, + { + LabID: '173545', + PatientID: '2524040', + ProviderID: '1289-8', + MFLCode: '15204', + AMRslocationID: '14', + AMRslocation: 'MTRH Module 3', + PatientNames: 'XXXXXXX', + DateCollected: '12-May-2016', + DateReceived: '26-May-2016', + DateTested: '30-May-2016', + Result: '78', + FinalResult: '288', + DateDispatched: '08-Jun-2016' + } + ]; + + var amrsObs = [ + { + uuid: 'uuid1', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-26T00:00:00+03:00', + concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + value: 0 + }, + { + uuid: 'uuid2', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-26T00:00:00+03:00', + concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + value: 130 + }, + { + uuid: 'uuid3', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-05T00:00:00+03:00', + concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + value: 0 + }, + { + uuid: 'uuid4', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-05T00:00:00+03:00', + concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, + groupMembers: [ + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-05-05T00:00:00+03:00' + }, + { + concept: 'a8a06fc6-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 'wewe tu', + obsDatetime: '2016-05-05T00:00:00+03:00' + } + ] + }, + { + uuid: 'uuid5', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-10T00:00:00+03:00', + concept: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + value: 0 + }, + { + uuid: 'uuid6', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-10T00:00:00+03:00', + concept: { uuid: '457c741d-8f71-4829-b59d-594e0a618892' }, + groupMembers: [ + { + concept: { uuid: 'f67ff075-f91e-4b71-897a-9ded87b34984' }, + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: { uuid: 'a8982474-1350-11df-a1f1-0026b9348838' }, + obsDatetime: '2016-05-10T00:00:00+03:00' + }, + { + concept: 'a8a06fc6-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 'wewe tu', + obsDatetime: '2016-05-10T00:00:00+03:00' + } + ] + }, + { + uuid: 'uuid6', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-10T00:00:00+03:00', + concept: { uuid: 'some other uuid' }, + value: 'some other' + } + ]; + + var conflicting = [ + { + eid: eidResults[0], + obs: [amrsObs[0]] + }, + { + eid: eidResults[1], + obs: [amrsObs[3]] + }, + { + eid: eidResults[2], + obs: [amrsObs[4]] + } + ]; + + var results = eidObsCompare.findConflictingEidAmrsViralLoadResults( + eidResults, + amrsObs + ); + + expect(results).to.deep.equal(conflicting); + }); }); diff --git a/test/etl-factory.test.js b/test/etl-factory.test.js index 5408da0f7..e0e46e41e 100755 --- a/test/etl-factory.test.js +++ b/test/etl-factory.test.js @@ -7,7 +7,7 @@ var mockData = require('./mock/mock-data'); var _ = require('underscore'); var Hapi = require('hapi'); var fakeServer = require('./sinon-server-1.17.3'); -var queryParams = { reportName: "test-report-01" }; +var queryParams = { reportName: 'test-report-01' }; var reports = mockData.getReportMock(); var reportFactory = require('../etl-factory'); @@ -17,12 +17,6 @@ global.should = chai.should; global.Assertion = chai.Assertion; global.assert = chai.assert; - chai.use(sinonChai); -describe('ETL-SERVER TESTS REPORT FACTORY TESTS', function () { - - -}); - - +describe('ETL-SERVER TESTS REPORT FACTORY TESTS', function () {}); diff --git a/test/expression-runner/expression-runner.test.js b/test/expression-runner/expression-runner.test.js index 81700ba09..eec696f84 100755 --- a/test/expression-runner/expression-runner.test.js +++ b/test/expression-runner/expression-runner.test.js @@ -18,38 +18,33 @@ var baseUrl = 'http://localhost:8002'; chai.use(sinonChai); describe('EXPRESSION RUNNER:', function () { - - beforeEach(function (done) { - done(); - }); - - afterEach(function () { - }); - - it('should load expression runner module', - function () { - expect(expressionRunner).to.be.defined; - }); - - - it('should run an expession given a scope and an expression', - function () { - var scope = { - programLocationUuid: 'some uuid', - intentedVisitUuid: 'some other uuid', - age: 8, - sum: function(a,b) { - return a + b; - } - }; - - var expression = "programLocationUuid === 'some uuid' && age > 7"; - var expression2 = "programLocationUuid === intentedVisitUuid"; - var expression3 = "programLocationUuid !== intentedVisitUuid && sum(1,2) === 3"; - - expect(expressionRunner.run(expression, scope)).to.be.true; - expect(expressionRunner.run(expression2, scope)).to.be.false; - expect(expressionRunner.run(expression3, scope)).to.be.true; - }); - -}); \ No newline at end of file + beforeEach(function (done) { + done(); + }); + + afterEach(function () {}); + + it('should load expression runner module', function () { + expect(expressionRunner).to.be.defined; + }); + + it('should run an expession given a scope and an expression', function () { + var scope = { + programLocationUuid: 'some uuid', + intentedVisitUuid: 'some other uuid', + age: 8, + sum: function (a, b) { + return a + b; + } + }; + + var expression = "programLocationUuid === 'some uuid' && age > 7"; + var expression2 = 'programLocationUuid === intentedVisitUuid'; + var expression3 = + 'programLocationUuid !== intentedVisitUuid && sum(1,2) === 3'; + + expect(expressionRunner.run(expression, scope)).to.be.true; + expect(expressionRunner.run(expression2, scope)).to.be.false; + expect(expressionRunner.run(expression3, scope)).to.be.true; + }); +}); diff --git a/test/lab-integration/adapters/lab-adapter.test.js b/test/lab-integration/adapters/lab-adapter.test.js index 3a40d1221..b59314034 100644 --- a/test/lab-integration/adapters/lab-adapter.test.js +++ b/test/lab-integration/adapters/lab-adapter.test.js @@ -3,220 +3,214 @@ import { DNAPCRAdapter } from '../../../app/lab-integration/adapters/dnapcr-adpa import { VLAdapter } from '../../../app/lab-integration/adapters/vl-adapter'; const chai = require('chai'), - should = chai.should(), - expect = chai.expect; + should = chai.should(), + expect = chai.expect; describe('Lab Adapters Unit Tests', function () { - const testCD4ArrayResult = [{ - "id": 14451, - "order_number": null, - "provider_identifier": "167948-9", - "facility_code": 15229, - "AMRs_location": 2, - "full_names": "Nicholas Kiptarbei Lagat", - "date_collected": "2018-11-16", - "date_received": "2018-11-16", - "date_tested": "", - "interpretation": null, - "result": 0, - "date_dispatched": "", - "sample_status": null, - "THelperSuppressorRatio": null, - "AVGCD3percentLymph": 81.49, - "AVGCD3AbsCnt": 1339.69, - "AVGCD3CD4percentLymph": 26.29, - "AVGCD3CD4AbsCnt": 432.28, - "CD45AbsCnt": 1644.03, - "AVGCD3CD8percentLymph": null, - "AVGCD3CD8AbsCnt": null, - "AVGCD3CD4CD8percentLymph": null, - "AVGCD3CD4CD8AbsCnt": null, - }]; + const testCD4ArrayResult = [ + { + id: 14451, + order_number: null, + provider_identifier: '167948-9', + facility_code: 15229, + AMRs_location: 2, + full_names: 'Nicholas Kiptarbei Lagat', + date_collected: '2018-11-16', + date_received: '2018-11-16', + date_tested: '', + interpretation: null, + result: 0, + date_dispatched: '', + sample_status: null, + THelperSuppressorRatio: null, + AVGCD3percentLymph: 81.49, + AVGCD3AbsCnt: 1339.69, + AVGCD3CD4percentLymph: 26.29, + AVGCD3CD4AbsCnt: 432.28, + CD45AbsCnt: 1644.03, + AVGCD3CD8percentLymph: null, + AVGCD3CD8AbsCnt: null, + AVGCD3CD4CD8percentLymph: null, + AVGCD3CD4CD8AbsCnt: null + } + ]; const testObjectResult = testCD4ArrayResult[0]; beforeEach(function (done) { done(); }); - - afterEach(function () { - + + afterEach(function () {}); + + it('should throw LabAdapterError if result is not array', function (done) { + (function () { + new CD4Adapter(testObjectResult, '12345'); + }.should.throw(Error, /Please provide lab results as an array/)); + done(); }); - - it('should throw LabAdapterError if result is not array', - function (done) { - (function () { - new CD4Adapter(testObjectResult, '12345'); - }).should.throw(Error, /Please provide lab results as an array/); + + it('should ensure that convertViralLoadPayloadToRestConsumableObs receives the right input and generates the correct payload', function (done) { + const patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + const expectedInput = [ + { + id: 590069, + order_number: null, + provider_identifier: null, + facility_code: 15204, + AMRs_location: null, + full_names: null, + date_collected: '2018-11-19', + date_received: '2018-11-19', + date_tested: '2018-11-19', + interpretation: null, + result: '450', + date_dispatched: '2018-11-19', + sample_status: 'Complete', + patient: '540000000' + } + ]; + var expectedOutput = { + concept: 'a8982474-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2018-11-19T00:00:00+03:00', + value: '450' + }; + const adapter = new VLAdapter(expectedInput, patientUuId); + adapter.getLabResults().then((results) => { + const p = results[0]; + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('value'); + expect(p).deep.equal(expectedOutput); done(); }); - - it('should ensure that convertViralLoadPayloadToRestConsumableObs receives the right input and generates the correct payload', - function (done) { - const patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - const expectedInput = [ + }); + + it('should ensure that convertCD4PayloadTORestConsumableObs receives the right input and generates the correct payload', function (done) { + const patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + const expectedOutput = { + concept: 'a896cce6-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2018-11-16T00:00:00+03:00', + groupMembers: [ { - "id": 590069, - "order_number": null, - "provider_identifier": null, - "facility_code": 15204, - "AMRs_location": null, - "full_names": null, - "date_collected": "2018-11-19", - "date_received": "2018-11-19", - "date_tested": "2018-11-19", - "interpretation": null, - "result": "450", - "date_dispatched": "2018-11-19", - "sample_status": "Complete", - "patient": "540000000" - } - ]; - var expectedOutput = { - concept: "a8982474-1350-11df-a1f1-0026b9348838", - person: "c6e4e026-3b49-4b64-81de-05cf8bd18594", - obsDatetime: "2018-11-19T00:00:00+03:00", - value: '450' - } - const adapter = new VLAdapter(expectedInput, patientUuId); - adapter.getLabResults().then((results) => { - const p = results[0]; - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("value"); - expect(p).deep.equal(expectedOutput); - done(); - }); - - }); - - it('should ensure that convertCD4PayloadTORestConsumableObs receives the right input and generates the correct payload', - function (done) { - const patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - const expectedOutput = { - concept: "a896cce6-1350-11df-a1f1-0026b9348838", - person: "c6e4e026-3b49-4b64-81de-05cf8bd18594", - obsDatetime: "2018-11-16T00:00:00+03:00", - groupMembers: [ - { - "concept": "a89c4220-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 81.49, - "obsDatetime": "2018-11-16T00:00:00+03:00" - }, - { - "concept": "a898fcd2-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 1339.69, - "obsDatetime": "2018-11-16T00:00:00+03:00" - }, - { - "concept": "a8970a26-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 26.29, - "obsDatetime": "2018-11-16T00:00:00+03:00" - }, - { - "concept": "a8a8bb18-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 432.28, - "obsDatetime": "2018-11-16T00:00:00+03:00" - }, - { - "concept": "a89c4914-1350-11df-a1f1-0026b9348838", - "person": "c6e4e026-3b49-4b64-81de-05cf8bd18594", - "value": 1644.03, - "obsDatetime": "2018-11-16T00:00:00+03:00" - } - ] - }; - const adapter = new CD4Adapter(testCD4ArrayResult, patientUuId); - adapter.getLabResults().then((results) => { - const p = results[0]; - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("groupMembers"); - expect(p.groupMembers).to.be.an("array"); - expect(p).deep.equal(expectedOutput); - done(); - }); - }); - - it('should ensure that convertDNAPCRPayloadTORestConsumableObs receives the right input and generates the correct payload: negative', - function (done) { - const patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - const expectedInput = [ + concept: 'a89c4220-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 81.49, + obsDatetime: '2018-11-16T00:00:00+03:00' + }, + { + concept: 'a898fcd2-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 1339.69, + obsDatetime: '2018-11-16T00:00:00+03:00' + }, + { + concept: 'a8970a26-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 26.29, + obsDatetime: '2018-11-16T00:00:00+03:00' + }, { - "id": 66915, - "order_number": "", - "provider_identifier": "", - "facility_code": 17342, - "AMRs_location": 0, - "full_names": "", - "date_collected": "2018-11-15", - "date_received": "2018-11-15", - "date_tested": "2018-11-15", - "interpretation": null, - "result": "Negative", - "date_dispatched": "2018-11-15", - "sample_status": "Complete", - "patient": "17342-2018-0170" + concept: 'a8a8bb18-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 432.28, + obsDatetime: '2018-11-16T00:00:00+03:00' + }, + { + concept: 'a89c4914-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + value: 1644.03, + obsDatetime: '2018-11-16T00:00:00+03:00' } - ]; - const expectedOutput = { - concept: "a898fe80-1350-11df-a1f1-0026b9348838", - person: "c6e4e026-3b49-4b64-81de-05cf8bd18594", - obsDatetime: "2018-11-15T00:00:00+03:00", - value: "a896d2cc-1350-11df-a1f1-0026b9348838" + ] + }; + const adapter = new CD4Adapter(testCD4ArrayResult, patientUuId); + adapter.getLabResults().then((results) => { + const p = results[0]; + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('groupMembers'); + expect(p.groupMembers).to.be.an('array'); + expect(p).deep.equal(expectedOutput); + done(); + }); + }); + + it('should ensure that convertDNAPCRPayloadTORestConsumableObs receives the right input and generates the correct payload: negative', function (done) { + const patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + const expectedInput = [ + { + id: 66915, + order_number: '', + provider_identifier: '', + facility_code: 17342, + AMRs_location: 0, + full_names: '', + date_collected: '2018-11-15', + date_received: '2018-11-15', + date_tested: '2018-11-15', + interpretation: null, + result: 'Negative', + date_dispatched: '2018-11-15', + sample_status: 'Complete', + patient: '17342-2018-0170' } - const adapter = new DNAPCRAdapter(expectedInput, patientUuId); - adapter.getLabResults().then((results) => { - const p = results[0]; - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("value"); - expect(p).deep.equal(expectedOutput); - done(); - }); + ]; + const expectedOutput = { + concept: 'a898fe80-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2018-11-15T00:00:00+03:00', + value: 'a896d2cc-1350-11df-a1f1-0026b9348838' + }; + const adapter = new DNAPCRAdapter(expectedInput, patientUuId); + adapter.getLabResults().then((results) => { + const p = results[0]; + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('value'); + expect(p).deep.equal(expectedOutput); + done(); }); - - it('should ensure that convertDNAPCRPayloadTORestConsumableObs receives the right input and generates the correct payload: positive', - function (done) { - const patientUuId = "c6e4e026-3b49-4b64-81de-05cf8bd18594"; - const expectedInput = [ - { - "id": 66915, - "order_number": "", - "provider_identifier": "", - "facility_code": 17342, - "AMRs_location": 0, - "full_names": "", - "date_collected": "2018-11-15", - "date_received": "2018-11-15", - "date_tested": "2018-11-15", - "interpretation": null, - "result": "Positive", - "date_dispatched": "2018-11-15", - "sample_status": "Complete", - "patient": "17342-2018-0170" - } - ]; - const expectedOutput = { - concept: "a898fe80-1350-11df-a1f1-0026b9348838", - person: "c6e4e026-3b49-4b64-81de-05cf8bd18594", - obsDatetime: "2018-11-15T00:00:00+03:00", - value: "a896f3a6-1350-11df-a1f1-0026b9348838" - }; - const adapter = new DNAPCRAdapter(expectedInput, patientUuId); - adapter.getLabResults().then((results) => { - const p = results[0]; - expect(p).to.have.property("concept"); - expect(p).to.have.property("person"); - expect(p).to.have.property("obsDatetime"); - expect(p).to.have.property("value"); - expect(p).deep.equal(expectedOutput); - done(); - }); + }); + + it('should ensure that convertDNAPCRPayloadTORestConsumableObs receives the right input and generates the correct payload: positive', function (done) { + const patientUuId = 'c6e4e026-3b49-4b64-81de-05cf8bd18594'; + const expectedInput = [ + { + id: 66915, + order_number: '', + provider_identifier: '', + facility_code: 17342, + AMRs_location: 0, + full_names: '', + date_collected: '2018-11-15', + date_received: '2018-11-15', + date_tested: '2018-11-15', + interpretation: null, + result: 'Positive', + date_dispatched: '2018-11-15', + sample_status: 'Complete', + patient: '17342-2018-0170' + } + ]; + const expectedOutput = { + concept: 'a898fe80-1350-11df-a1f1-0026b9348838', + person: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + obsDatetime: '2018-11-15T00:00:00+03:00', + value: 'a896f3a6-1350-11df-a1f1-0026b9348838' + }; + const adapter = new DNAPCRAdapter(expectedInput, patientUuId); + adapter.getLabResults().then((results) => { + const p = results[0]; + expect(p).to.have.property('concept'); + expect(p).to.have.property('person'); + expect(p).to.have.property('obsDatetime'); + expect(p).to.have.property('value'); + expect(p).deep.equal(expectedOutput); + done(); }); -}); \ No newline at end of file + }); +}); diff --git a/test/lab-integration/eid-compare-operator.test.js b/test/lab-integration/eid-compare-operator.test.js index 19ab80e88..254078f6e 100644 --- a/test/lab-integration/eid-compare-operator.test.js +++ b/test/lab-integration/eid-compare-operator.test.js @@ -13,193 +13,195 @@ global.assert = chai.assert; chai.use(sinonChai); describe('EID Obs Compare Operator Unit Tests', () => { - - const eidCompareOperator = new EidCompareOperator(); - - beforeEach(function (done) { - done(); - }); - - it('should load EID Obs operator', () => { - expect(eidCompareOperator).to.be.defined; - }); - - it('should check is a given eid result exists in an array of obsResults when findEquivalentObject is called', () => { - var obsResults = [ - { - uuid: 'uuid10', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-29', - concept: { uuid: 'uuid10' }, - value: 0 - }, - { - uuid: 'uuid20', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-04-27', - concept: { uuid: 'uuid10' }, - value: 0 - }, - { - uuid: 'uuid15', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-26T00:00:00+03:00', - concept: { uuid: 'uuid1' }, - value: 0 - }, - { - uuid: 'uuid13', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-26T00:00:00+03:00', - concept: { uuid: 'uuid13' }, - value: { - uuid: 'uuid14' - } - } - ]; - - var eidResult = { - concept: 'uuid13', - value: 'uuid14', - obsDatetime: '2016-05-26T00:00:00+03:00', - comment: 'test1' - }; - - var foundObs = eidCompareOperator.findEquivalentObject(eidResult, obsResults); - - expect(foundObs).to.be.true; - - }); - - it('should load missing eid results when getMissingResults is called', () => { - - var eidResults = [ - { - concept: 'uuid1', - value: 0, - obsDatetime: '2018-11-15', - comment: 'test1' - }, - { - concept: 'uuid2', - value: 13, - obsDatetime: '2018-11-15', - comment: 'test2' - }, - { - concept: 'uuid11', - value: 15, - obsDatetime: '2016-05-28', - comment: 'test3' - }, - { - concept: 'uuid12', - value: 20, - obsDatetime: '2016-05-29', - comment: 'test4' - } - ]; - - var obsResults = [ - { - uuid: 'uuid10', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-27', - concept: { uuid: 'uuid10' }, - value: 0 - }, - { - uuid: 'uuid11', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-28', - concept: { uuid: 'uuid11' }, - value: 15 - }, - { - uuid: 'uuid12', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-29', - concept: { uuid: 'uuid12' }, - value: 20 - } - ]; - - var missingResults = eidCompareOperator.getMissingResults(eidResults, obsResults); - expect(missingResults.length).to.equal(2); - - }); - - it('should load conflicting eid results when getConflictingResults is called', () => { - - var eidResults = [ - { - concept: 'uuid1', - value: 0, - obsDatetime: '2018-11-15', - comment: 'test1' - }, - { - concept: 'uuid2', - value: 13, - obsDatetime: '2018-11-15', - comment: 'test2' - }, - { - concept: 'uuid11', - value: '15', - obsDatetime: '2016-05-28', - comment: 'test3' - }, - { - concept: 'uuid12', - value: 20, - obsDatetime: '2016-05-29', - comment: 'test4' - }, - { - concept: 'uuid13', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-29', - value: 'uuid13' - } - ]; - - var obsResults = [ - { - uuid: 'uuid10', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-27', - concept: { uuid: 'uuid10' }, - value: 0 - }, - { - uuid: 'uuid11', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-28', - concept: { uuid: 'uuid11' }, - value: 15 - }, - { - uuid: 'uuid12', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-29', - concept: { uuid: 'uuid12' }, - value: 20 - }, - { - uuid: 'uuid13', - person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, - obsDatetime: '2016-05-29', - concept: { uuid: 'uuid13' }, - value: { - uuid: 'uuid13' - } - } - ]; - - var missingResults = eidCompareOperator.getConflictingResults(eidResults, obsResults); - expect(missingResults.length).to.equal(3); - - }); - -}); \ No newline at end of file + const eidCompareOperator = new EidCompareOperator(); + + beforeEach(function (done) { + done(); + }); + + it('should load EID Obs operator', () => { + expect(eidCompareOperator).to.be.defined; + }); + + it('should check is a given eid result exists in an array of obsResults when findEquivalentObject is called', () => { + var obsResults = [ + { + uuid: 'uuid10', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-29', + concept: { uuid: 'uuid10' }, + value: 0 + }, + { + uuid: 'uuid20', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-04-27', + concept: { uuid: 'uuid10' }, + value: 0 + }, + { + uuid: 'uuid15', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-26T00:00:00+03:00', + concept: { uuid: 'uuid1' }, + value: 0 + }, + { + uuid: 'uuid13', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-26T00:00:00+03:00', + concept: { uuid: 'uuid13' }, + value: { + uuid: 'uuid14' + } + } + ]; + + var eidResult = { + concept: 'uuid13', + value: 'uuid14', + obsDatetime: '2016-05-26T00:00:00+03:00', + comment: 'test1' + }; + + var foundObs = eidCompareOperator.findEquivalentObject( + eidResult, + obsResults + ); + + expect(foundObs).to.be.true; + }); + + it('should load missing eid results when getMissingResults is called', () => { + var eidResults = [ + { + concept: 'uuid1', + value: 0, + obsDatetime: '2018-11-15', + comment: 'test1' + }, + { + concept: 'uuid2', + value: 13, + obsDatetime: '2018-11-15', + comment: 'test2' + }, + { + concept: 'uuid11', + value: 15, + obsDatetime: '2016-05-28', + comment: 'test3' + }, + { + concept: 'uuid12', + value: 20, + obsDatetime: '2016-05-29', + comment: 'test4' + } + ]; + + var obsResults = [ + { + uuid: 'uuid10', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-27', + concept: { uuid: 'uuid10' }, + value: 0 + }, + { + uuid: 'uuid11', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-28', + concept: { uuid: 'uuid11' }, + value: 15 + }, + { + uuid: 'uuid12', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-29', + concept: { uuid: 'uuid12' }, + value: 20 + } + ]; + + var missingResults = eidCompareOperator.getMissingResults( + eidResults, + obsResults + ); + expect(missingResults.length).to.equal(2); + }); + + it('should load conflicting eid results when getConflictingResults is called', () => { + var eidResults = [ + { + concept: 'uuid1', + value: 0, + obsDatetime: '2018-11-15', + comment: 'test1' + }, + { + concept: 'uuid2', + value: 13, + obsDatetime: '2018-11-15', + comment: 'test2' + }, + { + concept: 'uuid11', + value: '15', + obsDatetime: '2016-05-28', + comment: 'test3' + }, + { + concept: 'uuid12', + value: 20, + obsDatetime: '2016-05-29', + comment: 'test4' + }, + { + concept: 'uuid13', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-29', + value: 'uuid13' + } + ]; + + var obsResults = [ + { + uuid: 'uuid10', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-27', + concept: { uuid: 'uuid10' }, + value: 0 + }, + { + uuid: 'uuid11', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-28', + concept: { uuid: 'uuid11' }, + value: 15 + }, + { + uuid: 'uuid12', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-29', + concept: { uuid: 'uuid12' }, + value: 20 + }, + { + uuid: 'uuid13', + person: { uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594' }, + obsDatetime: '2016-05-29', + concept: { uuid: 'uuid13' }, + value: { + uuid: 'uuid13' + } + } + ]; + + var missingResults = eidCompareOperator.getConflictingResults( + eidResults, + obsResults + ); + expect(missingResults.length).to.equal(3); + }); +}); diff --git a/test/lab-integration/lab-client.test.js b/test/lab-integration/lab-client.test.js index cb322a67c..f6a7d269e 100644 --- a/test/lab-integration/lab-client.test.js +++ b/test/lab-integration/lab-client.test.js @@ -2,7 +2,7 @@ var chai = require('chai'); var request = require('request'); var sinon = require('sinon'); //for creating spies, mocks and stubs var sinonChai = require('sinon-chai'); //expection engine for sinion -var chaiAsPromised = require("chai-as-promised"); +var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var Promise = require('bluebird'); @@ -10,327 +10,333 @@ var expect = chai.expect; var should = chai.should; import { LabClient } from '../../app/lab-integration/utils/lab-client'; describe.only('Lab Client Test Suite:', function () { - var client; - beforeEach(function () { - var config = { - 'serverUrl': 'https://ampath-test.nascop.org', - 'apiKey': 'test' + var client; + beforeEach(function () { + var config = { + serverUrl: 'https://ampath-test.nascop.org', + apiKey: 'test' + }; + client = new LabClient(config); + }); + + afterEach(function () { + client = null; + }); + it('Should Fetch Viral Load results given server config', function (done) { + (typeof client.fetchViralLoad).should.equals('function'); + sinon.stub(client, 'fetchViralLoad').resolves({ + current_page: 1, + data: [ + { + id: 428169, + order_number: null, + provider_identifier: '', + facility_code: 15204, + AMRs_location: 84, + full_names: '', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'hhshh-08036' + }, + { + id: 428171, + order_number: 'ORD-85401', + provider_identifier: '167687-3', + facility_code: 15204, + AMRs_location: 13, + full_names: 'Tesd', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'jjjs-3' } - client = new LabClient(config); + ], + first_page_url: 'http://ampath-test.nascop.org/api/function?page=1', + from: 1, + last_page: 3640, + last_page_url: 'http://ampath-test.nascop.org/api/function?page=3640', + next_page_url: 'http://ampath-test.nascop.org/api/function?page=2', + path: 'http://ampath-test.nascop.org/api/function', + per_page: 20, + prev_page_url: null, + to: 20, + total: 72797 }); - afterEach(function () { - client = null; - }); - it('Should Fetch Viral Load results given server config', - function (done) { - (typeof (client.fetchViralLoad)).should.equals('function'); - sinon.stub(client, 'fetchViralLoad').resolves({ - "current_page": 1, - "data": [ - { - "id": 428169, - "order_number": null, - "provider_identifier": "", - "facility_code": 15204, - "AMRs_location": 84, - "full_names": "", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "hhshh-08036" - }, - { - "id": 428171, - "order_number": "ORD-85401", - "provider_identifier": "167687-3", - "facility_code": 15204, - "AMRs_location": 13, - "full_names": "Tesd", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "jjjs-3" - } - ], - "first_page_url": "http://ampath-test.nascop.org/api/function?page=1", - "from": 1, - "last_page": 3640, - "last_page_url": "http://ampath-test.nascop.org/api/function?page=3640", - "next_page_url": "http://ampath-test.nascop.org/api/function?page=2", - "path": "http://ampath-test.nascop.org/api/function", - "per_page": 20, - "prev_page_url": null, - "to": 20, - "total": 72797 - }); - - client.fetchViralLoad({ start_date: '', end_date: '', patient_id: '' }).then((results) => { - expect(results).to.eql({ - "current_page": 1, - "data": [ - { - "id": 428169, - "order_number": null, - "provider_identifier": "", - "facility_code": 15204, - "AMRs_location": 84, - "full_names": "", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "hhshh-08036" - }, - { - "id": 428171, - "order_number": "ORD-85401", - "provider_identifier": "167687-3", - "facility_code": 15204, - "AMRs_location": 13, - "full_names": "Tesd", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "jjjs-3" - } - ], - "first_page_url": "http://ampath-test.nascop.org/api/function?page=1", - "from": 1, - "last_page": 3640, - "last_page_url": "http://ampath-test.nascop.org/api/function?page=3640", - "next_page_url": "http://ampath-test.nascop.org/api/function?page=2", - "path": "http://ampath-test.nascop.org/api/function", - "per_page": 20, - "prev_page_url": null, - "to": 20, - "total": 72797 - }); - }).finally(done); + client + .fetchViralLoad({ start_date: '', end_date: '', patient_id: '' }) + .then((results) => { + expect(results).to.eql({ + current_page: 1, + data: [ + { + id: 428169, + order_number: null, + provider_identifier: '', + facility_code: 15204, + AMRs_location: 84, + full_names: '', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'hhshh-08036' + }, + { + id: 428171, + order_number: 'ORD-85401', + provider_identifier: '167687-3', + facility_code: 15204, + AMRs_location: 13, + full_names: 'Tesd', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'jjjs-3' + } + ], + first_page_url: 'http://ampath-test.nascop.org/api/function?page=1', + from: 1, + last_page: 3640, + last_page_url: 'http://ampath-test.nascop.org/api/function?page=3640', + next_page_url: 'http://ampath-test.nascop.org/api/function?page=2', + path: 'http://ampath-test.nascop.org/api/function', + per_page: 20, + prev_page_url: null, + to: 20, + total: 72797 }); + }) + .finally(done); + }); - it('Should Fetch CD4 results given server config', - function (done) { - (typeof (client.fetchViralLoad)).should.equals('function'); - sinon.stub(client, 'fetchDNAPCR').resolves({ - "current_page": 1, - "data": [ - { - "id": 428169, - "order_number": null, - "provider_identifier": "", - "facility_code": 15204, - "AMRs_location": 84, - "full_names": "", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "hhshh-08036" - }, - { - "id": 428171, - "order_number": "ORD-85401", - "provider_identifier": "167687-3", - "facility_code": 15204, - "AMRs_location": 13, - "full_names": "Tesd", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "jjjs-3" - } - ], - "first_page_url": "http://ampath-test.nascop.org/api/function?page=1", - "from": 1, - "last_page": 3640, - "last_page_url": "http://ampath-test.nascop.org/api/function?page=3640", - "next_page_url": "http://ampath-test.nascop.org/api/function?page=2", - "path": "http://ampath-test.nascop.org/api/function", - "per_page": 20, - "prev_page_url": null, - "to": 20, - "total": 72797 - }); - var config = { - 'serverUrl': 'https://ampath-test.nascop.org', - 'apiKey': 'test' + it('Should Fetch CD4 results given server config', function (done) { + (typeof client.fetchViralLoad).should.equals('function'); + sinon.stub(client, 'fetchDNAPCR').resolves({ + current_page: 1, + data: [ + { + id: 428169, + order_number: null, + provider_identifier: '', + facility_code: 15204, + AMRs_location: 84, + full_names: '', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'hhshh-08036' + }, + { + id: 428171, + order_number: 'ORD-85401', + provider_identifier: '167687-3', + facility_code: 15204, + AMRs_location: 13, + full_names: 'Tesd', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'jjjs-3' + } + ], + first_page_url: 'http://ampath-test.nascop.org/api/function?page=1', + from: 1, + last_page: 3640, + last_page_url: 'http://ampath-test.nascop.org/api/function?page=3640', + next_page_url: 'http://ampath-test.nascop.org/api/function?page=2', + path: 'http://ampath-test.nascop.org/api/function', + per_page: 20, + prev_page_url: null, + to: 20, + total: 72797 + }); + var config = { + serverUrl: 'https://ampath-test.nascop.org', + apiKey: 'test' + }; + client + .fetchDNAPCR({ start_date: '', end_date: '', patient_id: '' }) + .then((results) => { + expect(results).to.eql({ + current_page: 1, + data: [ + { + id: 428169, + order_number: null, + provider_identifier: '', + facility_code: 15204, + AMRs_location: 84, + full_names: '', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'hhshh-08036' + }, + { + id: 428171, + order_number: 'ORD-85401', + provider_identifier: '167687-3', + facility_code: 15204, + AMRs_location: 13, + full_names: 'Tesd', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'jjjs-3' } - client.fetchDNAPCR({ start_date: '', end_date: '', patient_id: '' }).then((results) => { - expect(results).to.eql({ - "current_page": 1, - "data": [ - { - "id": 428169, - "order_number": null, - "provider_identifier": "", - "facility_code": 15204, - "AMRs_location": 84, - "full_names": "", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "hhshh-08036" - }, - { - "id": 428171, - "order_number": "ORD-85401", - "provider_identifier": "167687-3", - "facility_code": 15204, - "AMRs_location": 13, - "full_names": "Tesd", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "jjjs-3" - } - ], - "first_page_url": "http://ampath-test.nascop.org/api/function?page=1", - "from": 1, - "last_page": 3640, - "last_page_url": "http://ampath-test.nascop.org/api/function?page=3640", - "next_page_url": "http://ampath-test.nascop.org/api/function?page=2", - "path": "http://ampath-test.nascop.org/api/function", - "per_page": 20, - "prev_page_url": null, - "to": 20, - "total": 72797 - }); - }).finally(done); + ], + first_page_url: 'http://ampath-test.nascop.org/api/function?page=1', + from: 1, + last_page: 3640, + last_page_url: 'http://ampath-test.nascop.org/api/function?page=3640', + next_page_url: 'http://ampath-test.nascop.org/api/function?page=2', + path: 'http://ampath-test.nascop.org/api/function', + per_page: 20, + prev_page_url: null, + to: 20, + total: 72797 }); + }) + .finally(done); + }); - it('Should Fetch DNA PCR results given server config', - function (done) { - (typeof (client.fetchViralLoad)).should.equals('function'); - sinon.stub(client, 'fetchCD4').resolves({ - "current_page": 1, - "data": [ - { - "id": 428169, - "order_number": null, - "provider_identifier": "", - "facility_code": 15204, - "AMRs_location": 84, - "full_names": "", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "hhshh-08036" - }, - { - "id": 428171, - "order_number": "ORD-85401", - "provider_identifier": "167687-3", - "facility_code": 15204, - "AMRs_location": 13, - "full_names": "Tesd", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "jjjs-3" - } - ], - "first_page_url": "http://ampath-test.nascop.org/api/function?page=1", - "from": 1, - "last_page": 3640, - "last_page_url": "http://ampath-test.nascop.org/api/function?page=3640", - "next_page_url": "http://ampath-test.nascop.org/api/function?page=2", - "path": "http://ampath-test.nascop.org/api/function", - "per_page": 20, - "prev_page_url": null, - "to": 20, - "total": 72797 - }); - var config = { - 'serverUrl': 'https://ampath-test.nascop.org', - 'apiKey': 'test' + it('Should Fetch DNA PCR results given server config', function (done) { + (typeof client.fetchViralLoad).should.equals('function'); + sinon.stub(client, 'fetchCD4').resolves({ + current_page: 1, + data: [ + { + id: 428169, + order_number: null, + provider_identifier: '', + facility_code: 15204, + AMRs_location: 84, + full_names: '', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'hhshh-08036' + }, + { + id: 428171, + order_number: 'ORD-85401', + provider_identifier: '167687-3', + facility_code: 15204, + AMRs_location: 13, + full_names: 'Tesd', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'jjjs-3' + } + ], + first_page_url: 'http://ampath-test.nascop.org/api/function?page=1', + from: 1, + last_page: 3640, + last_page_url: 'http://ampath-test.nascop.org/api/function?page=3640', + next_page_url: 'http://ampath-test.nascop.org/api/function?page=2', + path: 'http://ampath-test.nascop.org/api/function', + per_page: 20, + prev_page_url: null, + to: 20, + total: 72797 + }); + var config = { + serverUrl: 'https://ampath-test.nascop.org', + apiKey: 'test' + }; + client + .fetchCD4({ start_date: '', end_date: '', patient_id: '' }) + .then((results) => { + expect(results).to.eql({ + current_page: 1, + data: [ + { + id: 428169, + order_number: null, + provider_identifier: '', + facility_code: 15204, + AMRs_location: 84, + full_names: '', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'hhshh-08036' + }, + { + id: 428171, + order_number: 'ORD-85401', + provider_identifier: '167687-3', + facility_code: 15204, + AMRs_location: 13, + full_names: 'Tesd', + date_collected: '02-Jan-2018', + date_received: '02-Jan-2018', + date_tested: '03-Jan-2018', + interpretation: 'Target Not Detected', + result: '< LDL copies/ml', + date_dispatched: '04-Jan-2018', + sample_status: 'Complete', + patient: 'jjjs-3' } - client.fetchCD4({ start_date: '', end_date: '', patient_id: '' }).then((results) => { - expect(results).to.eql({ - "current_page": 1, - "data": [ - { - "id": 428169, - "order_number": null, - "provider_identifier": "", - "facility_code": 15204, - "AMRs_location": 84, - "full_names": "", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "hhshh-08036" - }, - { - "id": 428171, - "order_number": "ORD-85401", - "provider_identifier": "167687-3", - "facility_code": 15204, - "AMRs_location": 13, - "full_names": "Tesd", - "date_collected": "02-Jan-2018", - "date_received": "02-Jan-2018", - "date_tested": "03-Jan-2018", - "interpretation": "Target Not Detected", - "result": "< LDL copies/ml", - "date_dispatched": "04-Jan-2018", - "sample_status": "Complete", - "patient": "jjjs-3" - } - ], - "first_page_url": "http://ampath-test.nascop.org/api/function?page=1", - "from": 1, - "last_page": 3640, - "last_page_url": "http://ampath-test.nascop.org/api/function?page=3640", - "next_page_url": "http://ampath-test.nascop.org/api/function?page=2", - "path": "http://ampath-test.nascop.org/api/function", - "per_page": 20, - "prev_page_url": null, - "to": 20, - "total": 72797 - }); - }).finally(done); + ], + first_page_url: 'http://ampath-test.nascop.org/api/function?page=1', + from: 1, + last_page: 3640, + last_page_url: 'http://ampath-test.nascop.org/api/function?page=3640', + next_page_url: 'http://ampath-test.nascop.org/api/function?page=2', + path: 'http://ampath-test.nascop.org/api/function', + per_page: 20, + prev_page_url: null, + to: 20, + total: 72797 }); -}) \ No newline at end of file + }) + .finally(done); + }); +}); diff --git a/test/mock/eid.mock.js b/test/mock/eid.mock.js index c68277ca2..983371a67 100755 --- a/test/mock/eid.mock.js +++ b/test/mock/eid.mock.js @@ -1,50 +1,50 @@ -(function(){ +(function () { 'use strict'; - module.exports = { - getDnaPcrMockPayload: getDnaPcrMockPayload, - getMockResponse: getMockResponse - }; + module.exports = { + getDnaPcrMockPayload: getDnaPcrMockPayload, + getMockResponse: getMockResponse + }; - function getDnaPcrMockPayload() { - return { - "type":"DNAPCR", - "locationUuid" : "0900b866-1352-11df-a1f1-0026b9348838", - "orderNumber" : "ORD-1", - "providerIdentifier": "provi8der id", - "patientName" : "Jtason", - "patientIdentifier" : "t45455/34/34g", - "sex": "m", - "birthDate": "2015-02-04", - "infantProphylaxisUuid": "a8967656-1350-11df-a1f1-0026b9348838", - "pmtctInterventionUuid": "mothe pmtct regi uuid", - "feedingTypeUuid": "infant deeding type uuid", - "entryPointUuid" : "3e5ad07b-2ced-4925-8264-cc4d8d1438d4", - "motherHivStatusUuid" : "a896f3a6-1350-11df-a1f1-0026b9348838", - "dateDrawn" : "2016-07-14", - "dateReceived" : "2016-07-14" - } - } + function getDnaPcrMockPayload() { + return { + type: 'DNAPCR', + locationUuid: '0900b866-1352-11df-a1f1-0026b9348838', + orderNumber: 'ORD-1', + providerIdentifier: 'provi8der id', + patientName: 'Jtason', + patientIdentifier: 't45455/34/34g', + sex: 'm', + birthDate: '2015-02-04', + infantProphylaxisUuid: 'a8967656-1350-11df-a1f1-0026b9348838', + pmtctInterventionUuid: 'mothe pmtct regi uuid', + feedingTypeUuid: 'infant deeding type uuid', + entryPointUuid: '3e5ad07b-2ced-4925-8264-cc4d8d1438d4', + motherHivStatusUuid: 'a896f3a6-1350-11df-a1f1-0026b9348838', + dateDrawn: '2016-07-14', + dateReceived: '2016-07-14' + }; + } - function getMockResponse() { - return { - "mflCode": "15204", - "mrsLocation": 84, - "mrsOrderNumber": "ORD-1", - "providerIdentifier": "provi8der id", - "patientName": "Jtason", - "patientId": "t45455/34/34g", - "sex": "m", - "birthdate": "2015-02-04", - "dateDrawn": "2016-07-14", - "dateReceived": "2016-07-14", - "receivedStatus": 1, - "infantProphylaxis": 1, - "pmtctIntervention": 0, - "feedingType": 0, - "entryPoint": 2, - "motherHivStatus": 2, - "numberOfSpots": 1 - } - } + function getMockResponse() { + return { + mflCode: '15204', + mrsLocation: 84, + mrsOrderNumber: 'ORD-1', + providerIdentifier: 'provi8der id', + patientName: 'Jtason', + patientId: 't45455/34/34g', + sex: 'm', + birthdate: '2015-02-04', + dateDrawn: '2016-07-14', + dateReceived: '2016-07-14', + receivedStatus: 1, + infantProphylaxis: 1, + pmtctIntervention: 0, + feedingType: 0, + entryPoint: 2, + motherHivStatus: 2, + numberOfSpots: 1 + }; + } })(); diff --git a/test/mock/encounter.mock.js b/test/mock/encounter.mock.js index 88ccbc37d..54f14785d 100755 --- a/test/mock/encounter.mock.js +++ b/test/mock/encounter.mock.js @@ -1,994 +1,1022 @@ -(function() { +(function () { 'use strict'; - module.exports = { - getAdultReturnRestMock: getAdultReturnRestMock, - getTriageRestMock: getTriageRestMock - }; - - function getAdultReturnRestMock() { - return { - 'uuid': 'adult-return-uuid', - 'encounterDatetime': '2016-04-11T11:18:11.000+0300', - 'patient': { - 'uuid': 'patient-uuid' - }, - 'form': { - 'uuid': '1339a535-e38f-44cd-8cf8-f42f7c5f2ab7', - 'name': 'AMPATH POC Adult Return Visit Form v0.01' - }, - 'location': { - 'uuid': '00b47ef5-a29b-40a2-a7f4-6851df8d6532', - 'display': 'Location-100', - 'links': [ + module.exports = { + getAdultReturnRestMock: getAdultReturnRestMock, + getTriageRestMock: getTriageRestMock + }; + + function getAdultReturnRestMock() { + return { + uuid: 'adult-return-uuid', + encounterDatetime: '2016-04-11T11:18:11.000+0300', + patient: { + uuid: 'patient-uuid' + }, + form: { + uuid: '1339a535-e38f-44cd-8cf8-f42f7c5f2ab7', + name: 'AMPATH POC Adult Return Visit Form v0.01' + }, + location: { + uuid: '00b47ef5-a29b-40a2-a7f4-6851df8d6532', + display: 'Location-100', + links: [ + { + uri: 'test-rest-url/location/00b47ef5-a29b-40a2-a7f4-6851df8d6532', + rel: 'self' + } + ] + }, + encounterType: { + uuid: '8d5b2be0-c2cc-11de-8d13-0010c6dffd0f', + display: 'ADULTRETURN', + links: [ + { + uri: + 'test-rest-url/encountertype/8d5b2be0-c2cc-11de-8d13-0010c6dffd0f', + rel: 'self' + } + ] + }, + encounterProviders: [ + { + provider: { + uuid: 'pd13dddc-1359-11df-a1f1-0026b9348838', + display: '641-1 - Unknown Unknown Unknown', + person: { + uuid: '5d13dddc-1359-11df-a1f1-0026b9348838', + display: 'Unknown Unknown Unknown', + links: [ + { + uri: + 'test-rest-urlperson/5d13dddc-1359-11df-a1f1-0026b9348838', + rel: 'self' + } + ] + }, + identifier: '641-1', + attributes: [], + retired: false, + links: [ + { + uri: + 'test-rest-url/provider/pd13dddc-1359-11df-a1f1-0026b9348838', + rel: 'self' + }, { - 'uri': 'test-rest-url/location/00b47ef5-a29b-40a2-a7f4-6851df8d6532', - 'rel': 'self' + uri: + 'test-rest-url/provider/pd13dddc-1359-11df-a1f1-0026b9348838?v=full', + rel: 'full' } - ] + ], + resourceVersion: '1.9' }, - 'encounterType': { - 'uuid': '8d5b2be0-c2cc-11de-8d13-0010c6dffd0f', - 'display': 'ADULTRETURN', - 'links': [ + encounterRole: { + uuid: 'a0b03050-c99b-11e0-9572-0800200c9a66', + display: 'Unknown', + links: [ { - 'uri': 'test-rest-url/encountertype/8d5b2be0-c2cc-11de-8d13-0010c6dffd0f', - 'rel': 'self' + uri: + 'test-rest-url/encounterrole/a0b03050-c99b-11e0-9572-0800200c9a66', + rel: 'self' } ] + } + } + ], + obs: [ + { + uuid: '311c17a6-6b8e-4041-9329-0ce763639335', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a8afdb8c-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a95c4ef8-1350-11df-a1f1-0026b9348838', + name: 'PATIENT REPORTED CURRENT TUBERCULOSIS TREATMENT, DETAILED' + } }, - 'encounterProviders': [ + value: null, + groupMembers: [ { - 'provider': { - 'uuid': 'pd13dddc-1359-11df-a1f1-0026b9348838', - 'display': '641-1 - Unknown Unknown Unknown', - 'person': { - 'uuid': '5d13dddc-1359-11df-a1f1-0026b9348838', - 'display': 'Unknown Unknown Unknown', - 'links': [ - { - 'uri': 'test-rest-urlperson/5d13dddc-1359-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'identifier': '641-1', - 'attributes': [], - 'retired': false, - 'links': [ + uuid: '16139a7f-9cc5-44c2-bdda-0415b634cccb', + concept: { + uuid: 'a899e444-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a941f814-1350-11df-a1f1-0026b9348838', + name: 'PATIENT REPORTED CURRENT TUBERCULOSIS TREATMENT' + } + }, + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: { + uuid: 'a899f51a-1350-11df-a1f1-0026b9348838', + display: 'RIFAMPICIN ISONIAZID PYRAZINAMIDE AND ETHAMBUTOL', + links: [ { - 'uri': 'test-rest-url/provider/pd13dddc-1359-11df-a1f1-0026b9348838', - 'rel': 'self' - }, - { - 'uri': 'test-rest-url/provider/pd13dddc-1359-11df-a1f1-0026b9348838?v=full', - 'rel': 'full' - } - ], - 'resourceVersion': '1.9' - }, - 'encounterRole': { - 'uuid': 'a0b03050-c99b-11e0-9572-0800200c9a66', - 'display': 'Unknown', - 'links': [ - { - 'uri': 'test-rest-url/encounterrole/a0b03050-c99b-11e0-9572-0800200c9a66', - 'rel': 'self' + uri: + 'test-rest-url/concept/a899f51a-1350-11df-a1f1-0026b9348838', + rel: 'self' } ] } - } - ], - 'obs': [ - { - 'uuid': '311c17a6-6b8e-4041-9329-0ce763639335', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a8afdb8c-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a95c4ef8-1350-11df-a1f1-0026b9348838', - 'name': 'PATIENT REPORTED CURRENT TUBERCULOSIS TREATMENT, DETAILED' - } - }, - 'value': null, - 'groupMembers': [ - { - 'uuid': '16139a7f-9cc5-44c2-bdda-0415b634cccb', - 'concept': { - 'uuid': 'a899e444-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a941f814-1350-11df-a1f1-0026b9348838', - 'name': 'PATIENT REPORTED CURRENT TUBERCULOSIS TREATMENT' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': { - 'uuid': 'a899f51a-1350-11df-a1f1-0026b9348838', - 'display': 'RIFAMPICIN ISONIAZID PYRAZINAMIDE AND ETHAMBUTOL', - 'links': [ - { - 'uri': 'test-rest-url/concept/a899f51a-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - } - }, - { - 'uuid': '85146eb9-2cfd-4def-8b31-76c5f49e1d5e', - 'concept': { - 'uuid': 'a8a07386-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a9483f12-1350-11df-a1f1-0026b9348838', - 'name': 'NUMBER OF TABLETS PER DAY' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': 3 - } - ] - }, - { - 'uuid': '78060287-6da7-466f-8e5e-c80aefad3b6f', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': '04616f5d-b961-4f41-bbd7-bcc0dd235577', - 'name': { - 'uuid': 'a505b1fc-4d0b-4195-8e7e-7a1cc625471f', - 'name': 'CURRENT HIV ANTIRETROVIRAL DRUG USE TREATMENT CATEGORY' - } - }, - 'value': { - 'uuid': '034047bd-3fa1-4b2a-b0f0-2787e9b9f7b3', - 'display': 'FIRST LINE HIV ANTIRETROVIRAL DRUG TREATMENT', - 'links': [ - { - 'uri': 'test-rest-url/concept/034047bd-3fa1-4b2a-b0f0-2787e9b9f7b3', - 'rel': 'self' - } - ] - }, - 'groupMembers': null - }, - { - 'uuid': '73ddb525-47f7-46b6-b4e7-dfb374d2d140', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': '2a4b87dd-977d-4ce8-a321-1f13df4a31b2', - 'name': { - 'uuid': '7acc4e85-1180-4da4-8fed-559d7bff2d28', - 'name': 'TUBERCULOSIS TREATMENT ADHERENCE SINCE LAST VISIT, DETAILED' - } - }, - 'value': null, - 'groupMembers': [ - { - 'uuid': 'bd485f24-34ef-47c7-a787-4eb9db50bbff', - 'concept': { - 'uuid': '479decbd-e964-41c3-9576-98b39089ebd3', - 'name': { - 'uuid': 'ba1a214a-24ad-4696-bc6c-abe603a25f7d', - 'name': 'TUBERCULOSIS TREATMENT ADHERENCE SINCE LAST VISIT' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': { - 'uuid': 'a8b0f882-1350-11df-a1f1-0026b9348838', - 'display': 'GOOD', - 'links': [ - { - 'uri': 'test-rest-url/concept/a8b0f882-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - } - } - ] - }, - { - 'uuid': '9ccdbf86-7814-4c8e-843a-6d95230f7331', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a8a07688-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a9484264-1350-11df-a1f1-0026b9348838', - 'name': 'REASON ANTIRETROVIRALS STOPPED, DETAILED' - } - }, - 'value': null, - 'groupMembers': [ - { - 'uuid': '73cd1e4b-fc77-443b-b9ea-04f3b01166cc', - 'concept': { - 'uuid': 'a89b7110-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a94350e2-1350-11df-a1f1-0026b9348838', - 'name': 'REASON ANTIRETROVIRALS STOPPED' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': { - 'uuid': 'c0c9eab3-46f6-453c-b29d-dc1c242317c5', - 'display': 'FACILITY STOCKED OUT OF MEDICATION', - 'links': [ - { - 'uri': 'test-rest-url/concept/c0c9eab3-46f6-453c-b29d-dc1c242317c5', - 'rel': 'self' - } - ] - } - } - ] - }, - { - 'uuid': '149995fd-4f8e-418c-be97-a731cee5f2cc', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a8afcafc-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a95c3a26-1350-11df-a1f1-0026b9348838', - 'name': 'REVIEW OF TUBERCULOSIS SCREENING QUESTIONS' - } - }, - 'value': { - 'uuid': 'a8afc8b8-1350-11df-a1f1-0026b9348838', - 'display': 'COUGH FOR MORE THAN TWO WEEKS', - 'links': [ - { - 'uri': 'test-rest-url/concept/a8afc8b8-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'groupMembers': null - }, - { - 'uuid': '8ffe48fe-0d2d-49d4-945b-819871afcb1f', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'b55a6d42-3189-4d4c-97bf-772dfe17b887', - 'name': { - 'uuid': '6459dafc-5c6f-48e0-810b-1fa79fd0d688', - 'name': 'TUBERCULOSIS MEDICATION PICKUP LOCATION, DETAILED' - } - }, - 'value': null, - 'groupMembers': [ - { - 'uuid': '96ad9c91-7798-4e61-992b-e4ac2f9614e6', - 'concept': { - 'uuid': '16db21cd-10cb-4c31-bb5a-b7619bfbea66', - 'name': { - 'uuid': 'dad3c3c4-2724-43bc-9424-22c0aa9c1d35', - 'name': 'TUBERCULOSIS MEDICATION PICKUP LOCATION' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': { - 'uuid': 'a89c2f42-1350-11df-a1f1-0026b9348838', - 'display': 'AMPATH', - 'links': [ - { - 'uri': 'test-rest-url/concept/a89c2f42-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - } - } - ] - }, - { - 'uuid': 'ec8371e4-b6bd-45fd-90fd-9eeaf47c544f', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'bc3834dd-ef07-4027-be30-729baa069291', - 'name': { - 'uuid': '00af9571-9056-4029-b39e-619c6620750e', - 'name': 'ANTIRETROVIRAL ADHERENCE SINCE LAST VISIT, DETAILED' - } - }, - 'value': null, - 'groupMembers': [ - { - 'uuid': '6285b315-b3d7-41dc-b5a6-917aef87e090', - 'concept': { - 'uuid': '2c363a0e-7cf9-42cd-9778-1301b09c4484', - 'name': { - 'uuid': '4a4ae47f-7758-44cc-a411-1f3209736e2d', - 'name': 'ANTIRETROVIRAL ADHERENCE SINCE LAST VISIT' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': { - 'uuid': 'a8b0f882-1350-11df-a1f1-0026b9348838', - 'display': 'GOOD', - 'links': [ - { - 'uri': 'test-rest-url/concept/a8b0f882-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - } - } - ] - }, - { - 'uuid': '03f32979-234c-4ea9-9f3e-8aa501ccd9f9', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a89fe6f0-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a947113c-1350-11df-a1f1-0026b9348838', - 'name': 'TB TREATMENT DRUGS STARTED, DETAILED' - } - }, - 'value': null, - 'groupMembers': [ - { - 'uuid': '1e3c0d17-5dc3-49de-92e8-04751ea08be8', - 'concept': { - 'uuid': 'a8a07386-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a9483f12-1350-11df-a1f1-0026b9348838', - 'name': 'NUMBER OF TABLETS PER DAY' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': 3 - }, - { - 'uuid': '0bdd7984-c0bd-4434-937f-c125474cce2b', - 'concept': { - 'uuid': 'a899e444-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a941f814-1350-11df-a1f1-0026b9348838', - 'name': 'PATIENT REPORTED CURRENT TUBERCULOSIS TREATMENT' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': { - 'uuid': 'a899f51a-1350-11df-a1f1-0026b9348838', - 'display': 'RIFAMPICIN ISONIAZID PYRAZINAMIDE AND ETHAMBUTOL', - 'links': [ - { - 'uri': 'test-rest-url/concept/a899f51a-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - } - } - ] - }, - { - 'uuid': 'e928f3cf-e594-43b0-959a-79632dbb9baf', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a8afcafc-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a95c3a26-1350-11df-a1f1-0026b9348838', - 'name': 'REVIEW OF TUBERCULOSIS SCREENING QUESTIONS' - } - }, - 'value': { - 'uuid': 'a892e4b4-1350-11df-a1f1-0026b9348838', - 'display': 'CHEST PAIN', - 'links': [ - { - 'uri': 'test-rest-url/concept/a892e4b4-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'groupMembers': null - }, - { - 'uuid': '04be1019-5c50-4a0a-b937-d2cdabaadd63', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a89c1fd4-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a9436230-1350-11df-a1f1-0026b9348838', - 'name': 'TUBERCULOSIS TREATMENT PLAN' - } - }, - 'value': { - 'uuid': 'a89b7908-1350-11df-a1f1-0026b9348838', - 'display': 'CONTINUE REGIMEN', - 'links': [ - { - 'uri': 'test-rest-url/concept/a89b7908-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'groupMembers': null - }, - { - 'uuid': 'a975ed2c-6b88-4d34-8b53-c1107fb8cbf0', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a8a666ba-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a948b4a6-1350-11df-a1f1-0026b9348838', - 'name': 'RETURN VISIT DATE' - } - }, - 'value': '2016-06-08T00:00:00.000+0300', - 'groupMembers': null - }, - { - 'uuid': '96a607b3-d8cd-444a-82b1-ce91a0b0a7d3', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a8afcc82-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a95c3bd4-1350-11df-a1f1-0026b9348838', - 'name': 'CURRENTLY ON TUBERCULOSIS TREATMENT' - } - }, - 'value': { - 'uuid': 'a899b35c-1350-11df-a1f1-0026b9348838', - 'display': 'YES', - 'links': [ - { - 'uri': 'test-rest-url/concept/a899b35c-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'groupMembers': null - }, - { - 'uuid': 'd12af1c2-f769-42f1-9b49-9c41e428277e', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a8afdb8c-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a95c4ef8-1350-11df-a1f1-0026b9348838', - 'name': 'PATIENT REPORTED CURRENT TUBERCULOSIS TREATMENT, DETAILED' - } - }, - 'value': null, - 'groupMembers': [ - { - 'uuid': '4feecaff-40a1-46e0-bb1a-c0a587d3e76e', - 'concept': { - 'uuid': 'a899e5f2-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a941f9cc-1350-11df-a1f1-0026b9348838', - 'name': 'TUBERCULOSIS DRUG TREATMENT START DATE' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': '2016-04-05T00:00:00.000+0300' - } - ] }, { - 'uuid': '67edaabc-1857-4e41-859a-ab50c9218698', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': '02ad9357-b996-4530-b1a4-aff91a105383', - 'name': { - 'uuid': '5b196452-2e1d-4fd1-8ac1-0742e37ee90a', - 'name': 'TUBERCULOSIS DISEASE STATUS' + uuid: '85146eb9-2cfd-4def-8b31-76c5f49e1d5e', + concept: { + uuid: 'a8a07386-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a9483f12-1350-11df-a1f1-0026b9348838', + name: 'NUMBER OF TABLETS PER DAY' } }, - 'value': { - 'uuid': 'a8afcc82-1350-11df-a1f1-0026b9348838', - 'display': 'CURRENTLY ON TUBERCULOSIS TREATMENT', - 'links': [ - { - 'uri': 'test-rest-url/concept/a8afcc82-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'groupMembers': null - }, + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: 3 + } + ] + }, + { + uuid: '78060287-6da7-466f-8e5e-c80aefad3b6f', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: '04616f5d-b961-4f41-bbd7-bcc0dd235577', + name: { + uuid: 'a505b1fc-4d0b-4195-8e7e-7a1cc625471f', + name: 'CURRENT HIV ANTIRETROVIRAL DRUG USE TREATMENT CATEGORY' + } + }, + value: { + uuid: '034047bd-3fa1-4b2a-b0f0-2787e9b9f7b3', + display: 'FIRST LINE HIV ANTIRETROVIRAL DRUG TREATMENT', + links: [ + { + uri: + 'test-rest-url/concept/034047bd-3fa1-4b2a-b0f0-2787e9b9f7b3', + rel: 'self' + } + ] + }, + groupMembers: null + }, + { + uuid: '73ddb525-47f7-46b6-b4e7-dfb374d2d140', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: '2a4b87dd-977d-4ce8-a321-1f13df4a31b2', + name: { + uuid: '7acc4e85-1180-4da4-8fed-559d7bff2d28', + name: + 'TUBERCULOSIS TREATMENT ADHERENCE SINCE LAST VISIT, DETAILED' + } + }, + value: null, + groupMembers: [ { - 'uuid': 'a0e37bc1-156e-4ad3-9e02-38b8c7d6d4d0', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a899e35e-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a941f738-1350-11df-a1f1-0026b9348838', - 'name': 'PATIENT REPORTED CURRENT TUBERCULOSIS PROPHYLAXIS' - } - }, - 'value': { - 'uuid': 'a899e0ac-1350-11df-a1f1-0026b9348838', - 'display': 'NONE', - 'links': [ + uuid: 'bd485f24-34ef-47c7-a787-4eb9db50bbff', + concept: { + uuid: '479decbd-e964-41c3-9576-98b39089ebd3', + name: { + uuid: 'ba1a214a-24ad-4696-bc6c-abe603a25f7d', + name: 'TUBERCULOSIS TREATMENT ADHERENCE SINCE LAST VISIT' + } + }, + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: { + uuid: 'a8b0f882-1350-11df-a1f1-0026b9348838', + display: 'GOOD', + links: [ { - 'uri': 'test-rest-url/concept/a899e0ac-1350-11df-a1f1-0026b9348838', - 'rel': 'self' + uri: + 'test-rest-url/concept/a8b0f882-1350-11df-a1f1-0026b9348838', + rel: 'self' } ] - }, - 'groupMembers': null - }, - { - 'uuid': '8321bdfd-920e-4a73-ae5b-bf279fea1813', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'b55a6d42-3189-4d4c-97bf-772dfe17b887', - 'name': { - 'uuid': '6459dafc-5c6f-48e0-810b-1fa79fd0d688', - 'name': 'TUBERCULOSIS MEDICATION PICKUP LOCATION, DETAILED' - } - }, - 'value': null, - 'groupMembers': [ - { - 'uuid': 'e3b4d1ac-0697-4913-b5e3-9e35032f0ceb', - 'concept': { - 'uuid': '16db21cd-10cb-4c31-bb5a-b7619bfbea66', - 'name': { - 'uuid': 'dad3c3c4-2724-43bc-9424-22c0aa9c1d35', - 'name': 'TUBERCULOSIS MEDICATION PICKUP LOCATION' - } - }, - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'value': { - 'uuid': 'a89c2f42-1350-11df-a1f1-0026b9348838', - 'display': 'AMPATH', - 'links': [ - { - 'uri': 'test-rest-url/concept/a89c2f42-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - } - } - ] - }, + } + } + ] + }, + { + uuid: '9ccdbf86-7814-4c8e-843a-6d95230f7331', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a8a07688-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a9484264-1350-11df-a1f1-0026b9348838', + name: 'REASON ANTIRETROVIRALS STOPPED, DETAILED' + } + }, + value: null, + groupMembers: [ { - 'uuid': '03c90069-43c7-4024-bccb-a1e1888c43fe', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a89b6a62-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a9434d86-1350-11df-a1f1-0026b9348838', - 'name': 'ANTIRETROVIRALS STARTED' - } - }, - 'value': { - 'uuid': 'a89cc876-1350-11df-a1f1-0026b9348838', - 'display': 'LAMIVUDINE AND TENOFOVIR', - 'links': [ + uuid: '73cd1e4b-fc77-443b-b9ea-04f3b01166cc', + concept: { + uuid: 'a89b7110-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a94350e2-1350-11df-a1f1-0026b9348838', + name: 'REASON ANTIRETROVIRALS STOPPED' + } + }, + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: { + uuid: 'c0c9eab3-46f6-453c-b29d-dc1c242317c5', + display: 'FACILITY STOCKED OUT OF MEDICATION', + links: [ { - 'uri': 'test-rest-url/concept/a89cc876-1350-11df-a1f1-0026b9348838', - 'rel': 'self' + uri: + 'test-rest-url/concept/c0c9eab3-46f6-453c-b29d-dc1c242317c5', + rel: 'self' } ] - }, - 'groupMembers': null - }, + } + } + ] + }, + { + uuid: '149995fd-4f8e-418c-be97-a731cee5f2cc', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a8afcafc-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a95c3a26-1350-11df-a1f1-0026b9348838', + name: 'REVIEW OF TUBERCULOSIS SCREENING QUESTIONS' + } + }, + value: { + uuid: 'a8afc8b8-1350-11df-a1f1-0026b9348838', + display: 'COUGH FOR MORE THAN TWO WEEKS', + links: [ + { + uri: + 'test-rest-url/concept/a8afc8b8-1350-11df-a1f1-0026b9348838', + rel: 'self' + } + ] + }, + groupMembers: null + }, + { + uuid: '8ffe48fe-0d2d-49d4-945b-819871afcb1f', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'b55a6d42-3189-4d4c-97bf-772dfe17b887', + name: { + uuid: '6459dafc-5c6f-48e0-810b-1fa79fd0d688', + name: 'TUBERCULOSIS MEDICATION PICKUP LOCATION, DETAILED' + } + }, + value: null, + groupMembers: [ { - 'uuid': 'e1135133-846c-477d-b39b-b27b93ed47d3', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a89ae254-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a943144c-1350-11df-a1f1-0026b9348838', - 'name': 'ANTIRETROVIRAL USE' - } - }, - 'value': { - 'uuid': 'a899b35c-1350-11df-a1f1-0026b9348838', - 'display': 'YES', - 'links': [ + uuid: '96ad9c91-7798-4e61-992b-e4ac2f9614e6', + concept: { + uuid: '16db21cd-10cb-4c31-bb5a-b7619bfbea66', + name: { + uuid: 'dad3c3c4-2724-43bc-9424-22c0aa9c1d35', + name: 'TUBERCULOSIS MEDICATION PICKUP LOCATION' + } + }, + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: { + uuid: 'a89c2f42-1350-11df-a1f1-0026b9348838', + display: 'AMPATH', + links: [ { - 'uri': 'test-rest-url/concept/a899b35c-1350-11df-a1f1-0026b9348838', - 'rel': 'self' + uri: + 'test-rest-url/concept/a89c2f42-1350-11df-a1f1-0026b9348838', + rel: 'self' } ] - }, - 'groupMembers': null - }, + } + } + ] + }, + { + uuid: 'ec8371e4-b6bd-45fd-90fd-9eeaf47c544f', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'bc3834dd-ef07-4027-be30-729baa069291', + name: { + uuid: '00af9571-9056-4029-b39e-619c6620750e', + name: 'ANTIRETROVIRAL ADHERENCE SINCE LAST VISIT, DETAILED' + } + }, + value: null, + groupMembers: [ { - 'uuid': '9b2f7815-12c1-4b03-ba21-c7e2b91ba118', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a899e282-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a941f666-1350-11df-a1f1-0026b9348838', - 'name': 'PATIENT REPORTED CURRENT PCP PROPHYLAXIS' - } - }, - 'value': { - 'uuid': 'a899e0ac-1350-11df-a1f1-0026b9348838', - 'display': 'NONE', - 'links': [ + uuid: '6285b315-b3d7-41dc-b5a6-917aef87e090', + concept: { + uuid: '2c363a0e-7cf9-42cd-9778-1301b09c4484', + name: { + uuid: '4a4ae47f-7758-44cc-a411-1f3209736e2d', + name: 'ANTIRETROVIRAL ADHERENCE SINCE LAST VISIT' + } + }, + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: { + uuid: 'a8b0f882-1350-11df-a1f1-0026b9348838', + display: 'GOOD', + links: [ { - 'uri': 'test-rest-url/concept/a899e0ac-1350-11df-a1f1-0026b9348838', - 'rel': 'self' + uri: + 'test-rest-url/concept/a8b0f882-1350-11df-a1f1-0026b9348838', + rel: 'self' } ] - }, - 'groupMembers': null - }, + } + } + ] + }, + { + uuid: '03f32979-234c-4ea9-9f3e-8aa501ccd9f9', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a89fe6f0-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a947113c-1350-11df-a1f1-0026b9348838', + name: 'TB TREATMENT DRUGS STARTED, DETAILED' + } + }, + value: null, + groupMembers: [ { - 'uuid': '050866f5-a6a5-4358-bad4-64b586d2f3c0', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a89b75d4-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a9435510-1350-11df-a1f1-0026b9348838', - 'name': 'ANTIRETROVIRAL PLAN' + uuid: '1e3c0d17-5dc3-49de-92e8-04751ea08be8', + concept: { + uuid: 'a8a07386-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a9483f12-1350-11df-a1f1-0026b9348838', + name: 'NUMBER OF TABLETS PER DAY' } }, - 'value': { - 'uuid': 'a89b7c50-1350-11df-a1f1-0026b9348838', - 'display': 'CHANGE REGIMEN', - 'links': [ - { - 'uri': 'test-rest-url/concept/a89b7c50-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'groupMembers': null + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: 3 }, { - 'uuid': 'd14aaec9-d047-4dba-9890-b9bc4d620adc', - 'obsDatetime': '2016-04-13T05:05:34.000+0300', - 'concept': { - 'uuid': 'a89b7e12-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a9435c54-1350-11df-a1f1-0026b9348838', - 'name': 'PCP PROPHYLAXIS PLAN' - } - }, - 'value': { - 'uuid': 'a899e0ac-1350-11df-a1f1-0026b9348838', - 'display': 'NONE', - 'links': [ + uuid: '0bdd7984-c0bd-4434-937f-c125474cce2b', + concept: { + uuid: 'a899e444-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a941f814-1350-11df-a1f1-0026b9348838', + name: 'PATIENT REPORTED CURRENT TUBERCULOSIS TREATMENT' + } + }, + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: { + uuid: 'a899f51a-1350-11df-a1f1-0026b9348838', + display: 'RIFAMPICIN ISONIAZID PYRAZINAMIDE AND ETHAMBUTOL', + links: [ { - 'uri': 'test-rest-url/concept/a899e0ac-1350-11df-a1f1-0026b9348838', - 'rel': 'self' + uri: + 'test-rest-url/concept/a899f51a-1350-11df-a1f1-0026b9348838', + rel: 'self' } ] - }, - 'groupMembers': null - }, + } + } + ] + }, + { + uuid: 'e928f3cf-e594-43b0-959a-79632dbb9baf', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a8afcafc-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a95c3a26-1350-11df-a1f1-0026b9348838', + name: 'REVIEW OF TUBERCULOSIS SCREENING QUESTIONS' + } + }, + value: { + uuid: 'a892e4b4-1350-11df-a1f1-0026b9348838', + display: 'CHEST PAIN', + links: [ + { + uri: + 'test-rest-url/concept/a892e4b4-1350-11df-a1f1-0026b9348838', + rel: 'self' + } + ] + }, + groupMembers: null + }, + { + uuid: '04be1019-5c50-4a0a-b937-d2cdabaadd63', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a89c1fd4-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a9436230-1350-11df-a1f1-0026b9348838', + name: 'TUBERCULOSIS TREATMENT PLAN' + } + }, + value: { + uuid: 'a89b7908-1350-11df-a1f1-0026b9348838', + display: 'CONTINUE REGIMEN', + links: [ + { + uri: + 'test-rest-url/concept/a89b7908-1350-11df-a1f1-0026b9348838', + rel: 'self' + } + ] + }, + groupMembers: null + }, + { + uuid: 'a975ed2c-6b88-4d34-8b53-c1107fb8cbf0', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a8a666ba-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a948b4a6-1350-11df-a1f1-0026b9348838', + name: 'RETURN VISIT DATE' + } + }, + value: '2016-06-08T00:00:00.000+0300', + groupMembers: null + }, + { + uuid: '96a607b3-d8cd-444a-82b1-ce91a0b0a7d3', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a8afcc82-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a95c3bd4-1350-11df-a1f1-0026b9348838', + name: 'CURRENTLY ON TUBERCULOSIS TREATMENT' + } + }, + value: { + uuid: 'a899b35c-1350-11df-a1f1-0026b9348838', + display: 'YES', + links: [ + { + uri: + 'test-rest-url/concept/a899b35c-1350-11df-a1f1-0026b9348838', + rel: 'self' + } + ] + }, + groupMembers: null + }, + { + uuid: 'd12af1c2-f769-42f1-9b49-9c41e428277e', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a8afdb8c-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a95c4ef8-1350-11df-a1f1-0026b9348838', + name: 'PATIENT REPORTED CURRENT TUBERCULOSIS TREATMENT, DETAILED' + } + }, + value: null, + groupMembers: [ { - "uuid": "bd9bc22d-5c23-48ee-9261-d2cb32646180", - "obsDatetime": "2016-04-21T07:22:13.000+0300", - "concept": { - "uuid": "a89c1cfa-1350-11df-a1f1-0026b9348838", - "name": { - "uuid": "a9435fb0-1350-11df-a1f1-0026b9348838", - "name": "TUBERCULOSIS PROPHYLAXIS PLAN" + uuid: '4feecaff-40a1-46e0-bb1a-c0a587d3e76e', + concept: { + uuid: 'a899e5f2-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a941f9cc-1350-11df-a1f1-0026b9348838', + name: 'TUBERCULOSIS DRUG TREATMENT START DATE' } }, - "value": { - "uuid": "a89b77aa-1350-11df-a1f1-0026b9348838", - "display": "START DRUGS", - "links": [ - { - "uri": "https://test1.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89b77aa-1350-11df-a1f1-0026b9348838", - "rel": "self" - } - ] - }, - "groupMembers": null + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: '2016-04-05T00:00:00.000+0300' } ] - }; - } - - function getTriageRestMock() { - return { - 'uuid': 'efa4d84b-4e16-41ae-83d6-565e8470f491', - 'encounterDatetime': '2016-04-11T11:18:11.000+0300', - 'patient': { - 'uuid': 'd0255a53-a8a6-4722-8439-3df4f4c5b1ba' - }, - 'form': { - 'uuid': 'a2b811ed-6942-405a-b7f8-e7ad6143966c', - 'name': 'AMPATH POC Triage Encounter Form v0.01' - }, - 'location': { - 'uuid': '79fcf21c-8a00-44ba-9555-dde4dd877c4a', - 'display': 'Location-101', - 'links': [ - { - 'uri': 'test-url/location/79fcf21c-8a00-44ba-9555-dde4dd877c4a', - 'rel': 'self' + }, + { + uuid: '67edaabc-1857-4e41-859a-ab50c9218698', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: '02ad9357-b996-4530-b1a4-aff91a105383', + name: { + uuid: '5b196452-2e1d-4fd1-8ac1-0742e37ee90a', + name: 'TUBERCULOSIS DISEASE STATUS' } - ] + }, + value: { + uuid: 'a8afcc82-1350-11df-a1f1-0026b9348838', + display: 'CURRENTLY ON TUBERCULOSIS TREATMENT', + links: [ + { + uri: + 'test-rest-url/concept/a8afcc82-1350-11df-a1f1-0026b9348838', + rel: 'self' + } + ] + }, + groupMembers: null }, - 'encounterType': { - 'uuid': 'a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7', - 'display': 'TRIAGE', - 'links': [ - { - 'uri': 'test-url/encountertype/a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7', - 'rel': 'self' + { + uuid: 'a0e37bc1-156e-4ad3-9e02-38b8c7d6d4d0', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a899e35e-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a941f738-1350-11df-a1f1-0026b9348838', + name: 'PATIENT REPORTED CURRENT TUBERCULOSIS PROPHYLAXIS' } - ] + }, + value: { + uuid: 'a899e0ac-1350-11df-a1f1-0026b9348838', + display: 'NONE', + links: [ + { + uri: + 'test-rest-url/concept/a899e0ac-1350-11df-a1f1-0026b9348838', + rel: 'self' + } + ] + }, + groupMembers: null }, - 'encounterProviders': [ - { - 'provider': { - 'uuid': 'pb6e31da-1359-11df-a1f1-0026b9348838', - 'display': '1-8 - Giniton Giniton Giniton', - 'person': { - 'uuid': '5b6e31da-1359-11df-a1f1-0026b9348838', - 'display': 'Giniton Giniton Giniton', - 'links': [ + { + uuid: '8321bdfd-920e-4a73-ae5b-bf279fea1813', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'b55a6d42-3189-4d4c-97bf-772dfe17b887', + name: { + uuid: '6459dafc-5c6f-48e0-810b-1fa79fd0d688', + name: 'TUBERCULOSIS MEDICATION PICKUP LOCATION, DETAILED' + } + }, + value: null, + groupMembers: [ + { + uuid: 'e3b4d1ac-0697-4913-b5e3-9e35032f0ceb', + concept: { + uuid: '16db21cd-10cb-4c31-bb5a-b7619bfbea66', + name: { + uuid: 'dad3c3c4-2724-43bc-9424-22c0aa9c1d35', + name: 'TUBERCULOSIS MEDICATION PICKUP LOCATION' + } + }, + obsDatetime: '2016-04-13T05:05:34.000+0300', + value: { + uuid: 'a89c2f42-1350-11df-a1f1-0026b9348838', + display: 'AMPATH', + links: [ { - 'uri': 'test-url/person/5b6e31da-1359-11df-a1f1-0026b9348838', - 'rel': 'self' + uri: + 'test-rest-url/concept/a89c2f42-1350-11df-a1f1-0026b9348838', + rel: 'self' } ] - }, - 'identifier': '1-8', - 'attributes': [], - 'retired': false, - 'links': [ - { - 'uri': 'test-url/provider/pb6e31da-1359-11df-a1f1-0026b9348838', - 'rel': 'self' - }, - { - 'uri': 'test-url/provider/pb6e31da-1359-11df-a1f1-0026b9348838?v=full', - 'rel': 'full' - } - ], - 'resourceVersion': '1.9' - }, - 'encounterRole': { - 'uuid': 'a0b03050-c99b-11e0-9572-0800200c9a66', - 'display': 'Unknown', - 'links': [ - { - 'uri': 'test-url/encounterrole/a0b03050-c99b-11e0-9572-0800200c9a66', - 'rel': 'self' - } - ] - } - } - ], - 'obs': [ - { - 'uuid': '9d482ea9-2a42-4034-b0fa-1ed9673ce28d', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a89c60c0-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a943a2fe-1350-11df-a1f1-0026b9348838', - 'name': 'BODY MASS INDEX' } - }, - 'value': 20.5, - 'groupMembers': null + } + ] + }, + { + uuid: '03c90069-43c7-4024-bccb-a1e1888c43fe', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a89b6a62-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a9434d86-1350-11df-a1f1-0026b9348838', + name: 'ANTIRETROVIRALS STARTED' + } }, - { - 'uuid': '235d4fac-7df5-4cef-a50c-ebe3cc469593', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a8a66354-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a948b14a-1350-11df-a1f1-0026b9348838', - 'name': 'BLOOD OXYGEN SATURATION' + value: { + uuid: 'a89cc876-1350-11df-a1f1-0026b9348838', + display: 'LAMIVUDINE AND TENOFOVIR', + links: [ + { + uri: + 'test-rest-url/concept/a89cc876-1350-11df-a1f1-0026b9348838', + rel: 'self' } - }, - 'value': 92, - 'groupMembers': null + ] }, - { - 'uuid': '481622c3-7d90-4719-9faa-65ccbef642bf', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a8b02524-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a95d5c12-1350-11df-a1f1-0026b9348838', - 'name': 'HEALTH INSURANCE' + groupMembers: null + }, + { + uuid: 'e1135133-846c-477d-b39b-b27b93ed47d3', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a89ae254-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a943144c-1350-11df-a1f1-0026b9348838', + name: 'ANTIRETROVIRAL USE' + } + }, + value: { + uuid: 'a899b35c-1350-11df-a1f1-0026b9348838', + display: 'YES', + links: [ + { + uri: + 'test-rest-url/concept/a899b35c-1350-11df-a1f1-0026b9348838', + rel: 'self' } - }, - 'value': { - 'uuid': '8b715fed-97f6-4e38-8f6a-c167a42f8923', - 'display': 'KENYA NATIONAL HEALTH INSURANCE FUND', - 'links': [ - { - 'uri': 'test-url/concept/8b715fed-97f6-4e38-8f6a-c167a42f8923', - 'rel': 'self' - } - ] - }, - 'groupMembers': null + ] }, - { - 'uuid': 'b1ebcca3-56a6-4402-9c80-045200a2fded', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a8a65e36-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a948ac40-1350-11df-a1f1-0026b9348838', - 'name': 'DIASTOLIC BLOOD PRESSURE' + groupMembers: null + }, + { + uuid: '9b2f7815-12c1-4b03-ba21-c7e2b91ba118', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a899e282-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a941f666-1350-11df-a1f1-0026b9348838', + name: 'PATIENT REPORTED CURRENT PCP PROPHYLAXIS' + } + }, + value: { + uuid: 'a899e0ac-1350-11df-a1f1-0026b9348838', + display: 'NONE', + links: [ + { + uri: + 'test-rest-url/concept/a899e0ac-1350-11df-a1f1-0026b9348838', + rel: 'self' } - }, - 'value': 70, - 'groupMembers': null + ] }, - { - 'uuid': '51594895-f053-4b3e-b29c-86fc270d0148', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a8a65fee-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a948adee-1350-11df-a1f1-0026b9348838', - 'name': 'TEMPERATURE (C)' + groupMembers: null + }, + { + uuid: '050866f5-a6a5-4358-bad4-64b586d2f3c0', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a89b75d4-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a9435510-1350-11df-a1f1-0026b9348838', + name: 'ANTIRETROVIRAL PLAN' + } + }, + value: { + uuid: 'a89b7c50-1350-11df-a1f1-0026b9348838', + display: 'CHANGE REGIMEN', + links: [ + { + uri: + 'test-rest-url/concept/a89b7c50-1350-11df-a1f1-0026b9348838', + rel: 'self' } - }, - 'value': 38, - 'groupMembers': null + ] }, - { - 'uuid': 'ca4c3013-b557-48c7-87a7-069810895a28', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a8a660ca-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a948aeca-1350-11df-a1f1-0026b9348838', - 'name': 'WEIGHT (KG)' + groupMembers: null + }, + { + uuid: 'd14aaec9-d047-4dba-9890-b9bc4d620adc', + obsDatetime: '2016-04-13T05:05:34.000+0300', + concept: { + uuid: 'a89b7e12-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a9435c54-1350-11df-a1f1-0026b9348838', + name: 'PCP PROPHYLAXIS PLAN' + } + }, + value: { + uuid: 'a899e0ac-1350-11df-a1f1-0026b9348838', + display: 'NONE', + links: [ + { + uri: + 'test-rest-url/concept/a899e0ac-1350-11df-a1f1-0026b9348838', + rel: 'self' } - }, - 'value': 70, - 'groupMembers': null + ] }, - { - 'uuid': '70280f7b-4556-4d8e-9080-0853cc3819fb', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a8a65d5a-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a948ab6e-1350-11df-a1f1-0026b9348838', - 'name': 'SYSTOLIC BLOOD PRESSURE' + groupMembers: null + }, + { + uuid: 'bd9bc22d-5c23-48ee-9261-d2cb32646180', + obsDatetime: '2016-04-21T07:22:13.000+0300', + concept: { + uuid: 'a89c1cfa-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a9435fb0-1350-11df-a1f1-0026b9348838', + name: 'TUBERCULOSIS PROPHYLAXIS PLAN' + } + }, + value: { + uuid: 'a89b77aa-1350-11df-a1f1-0026b9348838', + display: 'START DRUGS', + links: [ + { + uri: + 'https://test1.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89b77aa-1350-11df-a1f1-0026b9348838', + rel: 'self' } - }, - 'value': 100, - 'groupMembers': null + ] }, + groupMembers: null + } + ] + }; + } + + function getTriageRestMock() { + return { + uuid: 'efa4d84b-4e16-41ae-83d6-565e8470f491', + encounterDatetime: '2016-04-11T11:18:11.000+0300', + patient: { + uuid: 'd0255a53-a8a6-4722-8439-3df4f4c5b1ba' + }, + form: { + uuid: 'a2b811ed-6942-405a-b7f8-e7ad6143966c', + name: 'AMPATH POC Triage Encounter Form v0.01' + }, + location: { + uuid: '79fcf21c-8a00-44ba-9555-dde4dd877c4a', + display: 'Location-101', + links: [ { - 'uuid': '9c07e316-c801-4321-9316-02c8e0f3bf0b', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a89ff9a6-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a9473144-1350-11df-a1f1-0026b9348838', - 'name': 'CURRENT VISIT TYPE' - } - }, - 'value': { - 'uuid': 'a89b6440-1350-11df-a1f1-0026b9348838', - 'display': 'SCHEDULED VISIT', - 'links': [ + uri: 'test-url/location/79fcf21c-8a00-44ba-9555-dde4dd877c4a', + rel: 'self' + } + ] + }, + encounterType: { + uuid: 'a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7', + display: 'TRIAGE', + links: [ + { + uri: 'test-url/encountertype/a44ad5e2-b3ec-42e7-8cfa-8ba3dbcf5ed7', + rel: 'self' + } + ] + }, + encounterProviders: [ + { + provider: { + uuid: 'pb6e31da-1359-11df-a1f1-0026b9348838', + display: '1-8 - Giniton Giniton Giniton', + person: { + uuid: '5b6e31da-1359-11df-a1f1-0026b9348838', + display: 'Giniton Giniton Giniton', + links: [ { - 'uri': 'test-url/concept/a89b6440-1350-11df-a1f1-0026b9348838', - 'rel': 'self' + uri: 'test-url/person/5b6e31da-1359-11df-a1f1-0026b9348838', + rel: 'self' } ] }, - 'groupMembers': null + identifier: '1-8', + attributes: [], + retired: false, + links: [ + { + uri: 'test-url/provider/pb6e31da-1359-11df-a1f1-0026b9348838', + rel: 'self' + }, + { + uri: + 'test-url/provider/pb6e31da-1359-11df-a1f1-0026b9348838?v=full', + rel: 'full' + } + ], + resourceVersion: '1.9' }, - { - 'uuid': '4838e53d-4363-4458-b459-7351047a7d10', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': '9ce5dbf0-a141-4ad8-8c9d-cd2bf84fe72b', - 'name': { - 'uuid': 'dd66c002-ce80-4d1a-b12a-a9f115e993a2', - 'name': 'POSITIVE PREVENTION' + encounterRole: { + uuid: 'a0b03050-c99b-11e0-9572-0800200c9a66', + display: 'Unknown', + links: [ + { + uri: + 'test-url/encounterrole/a0b03050-c99b-11e0-9572-0800200c9a66', + rel: 'self' } - }, - 'value': { - 'uuid': 'bf51f71e-937c-4da5-ae07-654acf59f5bb', - 'display': 'COUPLES COUNSELLING ', - 'links': [ - { - 'uri': 'test-url/concept/bf51f71e-937c-4da5-ae07-654acf59f5bb', - 'rel': 'self' - } - ] - }, - 'groupMembers': null + ] + } + } + ], + obs: [ + { + uuid: '9d482ea9-2a42-4034-b0fa-1ed9673ce28d', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a89c60c0-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a943a2fe-1350-11df-a1f1-0026b9348838', + name: 'BODY MASS INDEX' + } }, - { - 'uuid': '2f4be6ed-f98b-4a49-b7bc-088bb410e399', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a8a65f12-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a948ad12-1350-11df-a1f1-0026b9348838', - 'name': 'PULSE' + value: 20.5, + groupMembers: null + }, + { + uuid: '235d4fac-7df5-4cef-a50c-ebe3cc469593', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a8a66354-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a948b14a-1350-11df-a1f1-0026b9348838', + name: 'BLOOD OXYGEN SATURATION' + } + }, + value: 92, + groupMembers: null + }, + { + uuid: '481622c3-7d90-4719-9faa-65ccbef642bf', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a8b02524-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a95d5c12-1350-11df-a1f1-0026b9348838', + name: 'HEALTH INSURANCE' + } + }, + value: { + uuid: '8b715fed-97f6-4e38-8f6a-c167a42f8923', + display: 'KENYA NATIONAL HEALTH INSURANCE FUND', + links: [ + { + uri: 'test-url/concept/8b715fed-97f6-4e38-8f6a-c167a42f8923', + rel: 'self' } - }, - 'value': 72, - 'groupMembers': null + ] }, - { - 'uuid': '80c1fb81-1561-49de-bf9e-55a4e3526b01', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a8af49d8-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a94e92fe-1350-11df-a1f1-0026b9348838', - 'name': 'DISCORDANT COUPLE' + groupMembers: null + }, + { + uuid: 'b1ebcca3-56a6-4402-9c80-045200a2fded', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a8a65e36-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a948ac40-1350-11df-a1f1-0026b9348838', + name: 'DIASTOLIC BLOOD PRESSURE' + } + }, + value: 70, + groupMembers: null + }, + { + uuid: '51594895-f053-4b3e-b29c-86fc270d0148', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a8a65fee-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a948adee-1350-11df-a1f1-0026b9348838', + name: 'TEMPERATURE (C)' + } + }, + value: 38, + groupMembers: null + }, + { + uuid: 'ca4c3013-b557-48c7-87a7-069810895a28', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a8a660ca-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a948aeca-1350-11df-a1f1-0026b9348838', + name: 'WEIGHT (KG)' + } + }, + value: 70, + groupMembers: null + }, + { + uuid: '70280f7b-4556-4d8e-9080-0853cc3819fb', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a8a65d5a-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a948ab6e-1350-11df-a1f1-0026b9348838', + name: 'SYSTOLIC BLOOD PRESSURE' + } + }, + value: 100, + groupMembers: null + }, + { + uuid: '9c07e316-c801-4321-9316-02c8e0f3bf0b', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a89ff9a6-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a9473144-1350-11df-a1f1-0026b9348838', + name: 'CURRENT VISIT TYPE' + } + }, + value: { + uuid: 'a89b6440-1350-11df-a1f1-0026b9348838', + display: 'SCHEDULED VISIT', + links: [ + { + uri: 'test-url/concept/a89b6440-1350-11df-a1f1-0026b9348838', + rel: 'self' } - }, - 'value': { - 'uuid': 'a899b35c-1350-11df-a1f1-0026b9348838', - 'display': 'YES', - 'links': [ - { - 'uri': 'test-url/concept/a899b35c-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'groupMembers': null + ] }, - { - 'uuid': '09fe1a31-f2dd-46b2-bb27-f20b955fc836', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': '93aa3f1d-1c39-4196-b5e6-8adc916cd5d6', - 'name': { - 'uuid': '720ebcd9-2a40-4622-b645-eaed90efe7bf', - 'name': 'MOST AT RISK PERSON FOR GETTING HIV INFECTION' + groupMembers: null + }, + { + uuid: '4838e53d-4363-4458-b459-7351047a7d10', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: '9ce5dbf0-a141-4ad8-8c9d-cd2bf84fe72b', + name: { + uuid: 'dd66c002-ce80-4d1a-b12a-a9f115e993a2', + name: 'POSITIVE PREVENTION' + } + }, + value: { + uuid: 'bf51f71e-937c-4da5-ae07-654acf59f5bb', + display: 'COUPLES COUNSELLING ', + links: [ + { + uri: 'test-url/concept/bf51f71e-937c-4da5-ae07-654acf59f5bb', + rel: 'self' } - }, - 'value': { - 'uuid': 'a8af49d8-1350-11df-a1f1-0026b9348838', - 'display': 'DISCORDANT COUPLE', - 'links': [ - { - 'uri': 'test-url/concept/a8af49d8-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'groupMembers': null + ] }, - { - 'uuid': 'd8b926e6-abf0-4b24-a0e5-e3f53a2addd8', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a899a9f2-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a941c3d0-1350-11df-a1f1-0026b9348838', - 'name': 'CIVIL STATUS' + groupMembers: null + }, + { + uuid: '2f4be6ed-f98b-4a49-b7bc-088bb410e399', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a8a65f12-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a948ad12-1350-11df-a1f1-0026b9348838', + name: 'PULSE' + } + }, + value: 72, + groupMembers: null + }, + { + uuid: '80c1fb81-1561-49de-bf9e-55a4e3526b01', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a8af49d8-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a94e92fe-1350-11df-a1f1-0026b9348838', + name: 'DISCORDANT COUPLE' + } + }, + value: { + uuid: 'a899b35c-1350-11df-a1f1-0026b9348838', + display: 'YES', + links: [ + { + uri: 'test-url/concept/a899b35c-1350-11df-a1f1-0026b9348838', + rel: 'self' } - }, - 'value': { - 'uuid': 'a8aa76b0-1350-11df-a1f1-0026b9348838', - 'display': 'MARRIED', - 'links': [ - { - 'uri': 'test-url/concept/a8aa76b0-1350-11df-a1f1-0026b9348838', - 'rel': 'self' - } - ] - }, - 'groupMembers': null + ] }, - { - 'uuid': '37cc4933-0d66-4040-ba6a-3c2532e7521d', - 'obsDatetime': '2016-04-11T11:18:11.000+0300', - 'concept': { - 'uuid': 'a8a6619c-1350-11df-a1f1-0026b9348838', - 'name': { - 'uuid': 'a948af9c-1350-11df-a1f1-0026b9348838', - 'name': 'HEIGHT (CM)' + groupMembers: null + }, + { + uuid: '09fe1a31-f2dd-46b2-bb27-f20b955fc836', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: '93aa3f1d-1c39-4196-b5e6-8adc916cd5d6', + name: { + uuid: '720ebcd9-2a40-4622-b645-eaed90efe7bf', + name: 'MOST AT RISK PERSON FOR GETTING HIV INFECTION' + } + }, + value: { + uuid: 'a8af49d8-1350-11df-a1f1-0026b9348838', + display: 'DISCORDANT COUPLE', + links: [ + { + uri: 'test-url/concept/a8af49d8-1350-11df-a1f1-0026b9348838', + rel: 'self' } - }, - 'value': 185, - 'groupMembers': null - } - ] - }; - } + ] + }, + groupMembers: null + }, + { + uuid: 'd8b926e6-abf0-4b24-a0e5-e3f53a2addd8', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a899a9f2-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a941c3d0-1350-11df-a1f1-0026b9348838', + name: 'CIVIL STATUS' + } + }, + value: { + uuid: 'a8aa76b0-1350-11df-a1f1-0026b9348838', + display: 'MARRIED', + links: [ + { + uri: 'test-url/concept/a8aa76b0-1350-11df-a1f1-0026b9348838', + rel: 'self' + } + ] + }, + groupMembers: null + }, + { + uuid: '37cc4933-0d66-4040-ba6a-3c2532e7521d', + obsDatetime: '2016-04-11T11:18:11.000+0300', + concept: { + uuid: 'a8a6619c-1350-11df-a1f1-0026b9348838', + name: { + uuid: 'a948af9c-1350-11df-a1f1-0026b9348838', + name: 'HEIGHT (CM)' + } + }, + value: 185, + groupMembers: null + } + ] + }; + } })(); diff --git a/test/mock/etl.mock.js b/test/mock/etl.mock.js index ed7cd5300..23a97afac 100755 --- a/test/mock/etl.mock.js +++ b/test/mock/etl.mock.js @@ -1,95 +1,95 @@ -(function(){ +(function () { 'use strict'; - - module.exports = { - getVitalsMock: getVitalsMock, - getHivSummaryMock: getHivSummaryMock + + module.exports = { + getVitalsMock: getVitalsMock, + getHivSummaryMock: getHivSummaryMock + }; + + function getVitalsMock() { + return { + person_id: 1000, + uuid: 'patient-uuid', + encounter_id: 6025923, + encounter_datetime: '2016-04-11T07:11:44.000Z', + location_id: 4, + weight: 70, + height: 172, + temp: 36, + oxygen_sat: 95, + systolic_bp: 105, + diastolic_bp: 69, + pulse: 87 }; - - function getVitalsMock() { - return { - 'person_id': 1000, - 'uuid': 'patient-uuid', - 'encounter_id': 6025923, - 'encounter_datetime': '2016-04-11T07:11:44.000Z', - 'location_id': 4, - 'weight': 70, - 'height': 172, - 'temp': 36, - 'oxygen_sat': 95, - 'systolic_bp': 105, - 'diastolic_bp': 69, - 'pulse': 87 - }; - } - - function getHivSummaryMock() { - return { - 'person_id': 1000, - 'uuid': 'patient-uuid', - 'encounter_id': 5979801, - 'encounter_datetime': '2016-04-11T21:00:00.000Z', - 'encounter_type': 2, - 'is_clinical_encounter': 1, - 'location_id': 4, - 'location_uuid': '08feb444-1352-11df-a1f1-0026b9348838', - 'visit_num': 25, - 'enrollment_date': '2013-09-15T21:00:00.000Z', - 'hiv_start_date': '2013-09-15T21:00:00.000Z', - 'death_date': null, - 'scheduled_visit': null, - 'transfer_out': null, - 'transfer_in': null, - 'patient_care_status': 6101, - 'out_of_care': null, - 'prev_rtc_date': '2016-02-17T21:00:00.000Z', - 'rtc_date': '2016-04-17T21:00:00.000Z', - 'arv_start_date': '2013-12-09T21:00:00.000Z', - 'arv_first_regimen': 'TDF AND 3TC AND EFV', - 'cur_arv_meds': 'TDF AND 3TC AND EFV', - 'cur_arv_line': 1, - 'first_evidence_patient_pregnant': null, - 'edd': null, - 'screened_for_tb': 1, - 'tb_prophylaxis_start_date': '2016-02-17T21:00:00.000Z', - 'tb_tx_start_date': null, - 'pcp_prophylaxis_start_date': '2013-09-15T21:00:00.000Z', - 'cd4_resulted': null, - 'cd4_resulted_date': null, - 'cd4_1': 149, - 'cd4_1_date': '2013-09-29T21:00:00.000Z', - 'cd4_2': null, - 'cd4_2_date': null, - 'cd4_percent_1': 8, - 'cd4_percent_1_date': '2013-09-29T21:00:00.000Z', - 'cd4_percent_2': null, - 'cd4_percent_2_date': null, - 'vl_resulted': null, - 'vl_resulted_date': null, - 'vl_1': 0, - 'vl_1_date': '2015-06-14T21:00:00.000Z', - 'vl_2': 0, - 'vl_2_date': null, - 'vl_order_date': null, - 'cd4_order_date': '2013-09-29T21:00:00.000Z', - 'hiv_dna_pcr_order_date': null, - 'hiv_dna_pcr_resulted': null, - 'hiv_dna_pcr_resulted_date': null, - 'hiv_dna_pcr_1': null, - 'hiv_dna_pcr_1_date': null, - 'hiv_dna_pcr_2': null, - 'hiv_dna_pcr_2_date': null, - 'condoms_provided': null, - 'using_modern_contraceptive_method': null, - 'cur_who_stage': 3, - 'prev_encounter_datetime_hiv': '2015-11-26T21:00:00.000Z', - 'next_encounter_datetime_hiv': '2016-03-07T07:11:44.000Z', - 'prev_encounter_type_hiv': 2, - 'next_encounter_type_hiv': 110, - 'prev_clinical_datetime_hiv': '2015-11-26T21:00:00.000Z', - 'next_clinical_datetime_hiv': '2016-03-07T07:24:05.000Z', - 'encounter_type_name': 'ADULTRETURN', - 'prev_encounter_type_name': 'ADULTRETURN' - }; - } + } + + function getHivSummaryMock() { + return { + person_id: 1000, + uuid: 'patient-uuid', + encounter_id: 5979801, + encounter_datetime: '2016-04-11T21:00:00.000Z', + encounter_type: 2, + is_clinical_encounter: 1, + location_id: 4, + location_uuid: '08feb444-1352-11df-a1f1-0026b9348838', + visit_num: 25, + enrollment_date: '2013-09-15T21:00:00.000Z', + hiv_start_date: '2013-09-15T21:00:00.000Z', + death_date: null, + scheduled_visit: null, + transfer_out: null, + transfer_in: null, + patient_care_status: 6101, + out_of_care: null, + prev_rtc_date: '2016-02-17T21:00:00.000Z', + rtc_date: '2016-04-17T21:00:00.000Z', + arv_start_date: '2013-12-09T21:00:00.000Z', + arv_first_regimen: 'TDF AND 3TC AND EFV', + cur_arv_meds: 'TDF AND 3TC AND EFV', + cur_arv_line: 1, + first_evidence_patient_pregnant: null, + edd: null, + screened_for_tb: 1, + tb_prophylaxis_start_date: '2016-02-17T21:00:00.000Z', + tb_tx_start_date: null, + pcp_prophylaxis_start_date: '2013-09-15T21:00:00.000Z', + cd4_resulted: null, + cd4_resulted_date: null, + cd4_1: 149, + cd4_1_date: '2013-09-29T21:00:00.000Z', + cd4_2: null, + cd4_2_date: null, + cd4_percent_1: 8, + cd4_percent_1_date: '2013-09-29T21:00:00.000Z', + cd4_percent_2: null, + cd4_percent_2_date: null, + vl_resulted: null, + vl_resulted_date: null, + vl_1: 0, + vl_1_date: '2015-06-14T21:00:00.000Z', + vl_2: 0, + vl_2_date: null, + vl_order_date: null, + cd4_order_date: '2013-09-29T21:00:00.000Z', + hiv_dna_pcr_order_date: null, + hiv_dna_pcr_resulted: null, + hiv_dna_pcr_resulted_date: null, + hiv_dna_pcr_1: null, + hiv_dna_pcr_1_date: null, + hiv_dna_pcr_2: null, + hiv_dna_pcr_2_date: null, + condoms_provided: null, + using_modern_contraceptive_method: null, + cur_who_stage: 3, + prev_encounter_datetime_hiv: '2015-11-26T21:00:00.000Z', + next_encounter_datetime_hiv: '2016-03-07T07:11:44.000Z', + prev_encounter_type_hiv: 2, + next_encounter_type_hiv: 110, + prev_clinical_datetime_hiv: '2015-11-26T21:00:00.000Z', + next_clinical_datetime_hiv: '2016-03-07T07:24:05.000Z', + encounter_type_name: 'ADULTRETURN', + prev_encounter_type_name: 'ADULTRETURN' + }; + } })(); diff --git a/test/mock/lab-data-samples.js b/test/mock/lab-data-samples.js index e17bbe015..da6ad9d8c 100755 --- a/test/mock/lab-data-samples.js +++ b/test/mock/lab-data-samples.js @@ -1,3434 +1,3730 @@ var moduleDefinition = { - getEidViralLoad: getEidViralLoad, - getAmrsViralLoadObs: getAmrsViralLoadObs, - getEidDnaPcr: getEidDnaPcr, - getAmrsEidPcrObs: getAmrsEidPcrObs, - getEidCd4Panel: getEidCd4Panel, - getAmrsCd4PanelObs: getAmrsCd4PanelObs + getEidViralLoad: getEidViralLoad, + getAmrsViralLoadObs: getAmrsViralLoadObs, + getEidDnaPcr: getEidDnaPcr, + getAmrsEidPcrObs: getAmrsEidPcrObs, + getEidCd4Panel: getEidCd4Panel, + getAmrsCd4PanelObs: getAmrsCd4PanelObs }; module.exports = moduleDefinition; function getEidViralLoad() { - return { - "LabID": "173545", - "PatientID": "000910191-6", - "ProviderID": "1289-8", - "MFLCode": "15204", - "AMRslocationID": "14", - "AMRslocation": "MTRH Module 3", - "PatientNames": "Test Patient", - "DateCollected": "26-May-2016", - "DateReceived": "26-May-2016", - "DateTested": "30-May-2016", - "Result": "4064 ", - "FinalResult": "4064", - "DateDispatched": "08-Jun-2016" - }; + return { + LabID: '173545', + PatientID: '000910191-6', + ProviderID: '1289-8', + MFLCode: '15204', + AMRslocationID: '14', + AMRslocation: 'MTRH Module 3', + PatientNames: 'Test Patient', + DateCollected: '26-May-2016', + DateReceived: '26-May-2016', + DateTested: '30-May-2016', + Result: '4064 ', + FinalResult: '4064', + DateDispatched: '08-Jun-2016' + }; } function getAmrsViralLoadObs() { - return { - "uuid": "64ec8c62-783b-4932-a2ae-5f1e4a9864e8", - "display": "HIV VIRAL LOAD, QUANTITATIVE: 4064.0", - "concept": { - "uuid": "a8982474-1350-11df-a1f1-0026b9348838", - "display": "HIV VIRAL LOAD, QUANTITATIVE", - "name": { - "display": "HIV VIRAL LOAD, QUANTITATIVE", - "uuid": "a940d9ca-1350-11df-a1f1-0026b9348838", - "name": "HIV VIRAL LOAD, QUANTITATIVE", - "locale": "en", - "localePreferred": true, - "conceptNameType": "FULLY_SPECIFIED", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a940d9ca-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a940d9ca-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.9" + return { + uuid: '64ec8c62-783b-4932-a2ae-5f1e4a9864e8', + display: 'HIV VIRAL LOAD, QUANTITATIVE: 4064.0', + concept: { + uuid: 'a8982474-1350-11df-a1f1-0026b9348838', + display: 'HIV VIRAL LOAD, QUANTITATIVE', + name: { + display: 'HIV VIRAL LOAD, QUANTITATIVE', + uuid: 'a940d9ca-1350-11df-a1f1-0026b9348838', + name: 'HIV VIRAL LOAD, QUANTITATIVE', + locale: 'en', + localePreferred: true, + conceptNameType: 'FULLY_SPECIFIED', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a940d9ca-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a940d9ca-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.9' + }, + datatype: { + uuid: '8d4a4488-c2cc-11de-8d13-0010c6dffd0f', + display: 'Numeric', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + conceptClass: { + uuid: '8d4907b2-c2cc-11de-8d13-0010c6dffd0f', + display: 'Test', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + set: false, + version: '0.1', + retired: false, + names: [ + { + uuid: 'a940d9ca-1350-11df-a1f1-0026b9348838', + display: 'HIV VIRAL LOAD, QUANTITATIVE', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a940d9ca-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a956dbbc-1350-11df-a1f1-0026b9348838', + display: 'HIV RNA PCR', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a956dbbc-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a95b5c50-1350-11df-a1f1-0026b9348838', + display: 'VIRAL LOAD', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a95b5c50-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a952ea52-1350-11df-a1f1-0026b9348838', + display: 'VIRAL LOAD, QUANT', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a952ea52-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a956daea-1350-11df-a1f1-0026b9348838', + display: 'HIV QUANT', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a956daea-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a956d4fa-1350-11df-a1f1-0026b9348838', + display: 'HIV MONITOR', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a956d4fa-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + descriptions: [ + { + uuid: 'a8fdeafc-1350-11df-a1f1-0026b9348838', + display: + 'This is a measure of the number of copies/ml of DNA/RNA in patients with HIV. This test is used to monitor disease progression/treatment efficacy in patients with established infection.', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/description/a8fdeafc-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + mappings: [ + { + uuid: '07ac4e30-df0a-45a1-9795-5ae89766a8be', + display: 'MCL/CIEL: 856', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/mapping/07ac4e30-df0a-45a1-9795-5ae89766a8be' + } + ] + }, + { + uuid: '17c33c09-e09c-4be0-87c1-99c5e31e9d9b', + display: 'local: 856', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/mapping/17c33c09-e09c-4be0-87c1-99c5e31e9d9b' + } + ] + } + ], + answers: [], + setMembers: [], + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.11' + }, + person: {}, + obsDatetime: '2016-05-26T00:00:01.000+0300', + accessionNumber: null, + obsGroup: null, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + auditInfo: { + creator: { + uuid: 'A4F30A1B-5EB9-11DF-A648-37A07F9C90FB', + display: 'daemon', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB' + } + ] + }, + dateCreated: '2016-06-03T16:04:30.000+0300', + changedBy: null, + dateChanged: null + }, + value: 4064, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/64ec8c62-783b-4932-a2ae-5f1e4a9864e8' + } + ], + resourceVersion: '1.11' + }; +} + +function getEidDnaPcr() { + return { + LabID: '24240', + PatientID: '277850056-7', + ProviderID: '1438-1', + MFLCode: '15204', + AMRslocationID: '15', + AMRslocation: 'MTRH Module 4', + PatientNames: 'Test Patient', + DateCollected: '17-May-2016', + DateReceived: '18-May-2016', + DateTested: '20-May-2016', + Result: 'Not Detected DBS', + FinalResult: 'Negative', + DateDispatched: '23-May-2016' + }; +} + +function getAmrsEidPcrObs() { + return { + uuid: '2c8954b9-f842-40b2-8a30-41eb5bfb6fc5', + display: 'HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE: NEGATIVE', + concept: { + uuid: 'a898fe80-1350-11df-a1f1-0026b9348838', + display: 'HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE', + name: { + display: 'HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE', + uuid: 'a941afc6-1350-11df-a1f1-0026b9348838', + name: 'HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE', + locale: 'en', + localePreferred: true, + conceptNameType: 'FULLY_SPECIFIED', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a941afc6-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a941afc6-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.9' + }, + datatype: { + uuid: '8d4a48b6-c2cc-11de-8d13-0010c6dffd0f', + display: 'Coded', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a48b6-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + conceptClass: { + uuid: '8d4907b2-c2cc-11de-8d13-0010c6dffd0f', + display: 'Test', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + set: false, + version: '', + retired: false, + names: [ + { + uuid: 'a956da0e-1350-11df-a1f1-0026b9348838', + display: 'HIV QUAL', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a956da0e-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a941afc6-1350-11df-a1f1-0026b9348838', + display: 'HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a941afc6-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a95267e4-1350-11df-a1f1-0026b9348838', + display: 'HIV PCR Qual', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a95267e4-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a956ce2e-1350-11df-a1f1-0026b9348838', + display: 'HIV DNA PCR', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a956ce2e-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a956cc76-1350-11df-a1f1-0026b9348838', + display: 'HIV DNA', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a956cc76-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + descriptions: [ + { + uuid: 'a8feb20c-1350-11df-a1f1-0026b9348838', + display: + 'Qualitiative test to determine HIV infection. Test which is used to detect genetic information inserted into the DNA of human cells by HIV. This test is used for diagnosis of infection.', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/description/a8feb20c-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + mappings: [ + { + uuid: '1a010ec8-2308-4947-becc-9e09c405c481', + display: 'MCL/CIEL: 1030', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/mapping/1a010ec8-2308-4947-becc-9e09c405c481' + } + ] + }, + { + uuid: 'c9fb8d29-e61e-48a9-af3d-14da09287256', + display: 'local: 1030', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/mapping/c9fb8d29-e61e-48a9-af3d-14da09287256' + } + ] + } + ], + answers: [ + { + uuid: 'a89a7ae4-1350-11df-a1f1-0026b9348838', + display: 'INDETERMINATE', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89a7ae4-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a896d2cc-1350-11df-a1f1-0026b9348838', + display: 'NEGATIVE', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a896f3a6-1350-11df-a1f1-0026b9348838', + display: 'POSITIVE', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896f3a6-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a89c3d8e-1350-11df-a1f1-0026b9348838', + display: 'POOR SAMPLE QUALITY', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c3d8e-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a899ea48-1350-11df-a1f1-0026b9348838', + display: 'NOT DONE', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a899ea48-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + setMembers: [], + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.11' + }, + person: {}, + obsDatetime: '2016-05-17T00:00:01.000+0300', + accessionNumber: null, + obsGroup: null, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + auditInfo: { + creator: { + uuid: 'A4F30A1B-5EB9-11DF-A648-37A07F9C90FB', + display: 'daemon', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB' + } + ] + }, + dateCreated: '2016-05-23T13:21:16.000+0300', + changedBy: null, + dateChanged: null + }, + value: { + uuid: 'a896d2cc-1350-11df-a1f1-0026b9348838', + display: 'NEGATIVE', + name: { + display: 'NEGATIVE', + uuid: 'a93f5e24-1350-11df-a1f1-0026b9348838', + name: 'NEGATIVE', + locale: 'en', + localePreferred: true, + conceptNameType: 'FULLY_SPECIFIED', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a93f5e24-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a93f5e24-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.9' + }, + datatype: { + uuid: '8d4a4c94-c2cc-11de-8d13-0010c6dffd0f', + display: 'N/A', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4c94-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + conceptClass: { + uuid: '8d492774-c2cc-11de-8d13-0010c6dffd0f', + display: 'Misc', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d492774-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + set: false, + version: '', + retired: false, + names: [ + { + uuid: 'a952f5ce-1350-11df-a1f1-0026b9348838', + display: '(-)', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a952f5ce-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a9587fc6-1350-11df-a1f1-0026b9348838', + display: 'NEG', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a9587fc6-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a952fcae-1350-11df-a1f1-0026b9348838', + display: '-', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a952fcae-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a93f5e24-1350-11df-a1f1-0026b9348838', + display: 'NEGATIVE', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a93f5e24-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + descriptions: [ + { + uuid: 'a8f78b08-1350-11df-a1f1-0026b9348838', + display: 'Response to a finding or test result.', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/description/a8f78b08-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + mappings: [ + { + uuid: '5efd601b-edbf-4faf-9cd6-25911ff71a11', + display: 'MCL/CIEL: 664', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/mapping/5efd601b-edbf-4faf-9cd6-25911ff71a11' + } + ] + }, + { + uuid: '65c48593-1fb5-4d63-893b-b1a15725b311', + display: 'local: 664', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/mapping/65c48593-1fb5-4d63-893b-b1a15725b311' + } + ] + } + ], + answers: [], + setMembers: [], + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.11' + }, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/2c8954b9-f842-40b2-8a30-41eb5bfb6fc5' + } + ], + resourceVersion: '1.11' + }; +} + +function getEidCd4Panel() { + return { + LabID: '6304', + PatientID: '000981160-5', + ProviderID: '', + MFLCode: '15753', + AMRslocationID: '3', + AMRslocation: 'Turbo', + PatientNames: 'Test Patient', + DateCollected: '02-Jun-2016', + DateReceived: '06-Jun-2016', + DateTested: '06-Jun-2016', + Result: '81.49', + AVGCD3percentLymph: '81.49', + AVGCD3AbsCnt: '1339.69', + AVGCD3CD4percentLymph: '26.29', + AVGCD3CD4AbsCnt: '432.28', + CD45AbsCnt: '1644.03', + DateDispatched: '' + }; +} + +function getAmrsCd4PanelObs() { + return { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + concept: { + uuid: 'a896cce6-1350-11df-a1f1-0026b9348838', + display: 'CD4 PANEL', + name: { + display: 'CD4 PANEL', + uuid: 'a93f5320-1350-11df-a1f1-0026b9348838', + name: 'CD4 PANEL', + locale: 'en', + localePreferred: true, + conceptNameType: 'FULLY_SPECIFIED', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/name/a93f5320-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/name/a93f5320-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.9' + }, + datatype: { + uuid: '8d4a4c94-c2cc-11de-8d13-0010c6dffd0f', + display: 'N/A', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4c94-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + conceptClass: { + uuid: '8d492026-c2cc-11de-8d13-0010c6dffd0f', + display: 'LabSet', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d492026-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + set: true, + version: '', + retired: false, + names: [ + { + uuid: 'a93f5320-1350-11df-a1f1-0026b9348838', + display: 'CD4 PANEL', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/name/a93f5320-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a957a664-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE SUBSET PANEL', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/name/a957a664-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + descriptions: [ + { + uuid: 'a8f782f2-1350-11df-a1f1-0026b9348838', + display: + 'Breakdown of lymphocytes by surface receptors, including counts, percentiles and ratios.', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/description/a8f782f2-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + mappings: [ + { + uuid: '66cdb436-97dd-4c44-a82e-ca8e76d6b6f6', + display: 'MCL/CIEL: 657', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/mapping/66cdb436-97dd-4c44-a82e-ca8e76d6b6f6' + } + ] + }, + { + uuid: '0bfe1fc1-2cd7-4d2d-843a-5d8e2a699efb', + display: 'local: 90', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/mapping/0bfe1fc1-2cd7-4d2d-843a-5d8e2a699efb' + } + ] + }, + { + uuid: '28af76e2-0eee-445b-aa43-1d55a3262496', + display: 'local: 657', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/mapping/28af76e2-0eee-445b-aa43-1d55a3262496' + } + ] + } + ], + answers: [], + setMembers: [ + { + uuid: 'a89c4220-1350-11df-a1f1-0026b9348838', + display: 'CD3%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a8970a26-1350-11df-a1f1-0026b9348838', + display: 'CD4%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838', + display: 'CD3, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a89821e0-1350-11df-a1f1-0026b9348838', + display: 'CD8, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89821e0-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838', + display: 'CD4, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a898fbf6-1350-11df-a1f1-0026b9348838', + display: 'CD8%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fbf6-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a89c4914-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE COUNT, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a89822bc-1350-11df-a1f1-0026b9348838', + display: 'CD4/CD8 RATIO, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89822bc-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.11' + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: null, + valueCodedName: null, + groupMembers: [ + { + uuid: 'f8cd76dc-6afa-4fca-8764-6c1a3d52d699', + display: 'CD4%, BY FACS: 26.29', + concept: { + uuid: 'a8970a26-1350-11df-a1f1-0026b9348838', + display: 'CD4%, BY FACS', + name: { + display: 'CD4%, BY FACS', + uuid: 'a93fc4ae-1350-11df-a1f1-0026b9348838', + name: 'CD4%, BY FACS', + locale: 'en', + localePreferred: true, + conceptNameType: 'FULLY_SPECIFIED', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a93fc4ae-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a93fc4ae-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.9' + }, + datatype: { + uuid: '8d4a4488-c2cc-11de-8d13-0010c6dffd0f', + display: 'Numeric', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + conceptClass: { + uuid: '8d4907b2-c2cc-11de-8d13-0010c6dffd0f', + display: 'Test', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + set: false, + version: '0.1', + retired: false, + names: [ + { + uuid: 'a95ab692-1350-11df-a1f1-0026b9348838', + display: 'T-HELPER CELL PERCENT', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a95ab692-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a93fc4ae-1350-11df-a1f1-0026b9348838', + display: 'CD4%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a93fc4ae-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a954a96e-1350-11df-a1f1-0026b9348838', + display: 'CD4 PERCENT FLOW', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a954a96e-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a954a2ca-1350-11df-a1f1-0026b9348838', + display: 'CD3+CD4+%LYMPH', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a954a2ca-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a9523e18-1350-11df-a1f1-0026b9348838', + display: 'CD4%', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a9523e18-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a954a89c-1350-11df-a1f1-0026b9348838', + display: 'CD4 PERCENT', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a954a89c-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + descriptions: [ + { + uuid: 'a8f7f5d4-1350-11df-a1f1-0026b9348838', + display: + 'Flow cytometry scanning analysis of T-cell population, helper cell subset (CD4 positive) percent of total lymphocytes. Percentage of T-helper lymphocytes.', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/description/a8f7f5d4-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + mappings: [ + { + uuid: 'cfa573db-a23f-48ae-9925-96d5fe2bc994', + display: 'local: 730', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/mapping/cfa573db-a23f-48ae-9925-96d5fe2bc994' + } + ] + }, + { + uuid: '4f257118-6537-4fa0-9145-8740abf6af02', + display: 'MCL/CIEL: 730', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/mapping/4f257118-6537-4fa0-9145-8740abf6af02' + } + ] + } + ], + answers: [], + setMembers: [], + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.11' + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + concept: { + uuid: 'a896cce6-1350-11df-a1f1-0026b9348838', + display: 'CD4 PANEL', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: null, + valueCodedName: null, + groupMembers: [ + { + uuid: 'f8cd76dc-6afa-4fca-8764-6c1a3d52d699', + display: 'CD4%, BY FACS: 26.29', + concept: { + uuid: 'a8970a26-1350-11df-a1f1-0026b9348838', + display: 'CD4%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 26.29, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf', + display: 'CD3%, BY FACS: 81.49', + concept: { + uuid: 'a89c4220-1350-11df-a1f1-0026b9348838', + display: 'CD3%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 81.49, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '7b51e86f-fada-46af-819f-c2134d2c35ae', + display: 'LYMPHOCYTE COUNT, BY FACS: 1644.03', + concept: { + uuid: 'a89c4914-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE COUNT, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1644.03, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: 'f5744e2b-f678-48cc-ada6-d6d6213f4ccd', + display: 'CD3, BY FACS: 1339.69', + concept: { + uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838', + display: 'CD3, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1339.69, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '511ed043-3868-45bf-9770-605de9a7a5a1', + display: 'CD4, BY FACS: 432.28', + concept: { + uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838', + display: 'CD4, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 432.28, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full' + } + ], + resourceVersion: '1.11' + } + ], + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: null, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full' + } + ], + resourceVersion: '1.11' + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + auditInfo: { + creator: { + uuid: 'A4F30A1B-5EB9-11DF-A648-37A07F9C90FB', + display: 'daemon', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB' + } + ] + }, + dateCreated: '2016-06-07T11:00:11.000+0300', + changedBy: null, + dateChanged: null + }, + value: 26.29, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf', + display: 'CD3%, BY FACS: 81.49', + concept: { + uuid: 'a89c4220-1350-11df-a1f1-0026b9348838', + display: 'CD3%, BY FACS', + name: { + display: 'CD3%, BY FACS', + uuid: 'a9438396-1350-11df-a1f1-0026b9348838', + name: 'CD3%, BY FACS', + locale: 'en', + localePreferred: true, + conceptNameType: 'FULLY_SPECIFIED', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9438396-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9438396-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.9' + }, + datatype: { + uuid: '8d4a4488-c2cc-11de-8d13-0010c6dffd0f', + display: 'Numeric', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + conceptClass: { + uuid: '8d4907b2-c2cc-11de-8d13-0010c6dffd0f', + display: 'Test', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + set: false, + version: '0.1', + retired: false, + names: [ + { + uuid: 'a958e204-1350-11df-a1f1-0026b9348838', + display: 'PERCENT T-CELLS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a958e204-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a9523c74-1350-11df-a1f1-0026b9348838', + display: 'CD3%', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9523c74-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a9549f6e-1350-11df-a1f1-0026b9348838', + display: 'CD3 PERCENT', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9549f6e-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a954a11c-1350-11df-a1f1-0026b9348838', + display: 'CD3+%LYMPH', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a954a11c-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a9438396-1350-11df-a1f1-0026b9348838', + display: 'CD3%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9438396-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a954a04a-1350-11df-a1f1-0026b9348838', + display: 'CD3 PERCENT FLOW', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a954a04a-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + descriptions: [ + { + uuid: 'a9006d18-1350-11df-a1f1-0026b9348838', + display: + 'Flow cytometry scanning analysis of T-cell population, percent of total lymphocytes. Percentage of t-cells which express the CD3 surface receptor.', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/description/a9006d18-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + mappings: [ + { + uuid: '16e79b3b-af28-450a-9ebd-230b01625cbf', + display: 'MCL/CIEL: 1310', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/mapping/16e79b3b-af28-450a-9ebd-230b01625cbf' + } + ] + }, + { + uuid: 'fb823cff-b089-4f7b-ab89-9d7325bb3dcf', + display: 'local: 1310', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/mapping/fb823cff-b089-4f7b-ab89-9d7325bb3dcf' + } + ] + } + ], + answers: [], + setMembers: [], + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.11' + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + concept: { + uuid: 'a896cce6-1350-11df-a1f1-0026b9348838', + display: 'CD4 PANEL', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: null, + valueCodedName: null, + groupMembers: [ + { + uuid: 'f8cd76dc-6afa-4fca-8764-6c1a3d52d699', + display: 'CD4%, BY FACS: 26.29', + concept: { + uuid: 'a8970a26-1350-11df-a1f1-0026b9348838', + display: 'CD4%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 26.29, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf', + display: 'CD3%, BY FACS: 81.49', + concept: { + uuid: 'a89c4220-1350-11df-a1f1-0026b9348838', + display: 'CD3%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 81.49, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '7b51e86f-fada-46af-819f-c2134d2c35ae', + display: 'LYMPHOCYTE COUNT, BY FACS: 1644.03', + concept: { + uuid: 'a89c4914-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE COUNT, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1644.03, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: 'f5744e2b-f678-48cc-ada6-d6d6213f4ccd', + display: 'CD3, BY FACS: 1339.69', + concept: { + uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838', + display: 'CD3, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1339.69, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '511ed043-3868-45bf-9770-605de9a7a5a1', + display: 'CD4, BY FACS: 432.28', + concept: { + uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838', + display: 'CD4, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 432.28, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full' + } + ], + resourceVersion: '1.11' + } + ], + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: null, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full' + } + ], + resourceVersion: '1.11' + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + auditInfo: { + creator: { + uuid: 'A4F30A1B-5EB9-11DF-A648-37A07F9C90FB', + display: 'daemon', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB' + } + ] + }, + dateCreated: '2016-06-07T11:00:11.000+0300', + changedBy: null, + dateChanged: null + }, + value: 81.49, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '7b51e86f-fada-46af-819f-c2134d2c35ae', + display: 'LYMPHOCYTE COUNT, BY FACS: 1644.03', + concept: { + uuid: 'a89c4914-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE COUNT, BY FACS', + name: { + display: 'LYMPHOCYTE COUNT, BY FACS', + uuid: 'a9438b0c-1350-11df-a1f1-0026b9348838', + name: 'LYMPHOCYTE COUNT, BY FACS', + locale: 'en', + localePreferred: true, + conceptNameType: 'FULLY_SPECIFIED', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9438b0c-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9438b0c-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.9' + }, + datatype: { + uuid: '8d4a4488-c2cc-11de-8d13-0010c6dffd0f', + display: 'Numeric', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + conceptClass: { + uuid: '8d4907b2-c2cc-11de-8d13-0010c6dffd0f', + display: 'Test', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + set: false, + version: '0.1', + retired: false, + names: [ + { + uuid: 'a9531d38-1350-11df-a1f1-0026b9348838', + display: 'ABSOLUTE LYMPHOCYTES BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9531d38-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a957a4c0-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE CELL COUNT BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a957a4c0-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a957a592-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE COUNT FLOW', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a957a592-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a9438b0c-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE COUNT, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9438b0c-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a954ab1c-1350-11df-a1f1-0026b9348838', + display: 'CD45+ABS CNT', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a954ab1c-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a9528378-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTES', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9528378-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + descriptions: [ + { + uuid: 'a9006e9e-1350-11df-a1f1-0026b9348838', + display: + 'Flow cytometry scanning analysis of total lymphocyte population. Immunology Test - CD45 plus lymphocyte count.', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/description/a9006e9e-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + mappings: [ + { + uuid: '90eefc4c-9e93-46ea-881c-34e469504035', + display: 'MCL/CIEL: 1319', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/mapping/90eefc4c-9e93-46ea-881c-34e469504035' + } + ] }, - "datatype": { - "uuid": "8d4a4488-c2cc-11de-8d13-0010c6dffd0f", - "display": "Numeric", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f" - } - ] + { + uuid: '973fb281-68af-4c05-85a3-4f32fe4b147c', + display: 'local: 1319', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/mapping/973fb281-68af-4c05-85a3-4f32fe4b147c' + } + ] + } + ], + answers: [], + setMembers: [], + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838' }, - "conceptClass": { - "uuid": "8d4907b2-c2cc-11de-8d13-0010c6dffd0f", - "display": "Test", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f" - } + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.11' + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + concept: { + uuid: 'a896cce6-1350-11df-a1f1-0026b9348838', + display: 'CD4 PANEL', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: null, + valueCodedName: null, + groupMembers: [ + { + uuid: 'f8cd76dc-6afa-4fca-8764-6c1a3d52d699', + display: 'CD4%, BY FACS: 26.29', + concept: { + uuid: 'a8970a26-1350-11df-a1f1-0026b9348838', + display: 'CD4%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838' + } ] - }, - "set": false, - "version": "0.1", - "retired": false, - "names": [ - { - "uuid": "a940d9ca-1350-11df-a1f1-0026b9348838", - "display": "HIV VIRAL LOAD, QUANTITATIVE", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a940d9ca-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a956dbbc-1350-11df-a1f1-0026b9348838", - "display": "HIV RNA PCR", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a956dbbc-1350-11df-a1f1-0026b9348838" - } - ] - }, + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 26.29, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ { - "uuid": "a95b5c50-1350-11df-a1f1-0026b9348838", - "display": "VIRAL LOAD", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a95b5c50-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699' }, { - "uuid": "a952ea52-1350-11df-a1f1-0026b9348838", - "display": "VIRAL LOAD, QUANT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a952ea52-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf', + display: 'CD3%, BY FACS: 81.49', + concept: { + uuid: 'a89c4220-1350-11df-a1f1-0026b9348838', + display: 'CD3%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 81.49, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ { - "uuid": "a956daea-1350-11df-a1f1-0026b9348838", - "display": "HIV QUANT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a956daea-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf' }, { - "uuid": "a956d4fa-1350-11df-a1f1-0026b9348838", - "display": "HIV MONITOR", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/name/a956d4fa-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full' } - ], - "descriptions": [ + ], + resourceVersion: '1.11' + }, + { + uuid: '7b51e86f-fada-46af-819f-c2134d2c35ae', + display: 'LYMPHOCYTE COUNT, BY FACS: 1644.03', + concept: { + uuid: 'a89c4914-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE COUNT, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1644.03, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ { - "uuid": "a8fdeafc-1350-11df-a1f1-0026b9348838", - "display": "This is a measure of the number of copies/ml of DNA/RNA in patients with HIV. This test is used to monitor disease progression/treatment efficacy in patients with established infection.", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/description/a8fdeafc-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "mappings": [ - { - "uuid": "07ac4e30-df0a-45a1-9795-5ae89766a8be", - "display": "MCL/CIEL: 856", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/mapping/07ac4e30-df0a-45a1-9795-5ae89766a8be" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae' }, { - "uuid": "17c33c09-e09c-4be0-87c1-99c5e31e9d9b", - "display": "local: 856", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838/mapping/17c33c09-e09c-4be0-87c1-99c5e31e9d9b" - } - ] + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full' } - ], - "answers": [], - "setMembers": [], - "links": [ + ], + resourceVersion: '1.11' + }, + { + uuid: 'f5744e2b-f678-48cc-ada6-d6d6213f4ccd', + display: 'CD3, BY FACS: 1339.69', + concept: { + uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838', + display: 'CD3, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1339.69, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838" + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd' }, { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8982474-1350-11df-a1f1-0026b9348838?v=full" + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full' } - ], - "resourceVersion": "1.11" - }, - "person": {}, - "obsDatetime": "2016-05-26T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": null, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "auditInfo": { - "creator": { - "uuid": "A4F30A1B-5EB9-11DF-A648-37A07F9C90FB", - "display": "daemon", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB" - } - ] + ], + resourceVersion: '1.11' }, - "dateCreated": "2016-06-03T16:04:30.000+0300", - "changedBy": null, - "dateChanged": null - }, - "value": 4064, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/64ec8c62-783b-4932-a2ae-5f1e4a9864e8" - } - ], - "resourceVersion": "1.11" - }; -} - -function getEidDnaPcr() { - return { - "LabID": "24240", - "PatientID": "277850056-7", - "ProviderID": "1438-1", - "MFLCode": "15204", - "AMRslocationID": "15", - "AMRslocation": "MTRH Module 4", - "PatientNames": "Test Patient", - "DateCollected": "17-May-2016", - "DateReceived": "18-May-2016", - "DateTested": "20-May-2016", - "Result": "Not Detected DBS", - "FinalResult": "Negative", - "DateDispatched": "23-May-2016" - }; -} - -function getAmrsEidPcrObs() { - return { - "uuid": "2c8954b9-f842-40b2-8a30-41eb5bfb6fc5", - "display": "HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE: NEGATIVE", - "concept": { - "uuid": "a898fe80-1350-11df-a1f1-0026b9348838", - "display": "HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE", - "name": { - "display": "HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE", - "uuid": "a941afc6-1350-11df-a1f1-0026b9348838", - "name": "HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE", - "locale": "en", - "localePreferred": true, - "conceptNameType": "FULLY_SPECIFIED", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a941afc6-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a941afc6-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.9" - }, - "datatype": { - "uuid": "8d4a48b6-c2cc-11de-8d13-0010c6dffd0f", - "display": "Coded", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a48b6-c2cc-11de-8d13-0010c6dffd0f" - } + uuid: '511ed043-3868-45bf-9770-605de9a7a5a1', + display: 'CD4, BY FACS: 432.28', + concept: { + uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838', + display: 'CD4, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838' + } ] - }, - "conceptClass": { - "uuid": "8d4907b2-c2cc-11de-8d13-0010c6dffd0f", - "display": "Test", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f" - } + }, + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } ] - }, - "set": false, - "version": "", - "retired": false, - "names": [ - { - "uuid": "a956da0e-1350-11df-a1f1-0026b9348838", - "display": "HIV QUAL", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a956da0e-1350-11df-a1f1-0026b9348838" - } - ] - }, + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 432.28, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ { - "uuid": "a941afc6-1350-11df-a1f1-0026b9348838", - "display": "HIV DNA POLYMERASE CHAIN REACTION, QUALITATIVE", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a941afc6-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1' }, { - "uuid": "a95267e4-1350-11df-a1f1-0026b9348838", - "display": "HIV PCR Qual", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a95267e4-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full' + } + ], + resourceVersion: '1.11' + } + ], + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: null, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full' + } + ], + resourceVersion: '1.11' + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + auditInfo: { + creator: { + uuid: 'A4F30A1B-5EB9-11DF-A648-37A07F9C90FB', + display: 'daemon', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB' + } + ] + }, + dateCreated: '2016-06-07T11:00:11.000+0300', + changedBy: null, + dateChanged: null + }, + value: 1644.03, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae' + } + ], + resourceVersion: '1.11' + }, + { + uuid: 'f5744e2b-f678-48cc-ada6-d6d6213f4ccd', + display: 'CD3, BY FACS: 1339.69', + concept: { + uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838', + display: 'CD3, BY FACS', + name: { + display: 'CD3, BY FACS', + uuid: 'a941ae22-1350-11df-a1f1-0026b9348838', + name: 'CD3, BY FACS', + locale: 'en', + localePreferred: true, + conceptNameType: 'FULLY_SPECIFIED', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a941ae22-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a941ae22-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.9' + }, + datatype: { + uuid: '8d4a4488-c2cc-11de-8d13-0010c6dffd0f', + display: 'Numeric', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + conceptClass: { + uuid: '8d4907b2-c2cc-11de-8d13-0010c6dffd0f', + display: 'Test', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + set: false, + version: '0.1', + retired: false, + names: [ + { + uuid: 'a9523ba2-1350-11df-a1f1-0026b9348838', + display: 'CD3 COUNT', + links: [ { - "uuid": "a956ce2e-1350-11df-a1f1-0026b9348838", - "display": "HIV DNA PCR", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a956ce2e-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a9523ba2-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a9549e9c-1350-11df-a1f1-0026b9348838', + display: 'CD3 COUNT FLOW', + links: [ { - "uuid": "a956cc76-1350-11df-a1f1-0026b9348838", - "display": "HIV DNA", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/name/a956cc76-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a9549e9c-1350-11df-a1f1-0026b9348838' } - ], - "descriptions": [ + ] + }, + { + uuid: 'a9531e00-1350-11df-a1f1-0026b9348838', + display: 'ABSOLUTE T-CELLS', + links: [ { - "uuid": "a8feb20c-1350-11df-a1f1-0026b9348838", - "display": "Qualitiative test to determine HIV infection. Test which is used to detect genetic information inserted into the DNA of human cells by HIV. This test is used for diagnosis of infection.", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/description/a8feb20c-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a9531e00-1350-11df-a1f1-0026b9348838' } - ], - "mappings": [ - { - "uuid": "1a010ec8-2308-4947-becc-9e09c405c481", - "display": "MCL/CIEL: 1030", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/mapping/1a010ec8-2308-4947-becc-9e09c405c481" - } - ] - }, + ] + }, + { + uuid: 'a954a1f8-1350-11df-a1f1-0026b9348838', + display: 'CD3+ABS CNT', + links: [ { - "uuid": "c9fb8d29-e61e-48a9-af3d-14da09287256", - "display": "local: 1030", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838/mapping/c9fb8d29-e61e-48a9-af3d-14da09287256" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a954a1f8-1350-11df-a1f1-0026b9348838' } - ], - "answers": [ - { - "uuid": "a89a7ae4-1350-11df-a1f1-0026b9348838", - "display": "INDETERMINATE", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89a7ae4-1350-11df-a1f1-0026b9348838" - } - ] - }, + ] + }, + { + uuid: 'a941ae22-1350-11df-a1f1-0026b9348838', + display: 'CD3, BY FACS', + links: [ { - "uuid": "a896d2cc-1350-11df-a1f1-0026b9348838", - "display": "NEGATIVE", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a941ae22-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a9549cee-1350-11df-a1f1-0026b9348838', + display: 'CD3', + links: [ { - "uuid": "a896f3a6-1350-11df-a1f1-0026b9348838", - "display": "POSITIVE", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896f3a6-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a9549cee-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a95ab4da-1350-11df-a1f1-0026b9348838', + display: 'T-CELL COUNT', + links: [ { - "uuid": "a89c3d8e-1350-11df-a1f1-0026b9348838", - "display": "POOR SAMPLE QUALITY", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c3d8e-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a95ab4da-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + descriptions: [ + { + uuid: 'a8feaf50-1350-11df-a1f1-0026b9348838', + display: + 'Flow cytometry scanning count of T-cell population. Count of t-cells which express the CD3 surface receptor.', + links: [ { - "uuid": "a899ea48-1350-11df-a1f1-0026b9348838", - "display": "NOT DONE", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a899ea48-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/description/a8feaf50-1350-11df-a1f1-0026b9348838' } - ], - "setMembers": [], - "links": [ + ] + } + ], + mappings: [ + { + uuid: '9d65337b-5a54-4e2e-8100-1df76cbc133b', + display: 'local: 1028', + links: [ { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838" - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/mapping/9d65337b-5a54-4e2e-8100-1df76cbc133b' + } + ] + }, + { + uuid: '525971db-70d9-42ec-a30a-871ddf7ad0f0', + display: 'MCL/CIEL: 1028', + links: [ { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fe80-1350-11df-a1f1-0026b9348838?v=full" + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/mapping/525971db-70d9-42ec-a30a-871ddf7ad0f0' } - ], - "resourceVersion": "1.11" - }, - "person":{}, - "obsDatetime": "2016-05-17T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": null, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "auditInfo": { - "creator": { - "uuid": "A4F30A1B-5EB9-11DF-A648-37A07F9C90FB", - "display": "daemon", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB" - } - ] + ] + } + ], + answers: [], + setMembers: [], + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838' }, - "dateCreated": "2016-05-23T13:21:16.000+0300", - "changedBy": null, - "dateChanged": null + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.11' }, - "value": { - "uuid": "a896d2cc-1350-11df-a1f1-0026b9348838", - "display": "NEGATIVE", - "name": { - "display": "NEGATIVE", - "uuid": "a93f5e24-1350-11df-a1f1-0026b9348838", - "name": "NEGATIVE", - "locale": "en", - "localePreferred": true, - "conceptNameType": "FULLY_SPECIFIED", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a93f5e24-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a93f5e24-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.9" - }, - "datatype": { - "uuid": "8d4a4c94-c2cc-11de-8d13-0010c6dffd0f", - "display": "N/A", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4c94-c2cc-11de-8d13-0010c6dffd0f" - } + person: {}, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + concept: { + uuid: 'a896cce6-1350-11df-a1f1-0026b9348838', + display: 'CD4 PANEL', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: null, + valueCodedName: null, + groupMembers: [ + { + uuid: 'f8cd76dc-6afa-4fca-8764-6c1a3d52d699', + display: 'CD4%, BY FACS: 26.29', + concept: { + uuid: 'a8970a26-1350-11df-a1f1-0026b9348838', + display: 'CD4%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838' + } ] - }, - "conceptClass": { - "uuid": "8d492774-c2cc-11de-8d13-0010c6dffd0f", - "display": "Misc", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d492774-c2cc-11de-8d13-0010c6dffd0f" - } + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } ] - }, - "set": false, - "version": "", - "retired": false, - "names": [ - { - "uuid": "a952f5ce-1350-11df-a1f1-0026b9348838", - "display": "(-)", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a952f5ce-1350-11df-a1f1-0026b9348838" - } - ] - }, + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 26.29, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ { - "uuid": "a9587fc6-1350-11df-a1f1-0026b9348838", - "display": "NEG", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a9587fc6-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699' }, { - "uuid": "a952fcae-1350-11df-a1f1-0026b9348838", - "display": "-", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a952fcae-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf', + display: 'CD3%, BY FACS: 81.49', + concept: { + uuid: 'a89c4220-1350-11df-a1f1-0026b9348838', + display: 'CD3%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e3c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 81.49, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf' }, { - "uuid": "a93f5e24-1350-11df-a1f1-0026b9348838", - "display": "NEGATIVE", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/name/a93f5e24-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full' } - ], - "descriptions": [ + ], + resourceVersion: '1.11' + }, + { + uuid: '7b51e86f-fada-46af-819f-c2134d2c35ae', + display: 'LYMPHOCYTE COUNT, BY FACS: 1644.03', + concept: { + uuid: 'a89c4914-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE COUNT, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1644.03, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ { - "uuid": "a8f78b08-1350-11df-a1f1-0026b9348838", - "display": "Response to a finding or test result.", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/description/a8f78b08-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "mappings": [ - { - "uuid": "5efd601b-edbf-4faf-9cd6-25911ff71a11", - "display": "MCL/CIEL: 664", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/mapping/5efd601b-edbf-4faf-9cd6-25911ff71a11" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae' }, { - "uuid": "65c48593-1fb5-4d63-893b-b1a15725b311", - "display": "local: 664", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838/mapping/65c48593-1fb5-4d63-893b-b1a15725b311" - } - ] + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full' } - ], - "answers": [], - "setMembers": [], - "links": [ + ], + resourceVersion: '1.11' + }, + { + uuid: 'f5744e2b-f678-48cc-ada6-d6d6213f4ccd', + display: 'CD3, BY FACS: 1339.69', + concept: { + uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838', + display: 'CD3, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1339.69, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838" + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd' }, { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896d2cc-1350-11df-a1f1-0026b9348838?v=full" + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full' } - ], - "resourceVersion": "1.11" - }, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/2c8954b9-f842-40b2-8a30-41eb5bfb6fc5" - } - ], - "resourceVersion": "1.11" - }; -} - -function getEidCd4Panel() { - return { - "LabID": "6304", - "PatientID": "000981160-5", - "ProviderID": "", - "MFLCode": "15753", - "AMRslocationID": "3", - "AMRslocation": "Turbo", - "PatientNames": "Test Patient", - "DateCollected": "02-Jun-2016", - "DateReceived": "06-Jun-2016", - "DateTested": "06-Jun-2016", - "Result": "81.49", - "AVGCD3percentLymph": "81.49", - "AVGCD3AbsCnt": "1339.69", - "AVGCD3CD4percentLymph": "26.29", - "AVGCD3CD4AbsCnt": "432.28", - "CD45AbsCnt": "1644.03", - "DateDispatched": "" - }; -} - -function getAmrsCd4PanelObs() { - return { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "concept": { - "uuid": "a896cce6-1350-11df-a1f1-0026b9348838", - "display": "CD4 PANEL", - "name": { - "display": "CD4 PANEL", - "uuid": "a93f5320-1350-11df-a1f1-0026b9348838", - "name": "CD4 PANEL", - "locale": "en", - "localePreferred": true, - "conceptNameType": "FULLY_SPECIFIED", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/name/a93f5320-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/name/a93f5320-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.9" + ], + resourceVersion: '1.11' }, - "datatype": { - "uuid": "8d4a4c94-c2cc-11de-8d13-0010c6dffd0f", - "display": "N/A", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4c94-c2cc-11de-8d13-0010c6dffd0f" - } + { + uuid: '511ed043-3868-45bf-9770-605de9a7a5a1', + display: 'CD4, BY FACS: 432.28', + concept: { + uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838', + display: 'CD4, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838' + } ] - }, - "conceptClass": { - "uuid": "8d492026-c2cc-11de-8d13-0010c6dffd0f", - "display": "LabSet", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d492026-c2cc-11de-8d13-0010c6dffd0f" - } + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } ] - }, - "set": true, - "version": "", - "retired": false, - "names": [ - { - "uuid": "a93f5320-1350-11df-a1f1-0026b9348838", - "display": "CD4 PANEL", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/name/a93f5320-1350-11df-a1f1-0026b9348838" - } - ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 432.28, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1' }, { - "uuid": "a957a664-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE SUBSET PANEL", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/name/a957a664-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full' } + ], + resourceVersion: '1.11' + } + ], + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: null, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full' + } + ], + resourceVersion: '1.11' + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + auditInfo: { + creator: { + uuid: 'A4F30A1B-5EB9-11DF-A648-37A07F9C90FB', + display: 'daemon', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB' + } + ] + }, + dateCreated: '2016-06-07T11:00:11.000+0300', + changedBy: null, + dateChanged: null + }, + value: 1339.69, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd' + } + ], + resourceVersion: '1.11' + }, + { + uuid: '511ed043-3868-45bf-9770-605de9a7a5a1', + display: 'CD4, BY FACS: 432.28', + concept: { + uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838', + display: 'CD4, BY FACS', + name: { + display: 'CD4, BY FACS', + uuid: 'a94b37ee-1350-11df-a1f1-0026b9348838', + name: 'CD4, BY FACS', + locale: 'en', + localePreferred: true, + conceptNameType: 'FULLY_SPECIFIED', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a94b37ee-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a94b37ee-1350-11df-a1f1-0026b9348838?v=full' + } ], - "descriptions": [ + resourceVersion: '1.9' + }, + datatype: { + uuid: '8d4a4488-c2cc-11de-8d13-0010c6dffd0f', + display: 'Numeric', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + conceptClass: { + uuid: '8d4907b2-c2cc-11de-8d13-0010c6dffd0f', + display: 'Test', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f' + } + ] + }, + set: false, + version: '0.1', + retired: false, + names: [ + { + uuid: 'a9531630-1350-11df-a1f1-0026b9348838', + display: 'ABSOLUTE CD4', + links: [ { - "uuid": "a8f782f2-1350-11df-a1f1-0026b9348838", - "display": "Breakdown of lymphocytes by surface receptors, including counts, percentiles and ratios.", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/description/a8f782f2-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a9531630-1350-11df-a1f1-0026b9348838' } - ], - "mappings": [ - { - "uuid": "66cdb436-97dd-4c44-a82e-ca8e76d6b6f6", - "display": "MCL/CIEL: 657", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/mapping/66cdb436-97dd-4c44-a82e-ca8e76d6b6f6" - } - ] - }, + ] + }, + { + uuid: 'a954a39c-1350-11df-a1f1-0026b9348838', + display: 'CD3+CD4+ABS CNT', + links: [ { - "uuid": "0bfe1fc1-2cd7-4d2d-843a-5d8e2a699efb", - "display": "local: 90", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/mapping/0bfe1fc1-2cd7-4d2d-843a-5d8e2a699efb" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a954a39c-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a954a61c-1350-11df-a1f1-0026b9348838', + display: 'CD4', + links: [ { - "uuid": "28af76e2-0eee-445b-aa43-1d55a3262496", - "display": "local: 657", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838/mapping/28af76e2-0eee-445b-aa43-1d55a3262496" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a954a61c-1350-11df-a1f1-0026b9348838' } - ], - "answers": [], - "setMembers": [ - { - "uuid": "a89c4220-1350-11df-a1f1-0026b9348838", - "display": "CD3%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838" - } - ] - }, + ] + }, + { + uuid: 'a9523d46-1350-11df-a1f1-0026b9348838', + display: 'CD4 COUNT', + links: [ { - "uuid": "a8970a26-1350-11df-a1f1-0026b9348838", - "display": "CD4%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a9523d46-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a94b37ee-1350-11df-a1f1-0026b9348838', + display: 'CD4, BY FACS', + links: [ { - "uuid": "a898fcd2-1350-11df-a1f1-0026b9348838", - "display": "CD3, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a94b37ee-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a954a7ca-1350-11df-a1f1-0026b9348838', + display: 'CD4 COUNT FLOW', + links: [ { - "uuid": "a89821e0-1350-11df-a1f1-0026b9348838", - "display": "CD8, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89821e0-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a954a7ca-1350-11df-a1f1-0026b9348838' + } + ] + }, + { + uuid: 'a95ab5b6-1350-11df-a1f1-0026b9348838', + display: 'T-HELPER CELL COUNT', + links: [ { - "uuid": "a8a8bb18-1350-11df-a1f1-0026b9348838", - "display": "CD4, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a95ab5b6-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + descriptions: [ + { + uuid: 'a90763d4-1350-11df-a1f1-0026b9348838', + display: + 'Flow cytometry scanning count of T-cell population, helper cell subset (CD4 positive). Measure of CD4 (T-helper cells) in blood', + links: [ { - "uuid": "a898fbf6-1350-11df-a1f1-0026b9348838", - "display": "CD8%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fbf6-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/description/a90763d4-1350-11df-a1f1-0026b9348838' + } + ] + } + ], + mappings: [ + { + uuid: 'c9687a91-3201-4591-9e4b-f2d5471e0b25', + display: 'local: 5497', + links: [ { - "uuid": "a89c4914-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE COUNT, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838" - } - ] - }, + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/mapping/c9687a91-3201-4591-9e4b-f2d5471e0b25' + } + ] + }, + { + uuid: '4822eba1-807e-4242-9585-97e389a36f37', + display: 'MCL/CIEL: 5497', + links: [ { - "uuid": "a89822bc-1350-11df-a1f1-0026b9348838", - "display": "CD4/CD8 RATIO, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89822bc-1350-11df-a1f1-0026b9348838" - } - ] + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/mapping/4822eba1-807e-4242-9585-97e389a36f37' } - ], - "links": [ + ] + } + ], + answers: [], + setMembers: [], + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838' + }, + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838?v=full' + } + ], + resourceVersion: '1.11' + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + concept: { + uuid: 'a896cce6-1350-11df-a1f1-0026b9348838', + display: 'CD4 PANEL', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: null, + valueCodedName: null, + groupMembers: [ + { + uuid: 'f8cd76dc-6afa-4fca-8764-6c1a3d52d699', + display: 'CD4%, BY FACS: 26.29', + concept: { + uuid: 'a8970a26-1350-11df-a1f1-0026b9348838', + display: 'CD4%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 26.29, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838" + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699' }, { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838?v=full" + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full' } - ], - "resourceVersion": "1.11" - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": null, - "valueCodedName": null, - "groupMembers": [ - { - "uuid": "f8cd76dc-6afa-4fca-8764-6c1a3d52d699", - "display": "CD4%, BY FACS: 26.29", - "concept": { - "uuid": "a8970a26-1350-11df-a1f1-0026b9348838", - "display": "CD4%, BY FACS", - "name": { - "display": "CD4%, BY FACS", - "uuid": "a93fc4ae-1350-11df-a1f1-0026b9348838", - "name": "CD4%, BY FACS", - "locale": "en", - "localePreferred": true, - "conceptNameType": "FULLY_SPECIFIED", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a93fc4ae-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a93fc4ae-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.9" - }, - "datatype": { - "uuid": "8d4a4488-c2cc-11de-8d13-0010c6dffd0f", - "display": "Numeric", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "conceptClass": { - "uuid": "8d4907b2-c2cc-11de-8d13-0010c6dffd0f", - "display": "Test", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "set": false, - "version": "0.1", - "retired": false, - "names": [ - { - "uuid": "a95ab692-1350-11df-a1f1-0026b9348838", - "display": "T-HELPER CELL PERCENT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a95ab692-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a93fc4ae-1350-11df-a1f1-0026b9348838", - "display": "CD4%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a93fc4ae-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954a96e-1350-11df-a1f1-0026b9348838", - "display": "CD4 PERCENT FLOW", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a954a96e-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954a2ca-1350-11df-a1f1-0026b9348838", - "display": "CD3+CD4+%LYMPH", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a954a2ca-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9523e18-1350-11df-a1f1-0026b9348838", - "display": "CD4%", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a9523e18-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954a89c-1350-11df-a1f1-0026b9348838", - "display": "CD4 PERCENT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/name/a954a89c-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "descriptions": [ - { - "uuid": "a8f7f5d4-1350-11df-a1f1-0026b9348838", - "display": "Flow cytometry scanning analysis of T-cell population, helper cell subset (CD4 positive) percent of total lymphocytes. Percentage of T-helper lymphocytes.", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/description/a8f7f5d4-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "mappings": [ - { - "uuid": "cfa573db-a23f-48ae-9925-96d5fe2bc994", - "display": "local: 730", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/mapping/cfa573db-a23f-48ae-9925-96d5fe2bc994" - } - ] - }, - { - "uuid": "4f257118-6537-4fa0-9145-8740abf6af02", - "display": "MCL/CIEL: 730", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838/mapping/4f257118-6537-4fa0-9145-8740abf6af02" - } - ] - } - ], - "answers": [], - "setMembers": [], - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.11" - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "concept": { - "uuid": "a896cce6-1350-11df-a1f1-0026b9348838", - "display": "CD4 PANEL", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": null, - "valueCodedName": null, - "groupMembers": [ - { - "uuid": "f8cd76dc-6afa-4fca-8764-6c1a3d52d699", - "display": "CD4%, BY FACS: 26.29", - "concept": { - "uuid": "a8970a26-1350-11df-a1f1-0026b9348838", - "display": "CD4%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 26.29, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf", - "display": "CD3%, BY FACS: 81.49", - "concept": { - "uuid": "a89c4220-1350-11df-a1f1-0026b9348838", - "display": "CD3%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 81.49, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "7b51e86f-fada-46af-819f-c2134d2c35ae", - "display": "LYMPHOCYTE COUNT, BY FACS: 1644.03", - "concept": { - "uuid": "a89c4914-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE COUNT, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1644.03, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "f5744e2b-f678-48cc-ada6-d6d6213f4ccd", - "display": "CD3, BY FACS: 1339.69", - "concept": { - "uuid": "a898fcd2-1350-11df-a1f1-0026b9348838", - "display": "CD3, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1339.69, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "511ed043-3868-45bf-9770-605de9a7a5a1", - "display": "CD4, BY FACS: 432.28", - "concept": { - "uuid": "a8a8bb18-1350-11df-a1f1-0026b9348838", - "display": "CD4, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 432.28, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full" - } - ], - "resourceVersion": "1.11" - } - ], - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": null, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full" - } - ], - "resourceVersion": "1.11" - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "auditInfo": { - "creator": { - "uuid": "A4F30A1B-5EB9-11DF-A648-37A07F9C90FB", - "display": "daemon", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB" - } - ] - }, - "dateCreated": "2016-06-07T11:00:11.000+0300", - "changedBy": null, - "dateChanged": null - }, - "value": 26.29, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699" - } - ], - "resourceVersion": "1.11" + ], + resourceVersion: '1.11' }, { - "uuid": "1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf", - "display": "CD3%, BY FACS: 81.49", - "concept": { - "uuid": "a89c4220-1350-11df-a1f1-0026b9348838", - "display": "CD3%, BY FACS", - "name": { - "display": "CD3%, BY FACS", - "uuid": "a9438396-1350-11df-a1f1-0026b9348838", - "name": "CD3%, BY FACS", - "locale": "en", - "localePreferred": true, - "conceptNameType": "FULLY_SPECIFIED", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9438396-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9438396-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.9" - }, - "datatype": { - "uuid": "8d4a4488-c2cc-11de-8d13-0010c6dffd0f", - "display": "Numeric", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "conceptClass": { - "uuid": "8d4907b2-c2cc-11de-8d13-0010c6dffd0f", - "display": "Test", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "set": false, - "version": "0.1", - "retired": false, - "names": [ - { - "uuid": "a958e204-1350-11df-a1f1-0026b9348838", - "display": "PERCENT T-CELLS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a958e204-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9523c74-1350-11df-a1f1-0026b9348838", - "display": "CD3%", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9523c74-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9549f6e-1350-11df-a1f1-0026b9348838", - "display": "CD3 PERCENT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9549f6e-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954a11c-1350-11df-a1f1-0026b9348838", - "display": "CD3+%LYMPH", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a954a11c-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9438396-1350-11df-a1f1-0026b9348838", - "display": "CD3%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a9438396-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954a04a-1350-11df-a1f1-0026b9348838", - "display": "CD3 PERCENT FLOW", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/name/a954a04a-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "descriptions": [ - { - "uuid": "a9006d18-1350-11df-a1f1-0026b9348838", - "display": "Flow cytometry scanning analysis of T-cell population, percent of total lymphocytes. Percentage of t-cells which express the CD3 surface receptor.", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/description/a9006d18-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "mappings": [ - { - "uuid": "16e79b3b-af28-450a-9ebd-230b01625cbf", - "display": "MCL/CIEL: 1310", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/mapping/16e79b3b-af28-450a-9ebd-230b01625cbf" - } - ] - }, - { - "uuid": "fb823cff-b089-4f7b-ab89-9d7325bb3dcf", - "display": "local: 1310", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838/mapping/fb823cff-b089-4f7b-ab89-9d7325bb3dcf" - } - ] - } - ], - "answers": [], - "setMembers": [], - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.11" - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "concept": { - "uuid": "a896cce6-1350-11df-a1f1-0026b9348838", - "display": "CD4 PANEL", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": null, - "valueCodedName": null, - "groupMembers": [ - { - "uuid": "f8cd76dc-6afa-4fca-8764-6c1a3d52d699", - "display": "CD4%, BY FACS: 26.29", - "concept": { - "uuid": "a8970a26-1350-11df-a1f1-0026b9348838", - "display": "CD4%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 26.29, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf", - "display": "CD3%, BY FACS: 81.49", - "concept": { - "uuid": "a89c4220-1350-11df-a1f1-0026b9348838", - "display": "CD3%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 81.49, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "7b51e86f-fada-46af-819f-c2134d2c35ae", - "display": "LYMPHOCYTE COUNT, BY FACS: 1644.03", - "concept": { - "uuid": "a89c4914-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE COUNT, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1644.03, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "f5744e2b-f678-48cc-ada6-d6d6213f4ccd", - "display": "CD3, BY FACS: 1339.69", - "concept": { - "uuid": "a898fcd2-1350-11df-a1f1-0026b9348838", - "display": "CD3, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1339.69, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "511ed043-3868-45bf-9770-605de9a7a5a1", - "display": "CD4, BY FACS: 432.28", - "concept": { - "uuid": "a8a8bb18-1350-11df-a1f1-0026b9348838", - "display": "CD4, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 432.28, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full" - } - ], - "resourceVersion": "1.11" - } - ], - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": null, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full" - } - ], - "resourceVersion": "1.11" - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "auditInfo": { - "creator": { - "uuid": "A4F30A1B-5EB9-11DF-A648-37A07F9C90FB", - "display": "daemon", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB" - } - ] - }, - "dateCreated": "2016-06-07T11:00:11.000+0300", - "changedBy": null, - "dateChanged": null + uuid: '1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf', + display: 'CD3%, BY FACS: 81.49', + concept: { + uuid: 'a89c4220-1350-11df-a1f1-0026b9348838', + display: 'CD3%, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 81.49, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf' }, - "value": 81.49, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf" - } - ], - "resourceVersion": "1.11" + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full' + } + ], + resourceVersion: '1.11' }, { - "uuid": "7b51e86f-fada-46af-819f-c2134d2c35ae", - "display": "LYMPHOCYTE COUNT, BY FACS: 1644.03", - "concept": { - "uuid": "a89c4914-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE COUNT, BY FACS", - "name": { - "display": "LYMPHOCYTE COUNT, BY FACS", - "uuid": "a9438b0c-1350-11df-a1f1-0026b9348838", - "name": "LYMPHOCYTE COUNT, BY FACS", - "locale": "en", - "localePreferred": true, - "conceptNameType": "FULLY_SPECIFIED", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9438b0c-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9438b0c-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.9" - }, - "datatype": { - "uuid": "8d4a4488-c2cc-11de-8d13-0010c6dffd0f", - "display": "Numeric", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "conceptClass": { - "uuid": "8d4907b2-c2cc-11de-8d13-0010c6dffd0f", - "display": "Test", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "set": false, - "version": "0.1", - "retired": false, - "names": [ - { - "uuid": "a9531d38-1350-11df-a1f1-0026b9348838", - "display": "ABSOLUTE LYMPHOCYTES BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9531d38-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a957a4c0-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE CELL COUNT BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a957a4c0-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a957a592-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE COUNT FLOW", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a957a592-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9438b0c-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE COUNT, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9438b0c-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954ab1c-1350-11df-a1f1-0026b9348838", - "display": "CD45+ABS CNT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a954ab1c-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9528378-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTES", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/name/a9528378-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "descriptions": [ - { - "uuid": "a9006e9e-1350-11df-a1f1-0026b9348838", - "display": "Flow cytometry scanning analysis of total lymphocyte population. Immunology Test - CD45 plus lymphocyte count.", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/description/a9006e9e-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "mappings": [ - { - "uuid": "90eefc4c-9e93-46ea-881c-34e469504035", - "display": "MCL/CIEL: 1319", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/mapping/90eefc4c-9e93-46ea-881c-34e469504035" - } - ] - }, - { - "uuid": "973fb281-68af-4c05-85a3-4f32fe4b147c", - "display": "local: 1319", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838/mapping/973fb281-68af-4c05-85a3-4f32fe4b147c" - } - ] - } - ], - "answers": [], - "setMembers": [], - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.11" - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "concept": { - "uuid": "a896cce6-1350-11df-a1f1-0026b9348838", - "display": "CD4 PANEL", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": null, - "valueCodedName": null, - "groupMembers": [ - { - "uuid": "f8cd76dc-6afa-4fca-8764-6c1a3d52d699", - "display": "CD4%, BY FACS: 26.29", - "concept": { - "uuid": "a8970a26-1350-11df-a1f1-0026b9348838", - "display": "CD4%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 26.29, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf", - "display": "CD3%, BY FACS: 81.49", - "concept": { - "uuid": "a89c4220-1350-11df-a1f1-0026b9348838", - "display": "CD3%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 81.49, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "7b51e86f-fada-46af-819f-c2134d2c35ae", - "display": "LYMPHOCYTE COUNT, BY FACS: 1644.03", - "concept": { - "uuid": "a89c4914-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE COUNT, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1644.03, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "f5744e2b-f678-48cc-ada6-d6d6213f4ccd", - "display": "CD3, BY FACS: 1339.69", - "concept": { - "uuid": "a898fcd2-1350-11df-a1f1-0026b9348838", - "display": "CD3, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": {}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1339.69, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "511ed043-3868-45bf-9770-605de9a7a5a1", - "display": "CD4, BY FACS: 432.28", - "concept": { - "uuid": "a8a8bb18-1350-11df-a1f1-0026b9348838", - "display": "CD4, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 432.28, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full" - } - ], - "resourceVersion": "1.11" - } - ], - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": null, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full" - } - ], - "resourceVersion": "1.11" - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "auditInfo": { - "creator": { - "uuid": "A4F30A1B-5EB9-11DF-A648-37A07F9C90FB", - "display": "daemon", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB" - } - ] - }, - "dateCreated": "2016-06-07T11:00:11.000+0300", - "changedBy": null, - "dateChanged": null + uuid: '7b51e86f-fada-46af-819f-c2134d2c35ae', + display: 'LYMPHOCYTE COUNT, BY FACS: 1644.03', + concept: { + uuid: 'a89c4914-1350-11df-a1f1-0026b9348838', + display: 'LYMPHOCYTE COUNT, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1644.03, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae' }, - "value": 1644.03, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae" - } - ], - "resourceVersion": "1.11" + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full' + } + ], + resourceVersion: '1.11' }, { - "uuid": "f5744e2b-f678-48cc-ada6-d6d6213f4ccd", - "display": "CD3, BY FACS: 1339.69", - "concept": { - "uuid": "a898fcd2-1350-11df-a1f1-0026b9348838", - "display": "CD3, BY FACS", - "name": { - "display": "CD3, BY FACS", - "uuid": "a941ae22-1350-11df-a1f1-0026b9348838", - "name": "CD3, BY FACS", - "locale": "en", - "localePreferred": true, - "conceptNameType": "FULLY_SPECIFIED", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a941ae22-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a941ae22-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.9" - }, - "datatype": { - "uuid": "8d4a4488-c2cc-11de-8d13-0010c6dffd0f", - "display": "Numeric", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "conceptClass": { - "uuid": "8d4907b2-c2cc-11de-8d13-0010c6dffd0f", - "display": "Test", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "set": false, - "version": "0.1", - "retired": false, - "names": [ - { - "uuid": "a9523ba2-1350-11df-a1f1-0026b9348838", - "display": "CD3 COUNT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a9523ba2-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9549e9c-1350-11df-a1f1-0026b9348838", - "display": "CD3 COUNT FLOW", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a9549e9c-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9531e00-1350-11df-a1f1-0026b9348838", - "display": "ABSOLUTE T-CELLS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a9531e00-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954a1f8-1350-11df-a1f1-0026b9348838", - "display": "CD3+ABS CNT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a954a1f8-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a941ae22-1350-11df-a1f1-0026b9348838", - "display": "CD3, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a941ae22-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9549cee-1350-11df-a1f1-0026b9348838", - "display": "CD3", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a9549cee-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a95ab4da-1350-11df-a1f1-0026b9348838", - "display": "T-CELL COUNT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/name/a95ab4da-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "descriptions": [ - { - "uuid": "a8feaf50-1350-11df-a1f1-0026b9348838", - "display": "Flow cytometry scanning count of T-cell population. Count of t-cells which express the CD3 surface receptor.", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/description/a8feaf50-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "mappings": [ - { - "uuid": "9d65337b-5a54-4e2e-8100-1df76cbc133b", - "display": "local: 1028", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/mapping/9d65337b-5a54-4e2e-8100-1df76cbc133b" - } - ] - }, - { - "uuid": "525971db-70d9-42ec-a30a-871ddf7ad0f0", - "display": "MCL/CIEL: 1028", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838/mapping/525971db-70d9-42ec-a30a-871ddf7ad0f0" - } - ] - } - ], - "answers": [], - "setMembers": [], - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.11" - }, - "person":{}, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "concept": { - "uuid": "a896cce6-1350-11df-a1f1-0026b9348838", - "display": "CD4 PANEL", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": null, - "valueCodedName": null, - "groupMembers": [ - { - "uuid": "f8cd76dc-6afa-4fca-8764-6c1a3d52d699", - "display": "CD4%, BY FACS: 26.29", - "concept": { - "uuid": "a8970a26-1350-11df-a1f1-0026b9348838", - "display": "CD4%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 26.29, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf", - "display": "CD3%, BY FACS: 81.49", - "concept": { - "uuid": "a89c4220-1350-11df-a1f1-0026b9348838", - "display": "CD3%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e3c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 81.49, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "7b51e86f-fada-46af-819f-c2134d2c35ae", - "display": "LYMPHOCYTE COUNT, BY FACS: 1644.03", - "concept": { - "uuid": "a89c4914-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE COUNT, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1644.03, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "f5744e2b-f678-48cc-ada6-d6d6213f4ccd", - "display": "CD3, BY FACS: 1339.69", - "concept": { - "uuid": "a898fcd2-1350-11df-a1f1-0026b9348838", - "display": "CD3, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1339.69, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "511ed043-3868-45bf-9770-605de9a7a5a1", - "display": "CD4, BY FACS: 432.28", - "concept": { - "uuid": "a8a8bb18-1350-11df-a1f1-0026b9348838", - "display": "CD4, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 432.28, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full" - } - ], - "resourceVersion": "1.11" - } - ], - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": null, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full" - } - ], - "resourceVersion": "1.11" - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "auditInfo": { - "creator": { - "uuid": "A4F30A1B-5EB9-11DF-A648-37A07F9C90FB", - "display": "daemon", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB" - } - ] - }, - "dateCreated": "2016-06-07T11:00:11.000+0300", - "changedBy": null, - "dateChanged": null + uuid: 'f5744e2b-f678-48cc-ada6-d6d6213f4ccd', + display: 'CD3, BY FACS: 1339.69', + concept: { + uuid: 'a898fcd2-1350-11df-a1f1-0026b9348838', + display: 'CD3, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 1339.69, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd' }, - "value": 1339.69, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd" - } - ], - "resourceVersion": "1.11" + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full' + } + ], + resourceVersion: '1.11' }, { - "uuid": "511ed043-3868-45bf-9770-605de9a7a5a1", - "display": "CD4, BY FACS: 432.28", - "concept": { - "uuid": "a8a8bb18-1350-11df-a1f1-0026b9348838", - "display": "CD4, BY FACS", - "name": { - "display": "CD4, BY FACS", - "uuid": "a94b37ee-1350-11df-a1f1-0026b9348838", - "name": "CD4, BY FACS", - "locale": "en", - "localePreferred": true, - "conceptNameType": "FULLY_SPECIFIED", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a94b37ee-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a94b37ee-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.9" - }, - "datatype": { - "uuid": "8d4a4488-c2cc-11de-8d13-0010c6dffd0f", - "display": "Numeric", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptdatatype/8d4a4488-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "conceptClass": { - "uuid": "8d4907b2-c2cc-11de-8d13-0010c6dffd0f", - "display": "Test", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/conceptclass/8d4907b2-c2cc-11de-8d13-0010c6dffd0f" - } - ] - }, - "set": false, - "version": "0.1", - "retired": false, - "names": [ - { - "uuid": "a9531630-1350-11df-a1f1-0026b9348838", - "display": "ABSOLUTE CD4", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a9531630-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954a39c-1350-11df-a1f1-0026b9348838", - "display": "CD3+CD4+ABS CNT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a954a39c-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954a61c-1350-11df-a1f1-0026b9348838", - "display": "CD4", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a954a61c-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a9523d46-1350-11df-a1f1-0026b9348838", - "display": "CD4 COUNT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a9523d46-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a94b37ee-1350-11df-a1f1-0026b9348838", - "display": "CD4, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a94b37ee-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a954a7ca-1350-11df-a1f1-0026b9348838", - "display": "CD4 COUNT FLOW", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a954a7ca-1350-11df-a1f1-0026b9348838" - } - ] - }, - { - "uuid": "a95ab5b6-1350-11df-a1f1-0026b9348838", - "display": "T-HELPER CELL COUNT", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/name/a95ab5b6-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "descriptions": [ - { - "uuid": "a90763d4-1350-11df-a1f1-0026b9348838", - "display": "Flow cytometry scanning count of T-cell population, helper cell subset (CD4 positive). Measure of CD4 (T-helper cells) in blood", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/description/a90763d4-1350-11df-a1f1-0026b9348838" - } - ] - } - ], - "mappings": [ - { - "uuid": "c9687a91-3201-4591-9e4b-f2d5471e0b25", - "display": "local: 5497", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/mapping/c9687a91-3201-4591-9e4b-f2d5471e0b25" - } - ] - }, - { - "uuid": "4822eba1-807e-4242-9585-97e389a36f37", - "display": "MCL/CIEL: 5497", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838/mapping/4822eba1-807e-4242-9585-97e389a36f37" - } - ] - } - ], - "answers": [], - "setMembers": [], - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838?v=full" - } - ], - "resourceVersion": "1.11" - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "concept": { - "uuid": "a896cce6-1350-11df-a1f1-0026b9348838", - "display": "CD4 PANEL", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a896cce6-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": null, - "valueCodedName": null, - "groupMembers": [ - { - "uuid": "f8cd76dc-6afa-4fca-8764-6c1a3d52d699", - "display": "CD4%, BY FACS: 26.29", - "concept": { - "uuid": "a8970a26-1350-11df-a1f1-0026b9348838", - "display": "CD4%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8970a26-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 26.29, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f8cd76dc-6afa-4fca-8764-6c1a3d52d699?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf", - "display": "CD3%, BY FACS: 81.49", - "concept": { - "uuid": "a89c4220-1350-11df-a1f1-0026b9348838", - "display": "CD3%, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4220-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 81.49, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/1a57c4b7-3b4f-42c5-a7ea-b372d11c3adf?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "7b51e86f-fada-46af-819f-c2134d2c35ae", - "display": "LYMPHOCYTE COUNT, BY FACS: 1644.03", - "concept": { - "uuid": "a89c4914-1350-11df-a1f1-0026b9348838", - "display": "LYMPHOCYTE COUNT, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a89c4914-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1644.03, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7b51e86f-fada-46af-819f-c2134d2c35ae?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "f5744e2b-f678-48cc-ada6-d6d6213f4ccd", - "display": "CD3, BY FACS: 1339.69", - "concept": { - "uuid": "a898fcd2-1350-11df-a1f1-0026b9348838", - "display": "CD3, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a898fcd2-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 1339.69, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/f5744e2b-f678-48cc-ada6-d6d6213f4ccd?v=full" - } - ], - "resourceVersion": "1.11" - }, - { - "uuid": "511ed043-3868-45bf-9770-605de9a7a5a1", - "display": "CD4, BY FACS: 432.28", - "concept": { - "uuid": "a8a8bb18-1350-11df-a1f1-0026b9348838", - "display": "CD4, BY FACS", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838" - } - ] - }, - "person": { - "uuid": "bb4d8538-e986-47bd-a44b-4bffa6e39c22", - "display": "test patient", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22" - } - ] - }, - "obsDatetime": "2016-06-02T00:00:01.000+0300", - "accessionNumber": null, - "obsGroup": { - "uuid": "7e55fc57-05a7-4cfa-938d-58e0aa3aeb97", - "display": "CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - } - ] - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": 432.28, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full" - } - ], - "resourceVersion": "1.11" - } - ], - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "value": null, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" - }, - { - "rel": "full", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full" - } - ], - "resourceVersion": "1.11" - }, - "valueCodedName": null, - "groupMembers": null, - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "auditInfo": { - "creator": { - "uuid": "A4F30A1B-5EB9-11DF-A648-37A07F9C90FB", - "display": "daemon", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB" - } - ] - }, - "dateCreated": "2016-06-07T11:00:11.000+0300", - "changedBy": null, - "dateChanged": null + uuid: '511ed043-3868-45bf-9770-605de9a7a5a1', + display: 'CD4, BY FACS: 432.28', + concept: { + uuid: 'a8a8bb18-1350-11df-a1f1-0026b9348838', + display: 'CD4, BY FACS', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/concept/a8a8bb18-1350-11df-a1f1-0026b9348838' + } + ] + }, + person: { + uuid: 'bb4d8538-e986-47bd-a44b-4bffa6e39c22', + display: 'test patient', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/patient/bb4d8538-e986-47bd-a44b-4bffa6e39c22' + } + ] + }, + obsDatetime: '2016-06-02T00:00:01.000+0300', + accessionNumber: null, + obsGroup: { + uuid: '7e55fc57-05a7-4cfa-938d-58e0aa3aeb97', + display: 'CD4 PANEL: 26.29, 81.49, 1644.03, 1339.69, 432.28', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ] + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: 432.28, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1' }, - "value": 432.28, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1" - } - ], - "resourceVersion": "1.11" + { + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1?v=full' + } + ], + resourceVersion: '1.11' } - ], - "comment": null, - "location": null, - "order": null, - "encounter": null, - "voided": false, - "auditInfo": { - "creator": { - "uuid": "A4F30A1B-5EB9-11DF-A648-37A07F9C90FB", - "display": "daemon", - "links": [ - { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB" - } - ] + ], + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + value: null, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' }, - "dateCreated": "2016-06-07T11:00:11.000+0300", - "changedBy": null, - "dateChanged": null - }, - "value": null, - "valueModifier": null, - "formFieldPath": null, - "formFieldNamespace": null, - "links": [ { - "rel": "self", - "uri": "https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97" + rel: 'full', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97?v=full' } + ], + resourceVersion: '1.11' + }, + valueCodedName: null, + groupMembers: null, + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + auditInfo: { + creator: { + uuid: 'A4F30A1B-5EB9-11DF-A648-37A07F9C90FB', + display: 'daemon', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB' + } + ] + }, + dateCreated: '2016-06-07T11:00:11.000+0300', + changedBy: null, + dateChanged: null + }, + value: 432.28, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/511ed043-3868-45bf-9770-605de9a7a5a1' + } ], - "resourceVersion": "1.11" - }; -} \ No newline at end of file + resourceVersion: '1.11' + } + ], + comment: null, + location: null, + order: null, + encounter: null, + voided: false, + auditInfo: { + creator: { + uuid: 'A4F30A1B-5EB9-11DF-A648-37A07F9C90FB', + display: 'daemon', + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/user/A4F30A1B-5EB9-11DF-A648-37A07F9C90FB' + } + ] + }, + dateCreated: '2016-06-07T11:00:11.000+0300', + changedBy: null, + dateChanged: null + }, + value: null, + valueModifier: null, + formFieldPath: null, + formFieldNamespace: null, + links: [ + { + rel: 'self', + uri: + 'https://amrs.ampath.or.ke:8443/amrs/ws/rest/v1/obs/7e55fc57-05a7-4cfa-938d-58e0aa3aeb97' + } + ], + resourceVersion: '1.11' + }; +} diff --git a/test/mock/mock-data.js b/test/mock/mock-data.js index 294fdde6d..829d8f11c 100755 --- a/test/mock/mock-data.js +++ b/test/mock/mock-data.js @@ -1,163 +1,158 @@ -"use strict"; +'use strict'; //mock data -module.exports = function () -{ - return { - getPatientMockData:function getPatientMockData() { - return [ - { - person_id: 123, - uuid: "c6e4e026-3b49-4b64-81de-05cf8bd18594", - encounter_id: 5480271, - encounter_datetime: "2015-08-05T08:33:17.000Z", - location_id: 100, - location_uuid: "00b47ef5-a29b-40a2-a7f4-6851df8d6532", - visit_num: null, - death_date: null, - scheduled_visit: null, - transfer_out: null, - out_of_care: null, - prev_rtc_date: "2015-08-05T21:00:00.000Z", - rtc_date: "2015-08-05T21:00:00.000Z", - arv_start_date: null, - arv_first_regimen: null, - cur_arv_meds: null, - cur_arv_line: null, - first_evidence_patient_pregnant: null, - edd: null, - screened_for_tb: null, - tb_tx_start_date: "2015-07-29T18:00:00.000Z", - pcp_prophylaxis_start_date: null, - cd4_resulted: null, - cd4_resulted_date: null, - cd4_1: 500, - cd4_1_date: "2015-07-25T21:00:00.000Z", - cd4_2: null, - cd4_2_date: null, - cd4_percent_1: null, - cd4_percent_1_date: null, - cd4_percent_2: null, - cd4_percent_2_date: null, - vl_resulted: null, - vl_resulted_date: null, - vl_1: 500, - vl_1_date: "2015-08-03T21:00:00.000Z", - vl_2: null, - vl_2_date: null, - vl_order_date: null, - cd4_order_date: null - } - ] - }, - - getCustomMockData: function getCustomMockData() { - return [ - { - patient_id: 1001, - creator: 3, - date_created: "2006-02-14T21:00:00.000Z", - changed_by: 164623, - date_changed: "2012-04-23T14:36:23.000Z", - voided: 0, - voided_by: null, - date_voided: null, - void_reason: null - } - ] - }, - getReportMock: function getReportMock() { - return [ - { - name: "test-report-01", - table: { - schema: "etl", - tableName: "test_flat_hiv_summary", - alias: "t1" - }, - sections: "first_test_section", - indicatorHandlers: [ - { processor: "testReportProcessorHandler", indicators: ["indicator1", "indicator2"] } - ], - - joins: [ - { - joinType: "INNER JOIN", - schema: "etl", - tableName: "derived_encounter", - alias: "t2", - joinExpression: "t1.encounter_id = t2.encounter_id" - } - ], - parameters: [ - { - name: "startDate", - defaultValue: [ - "10-10-2015" - ] - }, - { - name: "endDate", - defaultValue: [ - "defaultValue" - ] - }, - { - name: "locations", - defaultValue: [] - } - ], - filters: [ - { - expression: "t1.rtc_date >= ?", - parameter: "startDate" - }, - { - expression: "t1.rtc_date <= ?", - parameter: "endDate" - }, - { - expression: "t1.location_id = ?", - parameter: "locations" - } - ], - groupClause: [ - { parameter: "groupByd" }, - { parameter: "groupByw" } - ], - indicators: [{ - label: "test scheduled", - expression: "test_scheduled", - sql: "count(scheduled)" - }, { - label: "test2_scheduled", - expression: "test2_scheduled", - sql: "count(scheduled)", - section: "first_test_section" - } - ], - supplementColumns: [ - { - label: "encounter_id", - type: "single", - sql: "t1.encounter_id" - }, - { - label: "d", - type: "single", - sql: "date(rtc_date)" - } +module.exports = (function () { + return { + getPatientMockData: function getPatientMockData() { + return [ + { + person_id: 123, + uuid: 'c6e4e026-3b49-4b64-81de-05cf8bd18594', + encounter_id: 5480271, + encounter_datetime: '2015-08-05T08:33:17.000Z', + location_id: 100, + location_uuid: '00b47ef5-a29b-40a2-a7f4-6851df8d6532', + visit_num: null, + death_date: null, + scheduled_visit: null, + transfer_out: null, + out_of_care: null, + prev_rtc_date: '2015-08-05T21:00:00.000Z', + rtc_date: '2015-08-05T21:00:00.000Z', + arv_start_date: null, + arv_first_regimen: null, + cur_arv_meds: null, + cur_arv_line: null, + first_evidence_patient_pregnant: null, + edd: null, + screened_for_tb: null, + tb_tx_start_date: '2015-07-29T18:00:00.000Z', + pcp_prophylaxis_start_date: null, + cd4_resulted: null, + cd4_resulted_date: null, + cd4_1: 500, + cd4_1_date: '2015-07-25T21:00:00.000Z', + cd4_2: null, + cd4_2_date: null, + cd4_percent_1: null, + cd4_percent_1_date: null, + cd4_percent_2: null, + cd4_percent_2_date: null, + vl_resulted: null, + vl_resulted_date: null, + vl_1: 500, + vl_1_date: '2015-08-03T21:00:00.000Z', + vl_2: null, + vl_2_date: null, + vl_order_date: null, + cd4_order_date: null + } + ]; + }, + getCustomMockData: function getCustomMockData() { + return [ + { + patient_id: 1001, + creator: 3, + date_created: '2006-02-14T21:00:00.000Z', + changed_by: 164623, + date_changed: '2012-04-23T14:36:23.000Z', + voided: 0, + voided_by: null, + date_voided: null, + void_reason: null + } + ]; + }, + getReportMock: function getReportMock() { + return [ + { + name: 'test-report-01', + table: { + schema: 'etl', + tableName: 'test_flat_hiv_summary', + alias: 't1' + }, + sections: 'first_test_section', + indicatorHandlers: [ + { + processor: 'testReportProcessorHandler', + indicators: ['indicator1', 'indicator2'] + } + ], - ] - } - ] - }, - getReportProcessorMock: function getReportProcessorMock() { - return { testReportProcessorHandler: testReportProcessorHandlerFunction } - function testReportProcessorHandlerFunction(testValue, queryResults) { - queryResults.testindicators = testValue - return queryResults; + joins: [ + { + joinType: 'INNER JOIN', + schema: 'etl', + tableName: 'derived_encounter', + alias: 't2', + joinExpression: 't1.encounter_id = t2.encounter_id' + } + ], + parameters: [ + { + name: 'startDate', + defaultValue: ['10-10-2015'] + }, + { + name: 'endDate', + defaultValue: ['defaultValue'] + }, + { + name: 'locations', + defaultValue: [] + } + ], + filters: [ + { + expression: 't1.rtc_date >= ?', + parameter: 'startDate' + }, + { + expression: 't1.rtc_date <= ?', + parameter: 'endDate' + }, + { + expression: 't1.location_id = ?', + parameter: 'locations' + } + ], + groupClause: [{ parameter: 'groupByd' }, { parameter: 'groupByw' }], + indicators: [ + { + label: 'test scheduled', + expression: 'test_scheduled', + sql: 'count(scheduled)' + }, + { + label: 'test2_scheduled', + expression: 'test2_scheduled', + sql: 'count(scheduled)', + section: 'first_test_section' + } + ], + supplementColumns: [ + { + label: 'encounter_id', + type: 'single', + sql: 't1.encounter_id' + }, + { + label: 'd', + type: 'single', + sql: 'date(rtc_date)' } + ] } - } -}(); + ]; + }, + getReportProcessorMock: function getReportProcessorMock() { + return { testReportProcessorHandler: testReportProcessorHandlerFunction }; + function testReportProcessorHandlerFunction(testValue, queryResults) { + queryResults.testindicators = testValue; + return queryResults; + } + } + }; +})(); diff --git a/test/mock/patient-flow-sample.js b/test/mock/patient-flow-sample.js index 60d47c7a7..a106c4b70 100755 --- a/test/mock/patient-flow-sample.js +++ b/test/mock/patient-flow-sample.js @@ -1,111 +1,110 @@ var mocks = { - getPatientFlowSample: getPatientFlowSample + getPatientFlowSample: getPatientFlowSample }; module.exports = mocks; function getPatientFlowSample() { - return { - "startIndex": 0, - "size": 130, - "result": [ - { - "visit_id": 26727, - "visit_start": "2016-06-15T04:47:21.000Z", - "triaged": "2016-06-15T05:16:34.000Z", - "time_to_be_triaged": 29, - "seen_by_clinician": null, - "visit_end": null, - "encounter_type": 110, - "encounter_start": "2016-06-15T05:16:34.000Z", - "encounter_end": "2016-06-15T05:18:39.000Z", - "patient_id": 783782, - "given_name": "Test 1", - "middle_name": "Test 1", - "family_name": "Test 1", - "identifiers": "15204-33717,435990441-6" - }, - { - "visit_id": 26727, - "visit_start": "2016-06-15T04:47:21.000Z", - "triaged": null, - "time_to_be_triaged": null, - "seen_by_clinician": "2016-06-15T05:35:44.000Z", - "visit_end": "2016-06-15T05:45:25.000Z", - "encounter_type": 2, - "encounter_start": "2016-06-15T05:35:44.000Z", - "encounter_end": "2016-06-15T05:44:25.000Z", - "patient_id": 783782, - "given_name": "Test 1", - "middle_name": "Test 1", - "family_name": "Test 1", - "identifiers": "435990441-6,15204-33717" - }, - { - "visit_id": 26729, - "visit_start": "2016-06-15T04:48:28.000Z", - "triaged": "2016-06-15T05:19:58.000Z", - "time_to_be_triaged": 31, - "seen_by_clinician": null, - "visit_end": null, - "encounter_type": 110, - "encounter_start": "2016-06-15T05:19:58.000Z", - "encounter_end": "2016-06-15T05:22:10.000Z", - "patient_id": 57329, - "given_name": "Test 2", - "middle_name": "Test 2", - "family_name": "Test 2", - "identifiers": "299471344-0,16093MT-9,15204-14095" - }, - { - "visit_id": 26729, - "visit_start": "2016-06-15T04:48:28.000Z", - "triaged": null, - "time_to_be_triaged": null, - "seen_by_clinician": "2016-06-15T05:40:51.000Z", - "visit_end": null, - "encounter_type": 2, - "encounter_start": "2016-06-15T05:40:51.000Z", - "encounter_end": "2016-06-15T05:43:43.000Z", - "patient_id": 57329, - "given_name": "Test 2", - "middle_name": "Test 2", - "family_name": "Test 2", - "identifiers": "299471344-0,16093MT-9,15204-14095" - }, - { - "visit_id": 26729, - "visit_start": "2016-06-15T04:48:28.000Z", - "triaged": null, - "time_to_be_triaged": null, - "seen_by_clinician": "2016-06-15T05:46:52.000Z", - "visit_end": null, - "encounter_type": 3, - "encounter_start": "2016-06-15T05:46:52.000Z", - "encounter_end": "2016-06-15T05:56:59.000Z", - "patient_id": 94168, - "given_name": "Test 2", - "middle_name": "Test 2", - "family_name": "Test 2", - "identifiers": "23223MT-3,15204-20061,973642608-2" - }, - { - "visit_id": 26731, - "visit_start": "2016-06-15T04:49:26.000Z", - "triaged": "2016-06-15T05:16:34.000Z", - "time_to_be_triaged": 30, - "seen_by_clinician": null, - "visit_end": "2016-06-15T05:49:34.000Z", - "encounter_type": 110, - "encounter_start": "2016-06-15T05:16:34.000Z", - "encounter_end": "2016-06-15T05:48:14.000Z", - "patient_id": 94169, - "given_name": "Test 3", - "middle_name": "Test 3", - "family_name": "Test 3", - "identifiers": "23223MT-3,15204-20061,973642608-2" - }, - ] - }; + return { + startIndex: 0, + size: 130, + result: [ + { + visit_id: 26727, + visit_start: '2016-06-15T04:47:21.000Z', + triaged: '2016-06-15T05:16:34.000Z', + time_to_be_triaged: 29, + seen_by_clinician: null, + visit_end: null, + encounter_type: 110, + encounter_start: '2016-06-15T05:16:34.000Z', + encounter_end: '2016-06-15T05:18:39.000Z', + patient_id: 783782, + given_name: 'Test 1', + middle_name: 'Test 1', + family_name: 'Test 1', + identifiers: '15204-33717,435990441-6' + }, + { + visit_id: 26727, + visit_start: '2016-06-15T04:47:21.000Z', + triaged: null, + time_to_be_triaged: null, + seen_by_clinician: '2016-06-15T05:35:44.000Z', + visit_end: '2016-06-15T05:45:25.000Z', + encounter_type: 2, + encounter_start: '2016-06-15T05:35:44.000Z', + encounter_end: '2016-06-15T05:44:25.000Z', + patient_id: 783782, + given_name: 'Test 1', + middle_name: 'Test 1', + family_name: 'Test 1', + identifiers: '435990441-6,15204-33717' + }, + { + visit_id: 26729, + visit_start: '2016-06-15T04:48:28.000Z', + triaged: '2016-06-15T05:19:58.000Z', + time_to_be_triaged: 31, + seen_by_clinician: null, + visit_end: null, + encounter_type: 110, + encounter_start: '2016-06-15T05:19:58.000Z', + encounter_end: '2016-06-15T05:22:10.000Z', + patient_id: 57329, + given_name: 'Test 2', + middle_name: 'Test 2', + family_name: 'Test 2', + identifiers: '299471344-0,16093MT-9,15204-14095' + }, + { + visit_id: 26729, + visit_start: '2016-06-15T04:48:28.000Z', + triaged: null, + time_to_be_triaged: null, + seen_by_clinician: '2016-06-15T05:40:51.000Z', + visit_end: null, + encounter_type: 2, + encounter_start: '2016-06-15T05:40:51.000Z', + encounter_end: '2016-06-15T05:43:43.000Z', + patient_id: 57329, + given_name: 'Test 2', + middle_name: 'Test 2', + family_name: 'Test 2', + identifiers: '299471344-0,16093MT-9,15204-14095' + }, + { + visit_id: 26729, + visit_start: '2016-06-15T04:48:28.000Z', + triaged: null, + time_to_be_triaged: null, + seen_by_clinician: '2016-06-15T05:46:52.000Z', + visit_end: null, + encounter_type: 3, + encounter_start: '2016-06-15T05:46:52.000Z', + encounter_end: '2016-06-15T05:56:59.000Z', + patient_id: 94168, + given_name: 'Test 2', + middle_name: 'Test 2', + family_name: 'Test 2', + identifiers: '23223MT-3,15204-20061,973642608-2' + }, + { + visit_id: 26731, + visit_start: '2016-06-15T04:49:26.000Z', + triaged: '2016-06-15T05:16:34.000Z', + time_to_be_triaged: 30, + seen_by_clinician: null, + visit_end: '2016-06-15T05:49:34.000Z', + encounter_type: 110, + encounter_start: '2016-06-15T05:16:34.000Z', + encounter_end: '2016-06-15T05:48:14.000Z', + patient_id: 94169, + given_name: 'Test 3', + middle_name: 'Test 3', + family_name: 'Test 3', + identifiers: '23223MT-3,15204-20061,973642608-2' + } + ] + }; } - diff --git a/test/mock/user-mock.js b/test/mock/user-mock.js index 630aed4b2..5a7799f10 100755 --- a/test/mock/user-mock.js +++ b/test/mock/user-mock.js @@ -1,49 +1,48 @@ var mocks = { - getMockedUser: getMockedUser + getMockedUser: getMockedUser }; module.exports = mocks; function getMockedUser() { - return { - "uuid": "some-user-uuid", - "display": "test", - "username": "test", - "systemId": "4444-4", - "userProperties": { - "loginAttempts": "0" - }, - "person": { - "uuid": "d6a9190c-f47b-406d-a5e4-155081fc4929", - "display": "test user" - }, - "privileges": [ - { - "uuid": "d05118c6-2490-4d78-a41a-390e3596a240", - "display": "Get Forms" - }, - { - "uuid": "d05118c6-2490-4d78-a41a-390e3596a241", - "display": "Get Orders" - }, - { - "uuid": "78170500-1359-11df-a1f1-0026b9348838", - "display": "View Patient Cohorts" - } - ], - "roles": [ - { - "uuid": "ad6ea984-583a-43e9-b9ed-86d74b5658ff", - "display": "POCProvider" - }, - { - "uuid": "78d7696c-1359-11df-a1f1-0026b9348838", - "display": "Data Assistant" - } - ], - "retired": false, - "links": [], - "resourceVersion": "1.8" - }; + return { + uuid: 'some-user-uuid', + display: 'test', + username: 'test', + systemId: '4444-4', + userProperties: { + loginAttempts: '0' + }, + person: { + uuid: 'd6a9190c-f47b-406d-a5e4-155081fc4929', + display: 'test user' + }, + privileges: [ + { + uuid: 'd05118c6-2490-4d78-a41a-390e3596a240', + display: 'Get Forms' + }, + { + uuid: 'd05118c6-2490-4d78-a41a-390e3596a241', + display: 'Get Orders' + }, + { + uuid: '78170500-1359-11df-a1f1-0026b9348838', + display: 'View Patient Cohorts' + } + ], + roles: [ + { + uuid: 'ad6ea984-583a-43e9-b9ed-86d74b5658ff', + display: 'POCProvider' + }, + { + uuid: '78d7696c-1359-11df-a1f1-0026b9348838', + display: 'Data Assistant' + } + ], + retired: false, + links: [], + resourceVersion: '1.8' + }; } - diff --git a/test/programs/patient-data-resolver.service.test.js b/test/programs/patient-data-resolver.service.test.js index 79610ed85..055b418ef 100755 --- a/test/programs/patient-data-resolver.service.test.js +++ b/test/programs/patient-data-resolver.service.test.js @@ -21,144 +21,144 @@ var baseUrl = 'http://localhost:8002'; chai.use(sinonChai); describe('PROGRAM DATA RESOLVER SERVICE:', function () { - - beforeEach(function (done) { + beforeEach(function (done) { + done(); + }); + + afterEach(function () {}); + + it('should load program data resolver service', function () { + expect(dataResolver).to.be.defined; + expect(patientService).to.be.defined; + }); + + it('should use the patient service correctly to fetch a patient', function (done) { + var patientUuid = 'some uuid'; + var stub = sinon + .stub(patientService, 'getPatientByUuid') + .returns(function (patientUuid, params) { + expect(patientUuid).to.equal(patientUuid); + expect(params).to.deep.equal({ + rep: 'full' + }); //fetch default patient object + var promise = new Promise(function (resolve, reject) { + resolve({ + uuid: 'some uuid' + }); + }); + return promise; + }); + + dataResolver + .getPatient(patientUuid) + .then(function (data) { + expect(data).to.deep.equal({ + uuid: 'some uuid' + }); done(); - }); - - afterEach(function () {}); - - it('should load program data resolver service', - function () { - expect(dataResolver).to.be.defined; - expect(patientService).to.be.defined; + stub.restore(); + }) + .catch(function (error) { + stub.restore(); + expect(true).to.be.false; + done(); + }); + done(); + }); + + it('should use the program service correctly to fetch an enrollment', function (done) { + var enrollmentUuid = 'some uuid'; + var patientUuid = 'some patient uuid'; + var param = { + programEnrollmentUuid: enrollmentUuid + }; + + var stub = sinon + .stub(programService, 'getProgramEnrollmentByUuid') + .returns(function (uuid, params) { + expect(enrollmentUuid).to.equal(uuid); + expect(params).to.deep.equal({ + rep: + 'custom:(uuid,display,voided,dateEnrolled,dateCompleted,location,' + + 'program:(uuid),states:(uuid,startDate,endDate,state:(uuid,initial,terminal,' + + 'concept:(uuid,display))))' + }); //fetch default patient object + var promise = new Promise(function (resolve, reject) { + resolve({ + uuid: 'some uuid' + }); }); - - it('should use the patient service correctly to fetch a patient', - function (done) { - var patientUuid = 'some uuid'; - var stub = sinon.stub(patientService, 'getPatientByUuid').returns( - function (patientUuid, params) { - expect(patientUuid).to.equal(patientUuid); - expect(params).to.deep.equal({ - rep: 'full' - }); //fetch default patient object - var promise = - new Promise(function (resolve, reject) { - resolve({ - uuid: 'some uuid' - }); - }); - return promise; - }); - - dataResolver.getPatient(patientUuid) - .then(function (data) { - expect(data).to.deep.equal({ - uuid: 'some uuid' - }); - done(); - stub.restore(); - }) - .catch(function (error) { - stub.restore(); - expect(true).to.be.false; - done(); - }); - done(); + return promise; + }); + + dataResolver + .getProgramEnrollment(patientUuid, param) + .then(function (data) { + expect(data).to.deep.equal({ + uuid: 'some uuid' }); - - it('should use the program service correctly to fetch an enrollment', - function (done) { - var enrollmentUuid = 'some uuid'; - var patientUuid = 'some patient uuid'; - var param = { - programEnrollmentUuid: enrollmentUuid - }; - - var stub = sinon.stub(programService, 'getProgramEnrollmentByUuid').returns( - function (uuid, params) { - expect(enrollmentUuid).to.equal(uuid); - expect(params).to.deep.equal({ - rep: 'custom:(uuid,display,voided,dateEnrolled,dateCompleted,location,' + - 'program:(uuid),states:(uuid,startDate,endDate,state:(uuid,initial,terminal,' + - 'concept:(uuid,display))))' - }); //fetch default patient object - var promise = - new Promise(function (resolve, reject) { - resolve({ - uuid: 'some uuid' - }); - }); - return promise; - }); - - dataResolver.getProgramEnrollment(patientUuid, param) - .then(function (data) { - expect(data).to.deep.equal({ - uuid: 'some uuid' - }); - done(); - stub.restore(); - }) - .catch(function (error) { - stub.restore(); - expect(true).to.be.false; - done(); - }); - done(); + done(); + stub.restore(); + }) + .catch(function (error) { + stub.restore(); + expect(true).to.be.false; + done(); + }); + done(); + }); + + it('should fetch all the required patient data dependencies', function (done) { + var samplePatient = { + uuid: 'patient-uuid', + person: { + age: 10 + } + }; + + var sampleEnrollment = { + uuid: 'enrollment uuid' + }; + var patientUuid = 'some uuid'; + var keys = ['patient', 'dummyPatient', 'enrollment']; + var stub = sinon + .stub(patientService, 'getPatientByUuid') + .returns(function (patientUuid, params) { + return new Promise(function (success, error) { + success(samplePatient); }); + }); - it('should fetch all the required patient data dependencies', - function (done) { - var samplePatient = { - uuid: 'patient-uuid', - person: { - age: 10 - } - }; - - var sampleEnrollment = { - uuid: 'enrollment uuid' - }; - var patientUuid = 'some uuid'; - var keys = ['patient', 'dummyPatient', 'enrollment'] - var stub = sinon.stub(patientService, 'getPatientByUuid').returns( - function (patientUuid, params) { - return new Promise(function (success, error) { - success(samplePatient); - }) - }); - - var enrollmentStub = sinon.stub(programService, 'getProgramEnrollmentByUuid').returns( - function (patientUuid, params) { - return new Promise(function (success, error) { - success(sampleEnrollment); - }) - }); - - var params = { - programEnrollmentUuid: 'enrollment uuid' - }; - - dataResolver.getAllDataDependencies(keys, patientUuid, params) - .then(function (dataObject) { - expect(dataObject).to.deep.equal({ - 'patient': samplePatient, - 'dummyPatient': samplePatient, - 'enrollment': sampleEnrollment - }); - done(); - stub.restore(); - enrollmentStub.restore(); - }) - .catch(function (error) { - console.error('error:', error); - expect('not expecting an error using test case').to.be.true; - stub.restore(); - enrollmentStub.restore(); - }); - done(); + var enrollmentStub = sinon + .stub(programService, 'getProgramEnrollmentByUuid') + .returns(function (patientUuid, params) { + return new Promise(function (success, error) { + success(sampleEnrollment); }); - -}); \ No newline at end of file + }); + + var params = { + programEnrollmentUuid: 'enrollment uuid' + }; + + dataResolver + .getAllDataDependencies(keys, patientUuid, params) + .then(function (dataObject) { + expect(dataObject).to.deep.equal({ + patient: samplePatient, + dummyPatient: samplePatient, + enrollment: sampleEnrollment + }); + done(); + stub.restore(); + enrollmentStub.restore(); + }) + .catch(function (error) { + console.error('error:', error); + expect('not expecting an error using test case').to.be.true; + stub.restore(); + enrollmentStub.restore(); + }); + done(); + }); +}); diff --git a/test/programs/program-visit-types.service.test.js b/test/programs/program-visit-types.service.test.js index dc506b2c1..c596ebb97 100755 --- a/test/programs/program-visit-types.service.test.js +++ b/test/programs/program-visit-types.service.test.js @@ -19,188 +19,183 @@ var baseUrl = 'http://localhost:8002'; chai.use(sinonChai); describe('PROGRAM VISITTYPES SERVICE:', function () { - - beforeEach(function (done) { - done(); - }); - - afterEach(function () { - }); - - it('should load program visit types service', - function () { - expect(pVisitTypes).to.be.defined; - }); - - - it('should determine whether a visit type is allowed for a given patient', - function () { - var scope = { - enrollmentLocationUuid: 'some location uuid', - intendedLocationOfVisitUuid: 'some location uuid' - }; - - var visitType = { - uuid: 'some uuid', - name: 'some visit', - encounterTypes: [], - allowedIf: 'enrollmentLocationUuid === intendedLocationOfVisitUuid' - }; - var allowed = pVisitTypes.isVisitTypeAllowed(scope, visitType); - expect(allowed).to.be.true; - }); - - it('should seperate allowed visit and disallowed visit types' + - ' for a given patient within a program ', - function () { - var scope = { - enrollmentLocationUuid: 'some location uuid', - intendedLocationOfVisitUuid: 'some location uuid' - }; - - var programsConfig = { - visitTypes: [ - { - uuid: 'some uuid', - name: 'some visit', - encounterTypes: [], - allowedIf: 'enrollmentLocationUuid === intendedLocationOfVisitUuid' - }, - { - uuid: 'some uuid 2', - name: 'some visit 2', - encounterTypes: [], - allowedIf: 'enrollmentLocationUuid !== intendedLocationOfVisitUuid' - } - ] - }; - - var expected = { - allowed: [ - programsConfig.visitTypes[0] - ], - disallowed: [ - programsConfig.visitTypes[1] - ] - }; - - var actual = pVisitTypes. - separateAllowedDisallowedVisitTypes(scope, programsConfig.visitTypes); - - expect(actual).to.deep.equal(expected); - }); - - it('should fetch the visit types for a given patient, program, and intended visit location', - function (done) { - - // stub the data service and check it integrates well - - var patientUuid = 'some uuid'; - var programUuid = 'some program uuid'; - var programEnrollmentUuid = 'some program enrollment uuid'; - var intendedLocationUuid = 'some location uuid'; - - var programConfig = { - 'some program uuid': { - name: 'test program', - dataDependencies: ['patient'], - visitTypes: [ - { - 'uuid': 'visit one uuid', - 'name': 'Visit One', - 'encounterTypes': [] // one without rules - }, - { - 'uuid': 'visit two uuid', - 'name': 'Visit Two', - 'encounterTypes': [], // one with rule - 'allowedIf': 'age > 10', - 'ruleExplanation': 'should be of age greater than 10' - }, - { - 'uuid': 'visit three uuid', - 'name': 'Visit Three', - 'encounterTypes': [], // one with rule - 'allowedIf': 'age < 10', - 'ruleExplanation': 'should be of age less than 10' - } - ] - }, - 'some other program config': { - name: 'test program' - } + beforeEach(function (done) { + done(); + }); + + afterEach(function () {}); + + it('should load program visit types service', function () { + expect(pVisitTypes).to.be.defined; + }); + + it('should determine whether a visit type is allowed for a given patient', function () { + var scope = { + enrollmentLocationUuid: 'some location uuid', + intendedLocationOfVisitUuid: 'some location uuid' + }; + + var visitType = { + uuid: 'some uuid', + name: 'some visit', + encounterTypes: [], + allowedIf: 'enrollmentLocationUuid === intendedLocationOfVisitUuid' + }; + var allowed = pVisitTypes.isVisitTypeAllowed(scope, visitType); + expect(allowed).to.be.true; + }); + + it( + 'should seperate allowed visit and disallowed visit types' + + ' for a given patient within a program ', + function () { + var scope = { + enrollmentLocationUuid: 'some location uuid', + intendedLocationOfVisitUuid: 'some location uuid' + }; + + var programsConfig = { + visitTypes: [ + { + uuid: 'some uuid', + name: 'some visit', + encounterTypes: [], + allowedIf: 'enrollmentLocationUuid === intendedLocationOfVisitUuid' + }, + { + uuid: 'some uuid 2', + name: 'some visit 2', + encounterTypes: [], + allowedIf: 'enrollmentLocationUuid !== intendedLocationOfVisitUuid' + } + ] + }; + + var expected = { + allowed: [programsConfig.visitTypes[0]], + disallowed: [programsConfig.visitTypes[1]] + }; + + var actual = pVisitTypes.separateAllowedDisallowedVisitTypes( + scope, + programsConfig.visitTypes + ); + + expect(actual).to.deep.equal(expected); + } + ); + + it('should fetch the visit types for a given patient, program, and intended visit location', function (done) { + // stub the data service and check it integrates well + + var patientUuid = 'some uuid'; + var programUuid = 'some program uuid'; + var programEnrollmentUuid = 'some program enrollment uuid'; + var intendedLocationUuid = 'some location uuid'; + + var programConfig = { + 'some program uuid': { + name: 'test program', + dataDependencies: ['patient'], + visitTypes: [ + { + uuid: 'visit one uuid', + name: 'Visit One', + encounterTypes: [] // one without rules + }, + { + uuid: 'visit two uuid', + name: 'Visit Two', + encounterTypes: [], // one with rule + allowedIf: 'age > 10', + ruleExplanation: 'should be of age greater than 10' + }, + { + uuid: 'visit three uuid', + name: 'Visit Three', + encounterTypes: [], // one with rule + allowedIf: 'age < 10', + ruleExplanation: 'should be of age less than 10' + } + ] + }, + 'some other program config': { + name: 'test program' + } + }; + + // data resolver stub + var dataResolverStub = sinon + .stub(dataResolver, 'getAllDataDependencies') + .returns(function (keys, patientUuid, params) { + expect(keys).to.deep.equal(['patient']); + expect(patientUuid).to.equal(patientUuid); + expect(params).to.deep.equal({ + programUuid: programUuid, + programEnrollmentUuid: programEnrollmentUuid, + intendedVisitLocationUuid: intendedLocationUuid + }); // fetch default patient object + var promise = new Promise(function (resolve, reject) { + resolve({ + patient: { + uuid: 'some uuid', + person: { + age: 20 + } } - - // data resolver stub - var dataResolverStub = sinon.stub(dataResolver, 'getAllDataDependencies').returns( - function (keys, patientUuid, params) { - expect(keys).to.deep.equal(['patient']); - expect(patientUuid).to.equal(patientUuid); - expect(params).to.deep.equal({ - programUuid: programUuid, - programEnrollmentUuid: programEnrollmentUuid, - intendedVisitLocationUuid: intendedLocationUuid - }); // fetch default patient object - var promise = - new Promise(function (resolve, reject) { - resolve( - { - 'patient': { - uuid: 'some uuid', - person: { - age: 20 - } - } - } - ); - }); - return promise; - }); - - var expectedProgram = { - name: 'test program', - dataDependencies: ['patient'], - visitTypes: { - allowed: - [ - { - 'uuid': 'visit one uuid', - 'name': 'Visit One', - 'encounterTypes': [] // one without rules - }, - { - 'uuid': 'visit two uuid', - 'name': 'Visit Two', - 'encounterTypes': [], // one with rule - 'allowedIf': 'age > 10', - 'ruleExplanation': 'should be of age greater than 10' - } - ], - disallowed: [ - { - 'uuid': 'visit three uuid', - 'name': 'Visit Three', - 'encounterTypes': [], // one with rule but not allowed - 'allowedIf': 'age < 10', - 'ruleExplanation': 'should be of age less than 10' - } - ] - } - }; - - pVisitTypes.getPatientVisitTypes(patientUuid, programUuid, programEnrollmentUuid, - intendedLocationUuid, programConfig) - .then(function (configs) { - expect(configs).to.deep.equal(expectedProgram); - done(); - dataResolverStub.restore(); - }) - .catch(function (err) { - console.error('error:', err); - expect(true).to.be.false; - done(); - }); - done(); + }); }); - -}); \ No newline at end of file + return promise; + }); + + var expectedProgram = { + name: 'test program', + dataDependencies: ['patient'], + visitTypes: { + allowed: [ + { + uuid: 'visit one uuid', + name: 'Visit One', + encounterTypes: [] // one without rules + }, + { + uuid: 'visit two uuid', + name: 'Visit Two', + encounterTypes: [], // one with rule + allowedIf: 'age > 10', + ruleExplanation: 'should be of age greater than 10' + } + ], + disallowed: [ + { + uuid: 'visit three uuid', + name: 'Visit Three', + encounterTypes: [], // one with rule but not allowed + allowedIf: 'age < 10', + ruleExplanation: 'should be of age less than 10' + } + ] + } + }; + + pVisitTypes + .getPatientVisitTypes( + patientUuid, + programUuid, + programEnrollmentUuid, + intendedLocationUuid, + programConfig + ) + .then(function (configs) { + expect(configs).to.deep.equal(expectedProgram); + done(); + dataResolverStub.restore(); + }) + .catch(function (err) { + console.error('error:', err); + expect(true).to.be.false; + done(); + }); + done(); + }); +}); diff --git a/test/programs/scope-builder.service.test.js b/test/programs/scope-builder.service.test.js index 9371bb815..3547a891c 100755 --- a/test/programs/scope-builder.service.test.js +++ b/test/programs/scope-builder.service.test.js @@ -18,52 +18,45 @@ var baseUrl = 'http://localhost:8002'; chai.use(sinonChai); describe('SCOPE BUILDER SERVICE:', function () { - - beforeEach(function (done) { - done(); - }); - - afterEach(function () { - }); - - it('should load scope builder service', - function () { - expect(scopeBuilder).to.be.defined; - }); - - it('should build a scope object', - function () { - - var dataDictionary = { - 'patient' : { - 'person' : { - age: 20, - gender: 'F' - } - }, - 'intendedVisitLocationUuid' : 'location-uuid', - 'enrollment': { - 'uuid': 'some uuid', - 'program': { - 'uuid':'some program' - }, - 'location': { - 'uuid': 'some location uuid' - } - } - }; - - var expectedScopeObject = { - age: 20, - gender: 'F', - intendedVisitLocationUuid: 'location-uuid', - programLocation: 'some location uuid' - }; - - var actualScope = scopeBuilder.buildScope(dataDictionary); - - expect(expectedScopeObject).to.deep.equal(actualScope); - - }); - -}); \ No newline at end of file + beforeEach(function (done) { + done(); + }); + + afterEach(function () {}); + + it('should load scope builder service', function () { + expect(scopeBuilder).to.be.defined; + }); + + it('should build a scope object', function () { + var dataDictionary = { + patient: { + person: { + age: 20, + gender: 'F' + } + }, + intendedVisitLocationUuid: 'location-uuid', + enrollment: { + uuid: 'some uuid', + program: { + uuid: 'some program' + }, + location: { + uuid: 'some location uuid' + } + } + }; + + var expectedScopeObject = { + age: 20, + gender: 'F', + intendedVisitLocationUuid: 'location-uuid', + programLocation: 'some location uuid' + }; + + var actualScope = scopeBuilder.buildScope(dataDictionary); + + expect(expectedScopeObject).to.deep.equal(actualScope); + }); +}); diff --git a/test/report-post-processors/patient-flow-processor.js b/test/report-post-processors/patient-flow-processor.js index 8e324f8b1..f0aa5bc29 100755 --- a/test/report-post-processors/patient-flow-processor.js +++ b/test/report-post-processors/patient-flow-processor.js @@ -19,268 +19,264 @@ var baseUrl = 'http://localhost:8002'; chai.use(sinonChai); describe('PATIENT FLOW PROCESSOR TESTS', function () { - - beforeEach(function (done) { - done(); - }); - - afterEach(function () { - }); - - it('should inject patient flow samples', - function () { - expect(patientFlowSamples).to.be.defined; - }); - - it('should inject patient flow module', - function () { - expect(patientFlowProcessor).to.be.defined; - }); - - it('should group results by visit id when groupResultsByVisitId', - function () { - var unGroupedResults = patientFlowSamples.getPatientFlowSample(); - var groupedResults = patientFlowProcessor.groupResultsByVisitId(unGroupedResults.result); - - //examine results - //CHECK 1: the sample contians only three visits - expect(groupedResults.length).to.equal(3); - - //CHECK 2: should still be ordered - expect(groupedResults[0].visit_id).to.equal(26727); - expect(groupedResults[2].visit_id).to.equal(26731); - - //CHECK 3: sets time visit started correctly - expect(groupedResults[0].registered).to.equal("2016-06-15T04:47:21.000Z"); - expect(groupedResults[2].registered).to.equal("2016-06-15T04:49:26.000Z"); - - //CHECK 4: sets triage time correctly //use encounter_id 110 for triage - expect(groupedResults[0].triaged).to.equal("2016-06-15T05:16:34.000Z"); - expect(groupedResults[2].triaged).to.equal("2016-06-15T05:16:34.000Z"); - - //CHECK 5: sets waiting time to triage correctly - expect(groupedResults[0].time_to_be_triaged).to.equal(29); - expect(groupedResults[2].time_to_be_triaged).to.equal(30); - - //CHECK 6: sets time to be seen by a clinician correctly - //i.e the encounter date time for the first clinical encounter - expect(groupedResults[0].seen_by_clinician).to.equal("2016-06-15T05:35:44.000Z"); - expect(groupedResults[1].seen_by_clinician).to.equal("2016-06-15T05:40:51.000Z"); - expect(groupedResults[2].seen_by_clinician).to.equal(null); - - //CHECK 7: groups encounters correctly in order they arrived - expect(groupedResults[1].encounters.length).to.equal(3); - expect(groupedResults[1].encounters[0].encounter_type).to.equal(110); - expect(groupedResults[1].encounters[1].encounter_type).to.equal(2); - expect(groupedResults[1].encounters[2].encounter_type).to.equal(3); - - //CHECK 8: sets visit end time correctly - //this is usually the last encounter creation date - expect(groupedResults[0].completed_visit).to.equal("2016-06-15T05:44:25.000Z"); - expect(groupedResults[1].completed_visit).to.equal("2016-06-15T05:56:59.000Z"); - expect(groupedResults[2].completed_visit).to.equal("2016-06-15T05:48:14.000Z"); - - //CHECK 9: calculates time_to_be_seen_by_clinician - expect(groupedResults[0].time_to_be_seen_by_clinician !== undefined).to.be.true; - - //CHECK 10: calculates time_to_complete_visit - expect(groupedResults[0].time_to_complete_visit !== undefined).to.be.true; - }); - - it('should calculate time span in minutes when _getTimeSpanInMinutes', - function () { - - var difference = - patientFlowProcessor._getTimeSpanInMinutes("2016-06-15T05:16:34.000Z", "2016-06-15T05:46:30.000Z"); - expect(difference).to.equal(30); - }); - - it('should calculate time to be seen by clinician correctly when _handleTimeToBeSeenByClinician', - function () { - //CASE 1: triage exisits - var visitWithTriage = { - registered: "2016-06-15T05:10:34.000Z", - triaged: "2016-06-15T05:16:34.000Z", - seen_by_clinician: "2016-06-15T05:46:34.000Z" - }; - - patientFlowProcessor._handleTimeToBeSeenByClinician(visitWithTriage); - - expect(visitWithTriage.time_to_be_seen_by_clinician).to.equal(30); - - //CASE 2: triage doesn't exist - var visitWithoutTriage = { - registered: "2016-06-15T05:16:34.000Z", - seen_by_clinician: "2016-06-15T05:56:34.000Z" - }; - - patientFlowProcessor._handleTimeToBeSeenByClinician(visitWithoutTriage); - - expect(visitWithoutTriage.time_to_be_seen_by_clinician).to.equal(40); - }); - - it('should calculate time to complete visit correctly when _handleTimeToBeSeenByClinician', - function () { - - //case both values present - var visit = { - registered: "2016-06-15T05:10:30.000Z", - seen_by_clinician: "2016-06-15T05:56:34.000Z", - completed_visit: "2016-06-15T05:56:34.000Z" - }; - - patientFlowProcessor._handleTimeToCompleteVisit(visit); - - expect(visit.time_to_complete_visit).to.equal(46); - - //case values absent - var emptyVisit = {}; - patientFlowProcessor._handleTimeToCompleteVisit(emptyVisit); - - expect(emptyVisit.time_to_complete_visit).to.equal(null); - - }); - - - it('should calculate average waiting time when _calculateAverageWaitingTime', - function () { - - var arrayOfPatientFlowData = [ - { - time_to_be_seen_by_clinician: 5, - time_to_be_triaged: 5, - time_to_complete_visit: 3 - }, - { - time_to_be_seen_by_clinician: 10, - time_to_be_triaged: 10, - time_to_complete_visit: 84 - }, - { - time_to_be_seen_by_clinician: 15, - time_to_be_triaged: 16, - time_to_complete_visit: null - }, - { - time_to_be_seen_by_clinician: null, - time_to_be_triaged: null, - time_to_complete_visit: 8 - }, - { - time_to_be_seen_by_clinician: 5, - time_to_be_triaged: 5, - time_to_complete_visit: 4 - }, - { - time_to_be_seen_by_clinician: null, - time_to_be_triaged: null, - time_to_complete_visit: null - } - ]; - - //average triage waiting time = 36/4 = 9.00 - - //average clinician waiting time = 35/4 = 8.75 - - //average waitingTime = (9.00 + 8.75)/2 = 8.88 - - //average visit completion time = 99/4 = 24.75 - - //incomplete visits is where there's no clinical encounter - - var expectedAverageTimeObject = { - averageWaitingTime: '8.9', - averageVisitCompletionTime: '24.8', - averageTriageWaitingTime: '9.0', - averageClinicianWaitingTime: '8.8' - }; - - - var actualAverageTimeObject = - patientFlowProcessor.calculateAverageWaitingTime(arrayOfPatientFlowData); - //console.log(actualAverageWaitingTimeObject); - - expect(expectedAverageTimeObject).to.deep.equal(actualAverageTimeObject); - - }); - - it('should get incomplete visits count when _getIncompleteVisitsCount', - function () { - var arrayOfPatientFlowData = [ - { - seen_by_clinician: "2016-06-15T05:56:34.000Z" - }, - { - seen_by_clinician: "2016-06-15T05:56:34.000Z" - }, - { - seen_by_clinician: "2016-06-15T05:56:34.000Z" - }, - { - seen_by_clinician: null - }, - { - seen_by_clinician: "2016-06-15T05:56:34.000Z" - }, - { - seen_by_clinician: null - } - ]; - - expect(patientFlowProcessor.getIncompleteVisitsCount(arrayOfPatientFlowData)).to.equal(2); - - }); - - it('should calculate median waiting time when _calculateAverageWaitingTime', - function () { - - var arrayOfPatientFlowData = [ - { - time_to_be_seen_by_clinician: 5, - time_to_be_triaged: 5, - time_to_complete_visit: 3 - }, - { - time_to_be_seen_by_clinician: 10, - time_to_be_triaged: 10, - time_to_complete_visit: 84 - }, - { - time_to_be_seen_by_clinician: 15, - time_to_be_triaged: 16, - time_to_complete_visit: null - }, - { - time_to_be_seen_by_clinician: null, - time_to_be_triaged: null, - time_to_complete_visit: 8 - }, - { - time_to_be_seen_by_clinician: 5, - time_to_be_triaged: 5, - time_to_complete_visit: 4 - }, - { - time_to_be_seen_by_clinician: null, - time_to_be_triaged: null, - time_to_complete_visit: null - } - ]; - - var expectedMedianTimeObject = { - medianWaitingTime: '7.5', // 5,5,5,5,10,10,15,16 - medianVisitCompletionTime: '6.0', // 3,4,8,84 - medianTriageWaitingTime: '7.5',//5,5,10,16 - medianClinicianWaitingTime: '7.5'//5,5,10,15 - }; - - - var actualAverageTimeObject = - patientFlowProcessor.calculateMedianWaitingTime(arrayOfPatientFlowData); - //console.log(actualAverageWaitingTimeObject); - - expect(expectedMedianTimeObject).to.deep.equal(actualAverageTimeObject); - - }); - -}); \ No newline at end of file + beforeEach(function (done) { + done(); + }); + + afterEach(function () {}); + + it('should inject patient flow samples', function () { + expect(patientFlowSamples).to.be.defined; + }); + + it('should inject patient flow module', function () { + expect(patientFlowProcessor).to.be.defined; + }); + + it('should group results by visit id when groupResultsByVisitId', function () { + var unGroupedResults = patientFlowSamples.getPatientFlowSample(); + var groupedResults = patientFlowProcessor.groupResultsByVisitId( + unGroupedResults.result + ); + + //examine results + //CHECK 1: the sample contians only three visits + expect(groupedResults.length).to.equal(3); + + //CHECK 2: should still be ordered + expect(groupedResults[0].visit_id).to.equal(26727); + expect(groupedResults[2].visit_id).to.equal(26731); + + //CHECK 3: sets time visit started correctly + expect(groupedResults[0].registered).to.equal('2016-06-15T04:47:21.000Z'); + expect(groupedResults[2].registered).to.equal('2016-06-15T04:49:26.000Z'); + + //CHECK 4: sets triage time correctly //use encounter_id 110 for triage + expect(groupedResults[0].triaged).to.equal('2016-06-15T05:16:34.000Z'); + expect(groupedResults[2].triaged).to.equal('2016-06-15T05:16:34.000Z'); + + //CHECK 5: sets waiting time to triage correctly + expect(groupedResults[0].time_to_be_triaged).to.equal(29); + expect(groupedResults[2].time_to_be_triaged).to.equal(30); + + //CHECK 6: sets time to be seen by a clinician correctly + //i.e the encounter date time for the first clinical encounter + expect(groupedResults[0].seen_by_clinician).to.equal( + '2016-06-15T05:35:44.000Z' + ); + expect(groupedResults[1].seen_by_clinician).to.equal( + '2016-06-15T05:40:51.000Z' + ); + expect(groupedResults[2].seen_by_clinician).to.equal(null); + + //CHECK 7: groups encounters correctly in order they arrived + expect(groupedResults[1].encounters.length).to.equal(3); + expect(groupedResults[1].encounters[0].encounter_type).to.equal(110); + expect(groupedResults[1].encounters[1].encounter_type).to.equal(2); + expect(groupedResults[1].encounters[2].encounter_type).to.equal(3); + + //CHECK 8: sets visit end time correctly + //this is usually the last encounter creation date + expect(groupedResults[0].completed_visit).to.equal( + '2016-06-15T05:44:25.000Z' + ); + expect(groupedResults[1].completed_visit).to.equal( + '2016-06-15T05:56:59.000Z' + ); + expect(groupedResults[2].completed_visit).to.equal( + '2016-06-15T05:48:14.000Z' + ); + + //CHECK 9: calculates time_to_be_seen_by_clinician + expect(groupedResults[0].time_to_be_seen_by_clinician !== undefined).to.be + .true; + + //CHECK 10: calculates time_to_complete_visit + expect(groupedResults[0].time_to_complete_visit !== undefined).to.be.true; + }); + + it('should calculate time span in minutes when _getTimeSpanInMinutes', function () { + var difference = patientFlowProcessor._getTimeSpanInMinutes( + '2016-06-15T05:16:34.000Z', + '2016-06-15T05:46:30.000Z' + ); + expect(difference).to.equal(30); + }); + + it('should calculate time to be seen by clinician correctly when _handleTimeToBeSeenByClinician', function () { + //CASE 1: triage exisits + var visitWithTriage = { + registered: '2016-06-15T05:10:34.000Z', + triaged: '2016-06-15T05:16:34.000Z', + seen_by_clinician: '2016-06-15T05:46:34.000Z' + }; + + patientFlowProcessor._handleTimeToBeSeenByClinician(visitWithTriage); + + expect(visitWithTriage.time_to_be_seen_by_clinician).to.equal(30); + + //CASE 2: triage doesn't exist + var visitWithoutTriage = { + registered: '2016-06-15T05:16:34.000Z', + seen_by_clinician: '2016-06-15T05:56:34.000Z' + }; + + patientFlowProcessor._handleTimeToBeSeenByClinician(visitWithoutTriage); + + expect(visitWithoutTriage.time_to_be_seen_by_clinician).to.equal(40); + }); + + it('should calculate time to complete visit correctly when _handleTimeToBeSeenByClinician', function () { + //case both values present + var visit = { + registered: '2016-06-15T05:10:30.000Z', + seen_by_clinician: '2016-06-15T05:56:34.000Z', + completed_visit: '2016-06-15T05:56:34.000Z' + }; + + patientFlowProcessor._handleTimeToCompleteVisit(visit); + + expect(visit.time_to_complete_visit).to.equal(46); + + //case values absent + var emptyVisit = {}; + patientFlowProcessor._handleTimeToCompleteVisit(emptyVisit); + + expect(emptyVisit.time_to_complete_visit).to.equal(null); + }); + + it('should calculate average waiting time when _calculateAverageWaitingTime', function () { + var arrayOfPatientFlowData = [ + { + time_to_be_seen_by_clinician: 5, + time_to_be_triaged: 5, + time_to_complete_visit: 3 + }, + { + time_to_be_seen_by_clinician: 10, + time_to_be_triaged: 10, + time_to_complete_visit: 84 + }, + { + time_to_be_seen_by_clinician: 15, + time_to_be_triaged: 16, + time_to_complete_visit: null + }, + { + time_to_be_seen_by_clinician: null, + time_to_be_triaged: null, + time_to_complete_visit: 8 + }, + { + time_to_be_seen_by_clinician: 5, + time_to_be_triaged: 5, + time_to_complete_visit: 4 + }, + { + time_to_be_seen_by_clinician: null, + time_to_be_triaged: null, + time_to_complete_visit: null + } + ]; + + //average triage waiting time = 36/4 = 9.00 + + //average clinician waiting time = 35/4 = 8.75 + + //average waitingTime = (9.00 + 8.75)/2 = 8.88 + + //average visit completion time = 99/4 = 24.75 + + //incomplete visits is where there's no clinical encounter + + var expectedAverageTimeObject = { + averageWaitingTime: '8.9', + averageVisitCompletionTime: '24.8', + averageTriageWaitingTime: '9.0', + averageClinicianWaitingTime: '8.8' + }; + + var actualAverageTimeObject = patientFlowProcessor.calculateAverageWaitingTime( + arrayOfPatientFlowData + ); + //console.log(actualAverageWaitingTimeObject); + + expect(expectedAverageTimeObject).to.deep.equal(actualAverageTimeObject); + }); + + it('should get incomplete visits count when _getIncompleteVisitsCount', function () { + var arrayOfPatientFlowData = [ + { + seen_by_clinician: '2016-06-15T05:56:34.000Z' + }, + { + seen_by_clinician: '2016-06-15T05:56:34.000Z' + }, + { + seen_by_clinician: '2016-06-15T05:56:34.000Z' + }, + { + seen_by_clinician: null + }, + { + seen_by_clinician: '2016-06-15T05:56:34.000Z' + }, + { + seen_by_clinician: null + } + ]; + + expect( + patientFlowProcessor.getIncompleteVisitsCount(arrayOfPatientFlowData) + ).to.equal(2); + }); + + it('should calculate median waiting time when _calculateAverageWaitingTime', function () { + var arrayOfPatientFlowData = [ + { + time_to_be_seen_by_clinician: 5, + time_to_be_triaged: 5, + time_to_complete_visit: 3 + }, + { + time_to_be_seen_by_clinician: 10, + time_to_be_triaged: 10, + time_to_complete_visit: 84 + }, + { + time_to_be_seen_by_clinician: 15, + time_to_be_triaged: 16, + time_to_complete_visit: null + }, + { + time_to_be_seen_by_clinician: null, + time_to_be_triaged: null, + time_to_complete_visit: 8 + }, + { + time_to_be_seen_by_clinician: 5, + time_to_be_triaged: 5, + time_to_complete_visit: 4 + }, + { + time_to_be_seen_by_clinician: null, + time_to_be_triaged: null, + time_to_complete_visit: null + } + ]; + + var expectedMedianTimeObject = { + medianWaitingTime: '7.5', // 5,5,5,5,10,10,15,16 + medianVisitCompletionTime: '6.0', // 3,4,8,84 + medianTriageWaitingTime: '7.5', //5,5,10,16 + medianClinicianWaitingTime: '7.5' //5,5,10,15 + }; + + var actualAverageTimeObject = patientFlowProcessor.calculateMedianWaitingTime( + arrayOfPatientFlowData + ); + //console.log(actualAverageWaitingTimeObject); + + expect(expectedMedianTimeObject).to.deep.equal(actualAverageTimeObject); + }); +}); diff --git a/test/reporting-framework/base-mysql.report.test.js b/test/reporting-framework/base-mysql.report.test.js index 95eb3ac1b..dce4773b8 100755 --- a/test/reporting-framework/base-mysql.report.test.js +++ b/test/reporting-framework/base-mysql.report.test.js @@ -26,34 +26,44 @@ describe('BaseMysqlReport:', () => { it('should generate report', (done) => { let reports = { - 'main': {}, - 'report1': {}, - 'report2': {} + main: {}, + report1: {}, + report2: {} }; let reportQuery = 'select * from everything'; let results = { results: [] }; - let fetchReportSchemaStub = sinon.stub(report, 'fetchReportSchema') + let fetchReportSchemaStub = sinon + .stub(report, 'fetchReportSchema') .returns(Promise.resolve(reports)); - let generateReportQueryStub = sinon.stub(report, 'generateReportQuery') + let generateReportQueryStub = sinon + .stub(report, 'generateReportQuery') .returns(Promise.resolve(reportQuery)); - let executeReportQueryStub = sinon.stub(report, 'executeReportQuery') + let executeReportQueryStub = sinon + .stub(report, 'executeReportQuery') .returns(Promise.resolve(results)); report.generateReport().then((generated) => { // fetched reports - expect(fetchReportSchemaStub.calledWithExactly(report.reportName)).to.be.true; + expect(fetchReportSchemaStub.calledWithExactly(report.reportName)).to.be + .true; expect(report.reportSchemas).to.equal(reports); // generated report query - expect(generateReportQueryStub.calledWithExactly(report.reportSchemas, report.params)).to.be.true; + expect( + generateReportQueryStub.calledWithExactly( + report.reportSchemas, + report.params + ) + ).to.be.true; expect(report.reportQuery).to.equal(reportQuery); // execute report query - expect(executeReportQueryStub.calledWithExactly(report.reportQuery)).to.be.true; + expect(executeReportQueryStub.calledWithExactly(report.reportQuery)).to.be + .true; expect(report.queryResults).to.equal(results); expect(generated).to.deep.equal({ @@ -71,14 +81,13 @@ describe('BaseMysqlReport:', () => { generateSQL: () => { return { toString: () => { - return 'select * from everything' + return 'select * from everything'; } - } + }; } }; - let getJson2SqlStub = sinon.stub(report, 'getJson2Sql') - .returns(jSql); + let getJson2SqlStub = sinon.stub(report, 'getJson2Sql').returns(jSql); let schemas = {}; @@ -86,12 +95,11 @@ describe('BaseMysqlReport:', () => { startDate: '2018-01-20' }; - report.generateReportQuery(schemas, params) - .then((sql) => { - expect(getJson2SqlStub.calledWithExactly(schemas, params)).to.be.true; - expect(sql).to.equal('select * from everything'); - done(); - }); + report.generateReportQuery(schemas, params).then((sql) => { + expect(getJson2SqlStub.calledWithExactly(schemas, params)).to.be.true; + expect(sql).to.equal('select * from everything'); + done(); + }); }); it('should execute report query', (done) => { @@ -109,17 +117,14 @@ describe('BaseMysqlReport:', () => { } }; - let getSqlRunnerStub = sinon.stub(report, 'getSqlRunner') - .returns(runner); + let getSqlRunnerStub = sinon.stub(report, 'getSqlRunner').returns(runner); - report.executeReportQuery(sqlParam) - .then((res) => { - expect(getSqlRunnerStub.called).to.be.true; - expect(res).to.deep.equal({ - results: results - }); - done(); + report.executeReportQuery(sqlParam).then((res) => { + expect(getSqlRunnerStub.called).to.be.true; + expect(res).to.deep.equal({ + results: results }); + done(); + }); }); - -}); \ No newline at end of file +}); diff --git a/test/reporting-framework/multi-dataset.report.test.js b/test/reporting-framework/multi-dataset.report.test.js index 084f697d3..02ee1c984 100755 --- a/test/reporting-framework/multi-dataset.report.test.js +++ b/test/reporting-framework/multi-dataset.report.test.js @@ -13,120 +13,131 @@ global.Assertion = chai.Assertion; global.assert = chai.assert; let report; let params = { - startDate: '2018-01-01' + startDate: '2018-01-01' }; describe('MultiDatasetReport:', () => { - beforeEach(() => { - report = new MultiDatasetReport('MOH731', params); + beforeEach(() => { + report = new MultiDatasetReport('MOH731', params); + }); + + it('should be defined', () => { + expect(report).to.exist; + }); + + it('should generate reports', (done) => { + let reports = { + main: { + reports: ['report1', 'report2'] + } + }; + + let additionalParams = {}; + + let results = []; + + let fetchReportSchemaStub = sinon + .stub(report, '_fetchAndInitReports') + .returns(Promise.resolve(reports)); + + let executeReportHandlersStub = sinon + .stub(report, 'executeReportHandlers') + .returns(Promise.resolve(results)); + + report.generateReport(additionalParams).then((generated) => { + // fetched reports + expect(fetchReportSchemaStub.called).to.be.true; + expect( + executeReportHandlersStub.calledWithExactly( + report.reportHandlers, + additionalParams + ) + ).to.be.true; + expect(generated).to.equal(results); + done(); }); - - it('should be defined', () => { - expect(report).to.exist; - }); - - it('should generate reports', (done) => { - let reports = { - 'main': { - reports: ['report1', 'report2'] - } - }; - - let additionalParams = {}; - - let results = []; - - let fetchReportSchemaStub = sinon.stub(report, '_fetchAndInitReports') - .returns(Promise.resolve(reports)); - - let executeReportHandlersStub = sinon.stub(report, 'executeReportHandlers') - .returns(Promise.resolve(results)); - - report.generateReport(additionalParams).then((generated) => { - // fetched reports - expect(fetchReportSchemaStub.called).to.be.true; - expect(executeReportHandlersStub.calledWithExactly(report.reportHandlers, additionalParams)).to.be.true; - expect(generated).to.equal(results); - done(); - }); + }); + + it('should fetch report and init report handlers', (done) => { + let reports = { + main: { + reports: ['report1', 'report2'] + } + }; + + let fetchReportSchemaStub = sinon + .stub(report, 'fetchReportSchema') + .returns(Promise.resolve(reports)); + + report._fetchAndInitReports().then((generated) => { + // fetched reports + expect(fetchReportSchemaStub.calledWithExactly(report.reportName)).to.be + .true; + expect(report.reportSchemas).to.equal(reports); + expect(report.reportHandlers.length).to.equal(2); + expect(report.reportHandlers[0].reportName).to.equal('report1'); + expect(report.reportHandlers[1].reportName).to.equal('report2'); + done(); }); - - it('should fetch report and init report handlers', (done) => { - - let reports = { - 'main': { - reports: ['report1', 'report2'] - } - }; - - let fetchReportSchemaStub = sinon.stub(report, 'fetchReportSchema') - .returns(Promise.resolve(reports)); - - report._fetchAndInitReports().then((generated) => { - // fetched reports - expect(fetchReportSchemaStub.calledWithExactly(report.reportName)).to.be.true; - expect(report.reportSchemas).to.equal(reports); - expect(report.reportHandlers.length).to.equal(2); - expect(report.reportHandlers[0].reportName).to.equal('report1'); - expect(report.reportHandlers[1].reportName).to.equal('report2'); - done(); - }); - - }); - - it('should execute report handlers', (done) => { - let reportHandlers = [ - { - name: 'report1' - }, - { - name: 'report2' - } - ]; - - let sampleResult = { - schemas: null, - sqlQuery: '', - results: [] - }; - - let additionalParams = { - 'type': 'aggregateReport' - }; - - let runSingleReportStub = sinon.stub(report, 'runSingleReport') - .returns(Promise.resolve(sampleResult)); - - report.executeReportHandlers(reportHandlers, additionalParams) - .then((results) => { - expect(runSingleReportStub.getCalls()[0].calledWithExactly(reportHandlers[0], additionalParams)); - expect(results).to.deep.equal( - [ - { - report: reportHandlers[0], - results: sampleResult - }, - { - report: reportHandlers[1], - results: sampleResult - } - ] - ); - done(); - }); - }) - - // it('should fetch all individual reports', () => { - - // let reports = { - // 'main': { - // reports: ['report1', 'report2'] - // } - // }; - - // }); - - // it('should fetch a single report', (done) => { - - // }); -}); \ No newline at end of file + }); + + it('should execute report handlers', (done) => { + let reportHandlers = [ + { + name: 'report1' + }, + { + name: 'report2' + } + ]; + + let sampleResult = { + schemas: null, + sqlQuery: '', + results: [] + }; + + let additionalParams = { + type: 'aggregateReport' + }; + + let runSingleReportStub = sinon + .stub(report, 'runSingleReport') + .returns(Promise.resolve(sampleResult)); + + report + .executeReportHandlers(reportHandlers, additionalParams) + .then((results) => { + expect( + runSingleReportStub + .getCalls()[0] + .calledWithExactly(reportHandlers[0], additionalParams) + ); + expect(results).to.deep.equal([ + { + report: reportHandlers[0], + results: sampleResult + }, + { + report: reportHandlers[1], + results: sampleResult + } + ]); + done(); + }); + }); + + // it('should fetch all individual reports', () => { + + // let reports = { + // 'main': { + // reports: ['report1', 'report2'] + // } + // }; + + // }); + + // it('should fetch a single report', (done) => { + + // }); +}); diff --git a/test/reporting-framework/patientlist-mysql.report.test.js b/test/reporting-framework/patientlist-mysql.report.test.js index 570c4ba44..e3403dd0a 100755 --- a/test/reporting-framework/patientlist-mysql.report.test.js +++ b/test/reporting-framework/patientlist-mysql.report.test.js @@ -26,21 +26,19 @@ describe('PatientlistMysqlReport:', () => { it('should determine the aggregate and the base schemas for an indicator', () => { let schemas = { - 'main': { - - }, - 'aggr1': { + main: {}, + aggr1: { uses: [ { - 'name': 'base3', - 'version': '1.0', - 'type': 'dataset_def' + name: 'base3', + version: '1.0', + type: 'dataset_def' } ], sources: [ { - 'dataset': 'base3', - 'alias': 'b3' + dataset: 'base3', + alias: 'b3' } ], columns: [ @@ -53,18 +51,18 @@ describe('PatientlistMysqlReport:', () => { ], dynamicJsonQueryGenerationDirectives: {} }, - 'aggr2': { + aggr2: { uses: [ { - 'name': 'base4', - 'version': '1.0', - 'type': 'dataset_def' + name: 'base4', + version: '1.0', + type: 'dataset_def' } ], sources: [ { - 'dataset': 'base4', - 'alias': 'b4' + dataset: 'base4', + alias: 'b4' } ], columns: [ @@ -77,7 +75,7 @@ describe('PatientlistMysqlReport:', () => { ], dynamicJsonQueryGenerationDirectives: {} }, - 'base3': { + base3: { sources: [ { table: 'a.t1', @@ -95,7 +93,7 @@ describe('PatientlistMysqlReport:', () => { } ] }, - 'base4': { + base4: { sources: [ { table: 'b.t2', @@ -128,54 +126,45 @@ describe('PatientlistMysqlReport:', () => { expect(withX[0].base).to.equal(schemas.base3); let withNone = report.determineBaseAndAggrSchema(schemas, ['none']); - expect(withNone.length).to.equal(0) - + expect(withNone.length).to.equal(0); }); - it('should fetch patientlist template', (done) => { - let reports = { - 'main': {} + main: {} }; let aggregate = { dynamicJsonQueryGenerationDirectives: { patientListGenerator: { useTemplate: 'patient_list_template', - 'useTemplateVersion': '1.0', + useTemplateVersion: '1.0' } } }; - let fetchReportSchemaStub = sinon.stub(report, 'fetchReportSchema') + let fetchReportSchemaStub = sinon + .stub(report, 'fetchReportSchema') .returns(Promise.resolve(reports)); report.fetchPatientListTemplate(aggregate).then((result) => { // fetched reports - expect(fetchReportSchemaStub.calledWithExactly('patient_list_template', '1.0')).to.be.true; + expect( + fetchReportSchemaStub.calledWithExactly('patient_list_template', '1.0') + ).to.be.true; expect(result).to.equal(reports); done(); }); - }); it('should generate the patientlist json query', () => { - let aggregateSchema = { - - }; - - let templateSchema = { - - }; + let aggregateSchema = {}; - let baseSchema = { + let templateSchema = {}; - }; - - let params = { + let baseSchema = {}; - }; + let params = {}; let expectedDynamicQuery = { params: { a: 'a' }, @@ -188,116 +177,167 @@ describe('PatientlistMysqlReport:', () => { } }; - let getPlistGenStub = sinon.stub(report, 'getPatientListGenerator') + let getPlistGenStub = sinon + .stub(report, 'getPatientListGenerator') .returns(plGen); - let results = report.generatePatientListJsonQuery(aggregateSchema, baseSchema, templateSchema, params); - - expect(getPlistGenStub.calledWithExactly(aggregateSchema, baseSchema, templateSchema, params)).to.be.true; + let results = report.generatePatientListJsonQuery( + aggregateSchema, + baseSchema, + templateSchema, + params + ); + + expect( + getPlistGenStub.calledWithExactly( + aggregateSchema, + baseSchema, + templateSchema, + params + ) + ).to.be.true; expect(results).to.equal(expectedDynamicQuery); }); it('should generate the patientlist report', (done) => { let reports = { - 'main': {}, - 'report1': {}, - 'report2': {} + main: {}, + report1: {}, + report2: {} }; let reportQuery = 'select * from everything'; let results = { results: [] }; - let plSchemasRaw = [{ - aggregate: reports.report1, - base: reports.report2 - }]; + let plSchemasRaw = [ + { + aggregate: reports.report1, + base: reports.report2 + } + ]; let patientListTemplate = { - 'main': { - 'name': 'name' + main: { + name: 'name' } }; let generated = { - generated: { 'yyy': 'xxx' }, - params: { 'r': 'x' } + generated: { yyy: 'xxx' }, + params: { r: 'x' } }; - let fetchReportSchemaStub = sinon.stub(report, 'fetchReportSchema') + let fetchReportSchemaStub = sinon + .stub(report, 'fetchReportSchema') .returns(Promise.resolve(reports)); - let determineBaseAndAggrSchemaStub = sinon.stub(report, 'determineBaseAndAggrSchema') + let determineBaseAndAggrSchemaStub = sinon + .stub(report, 'determineBaseAndAggrSchema') .returns(plSchemasRaw); - let fetchPatientListTemplateStub = sinon.stub(report, 'fetchPatientListTemplate') + let fetchPatientListTemplateStub = sinon + .stub(report, 'fetchPatientListTemplate') .returns(Promise.resolve(patientListTemplate)); - let generatePlJsonStub = sinon.stub(report, 'generatePatientListJsonQuery') + let generatePlJsonStub = sinon + .stub(report, 'generatePatientListJsonQuery') .returns(generated); - let generateReportQueryStub = sinon.stub(report, 'generateReportQuery') + let generateReportQueryStub = sinon + .stub(report, 'generateReportQuery') .returns(Promise.resolve(reportQuery)); - let executeReportQueryStub = sinon.stub(report, 'executeReportQuery') + let executeReportQueryStub = sinon + .stub(report, 'executeReportQuery') .returns(Promise.resolve(results)); - report.generatePatientListReport(['test', 'test2', 'startDate']).then((res) => { - // fetched reports - expect(fetchReportSchemaStub.getCalls()[0].calledWithExactly(report.reportName)).to.be.true; - expect(report.reportSchemas).to.equal(reports); - - // determined patient list base and aggregate - expect(determineBaseAndAggrSchemaStub.getCalls()[0].calledWithExactly(report.reportSchemas, ['test', 'test2', 'startDate'])).to.be.true; - expect(report.plSchemasRaw).to.equal(plSchemasRaw[0]); - - // should add indicators as params if they do not exist - expect(report.params).to.deep.equal({ - 'test': 1, - 'test2': 1, - 'startDate': '2018-01-01' + report + .generatePatientListReport(['test', 'test2', 'startDate']) + .then((res) => { + // fetched reports + expect( + fetchReportSchemaStub + .getCalls()[0] + .calledWithExactly(report.reportName) + ).to.be.true; + expect(report.reportSchemas).to.equal(reports); + + // determined patient list base and aggregate + expect( + determineBaseAndAggrSchemaStub + .getCalls()[0] + .calledWithExactly(report.reportSchemas, [ + 'test', + 'test2', + 'startDate' + ]) + ).to.be.true; + expect(report.plSchemasRaw).to.equal(plSchemasRaw[0]); + + // should add indicators as params if they do not exist + expect(report.params).to.deep.equal({ + test: 1, + test2: 1, + startDate: '2018-01-01' + }); + + // fetched templatereport + expect( + fetchPatientListTemplateStub + .getCalls()[0] + .calledWithExactly(report.plSchemasRaw.aggregate) + ).to.be.true; + expect(report.plTemplate).to.equal(patientListTemplate.main); + + // generate patientListJsonQuery + expect( + generatePlJsonStub.calledWithExactly( + report.plSchemasRaw.aggregate, + report.plSchemasRaw.base, + report.plTemplate, + report.params + ) + ).to.be.true; + expect(report.generatedPL.main).to.equal(generated.generated); + expect(report.modifiedParam).to.deep.equal(generated.params); + + // generated report query + + console.log('Called with', generateReportQueryStub.firstCall.args); + console.log('report.generatedPL', report.generatedPL); + console.log('report.modifiedParam', report.modifiedParam); //(report.generatedPL, report.modifiedParam) + expect(generateReportQueryStub.firstCall.args[0]).to.deep.equal( + report.generatedPL + ); + expect(generateReportQueryStub.firstCall.args[1]).to.deep.equal( + report.modifiedParam + ); + expect(report.reportQuery).to.equal(reportQuery); + + // execute report query + expect(executeReportQueryStub.calledWithExactly(report.reportQuery)).to + .be.true; + expect(report.queryResults).to.equal(results); + + expect(res).to.deep.equal({ + schemas: reports, + generatedSchemas: report.generatedPL, + sqlQuery: reportQuery, + results: results + }); + + done(); }); - - // fetched templatereport - expect(fetchPatientListTemplateStub.getCalls()[0].calledWithExactly(report.plSchemasRaw.aggregate)).to.be.true; - expect(report.plTemplate).to.equal(patientListTemplate.main); - - // generate patientListJsonQuery - expect(generatePlJsonStub.calledWithExactly(report.plSchemasRaw.aggregate, report.plSchemasRaw.base, report.plTemplate, report.params)).to.be.true; - expect(report.generatedPL.main).to.equal(generated.generated); - expect(report.modifiedParam).to.deep.equal(generated.params); - - // generated report query - - console.log('Called with', generateReportQueryStub.firstCall.args); - console.log('report.generatedPL', report.generatedPL); - console.log('report.modifiedParam', report.modifiedParam); //(report.generatedPL, report.modifiedParam) - expect(generateReportQueryStub.firstCall.args[0]).to.deep.equal(report.generatedPL); - expect(generateReportQueryStub.firstCall.args[1]).to.deep.equal(report.modifiedParam); - expect(report.reportQuery).to.equal(reportQuery); - - // execute report query - expect(executeReportQueryStub.calledWithExactly(report.reportQuery)).to.be.true; - expect(report.queryResults).to.equal(results); - - expect(res).to.deep.equal({ - schemas: reports, - generatedSchemas: report.generatedPL, - sqlQuery: reportQuery, - results: results - }); - - done(); - }); }); it('should extract individual indicators from a string containing combined indicators', () => { let dynamicIndictor = 'dc__gender__f__age_group__0_to_1__on_art'; let extractedIndicators = { - 'gender': 'f', - 'age_group': '0_to_1', - 'on_art': null + gender: 'f', + age_group: '0_to_1', + on_art: null }; let actual = report.extractIndicators(dynamicIndictor); @@ -308,9 +348,9 @@ describe('PatientlistMysqlReport:', () => { let extracted = report.extractIndicators(anotherDynamic); expect(extracted).to.deep.equal({ - 'active_on_art': null, - 'age_range': '15_to_19', - 'gender': 'F' + active_on_art: null, + age_range: '15_to_19', + gender: 'F' }); }); @@ -321,27 +361,39 @@ describe('PatientlistMysqlReport:', () => { }); it('should consolidate params and indicators', () => { - let indicators = ['active', 'existing', 'dc__gender__F__age_range__15_to_19__active_on_art']; + let indicators = [ + 'active', + 'existing', + 'dc__gender__F__age_range__15_to_19__active_on_art' + ]; let params = { - 'startDate': '2018-01-01', - 'existing': 'some-value' + startDate: '2018-01-01', + existing: 'some-value' }; let expectedParams = { - 'startDate': '2018-01-01', - 'existing': 'some-value', - 'active': 1, - 'gender': 'F', - 'age_range': '15_to_19', - 'active_on_art': 1 + startDate: '2018-01-01', + existing: 'some-value', + active: 1, + gender: 'F', + age_range: '15_to_19', + active_on_art: 1 }; - let expectedIndicators = ['active', 'existing', 'gender', 'age_range', 'active_on_art']; + let expectedIndicators = [ + 'active', + 'existing', + 'gender', + 'age_range', + 'active_on_art' + ]; - let consolidatedIndicators = report.consolidateParamsAndIndicators(params, indicators); + let consolidatedIndicators = report.consolidateParamsAndIndicators( + params, + indicators + ); expect(params).to.deep.equal(expectedParams); expect(consolidatedIndicators).to.deep.equal(expectedIndicators); }); - -}); \ No newline at end of file +}); diff --git a/test/reporting-framework/report-processor-helpers.service.test.js b/test/reporting-framework/report-processor-helpers.service.test.js index 0dd860afa..e514abaa3 100755 --- a/test/reporting-framework/report-processor-helpers.service.test.js +++ b/test/reporting-framework/report-processor-helpers.service.test.js @@ -1,134 +1,147 @@ import ReportProcessorHelpersService from '../../app/reporting-framework/report-processor-helpers.service'; import mlog from 'mocha-logger'; const chai = require('chai'), - should = chai.should(), - expect = chai.expect, - chaiAsPromised = require('chai-as-promised'), - Mysql = require('mysql'), - sinon = require('sinon'), - Promise = require('bluebird'); + should = chai.should(), + expect = chai.expect, + chaiAsPromised = require('chai-as-promised'), + Mysql = require('mysql'), + sinon = require('sinon'), + Promise = require('bluebird'); chai.use(chaiAsPromised); describe('MOH731 Helpers', function () { - const reportProcessorHelpersService = new ReportProcessorHelpersService(); - beforeEach(() => { + const reportProcessorHelpersService = new ReportProcessorHelpersService(); + beforeEach(() => {}); + afterEach(() => {}); + it('should transform a set given aggregation columns and join constant when transform() is called', () => { + let set1 = [ + { + location_id: 1, + age_range: '0_to_1', + gender: 'M', + on_art: 40 + }, + { + location_id: 1, + age_range: '0_to_1', + gender: 'F', + on_art: 20 + }, + { + location_id: 1, + age_range: '1_to_2', + gender: 'M', + on_art: 20 + }, + { + location_id: 1, + age_range: '1_to_2', + gender: 'F', + on_art: 10 + }, + { + location_id: 2, + age_range: '0_to_1', + gender: 'M', + on_art: 50 + }, + { + location_id: 2, + age_range: '0_to_1', + gender: 'F', + on_art: 60 + }, + { + location_id: 2, + age_range: '1_to_2', + gender: 'M', + on_art: 30 + }, + { + location_id: 2, + age_range: '1_to_2', + gender: 'F', + on_art: 70 + } + ]; + let result = reportProcessorHelpersService.tranform(set1, { + use: ['gender', 'age_range'], + joinColumn: 'location_id', + skip: [] }); - afterEach(() => {}); + mlog.log('Result', JSON.stringify(result)); + expect(result).to.be.an('array'); - it('should transform a set given aggregation columns and join constant when transform() is called', () => { - let set1 = [{ - location_id: 1, - age_range: '0_to_1', - gender: 'M', - on_art: 40 - }, - { - location_id: 1, - age_range: '0_to_1', - gender: 'F', - on_art: 20 - }, - { - location_id: 1, - age_range: '1_to_2', - gender: 'M', - on_art: 20 - }, { - location_id: 1, - age_range: '1_to_2', - gender: 'F', - on_art: 10 - }, - { - location_id: 2, - age_range: '0_to_1', - gender: 'M', - on_art: 50 - }, - { - location_id: 2, - age_range: '0_to_1', - gender: 'F', - on_art: 60 - }, - { - location_id: 2, - age_range: '1_to_2', - gender: 'M', - on_art: 30 - }, { - location_id: 2, - age_range: '1_to_2', - gender: 'F', - on_art: 70 - }, - ] - let result = reportProcessorHelpersService.tranform(set1, { - use: ['gender', 'age_range'], - joinColumn: 'location_id', - skip:[] - }); - mlog.log('Result', JSON.stringify(result)); - expect(result).to.be.an('array'); + let finalSet1 = { + location_id: 1, + dc__gender__M__age_range__0_to_1__on_art: 40, + dc__gender__F__age_range__0_to_1__on_art: 20, + dc__gender__M__age_range__1_to_2__on_art: 20, + dc__gender__F__age_range__1_to_2__on_art: 10 + }; - let finalSet1 = { - location_id: 1, - dc__gender__M__age_range__0_to_1__on_art: 40, - dc__gender__F__age_range__0_to_1__on_art: 20, - dc__gender__M__age_range__1_to_2__on_art: 20, - dc__gender__F__age_range__1_to_2__on_art: 10 - } + let finalSet2 = { + location_id: 2, + dc__gender__M__age_range__0_to_1__on_art: 50, + dc__gender__F__age_range__0_to_1__on_art: 60, + dc__gender__M__age_range__1_to_2__on_art: 30, + dc__gender__F__age_range__1_to_2__on_art: 70 + }; + expect(result).to.deep.include(finalSet1); + expect(result).to.deep.include(finalSet2); + }); - let finalSet2 = { - location_id: 2, - dc__gender__M__age_range__0_to_1__on_art: 50, - dc__gender__F__age_range__0_to_1__on_art: 60, - dc__gender__M__age_range__1_to_2__on_art: 30, - dc__gender__F__age_range__1_to_2__on_art: 70 - } - expect(result).to.deep.include(finalSet1); - expect(result).to.deep.include(finalSet2); - }); - - it('should join to datasets when joinDatasets in called with a join column and data sets', () => { - let set1 = [{ - location_id: 1, - art: 40 - }]; + it('should join to datasets when joinDatasets in called with a join column and data sets', () => { + let set1 = [ + { + location_id: 1, + art: 40 + } + ]; - let set2 = [{ - location_id: 1, - active: 60 - }, - { - location_id: 2, - active: 40 - } - ]; + let set2 = [ + { + location_id: 1, + active: 60 + }, + { + location_id: 2, + active: 40 + } + ]; - let set3 = [{ - location_id: 2, - ltfu: 60 - }]; + let set3 = [ + { + location_id: 2, + ltfu: 60 + } + ]; - let finalSet1 = { - location_id: 1, - art: 40, - active: 60 - } - - let finalSet2 = { - location_id: 2, - active: 40, - ltfu: 60 - } - let result = reportProcessorHelpersService.joinDataSets('location_id', set1, set2); - let finalResult = reportProcessorHelpersService.joinDataSets('location_id',result, set3); - mlog.log('Result', JSON.stringify(finalResult)); - expect(finalResult).to.be.an('array'); - expect(finalResult).to.deep.include(finalSet1); - expect(finalResult).to.deep.include(finalSet2); - }); + let finalSet1 = { + location_id: 1, + art: 40, + active: 60 + }; -}); \ No newline at end of file + let finalSet2 = { + location_id: 2, + active: 40, + ltfu: 60 + }; + let result = reportProcessorHelpersService.joinDataSets( + 'location_id', + set1, + set2 + ); + let finalResult = reportProcessorHelpersService.joinDataSets( + 'location_id', + result, + set3 + ); + mlog.log('Result', JSON.stringify(finalResult)); + expect(finalResult).to.be.an('array'); + expect(finalResult).to.deep.include(finalSet1); + expect(finalResult).to.deep.include(finalSet2); + }); +}); diff --git a/test/service/eid.service.test.js b/test/service/eid.service.test.js index 8b72c8997..f0c88dbf4 100755 --- a/test/service/eid.service.test.js +++ b/test/service/eid.service.test.js @@ -1,676 +1,714 @@ (function () { - 'use strict' - var chai = require('chai'); - var chaiAsPromised = require('chai-as-promised'); - var sinon = require('sinon'); // for creating spies, mocks and stubs - var sinonChai = require('sinon-chai'); // expection engine for sinion - var nock = require('nock'); - var testRestUrl = 'http://testingurl:8080/openmrs'; - var eidService = require('../../service/eid.service.js'); - var patientService = require('../../service/openmrs-rest/patient.service.js'); - var _ = require('underscore'); - - // Some setup - var expect = chai.expect; - chai.use(sinonChai); - - describe('EID Service Unit Tests', function () { - var getResourceStub, getCd4ResourceStub; - var fakeResource = { - uri: 'http://eid.ampath.or.ke:56/order', - query: { - apikey: 'XXX' - } - }; + 'use strict'; + var chai = require('chai'); + var chaiAsPromised = require('chai-as-promised'); + var sinon = require('sinon'); // for creating spies, mocks and stubs + var sinonChai = require('sinon-chai'); // expection engine for sinion + var nock = require('nock'); + var testRestUrl = 'http://testingurl:8080/openmrs'; + var eidService = require('../../service/eid.service.js'); + var patientService = require('../../service/openmrs-rest/patient.service.js'); + var _ = require('underscore'); + + // Some setup + var expect = chai.expect; + chai.use(sinonChai); + + describe('EID Service Unit Tests', function () { + var getResourceStub, getCd4ResourceStub; + var fakeResource = { + uri: 'http://eid.ampath.or.ke:56/order', + query: { + apikey: 'XXX' + } + }; + + beforeEach(function () { + nock.disableNetConnect(); + + getResourceStub = sinon + .stub(eidService, 'getResource') + .returns(function (host, apiKey) { + return fakeResource; + }); + + getCd4ResourceStub = sinon + .stub(eidService, 'getCd4Resource') + .returns(function (host, apiKey) { + return fakeResource; + }); + }); - beforeEach(function () { - nock.disableNetConnect(); + afterEach(function () { + nock.cleanAll(); + nock.enableNetConnect(); + getResourceStub.restore(); + getCd4ResourceStub.restore(); + }); - getResourceStub = sinon.stub(eidService, 'getResource').returns( - function (host, apiKey) { - return fakeResource; - }); + var dummyResponse = { + posts: [ + { + PatientID: 'id 1', + SampleStatus: 'Complete' + }, + { + PatientID: 'id 2', + SampleStatus: 'Complete' + }, + { + PatientID: 'id 3', + SampleStatus: 'in progress' + }, + { + PatientID: 'id 4', + SampleStatus: 'Complete' + } + ] + }; + + var dummyResponse2 = { + posts: [ + { + PatientID: 'id 5', + SampleStatus: 'Complete' + }, + { + PatientID: 'id 6', + SampleStatus: 'Complete' + }, + { + PatientID: 'id 7', + SampleStatus: 'in progress' + }, + { + PatientID: 'id 8', + SampleStatus: 'Complete' + } + ] + }; + + it('should have service defined', function () { + expect(eidService).to.exists; + }); - getCd4ResourceStub = sinon.stub(eidService, 'getCd4Resource').returns( - function (host, apiKey) { - return fakeResource; - }); + it('should set-up stubs for resource getters', function () { + // var promise = eidService.getViralLoadTestResultsByPatientIdentifier( + // 'id 1', 'some host', 'some api key' + // ); + // promise.catch(function (error) { /*do nothing, meant to hide errors*/ }); + // var promise2 = eidService.getCd4TestResultsByPatientIdentifier( + // 'id 1', 'some host', 'some api key' + // ); + // promise2.catch(function (error) { /*do nothing, meant to hide errors*/ }); + // expect(getResourceStub.calledWithExactly('some host', 'some api key')).to.be.true; + // expect(getCd4ResourceStub.calledWithExactly('some host', 'some api key')).to.be.true; + }); + + it('should fetch EID viral load results by date range and paging details', function (done) { + var mockedRequest = nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 2, // viral load is always test 2 + page: 1, + startDate: '2004-01-01', + endDate: '2004-01-05' + }); + mockedRequest.reply(200, dummyResponse); + + var promise = eidService.getEidViralLoadResults( + 'host', + 'key', + '2004-01-01', + '2004-01-05', + 1 + ); + + promise + .then(function (response) { + expect(getResourceStub.calledWithExactly('host', 'key')).to.be.true; + expect(response).to.deep.equal(dummyResponse); + done(); + }) + .catch(function (error) { + console.error('getEidViralLoadResults error', error); + expect(true).to.be.false; // we don't expect error + done(); }); + done(); + }); - afterEach(function () { - nock.cleanAll(); - nock.enableNetConnect(); - getResourceStub.restore(); - getCd4ResourceStub.restore(); + it('should fetch EID DNA PCR results by date range and paging details', function (done) { + var mockedRequest = nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 1, // dna pcr is always test 1 + page: 1, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse); + + var promise = eidService.getEidDnaPcrResults( + 'host', + 'key', + '2004-01-01', + '2004-01-05', + 1 + ); + + promise + .then(function (response) { + expect(getResourceStub.calledWithExactly('host', 'key')).to.be.true; + expect(response).to.deep.equal(dummyResponse); + done(); + }) + .catch(function (error) { + console.error('getEidDnaPcrResults error', error); + expect(true).to.be.false; // we don't expect error + done(); }); + done(); + }); - var dummyResponse = { - 'posts': [{ - 'PatientID': 'id 1', - 'SampleStatus': 'Complete' - }, - { - 'PatientID': 'id 2', - 'SampleStatus': 'Complete' - }, - { - 'PatientID': 'id 3', - 'SampleStatus': 'in progress' - }, - { - 'PatientID': 'id 4', - 'SampleStatus': 'Complete' - } - ] - }; + it('should fetch EID CD4 results by date range and paging details', function (done) { + var mockedRequest = nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + page: 1, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse); + + var promise = eidService.getEidCD4Results( + 'host', + 'key', + '2004-01-01', + '2004-01-05', + 1 + ); + + promise + .then(function (response) { + expect( + getCd4ResourceStub.calledWithExactly('host', 'key') + ).to.be.true; + expect(response).to.deep.equal(dummyResponse); + done(); + }) + .catch(function (error) { + console.error('getEidCD4Results error', error); + expect(true).to.be.false; // we don't expect error + done(); + }); + done(); + }); - var dummyResponse2 = { - 'posts': [{ - 'PatientID': 'id 5', - 'SampleStatus': 'Complete' - }, - { - 'PatientID': 'id 6', - 'SampleStatus': 'Complete' - }, - { - 'PatientID': 'id 7', - 'SampleStatus': 'in progress' - }, - { - 'PatientID': 'id 8', - 'SampleStatus': 'Complete' - } - ] - }; + it('should fetch all EID results to the last page per type and date range', function (done) { + // set up mocks for viral load + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 2, // viral load is always test 2 + page: 1, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse); + + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 2, // viral load is always test 2 + page: 2, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse2); + + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 2, // viral load is always test 2 + page: 3, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, { + posts: [] + }); + + var promise = eidService.getAllEidResultsByType( + 'host', + 'key', + '2004-01-01', + '2004-01-05', + eidService.getEidViralLoadResults + ); + + promise + .then(function (results) { + expect(results.posts.length).to.equal(8); + expect(results.posts[0]).to.deep.equal(dummyResponse.posts[0]); + expect(results.posts[4]).to.deep.equal(dummyResponse2.posts[0]); + done(); + }) + .catch(function (error) { + console.error(error); + expect(true).to.be.false; // error not expected with the test case + done(); + }); + done(); + }); - it('should have service defined', function () { - expect(eidService).to.exists; + it('should fetch patient identifiers with results by lab type', function (done) { + // stub a list of all available labs + var resultsByTypeStub = sinon + .stub(eidService, 'getAllEidResultsByType') + .returns(function (host, apikey, startDate, endDate, fetchingFunc) { + return new Promise(function (resolve, reject) { + resolve(dummyResponse); + }); }); - it('should set-up stubs for resource getters', function () { + eidService + .getPatientIdentifiersWithEidResultsByType( + 'host', + 'key', + '2017-01-01', + '2017-01-31', + eidService.getEidViralLoadResults + ) + .then(function (response) { + expect(response).to.deep.equal({ + patientIdentifiers: ['id 1', 'id 2', 'id 4'] + }); + resultsByTypeStub.restore(); + done(); + }) + .catch(function (error) { + console.error('unexpected error', error); + expect(true).to.be.false; + resultsByTypeStub.restore(); + done(); + }); + done(); + resultsByTypeStub.restore(); + }); - // var promise = eidService.getViralLoadTestResultsByPatientIdentifier( - // 'id 1', 'some host', 'some api key' - // ); - // promise.catch(function (error) { /*do nothing, meant to hide errors*/ }); + it('should return error when fetching patient identifiers with results by lab type fails', function (done) { + // stub a list of all available labs + var resultsByTypeStub = sinon + .stub(eidService, 'getAllEidResultsByType') + .returns(function (host, apikey, startDate, endDate, fetchingFunc) { + return new Promise(function (resolve, reject) { + reject('unknown error'); + }); + }); - // var promise2 = eidService.getCd4TestResultsByPatientIdentifier( - // 'id 1', 'some host', 'some api key' - // ); - // promise2.catch(function (error) { /*do nothing, meant to hide errors*/ }); + eidService + .getPatientIdentifiersWithEidResultsByType( + 'host', + 'key', + '2017-01-01', + '2017-01-31', + eidService.getEidViralLoadResults + ) + .then(function (response) { + expect(true).to.be.false; // we don't expect error at this point + resultsByTypeStub.restore(); + done(); + }) + .catch(function (error) { + expect(error).to.deep.equal({ + patientIdentifiers: [], + host: 'host', + error: 'unknown error' + }); + resultsByTypeStub.restore(); + done(); + }); + done(); + }); - // expect(getResourceStub.calledWithExactly('some host', 'some api key')).to.be.true; - // expect(getCd4ResourceStub.calledWithExactly('some host', 'some api key')).to.be.true; + it('should fetch all EID lab results by date range', function (done) { + // set up mocks for viral load + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 2, // viral load is always test 2 + page: 1, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse); + + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 2, // viral load is always test 2 + page: 2, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse2); + + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 2, // viral load is always test 2 + page: 3, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, { + posts: [] + }); + // set up mocks for DNA PCR + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 1, + page: 1, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse); + + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 1, + page: 2, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse2); + + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + test: 1, + page: 3, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, { + posts: [] }); - it('should fetch EID viral load results by date range and paging details', - function (done) { - var mockedRequest = nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 2, // viral load is always test 2 - page: 1, - startDate: '2004-01-01', - endDate: '2004-01-05' - }); - mockedRequest.reply(200, dummyResponse); - - var promise = - eidService.getEidViralLoadResults('host', 'key', '2004-01-01', '2004-01-05', 1); - - promise - .then(function (response) { - expect(getResourceStub.calledWithExactly('host', 'key')).to.be.true; - expect(response).to.deep.equal(dummyResponse); - done(); - }) - .catch(function (error) { - console.error('getEidViralLoadResults error', error); - expect(true).to.be.false; // we don't expect error - done(); - }); - done(); - }); - - it('should fetch EID DNA PCR results by date range and paging details', - function (done) { - var mockedRequest = nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 1, // dna pcr is always test 1 - page: 1, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse); - - var promise = - eidService.getEidDnaPcrResults('host', 'key', '2004-01-01', '2004-01-05', 1); - - promise - .then(function (response) { - expect(getResourceStub.calledWithExactly('host', 'key')).to.be.true; - expect(response).to.deep.equal(dummyResponse); - done(); - }) - .catch(function (error) { - console.error('getEidDnaPcrResults error', error); - expect(true).to.be.false; // we don't expect error - done(); - }); - done(); - }); - - it('should fetch EID CD4 results by date range and paging details', - function (done) { - var mockedRequest = nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - page: 1, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse); - - var promise = - eidService.getEidCD4Results('host', 'key', '2004-01-01', '2004-01-05', 1); - - promise - .then(function (response) { - expect(getCd4ResourceStub.calledWithExactly('host', 'key')).to.be.true; - expect(response).to.deep.equal(dummyResponse); - done(); - }) - .catch(function (error) { - console.error('getEidCD4Results error', error); - expect(true).to.be.false; // we don't expect error - done(); - }); - done(); - }); - - it('should fetch all EID results to the last page per type and date range', function (done) { - - // set up mocks for viral load - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 2, // viral load is always test 2 - page: 1, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse); - - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 2, // viral load is always test 2 - page: 2, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse2); - - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 2, // viral load is always test 2 - page: 3, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, { - posts: [] - }); - - var promise = - eidService.getAllEidResultsByType('host', 'key', '2004-01-01', '2004-01-05', eidService.getEidViralLoadResults); - - promise - .then(function (results) { - expect(results.posts.length).to.equal(8); - expect(results.posts[0]).to.deep.equal(dummyResponse.posts[0]); - expect(results.posts[4]).to.deep.equal(dummyResponse2.posts[0]); - done(); - }) - .catch(function (error) { - console.error(error); - expect(true).to.be.false; // error not expected with the test case - done(); - }); - done(); + // set up mocks for CD4 + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + page: 1, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse); + + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + page: 2, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, dummyResponse2); + + nock('http://eid.ampath.or.ke:56') + .get('/order') // the entire URI always comes from some config file + .query({ + apikey: fakeResource.query.apikey, + page: 3, + startDate: '2004-01-01', + endDate: '2004-01-05' + }) + .reply(200, { + posts: [] + }); + + var promise = eidService.getAllEidResults( + { + host: 'host', + generalApiKey: 'key', + cd4ApiKey: 'key' + }, + '2004-01-01', + '2004-01-05' + ); + + promise + .then(function (results) { + expect(results.viralLoad.posts.length).to.equal(8); + expect(results.viralLoad.posts[0]).to.deep.equal( + dummyResponse.posts[0] + ); + expect(results.viralLoad.posts[4]).to.deep.equal( + dummyResponse2.posts[0] + ); + + expect(results.cd4.posts.length).to.equal(8); + expect(results.cd4.posts[0]).to.deep.equal(dummyResponse.posts[0]); + expect(results.cd4.posts[4]).to.deep.equal(dummyResponse2.posts[0]); + + expect(results.dnaPcr.posts.length).to.equal(8); + expect(results.dnaPcr.posts[0]).to.deep.equal(dummyResponse.posts[0]); + expect(results.dnaPcr.posts[4]).to.deep.equal( + dummyResponse2.posts[0] + ); + + done(); + }) + .catch(function (error) { + console.error(error); + expect(true).to.be.false; // error not expected with the test case + done(); + }); + done(); + }); + + it('should fetch all EID results from all labs for a given date range', function (done) { + // stub a list of all available labs + var locationStub = sinon + .stub(eidService, 'getAvailableLabServers') + .returns(function (filterLocations) { + return new Promise(function (resolve, reject) { + resolve([ + { + name: 'ampath', + host: 'http://blah.ampath.or.ke', + generalApiKey: 'xx1', + cd4ApiKey: 'xx2', + loadCd4: true + }, + { + name: 'alupe', + host: 'http://10.50.80.1', + generalApiKey: 'xx3', + cd4ApiKey: 'xx4', + loadCd4: true + } + ]); + }); + }); + + var allResultsStub = sinon + .stub(eidService, 'getAllEidResults') + .returns(function (server, startDate, endDate) { + return new Promise(function (resolve, reject) { + if (server.host === 'http://blah.ampath.or.ke') { + resolve({ + viralLoad: { + posts: dummyResponse.posts + }, + cd4: { + posts: [] + }, + dnaPcr: { + posts: dummyResponse2.posts + } + }); + } else { + resolve({ + viralLoad: { + posts: [] + }, + cd4: { + posts: dummyResponse.posts + }, + dnaPcr: { + posts: [] + } + }); + } + }); + }); + + var promise = eidService.getAllEidResultsFromAllSites( + '01-01-2017', + '01-04-2017' + ); + + promise + .then(function (results) { + expect(results).to.deep.equal([ + { + viralLoad: { + posts: dummyResponse.posts + }, + cd4: { + posts: [] + }, + dnaPcr: { + posts: dummyResponse2.posts + }, + lab: 'ampath' + }, + { + viralLoad: { + posts: [] + }, + cd4: { + posts: dummyResponse.posts + }, + dnaPcr: { + posts: [] + }, + lab: 'alupe' + } + ]); + done(); + locationStub.restore(); + allResultsStub.restore(); + }) + .catch(function (error) { + // didn't expect an error at this point + console.error(error); + expect(true).to.be.false; + done(); + locationStub.restore(); + allResultsStub.restore(); }); + done(); + }); - it('should fetch patient identifiers with results by lab type', - function (done) { - - // stub a list of all available labs - var resultsByTypeStub = sinon.stub(eidService, 'getAllEidResultsByType').returns( - function (host, apikey, startDate, endDate, fetchingFunc) { - return new Promise(function (resolve, reject) { - resolve(dummyResponse); - }); - }); - - eidService.getPatientIdentifiersWithEidResultsByType('host', 'key', - '2017-01-01', '2017-01-31', eidService.getEidViralLoadResults) - .then(function (response) { - expect(response).to.deep.equal({ - patientIdentifiers: ['id 1', 'id 2', 'id 4'] - }) - resultsByTypeStub.restore(); - done(); - }) - .catch(function (error) { - console.error('unexpected error', error); - expect(true).to.be.false; - resultsByTypeStub.restore(); - done(); - }); - done(); - resultsByTypeStub.restore(); - }); - - it('should return error when fetching patient identifiers with results by lab type fails', - function (done) { - - // stub a list of all available labs - var resultsByTypeStub = sinon.stub(eidService, 'getAllEidResultsByType').returns( - function (host, apikey, startDate, endDate, fetchingFunc) { - return new Promise(function (resolve, reject) { - reject('unknown error') - }); - }); - - eidService.getPatientIdentifiersWithEidResultsByType('host', 'key', - '2017-01-01', '2017-01-31', eidService.getEidViralLoadResults) - .then(function (response) { - expect(true).to.be.false; // we don't expect error at this point - resultsByTypeStub.restore(); - done(); - }) - .catch(function (error) { - expect(error).to.deep.equal({ - patientIdentifiers: [], - host: 'host', - error: 'unknown error' - }); - resultsByTypeStub.restore(); - done(); - }); - done(); - }); - - it('should fetch all EID lab results by date range', function (done) { - - // set up mocks for viral load - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 2, // viral load is always test 2 - page: 1, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse); - - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 2, // viral load is always test 2 - page: 2, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse2); - - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 2, // viral load is always test 2 - page: 3, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, { + it('should fetch patient uuids with EID results for a given time period', function (done) { + var labResultsStub = sinon + .stub(eidService, 'getAllEidResultsFromAllSites') + .returns(function (startDate, endDate) { + return new Promise(function (resolve, reject) { + if (startDate === '01-01-2017' && endDate === '01-04-2017') { + resolve([ + { + viralLoad: { + posts: dummyResponse.posts + }, + cd4: { posts: [] - }); - - - - // set up mocks for DNA PCR - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 1, - page: 1, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse); - - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 1, - page: 2, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse2); - - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - test: 1, - page: 3, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, { + }, + dnaPcr: { + posts: dummyResponse2.posts + }, + lab: 'ampath' + }, + { + viralLoad: { posts: [] - }); - - - // set up mocks for CD4 - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - page: 1, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse); - - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - page: 2, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, dummyResponse2); - - nock('http://eid.ampath.or.ke:56') - .get('/order') // the entire URI always comes from some config file - .query({ - apikey: fakeResource.query.apikey, - page: 3, - startDate: '2004-01-01', - endDate: '2004-01-05' - }) - .reply(200, { + }, + cd4: { + posts: dummyResponse.posts + }, + dnaPcr: { posts: [] - }); - - var promise = - eidService.getAllEidResults({ - host: 'host', - generalApiKey: 'key', - cd4ApiKey: 'key' - }, - '2004-01-01', '2004-01-05'); - - promise - .then(function (results) { - expect(results.viralLoad.posts.length).to.equal(8); - expect(results.viralLoad.posts[0]).to.deep.equal(dummyResponse.posts[0]); - expect(results.viralLoad.posts[4]).to.deep.equal(dummyResponse2.posts[0]); - - expect(results.cd4.posts.length).to.equal(8); - expect(results.cd4.posts[0]).to.deep.equal(dummyResponse.posts[0]); - expect(results.cd4.posts[4]).to.deep.equal(dummyResponse2.posts[0]); - - expect(results.dnaPcr.posts.length).to.equal(8); - expect(results.dnaPcr.posts[0]).to.deep.equal(dummyResponse.posts[0]); - expect(results.dnaPcr.posts[4]).to.deep.equal(dummyResponse2.posts[0]); - - done(); - }) - .catch(function (error) { - console.error(error); - expect(true).to.be.false; // error not expected with the test case - done(); - }); - done(); + }, + lab: 'alupe' + } + ]); + } else { + reject('Unexpected date params'); + } + }); + }); + + var patientServiceStub = sinon + .stub(patientService, 'getPatientUuidsByIdentifiers') + .returns(function (patientIds) { + return new Promise(function (resolve, reject) { + function allArraysAlike(arrays) { + return _.all(arrays, function (array) { + return ( + array.length == arrays[0].length && + _.difference(array, arrays[0]).length == 0 + ); + }); + } + + if ( + _(patientIds).isEqual([ + 'id 1', + 'id 2', + 'id 4', + 'id 5', + 'id 6', + 'id 8' + ]) + ) { + resolve([ + { + identifier: 'id 1', + patientUuid: 'uuid 1' + }, + { + identifier: 'id 2', + patientUuid: 'uuid 2' + }, + { + identifier: 'id 4', + hasError: true + }, + { + identifier: 'id 5', + patientUuid: 'uuid 5' + }, + { + identifier: 'id 6', + patientUuid: 'uuid 6' + }, + { + identifier: 'id 8', + patientUuid: 'uuid 8' + } + ]); + } else { + reject('Unexpected patient identifier list'); + } + }); }); - it('should fetch all EID results from all labs for a given date range', - function (done) { - - // stub a list of all available labs - var locationStub = sinon.stub(eidService, 'getAvailableLabServers').returns( - function (filterLocations) { - return new Promise(function (resolve, reject) { - resolve([{ - "name": "ampath", - "host": "http://blah.ampath.or.ke", - "generalApiKey": "xx1", - "cd4ApiKey": "xx2", - "loadCd4": true - }, - { - "name": "alupe", - "host": "http://10.50.80.1", - "generalApiKey": "xx3", - "cd4ApiKey": "xx4", - "loadCd4": true - } - ]); - }); - }); - - var allResultsStub = sinon.stub(eidService, 'getAllEidResults').returns( - function (server, startDate, endDate) { - return new Promise( - function (resolve, reject) { - if (server.host === 'http://blah.ampath.or.ke') { - resolve({ - viralLoad: { - posts: dummyResponse.posts - }, - cd4: { - posts: [] - }, - dnaPcr: { - posts: dummyResponse2.posts - } - }); - } else { - resolve({ - viralLoad: { - posts: [] - }, - cd4: { - posts: dummyResponse.posts - }, - dnaPcr: { - posts: [] - } - }); - } - } - ); - }); - - - var promise = - eidService.getAllEidResultsFromAllSites('01-01-2017', '01-04-2017'); - - promise - .then(function (results) { - expect(results).to.deep.equal( - [{ - viralLoad: { - posts: dummyResponse.posts - }, - cd4: { - posts: [] - }, - dnaPcr: { - posts: dummyResponse2.posts - }, - lab: 'ampath' - }, - { - viralLoad: { - posts: [] - }, - cd4: { - posts: dummyResponse.posts - }, - dnaPcr: { - posts: [] - }, - lab: 'alupe' - } - ] - ); - done(); - locationStub.restore(); - allResultsStub.restore(); - - }) - .catch(function (error) { - // didn't expect an error at this point - console.error(error); - expect(true).to.be.false; - done(); - locationStub.restore(); - allResultsStub.restore(); - }); - done(); - }); - - it('should fetch patient uuids with EID results for a given time period', - function (done) { - var labResultsStub = sinon.stub(eidService, 'getAllEidResultsFromAllSites').returns( - function (startDate, endDate) { - return new Promise(function (resolve, reject) { - if (startDate === '01-01-2017' && endDate === '01-04-2017') { - resolve( - [{ - viralLoad: { - posts: dummyResponse.posts - }, - cd4: { - posts: [] - }, - dnaPcr: { - posts: dummyResponse2.posts - }, - lab: 'ampath' - }, - { - viralLoad: { - posts: [] - }, - cd4: { - posts: dummyResponse.posts - }, - dnaPcr: { - posts: [] - }, - lab: 'alupe' - } - ] - ); - } else { - reject('Unexpected date params') - } - }); - }); - - var patientServiceStub = sinon.stub(patientService, 'getPatientUuidsByIdentifiers').returns( - function (patientIds) { - return new Promise(function (resolve, reject) { - - function allArraysAlike(arrays) { - return _.all(arrays, function (array) { - return array.length == arrays[0].length && _.difference(array, arrays[0]).length == 0; - }); - } - - if (_(patientIds).isEqual(['id 1', 'id 2', 'id 4', 'id 5', 'id 6', 'id 8'])) { - resolve( - [{ - identifier: 'id 1', - patientUuid: 'uuid 1' - }, - { - identifier: 'id 2', - patientUuid: 'uuid 2' - }, - { - identifier: 'id 4', - hasError: true - }, - { - identifier: 'id 5', - patientUuid: 'uuid 5' - }, - { - identifier: 'id 6', - patientUuid: 'uuid 6' - }, - { - identifier: 'id 8', - patientUuid: 'uuid 8' - } - ] - ); - } else { - reject('Unexpected patient identifier list') - } - }); - }); - - - var promise = - eidService.getPatientsWithEidResults('01-01-2017', '01-04-2017'); - - promise - .then(function (results) { - expect(results).to.deep.equal( - [ - 'uuid 1', - 'uuid 2', - 'uuid 5', - 'uuid 6', - 'uuid 8' - ] - ); - done(); - labResultsStub.restore(); - patientServiceStub.restore(); - - }) - .catch(function (error) { - // didn't expect an error at this point - console.error(error); - expect(true).to.be.false; - done(); - labResultsStub.restore(); - patientServiceStub.restore(); - }); - done(); - }); + var promise = eidService.getPatientsWithEidResults( + '01-01-2017', + '01-04-2017' + ); + + promise + .then(function (results) { + expect(results).to.deep.equal([ + 'uuid 1', + 'uuid 2', + 'uuid 5', + 'uuid 6', + 'uuid 8' + ]); + done(); + labResultsStub.restore(); + patientServiceStub.restore(); + }) + .catch(function (error) { + // didn't expect an error at this point + console.error(error); + expect(true).to.be.false; + done(); + labResultsStub.restore(); + patientServiceStub.restore(); + }); + done(); }); -})(); \ No newline at end of file + }); +})(); diff --git a/test/service/eid/eid.service.test.js b/test/service/eid/eid.service.test.js index 7c8998a25..8f5fdcf72 100755 --- a/test/service/eid/eid.service.test.js +++ b/test/service/eid/eid.service.test.js @@ -18,56 +18,50 @@ global.assert = chai.assert; chai.use(sinonChai); describe('EID SERVICES TESTS', function () { + describe('Testing eid service layer', function () { + beforeEach(function (done) { + this.request = sinon.stub(http, 'request'); + done(); + }); - describe('Testing eid service layer', function () { - - beforeEach(function (done) { - this.request = sinon.stub(http, 'request'); - done(); - }); - - afterEach(function () { - http.request.restore(); - }); - - it('should create the right payload object when generatePayload service is called with a raw DNAPCR Client Payload', - function (done) { - var options = { - params: { - lab: 'ampath' - }, - query: {}, - payload: mockData.getDnaPcrMockPayload() - - }; - var payload = {}; - - eidService.generatePayload(options.payload, - function (res) { - payload=res; - done(); - }, function (res) { - console.log('An error occurred:', res); - done(); - }); - - - //check to ensure location has been resolved - expect(payload.mflCode).to.equal('15204'); - //check to ensure infantProphylaxis: has been resolved - expect(payload.infantProphylaxis).to.equal(5); - //check to ensure pmtctIntervention: has been resolved - expect(payload.pmtctIntervention).to.equal(5); - //check to ensure feedingType: has been resolved - expect(payload.feedingType).to.equal(0); - //check to ensure entryPoint:: has been resolved - expect(payload.entryPoint).to.equal(2); - //check to ensure entryPoint:: has been resolved - expect(payload.motherHivStatus).to.equal(2); - + afterEach(function () { + http.request.restore(); + }); - }); + it('should create the right payload object when generatePayload service is called with a raw DNAPCR Client Payload', function (done) { + var options = { + params: { + lab: 'ampath' + }, + query: {}, + payload: mockData.getDnaPcrMockPayload() + }; + var payload = {}; + eidService.generatePayload( + options.payload, + function (res) { + payload = res; + done(); + }, + function (res) { + console.log('An error occurred:', res); + done(); + } + ); + //check to ensure location has been resolved + expect(payload.mflCode).to.equal('15204'); + //check to ensure infantProphylaxis: has been resolved + expect(payload.infantProphylaxis).to.equal(5); + //check to ensure pmtctIntervention: has been resolved + expect(payload.pmtctIntervention).to.equal(5); + //check to ensure feedingType: has been resolved + expect(payload.feedingType).to.equal(0); + //check to ensure entryPoint:: has been resolved + expect(payload.entryPoint).to.equal(2); + //check to ensure entryPoint:: has been resolved + expect(payload.motherHivStatus).to.equal(2); }); + }); }); diff --git a/test/service/indicator-processor/indicator-processor.service.test.js b/test/service/indicator-processor/indicator-processor.service.test.js index b384b3b2d..7a5cf9d42 100755 --- a/test/service/indicator-processor/indicator-processor.service.test.js +++ b/test/service/indicator-processor/indicator-processor.service.test.js @@ -10,114 +10,165 @@ var expect = chai.expect; chai.use(sinonChai); describe('Indicator Processor Service Unit Tests', function () { - - beforeEach(function (done) { - - done(); - }); - - afterEach(function () { - - }); - - it('should be defined', function () { - expect(indicatorProcessor).to.be.defined; - }); - - it('should have required methods defined', function () { - expect(indicatorProcessor.disaggregateDynamicIndicators).to.be.defined; - expect(indicatorProcessor.disaggregateFixedIndicators).to.be.defined; - expect(indicatorProcessor.replaceIndicatorParam).to.be.defined; - }); - - it('should be able to disaggregate and mutate any indicator by age range ', function () { - var request = { - requestParams: { - ageRangeFilter: '5,30', // meaning 5 to 30 - - } - } - var result = indicatorProcessor.disaggregateDynamicIndicators(sampleReport, indicatorsSchemaDefinition, request); - expect(result).to.be // for age 6 - .an('array').that.includes('count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (timestampdiff(year,t3.birthdate,t2.endDate) > 5 and timestampdiff(year,t3.birthdate,t2.endDate) <= 6), t1.person_id,null)) as patients_requiring_vl_age_6'); - expect(result).to.be // for age 8... and so on - .an('array').that.includes('count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (timestampdiff(year,t3.birthdate,t2.endDate) > 7 and timestampdiff(year,t3.birthdate,t2.endDate) <= 8), t1.person_id,null)) as patients_requiring_vl_age_8'); - - }); - - it('should be able to disaggregate and mutate any indicator by age group ', function () { - var request = { - requestParams: { - ageGroupFilter: '0_to_5,6_to_10', // meaning age_group_0_to_5 e.t.c - - - } - } - var result = indicatorProcessor.disaggregateDynamicIndicators(sampleReport, indicatorsSchemaDefinition, request); - expect(result).to.be.an('array'); - - // for age 0_to_5 - expect(result).to.be.an('array').that.includes('count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (timestampdiff(year,t3.birthdate,t2.endDate) >= 0 and timestampdiff(year,t3.birthdate,t2.endDate) <= 5), t1.person_id,null)) as patients_requiring_vl_age_0_to_5'); - - // for age 6_to_10 - expect(result).to.be.an('array').that.includes('count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (timestampdiff(year,t3.birthdate,t2.endDate) >= 6 and timestampdiff(year,t3.birthdate,t2.endDate) <= 10), t1.person_id,null)) as patients_requiring_vl_age_6_to_10'); - - - }); - - it('should be able to disaggregate and mutate any indicator by gender', function () { - var request = { - requestParams: { - genderFilter: 'male,female', - - } - } - var result = indicatorProcessor.disaggregateDynamicIndicators(sampleReport, indicatorsSchemaDefinition, request); - expect(result).to.be.an('array'); - // for M - expect(result).to.be.an('array').that.includes('count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (t3.gender=\'M\'), t1.person_id,null)) as patients_requiring_vl_male'); - // for F - expect(result).to.be.an('array').that.includes('count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (t3.gender=\'F\'), t1.person_id,null)) as patients_requiring_vl_female'); - - - }); - - it('should be able to disaggregate and mutate any indicator by patient Care Status', function () { - var request = { - requestParams: { - patientCareStatusFilter: 'ltfu', // >90 means LTFU, <1 means Active, between 0 and 91 means defaulter - - } - } - var result = indicatorProcessor.disaggregateDynamicIndicators(sampleReport, indicatorsSchemaDefinition, request); - expect(result).to.be.an('array'); - // case LTFU - expect(result).to.be.an('array').that.includes('count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) >90 then 1 else null end), t1.person_id,null)) as patients_requiring_vl_ltfu'); - // TODO: case Defaulters - - // TODO: case Active in care - }); - - it('should NOT disaggregate indicators with no property "canBeDisaggregated" and it should be set to true', function () { - var request = { - requestParams: { - ageRangeFilter: '5,7', // meaning age 5 to 7 - ageGroupFilter: '0_to_5', - genderFilter: 'male', - patientCareStatusFilter: 'active_in_care',// >90 means LTFU, <1 means Active, between 0 and 91 means defaulter - - } - } - var result = indicatorProcessor.disaggregateDynamicIndicators(sampleReport, indicatorsSchemaDefinition, request); - expect(result).to.be.an('array'); - expect(result).to.be.an('array').to.not.include('if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_age_6'); - expect(result).to.be.an('array').to.not.include('if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_age_7'); - expect(result).to.be.an('array').to.not.include('if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_age_0_to_5'); - expect(result).to.be.an('array').to.not.include('if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_male'); - expect(result).to.be.an('array').to.not.include('if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_active_in_care'); - - console.log(result); - }); - - + beforeEach(function (done) { + done(); + }); + + afterEach(function () {}); + + it('should be defined', function () { + expect(indicatorProcessor).to.be.defined; + }); + + it('should have required methods defined', function () { + expect(indicatorProcessor.disaggregateDynamicIndicators).to.be.defined; + expect(indicatorProcessor.disaggregateFixedIndicators).to.be.defined; + expect(indicatorProcessor.replaceIndicatorParam).to.be.defined; + }); + + it('should be able to disaggregate and mutate any indicator by age range ', function () { + var request = { + requestParams: { + ageRangeFilter: '5,30' // meaning 5 to 30 + } + }; + var result = indicatorProcessor.disaggregateDynamicIndicators( + sampleReport, + indicatorsSchemaDefinition, + request + ); + expect(result) + .to.be // for age 6 + .an('array') + .that.includes( + 'count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (timestampdiff(year,t3.birthdate,t2.endDate) > 5 and timestampdiff(year,t3.birthdate,t2.endDate) <= 6), t1.person_id,null)) as patients_requiring_vl_age_6' + ); + expect(result) + .to.be // for age 8... and so on + .an('array') + .that.includes( + 'count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (timestampdiff(year,t3.birthdate,t2.endDate) > 7 and timestampdiff(year,t3.birthdate,t2.endDate) <= 8), t1.person_id,null)) as patients_requiring_vl_age_8' + ); + }); + + it('should be able to disaggregate and mutate any indicator by age group ', function () { + var request = { + requestParams: { + ageGroupFilter: '0_to_5,6_to_10' // meaning age_group_0_to_5 e.t.c + } + }; + var result = indicatorProcessor.disaggregateDynamicIndicators( + sampleReport, + indicatorsSchemaDefinition, + request + ); + expect(result).to.be.an('array'); + + // for age 0_to_5 + expect(result) + .to.be.an('array') + .that.includes( + 'count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (timestampdiff(year,t3.birthdate,t2.endDate) >= 0 and timestampdiff(year,t3.birthdate,t2.endDate) <= 5), t1.person_id,null)) as patients_requiring_vl_age_0_to_5' + ); + + // for age 6_to_10 + expect(result) + .to.be.an('array') + .that.includes( + 'count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (timestampdiff(year,t3.birthdate,t2.endDate) >= 6 and timestampdiff(year,t3.birthdate,t2.endDate) <= 10), t1.person_id,null)) as patients_requiring_vl_age_6_to_10' + ); + }); + + it('should be able to disaggregate and mutate any indicator by gender', function () { + var request = { + requestParams: { + genderFilter: 'male,female' + } + }; + var result = indicatorProcessor.disaggregateDynamicIndicators( + sampleReport, + indicatorsSchemaDefinition, + request + ); + expect(result).to.be.an('array'); + // for M + expect(result) + .to.be.an('array') + .that.includes( + "count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (t3.gender='M'), t1.person_id,null)) as patients_requiring_vl_male" + ); + // for F + expect(result) + .to.be.an('array') + .that.includes( + "count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (t3.gender='F'), t1.person_id,null)) as patients_requiring_vl_female" + ); + }); + + it('should be able to disaggregate and mutate any indicator by patient Care Status', function () { + var request = { + requestParams: { + patientCareStatusFilter: 'ltfu' // >90 means LTFU, <1 means Active, between 0 and 91 means defaulter + } + }; + var result = indicatorProcessor.disaggregateDynamicIndicators( + sampleReport, + indicatorsSchemaDefinition, + request + ); + expect(result).to.be.an('array'); + // case LTFU + expect(result) + .to.be.an('array') + .that.includes( + 'count(distinct if(timestampdiff(month,arv_start_date,encounter_datetime) >= 6 and (case when date(t1.death_date) <= t2.endDate or (date(outreach_death_date_bncd) <= t2.endDate and date(outreach_date_bncd) <= t2.endDate) then null when t1.transfer_out is not null or (outreach_patient_care_status_bncd in (1287,1594,9068,9504,1285) and date(outreach_date_bncd) <= t2.endDate) or (transfer_transfer_out_bncd is not null and date(transfer_date_bncd) <= t2.endDate) then null when t1.patient_care_status in (9083) or (outreach_patient_care_status_bncd in (9083) and date(outreach_date_bncd) <= t2.endDate) then null when (outreach_patient_care_status_bncd in (9036) and date(outreach_date_bncd) <= t2.endDate) or t1.patient_care_status in (9036) then null when timestampdiff(day, if(t1.rtc_date, t1.rtc_date, DATE_ADD(t1.encounter_datetime, INTERVAL 30 DAY)), t2.endDate) >90 then 1 else null end), t1.person_id,null)) as patients_requiring_vl_ltfu' + ); + // TODO: case Defaulters + + // TODO: case Active in care + }); + + it('should NOT disaggregate indicators with no property "canBeDisaggregated" and it should be set to true', function () { + var request = { + requestParams: { + ageRangeFilter: '5,7', // meaning age 5 to 7 + ageGroupFilter: '0_to_5', + genderFilter: 'male', + patientCareStatusFilter: 'active_in_care' // >90 means LTFU, <1 means Active, between 0 and 91 means defaulter + } + }; + var result = indicatorProcessor.disaggregateDynamicIndicators( + sampleReport, + indicatorsSchemaDefinition, + request + ); + expect(result).to.be.an('array'); + expect(result) + .to.be.an('array') + .to.not.include( + 'if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_age_6' + ); + expect(result) + .to.be.an('array') + .to.not.include( + 'if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_age_7' + ); + expect(result) + .to.be.an('array') + .to.not.include( + 'if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_age_0_to_5' + ); + expect(result) + .to.be.an('array') + .to.not.include( + 'if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_male' + ); + expect(result) + .to.be.an('array') + .to.not.include( + 'if([tested_appropriately]=0, 0,([tested_appropriately]/[patients_requiring_vl])*100) as perc_tested_appropriately_active_in_care' + ); + + console.log(result); + }); }); diff --git a/test/service/indicator-processor/sample-report.json b/test/service/indicator-processor/sample-report.json index 2e8f6aca5..4e33364f4 100755 --- a/test/service/indicator-processor/sample-report.json +++ b/test/service/indicator-processor/sample-report.json @@ -32,15 +32,11 @@ "parameters": [ { "name": "startDate", - "defaultValue": [ - "01-01-1980" - ] + "defaultValue": ["01-01-1980"] }, { "name": "endDate", - "defaultValue": [ - "Now()" - ] + "defaultValue": ["Now()"] }, { "name": "locations", @@ -122,4 +118,4 @@ "sql": "date_format(t2.endDate, '%m/%Y')" } ] -} \ No newline at end of file +} diff --git a/test/service/monthly-schedule-service.test.js b/test/service/monthly-schedule-service.test.js index 70eebafaa..25e6834f4 100755 --- a/test/service/monthly-schedule-service.test.js +++ b/test/service/monthly-schedule-service.test.js @@ -1,87 +1,94 @@ -import { - MonthlyScheduleService -} from '../../service/monthly-schedule-service' +import { MonthlyScheduleService } from '../../service/monthly-schedule-service'; let chai = require('chai'); -let sinon = require("sinon"); -let sinonChai = require("sinon-chai"); +let sinon = require('sinon'); +let sinonChai = require('sinon-chai'); let expect = chai.expect; const dao = require('../../etl-dao'); -const Promise = require("bluebird"); +const Promise = require('bluebird'); chai.use(sinonChai); describe('Monthly Schedule Service Test Suite', () => { - let service; - beforeEach(() => { - service = new MonthlyScheduleService(); - }) - it('It should be defined', () => { - expect(service).to.be.ok + let service; + beforeEach(() => { + service = new MonthlyScheduleService(); + }); + it('It should be defined', () => { + expect(service).to.be.ok; + }); + it('Should return a list of actual visits and scheduled visits for a given month', (done) => { + let runReportStub = sinon.stub(dao, 'runReport').returns((reportParams) => { + return new Promise((resolve, reject) => { + if (reportParams['reportName'] === 'attended') { + resolve({ + startIndex: 0, + size: 9, + result: [ + { + attended_date: '2017-01-31T21:00:00.000Z', + attended: 84 + } + ], + sql: + 'SELECT date(t1.encounter_datetime) as attended_date, count(distinct person_id) as attended FROM etl.flat_hiv_summary `t1` WHERE (t1.encounter_datetime >= ? and t1.encounter_datetime <= ? and t1.location_id in (?) and encounter_type not in (21,99999) ) GROUP BY attended_date LIMIT 1000000', + sqlParams: ['2017-02-01', '2017-02-28', '1'] + }); + } + if (reportParams['reportName'] === 'scheduled') { + resolve({ + startIndex: 0, + size: 1, + result: [ + { + scheduled_date: '2017-02-01', + scheduled: 102 + } + ], + sql: + "SELECT date_format(t1.rtc_date,'%Y-%m-%d') as scheduled_date, count(distinct t1.person_id) as scheduled, if(next_encounter_type_hiv =21, 1,0) as followed_up_by_outreach, count(distinct if(date(t1.rtc_date) >='2017-02-01' and date(t1.rtc_date)< date(now()) and next_clinical_datetime_hiv is null and death_date is null and transfer_out is null, t1.person_id, null)) as has_not_returned, count(distinct if(date(t1.rtc_date)<>date(next_clinical_datetime_hiv), t1.person_id, null)) as not_attended FROM etl.flat_hiv_summary `t1` WHERE (t1.rtc_date >= ? and t1.rtc_date <= ? and t1.location_id in (?) and coalesce(t1.transfer_out) is null and coalesce(t1.death_date) is null and encounter_type not in (99999) ) GROUP BY scheduled_date LIMIT 1000000", + sqlParams: ['2017-02-01', '2017-02-28', '1'] + }); + } + if (reportParams['reportName'] === 'has-not-returned-report') { + resolve({ + startIndex: 0, + size: 1, + result: [ + { + d: '2017-02-01', + has_not_returned: 3 + } + ] + }); + } + reject('report name required'); + }); }); - it('Should return a list of actual visits and scheduled visits for a given month', (done) => { - let runReportStub = sinon.stub(dao, 'runReport').returns((reportParams) => { - return new Promise((resolve, reject) => { - if (reportParams['reportName'] === 'attended') { - resolve({ - "startIndex": 0, - "size": 9, - "result": [{ - "attended_date": "2017-01-31T21:00:00.000Z", - "attended": 84 - }], - "sql": "SELECT date(t1.encounter_datetime) as attended_date, count(distinct person_id) as attended FROM etl.flat_hiv_summary `t1` WHERE (t1.encounter_datetime >= ? and t1.encounter_datetime <= ? and t1.location_id in (?) and encounter_type not in (21,99999) ) GROUP BY attended_date LIMIT 1000000", - "sqlParams": ["2017-02-01", "2017-02-28", "1"] - }); - } - if (reportParams['reportName'] === 'scheduled') { - - resolve({ - "startIndex": 0, - "size": 1, - "result": [{ - "scheduled_date": "2017-02-01", - "scheduled": 102 - }], - "sql": "SELECT date_format(t1.rtc_date,'%Y-%m-%d') as scheduled_date, count(distinct t1.person_id) as scheduled, if(next_encounter_type_hiv =21, 1,0) as followed_up_by_outreach, count(distinct if(date(t1.rtc_date) >='2017-02-01' and date(t1.rtc_date)< date(now()) and next_clinical_datetime_hiv is null and death_date is null and transfer_out is null, t1.person_id, null)) as has_not_returned, count(distinct if(date(t1.rtc_date)<>date(next_clinical_datetime_hiv), t1.person_id, null)) as not_attended FROM etl.flat_hiv_summary `t1` WHERE (t1.rtc_date >= ? and t1.rtc_date <= ? and t1.location_id in (?) and coalesce(t1.transfer_out) is null and coalesce(t1.death_date) is null and encounter_type not in (99999) ) GROUP BY scheduled_date LIMIT 1000000", - "sqlParams": ["2017-02-01", "2017-02-28", "1"] - }); - } - if (reportParams['reportName'] === 'has-not-returned-report') { - - resolve({ - "startIndex": 0, - "size": 1, - "result": [{ - "d": "2017-02-01", - "has_not_returned": 3 - }] - }); - } - reject('report name required'); - }); - }); - let expectedData = { - "results": [{ - "date": "2017-02-01", - "count": { - "attended": 84, - "scheduled": 102, - "has_not_returned": 3 - } - }] - }; - service.getMonthlyScheduled({}) - .then((result) => { - expect(runReportStub.called).to.be.true; - expect(result.results).to.be.ok; - expect(result.results[0]).to.deep.equal(expectedData.results[0]); - runReportStub.restore(); - done(); - }) - .catch((error) => { - console.log(error); - runReportStub.restore(); - expect(false).to.be.true; // for the test case, no error - done(); - }); + let expectedData = { + results: [ + { + date: '2017-02-01', + count: { + attended: 84, + scheduled: 102, + has_not_returned: 3 + } + } + ] + }; + service + .getMonthlyScheduled({}) + .then((result) => { + expect(runReportStub.called).to.be.true; + expect(result.results).to.be.ok; + expect(result.results[0]).to.deep.equal(expectedData.results[0]); + runReportStub.restore(); done(); - }); -}); \ No newline at end of file + }) + .catch((error) => { + console.log(error); + runReportStub.restore(); + expect(false).to.be.true; // for the test case, no error + done(); + }); + done(); + }); +}); diff --git a/test/service/notes.service.test.js b/test/service/notes.service.test.js index 305115d6d..176e8e8cf 100755 --- a/test/service/notes.service.test.js +++ b/test/service/notes.service.test.js @@ -24,26 +24,28 @@ vitals = etlMocks.getVitalsMock(); function getEstimatedDate(startDate, period) { - return moment(startDate).add(period, 'months') - .toDate().toISOString(); + return moment(startDate).add(period, 'months').toDate().toISOString(); } // bmi var bmi = math.round(utils.calculateBMI(vitals.weight, vitals.height), 1); expectedNote = { visitDate: hivSummary.encounter_datetime, scheduled: hivSummary.scheduled_visit, - providers: [{ - uuid: 'pd13dddc-1359-11df-a1f1-0026b9348838', - name: 'Unknown Unknown Unknown', - encounterType: 'ADULTRETURN' - }, { - uuid: 'pb6e31da-1359-11df-a1f1-0026b9348838', - name: 'Giniton Giniton Giniton', - encounterType: 'TRIAGE' - }], + providers: [ + { + uuid: 'pd13dddc-1359-11df-a1f1-0026b9348838', + name: 'Unknown Unknown Unknown', + encounterType: 'ADULTRETURN' + }, + { + uuid: 'pb6e31da-1359-11df-a1f1-0026b9348838', + name: 'Giniton Giniton Giniton', + encounterType: 'TRIAGE' + } + ], lastViralLoad: { value: hivSummary.vl_1, - date: hivSummary.vl_1_date, + date: hivSummary.vl_1_date }, lastCD4Count: { value: hivSummary.cd4_1, @@ -58,7 +60,9 @@ plan: 'START DRUGS', startDate: hivSummary.tb_prophylaxis_start_date, estimatedEndDate: getEstimatedDate( - hivSummary.tb_prophylaxis_start_date, 6) + hivSummary.tb_prophylaxis_start_date, + 6 + ) }, ccHpi: [], assessment: [], @@ -77,49 +81,52 @@ }; }); - it('generateNote() should generate a correct note given all required ' + - 'parameters', function () { + it( + 'generateNote() should generate a correct note given all required ' + + 'parameters', + function () { var aNote = noteGS.generateNote(hivSummary, vitals, encounters); // console.log('expected', JSON.stringify(expectedNote,null,2)); // console.log('aNote',JSON.stringify(aNote,null,2)); expect(aNote).to.be.an.object; expect(aNote).to.deep.equal(expectedNote); - }); + } + ); it('generateNotes() should generate an expected array of notes', function () { - var expectedNote ={ - visitDate: '2016-04-11T21:00:00.000Z', - scheduled: null, - providers: [], - lastViralLoad: { value: 0, date: '2015-06-14T21:00:00.000Z' }, - lastCD4Count: { value: 149, date: '2013-09-29T21:00:00.000Z' }, - artRegimen: { - curArvMeds: 'TDF AND 3TC AND EFV', - curArvLine: 1, - arvStartDate: '2013-12-09T21:00:00.000Z' - }, - tbProphylaxisPlan: { - plan: '', - startDate: '', - estimatedEndDate: '' - }, - ccHpi: [], - assessment: [], - otherAssessment: [], - vitals: { - weight: '', - height: '', - bmi: '', - temperature: '', - oxygenSaturation: '', - systolicBp: '', - diastolicBp: '', - pulse: '' - }, - rtcDate: '2016-04-17T21:00:00.000Z' + var expectedNote = { + visitDate: '2016-04-11T21:00:00.000Z', + scheduled: null, + providers: [], + lastViralLoad: { value: 0, date: '2015-06-14T21:00:00.000Z' }, + lastCD4Count: { value: 149, date: '2013-09-29T21:00:00.000Z' }, + artRegimen: { + curArvMeds: 'TDF AND 3TC AND EFV', + curArvLine: 1, + arvStartDate: '2013-12-09T21:00:00.000Z' + }, + tbProphylaxisPlan: { + plan: '', + startDate: '', + estimatedEndDate: '' + }, + ccHpi: [], + assessment: [], + otherAssessment: [], + vitals: { + weight: '', + height: '', + bmi: '', + temperature: '', + oxygenSaturation: '', + systolicBp: '', + diastolicBp: '', + pulse: '' + }, + rtcDate: '2016-04-17T21:00:00.000Z' }; var expected = [expectedNote]; - // console.log('expected===',expected) + // console.log('expected===',expected) var notes = noteGS.generateNotes(encounters, [hivSummary], [vitals]); expect(notes).to.be.an.array; expect(notes.length).to.equal(1); @@ -133,19 +140,19 @@ // Change encounterDatetime to have slightly different time adultReturn.encounterDatetime = '2016-04-11T11:18:10.000+0300'; - triage.encounterDatetime = '2016-04-11T11:17:30.000+0300'; // happen earlier + triage.encounterDatetime = '2016-04-11T11:17:30.000+0300'; // happen earlier // Inject assessment in triage & adult return mocks. var triageAssessment = { - 'concept': { - 'uuid': ASSESSMENT, - 'name': { - 'uuid': 'some-name-uuid', - 'name': 'ASSESSMENT' + concept: { + uuid: ASSESSMENT, + name: { + uuid: 'some-name-uuid', + name: 'ASSESSMENT' } }, - 'value': 'High Blood pressure, low weight', - 'groupMembers': null + value: 'High Blood pressure, low weight', + groupMembers: null }; triage.obs.push(triageAssessment); diff --git a/test/service/openmrs-rest/encounter.test.js b/test/service/openmrs-rest/encounter.test.js index edabe47f3..4b0fbc68a 100755 --- a/test/service/openmrs-rest/encounter.test.js +++ b/test/service/openmrs-rest/encounter.test.js @@ -1,5 +1,5 @@ -(function() { - 'use strict' +(function () { + 'use strict'; var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); var nock = require('nock'); @@ -10,50 +10,60 @@ var expect = chai.expect; chai.use(chaiAsPromised); - describe('Open MRS Encounter Service Unit Tests', function() { - beforeEach(function() { - nock.disableNetConnect(); - }); + describe('Open MRS Encounter Service Unit Tests', function () { + beforeEach(function () { + nock.disableNetConnect(); + }); - afterEach(function() { - nock.cleanAll(); + afterEach(function () { + nock.cleanAll(); nock.enableNetConnect(); - }); + }); var dummyResponse = { - 'results': [{ - 'uuid': 'encounter-uuid-for-first-element', - 'display': 'ADULTRETURN 01/02/2006', - }, { - 'uuid': 'bf218490-1691-11df-97a5-7038c432aabf', - 'display': 'ADULTRETURN 07/02/2006', - 'links': [{ - 'uri': testRestUrl + '/ws/rest/v1/encounter/bf218490-1691-11df-97a5-7038c432aabf', - 'rel': 'self' - }] - }] - } - - it('Should have encounter service defined', function() { + results: [ + { + uuid: 'encounter-uuid-for-first-element', + display: 'ADULTRETURN 01/02/2006' + }, + { + uuid: 'bf218490-1691-11df-97a5-7038c432aabf', + display: 'ADULTRETURN 07/02/2006', + links: [ + { + uri: + testRestUrl + + '/ws/rest/v1/encounter/bf218490-1691-11df-97a5-7038c432aabf', + rel: 'self' + } + ] + } + ] + }; + + it('Should have encounter service defined', function () { expect(encounterService).to.exists; }); - it('getPatientEncounters Should make a call to retrieve a list of ' + - 'encounters for a patient', function() { - var params = { - patientUuid: 'patient-uuid', - rep: 'ref', - openmrsBaseUrl: testRestUrl - }; - var request = nock(testRestUrl) - .get('/ws/rest/v1/encounter') - .query({ patient: params.patientUuid, v: params.rep }) - .reply(200, dummyResponse); - - var promise = encounterService.getPatientEncounters(params); - - expect(promise).to.be.resolved; - expect(promise).to.eventually.deep.equal(dummyResponse.results); - }); + it( + 'getPatientEncounters Should make a call to retrieve a list of ' + + 'encounters for a patient', + function () { + var params = { + patientUuid: 'patient-uuid', + rep: 'ref', + openmrsBaseUrl: testRestUrl + }; + var request = nock(testRestUrl) + .get('/ws/rest/v1/encounter') + .query({ patient: params.patientUuid, v: params.rep }) + .reply(200, dummyResponse); + + var promise = encounterService.getPatientEncounters(params); + + expect(promise).to.be.resolved; + expect(promise).to.eventually.deep.equal(dummyResponse.results); + } + ); }); })(); diff --git a/test/service/openmrs-rest/patient.service.test.js b/test/service/openmrs-rest/patient.service.test.js index d01c6df74..a34f6e131 100755 --- a/test/service/openmrs-rest/patient.service.test.js +++ b/test/service/openmrs-rest/patient.service.test.js @@ -1,230 +1,221 @@ (function () { - 'use strict' - var chai = require('chai'); - var chaiAsPromised = require('chai-as-promised'); - var nock = require('nock'); - var testRestUrl = 'http://testingurl:8080/openmrs'; - var patientService = require('../../../service/openmrs-rest/patient.service.js'); - - // Some setup - var expect = chai.expect; - chai.use(chaiAsPromised); - - describe('Open MRS Patient Service Unit Tests', function () { - beforeEach(function () { - nock.disableNetConnect(); + 'use strict'; + var chai = require('chai'); + var chaiAsPromised = require('chai-as-promised'); + var nock = require('nock'); + var testRestUrl = 'http://testingurl:8080/openmrs'; + var patientService = require('../../../service/openmrs-rest/patient.service.js'); + + // Some setup + var expect = chai.expect; + chai.use(chaiAsPromised); + + describe('Open MRS Patient Service Unit Tests', function () { + beforeEach(function () { + nock.disableNetConnect(); + }); + + afterEach(function () { + nock.cleanAll(); + nock.enableNetConnect(); + }); + + var dummyResponse = { + results: [ + { + uuid: 'uuid 1', + display: 'Test Patient One' + } + ] + }; + + it('Should have encounter service defined', function () { + expect(patientService).to.exists; + }); + + it( + 'getPatientUuidByUuid should make a call to retrieve a' + + 'patient by uuid', + function (done) { + var uuid = 'some-patient-uuid'; + var params = { + rep: 'ref', + openmrsBaseUrl: testRestUrl + }; + + var dummyRes = { + uuid: 'some-patient-uuid' + }; + + var request = nock(testRestUrl) + .get('/ws/rest/v1/patient/' + uuid) + .query({ v: params.rep }) + .reply(200, dummyRes); + + var promise = patientService.getPatientByUuid(uuid, params); + + promise.then(function (response) { + expect(response).to.deep.equal(dummyRes); + done(); + }); + } + ); + + it('getPatientUuidByUuid should respond with an error incase of error ', function (done) { + var uuid = 'some-patient-uuid2'; + var params = { + rep: 'ref', + openmrsBaseUrl: testRestUrl + }; + + var request = nock(testRestUrl) + .get('/ws/rest/v1/patient/' + uuid) + .query({ v: params.rep }) + .replyWithError({ + message: 'timed out', + code: 500 }); - afterEach(function () { - nock.cleanAll(); - nock.enableNetConnect(); + var promise = patientService.getPatientByUuid(uuid, params); + + promise + .then(function (response) { + expect(true).to.be.false; + done(); + }) + .catch(function (error) { + expect(error.error.message).to.equal('timed out'); + done(); }); + }); - var dummyResponse = { - 'results': [ - { - 'uuid': 'uuid 1', - 'display': 'Test Patient One', - } - ] + it( + 'getPatientUuidByIdentifier should make a call to retrieve a list of ' + + 'patients by identifier', + function (done) { + var params = { + q: 'patient-id', + rep: 'ref', + openmrsBaseUrl: testRestUrl }; + var request = nock(testRestUrl) + .get('/ws/rest/v1/patient') + .query({ q: params.q, v: params.rep }) + .reply(200, dummyResponse); + + var promise = patientService.getPatientByIdentifier(params); + + promise.then(function (response) { + expect(response).to.deep.equal(dummyResponse.results); + done(); + }); + } + ); + + it('getPatientUuidByIdentifier should respond with an error incase of error ', function (done) { + var params = { + q: 'patient-id2', + rep: 'ref', + openmrsBaseUrl: testRestUrl + }; + var request = nock(testRestUrl) + .get('/ws/rest/v1/patient') + .query({ q: params.q, v: params.rep }) + .replyWithError({ + message: 'timed out', + code: 500 + }); + + var promise = patientService.getPatientByIdentifier(params); + + promise + .then(function (response) { + expect(true).to.be.false; + done(); + }) + .catch(function (error) { + expect(error.error.message).to.equal('timed out'); + done(); + }); + }); + + it('should fetch patient uuids by patient ids', function (done) { + var params = { + q: 'id 1', + rep: 'default', + openmrsBaseUrl: testRestUrl + }; + var request = nock(testRestUrl) + .get('/ws/rest/v1/patient') + .query({ q: params.q, v: params.rep }) + .reply(200, { + results: [ + { + uuid: 'uuid 1', + display: 'Test Patient 1' + } + ] + }); - it('Should have encounter service defined', function () { - expect(patientService).to.exists; + var params2 = { + q: 'id 2', + rep: 'default', + openmrsBaseUrl: testRestUrl + }; + + var request2 = nock(testRestUrl) + .get('/ws/rest/v1/patient') + .query({ q: params2.q, v: params2.rep }) + .reply(200, { + results: [ + { + uuid: 'uuid 2', + display: 'Test Patient 2' + } + ] }); - it('getPatientUuidByUuid should make a call to retrieve a' + - 'patient by uuid', function (done) { - var uuid = 'some-patient-uuid'; - var params = { - rep: 'ref', - openmrsBaseUrl: testRestUrl - }; - - var dummyRes = { - uuid: 'some-patient-uuid' - }; - - var request = nock(testRestUrl) - .get('/ws/rest/v1/patient/' + uuid) - .query({ v: params.rep }) - .reply(200, dummyRes); - - var promise = patientService.getPatientByUuid(uuid, params); - - promise.then(function (response) { - expect(response).to.deep.equal(dummyRes); - done(); - }); - - }); - - it('getPatientUuidByUuid should respond with an error incase of error ', - function (done) { - var uuid = 'some-patient-uuid2'; - var params = { - rep: 'ref', - openmrsBaseUrl: testRestUrl - }; - - var request = nock(testRestUrl) - .get('/ws/rest/v1/patient/' + uuid) - .query({ v: params.rep }) - .replyWithError( - { - message: 'timed out', - code: 500 - } - ); - - var promise = patientService.getPatientByUuid(uuid, params); - - promise - .then(function (response) { - expect(true).to.be.false; - done(); - }) - .catch(function (error) { - expect(error.error.message).to.equal('timed out'); - done(); - }); - - }); - - it('getPatientUuidByIdentifier should make a call to retrieve a list of ' + - 'patients by identifier', function (done) { - var params = { - q: 'patient-id', - rep: 'ref', - openmrsBaseUrl: testRestUrl - }; - var request = nock(testRestUrl) - .get('/ws/rest/v1/patient') - .query({ q: params.q, v: params.rep }) - .reply(200, dummyResponse); - - var promise = patientService.getPatientByIdentifier(params); - - promise.then(function (response) { - expect(response).to.deep.equal(dummyResponse.results); - done(); - }); - - }); - - it('getPatientUuidByIdentifier should respond with an error incase of error ', - function (done) { - var params = { - q: 'patient-id2', - rep: 'ref', - openmrsBaseUrl: testRestUrl - }; - var request = nock(testRestUrl) - .get('/ws/rest/v1/patient') - .query({ q: params.q, v: params.rep }) - .replyWithError( - { - message: 'timed out', - code: 500 - } - ); - - var promise = patientService.getPatientByIdentifier(params); - - promise - .then(function (response) { - expect(true).to.be.false; - done(); - }) - .catch(function (error) { - expect(error.error.message).to.equal('timed out'); - done(); - }); - - }); - - it('should fetch patient uuids by patient ids', - function (done) { - - var params = { - q: 'id 1', - rep: 'default', - openmrsBaseUrl: testRestUrl - }; - var request = nock(testRestUrl) - .get('/ws/rest/v1/patient') - .query({ q: params.q, v: params.rep }) - .reply(200, { - 'results': [ - { - 'uuid': 'uuid 1', - 'display': 'Test Patient 1', - } - ] - }); - - var params2 = { - q: 'id 2', - rep: 'default', - openmrsBaseUrl: testRestUrl - }; - - var request2 = nock(testRestUrl) - .get('/ws/rest/v1/patient') - .query({ q: params2.q, v: params2.rep }) - .reply(200, { - 'results': [ - { - 'uuid': 'uuid 2', - 'display': 'Test Patient 2', - } - ] - }); - - var params3 = { - q: 'id 3', - rep: 'ref', - openmrsBaseUrl: testRestUrl - }; - - var request2 = nock(testRestUrl) - .get('/ws/rest/v1/patient') - .query({ q: params3.q, v: params3.rep }) - .replyWithError( - { - message: 'timed out', - code: 500 - } - ); - - - var promise = patientService.getPatientUuidsByIdentifiers(['id 1', 'id 2', 'id 3'], testRestUrl); - - promise - .then(function (response) { - expect(response).to.deep.equal( - [ - { - identifier: 'id 1', - patientUuid: 'uuid 1' - }, - { - identifier: 'id 2', - patientUuid: 'uuid 2' - }, - { - identifier: 'id 3', - hasError: true - } - ] - ); - done(); - }) - .catch(function (error) { - expect(true).to.be.false; - done(); - }); - - }); + var params3 = { + q: 'id 3', + rep: 'ref', + openmrsBaseUrl: testRestUrl + }; + + var request2 = nock(testRestUrl) + .get('/ws/rest/v1/patient') + .query({ q: params3.q, v: params3.rep }) + .replyWithError({ + message: 'timed out', + code: 500 + }); + + var promise = patientService.getPatientUuidsByIdentifiers( + ['id 1', 'id 2', 'id 3'], + testRestUrl + ); + + promise + .then(function (response) { + expect(response).to.deep.equal([ + { + identifier: 'id 1', + patientUuid: 'uuid 1' + }, + { + identifier: 'id 2', + patientUuid: 'uuid 2' + }, + { + identifier: 'id 3', + hasError: true + } + ]); + done(); + }) + .catch(function (error) { + expect(true).to.be.false; + done(); + }); }); + }); })(); diff --git a/test/service/openmrs-rest/program.service.test.js b/test/service/openmrs-rest/program.service.test.js index 709dc77b3..d861b6aea 100755 --- a/test/service/openmrs-rest/program.service.test.js +++ b/test/service/openmrs-rest/program.service.test.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); var nock = require('nock'); @@ -10,79 +10,80 @@ var expect = chai.expect; chai.use(chaiAsPromised); describe('Open MRS Program Service Unit Tests', function () { - beforeEach(function () { - nock.disableNetConnect(); - }); - - afterEach(function () { - nock.cleanAll(); - nock.enableNetConnect(); - }); - - it('Should have patient service defined', function () { - expect(programService).to.exists; - }); - - it('should have getProgramEnrollmentByUuid make a call to retrieve a' + - 'patient program enrollment by uuid', function (done) { - var uuid = 'some-program-uuid'; - var params = { - rep: 'ref', - openmrsBaseUrl: testRestUrl - }; - - var dummyRes = { - uuid: 'some-program-uuid' - }; - - var request = nock(testRestUrl) - .get('/ws/rest/v1/programenrollment/' + uuid) - .query({ v: params.rep }) - .reply(200, dummyRes); - - var promise = programService.getProgramEnrollmentByUuid(uuid, params); - - promise.then(function (response) { - expect(response).to.deep.equal(dummyRes); - done(); - }); - + beforeEach(function () { + nock.disableNetConnect(); + }); + + afterEach(function () { + nock.cleanAll(); + nock.enableNetConnect(); + }); + + it('Should have patient service defined', function () { + expect(programService).to.exists; + }); + + it( + 'should have getProgramEnrollmentByUuid make a call to retrieve a' + + 'patient program enrollment by uuid', + function (done) { + var uuid = 'some-program-uuid'; + var params = { + rep: 'ref', + openmrsBaseUrl: testRestUrl + }; + + var dummyRes = { + uuid: 'some-program-uuid' + }; + + var request = nock(testRestUrl) + .get('/ws/rest/v1/programenrollment/' + uuid) + .query({ v: params.rep }) + .reply(200, dummyRes); + + var promise = programService.getProgramEnrollmentByUuid(uuid, params); + + promise.then(function (response) { + expect(response).to.deep.equal(dummyRes); + done(); + }); + } + ); + + it( + 'should have getProgramEnrollmentByUuid return an error when call to retrieve a' + + 'patient program enrollment by uuid fails', + function (done) { + var uuid = 'some-program-uuid'; + var params = { + rep: 'ref', + openmrsBaseUrl: testRestUrl + }; + + var dummyRes = { + uuid: 'some-program-uuid' + }; + + var request = nock(testRestUrl) + .get('/ws/rest/v1/programenrollment/' + uuid) + .query({ v: params.rep }) + .replyWithError({ + message: 'timed out', + code: 500 }); - it('should have getProgramEnrollmentByUuid return an error when call to retrieve a' + - 'patient program enrollment by uuid fails', function (done) { - var uuid = 'some-program-uuid'; - var params = { - rep: 'ref', - openmrsBaseUrl: testRestUrl - }; - - var dummyRes = { - uuid: 'some-program-uuid' - }; - - var request = nock(testRestUrl) - .get('/ws/rest/v1/programenrollment/' + uuid) - .query({ v: params.rep }) - .replyWithError( - { - message: 'timed out', - code: 500 - } - ); - - var promise = programService.getProgramEnrollmentByUuid(uuid, params); - - promise - .then(function (response) { - expect(true).to.be.false; - done(); - }) - .catch(function (error) { - expect(error.error.message).to.equal('timed out'); - done(); - }); + var promise = programService.getProgramEnrollmentByUuid(uuid, params); + promise + .then(function (response) { + expect(true).to.be.false; + done(); + }) + .catch(function (error) { + expect(error.error.message).to.equal('timed out'); + done(); }); - -}); \ No newline at end of file + } + ); +}); diff --git a/test/service/patient-list-compare.service.test.js b/test/service/patient-list-compare.service.test.js index c5a340a92..594ae72a0 100755 --- a/test/service/patient-list-compare.service.test.js +++ b/test/service/patient-list-compare.service.test.js @@ -9,116 +9,106 @@ var expect = chai.expect; chai.use(sinonChai); describe('Patient List COMPARE TESTS', function () { - - beforeEach(function (done) { - - done(); - }); - - afterEach(function () { - - }); - - it('should load eid-obs-compare module', - function () { - expect(listCompare).to.be.defined; - }); - - it('should compare 2 patient lists and output the comparison details', - function () { - var incomingList = [ - { - person_id: 1 - }, - { - person_id: 2 - }, - { - person_id: 3 - }, - { - person_id: 4 - } - - ]; - - var pocList = [ - { - person_id: 3 - }, - { - person_id: 4 - }, - { - person_id: 5 - }, - { - person_id: 6 - } - ]; - - var expectedSetDifference = { - both: [ - { - person_id: 3 - }, - { - person_id: 4 - } - ], - onlyPoc: [ - { - person_id: 5 - }, - { - person_id: 6 - } - ], - onlyIncoming: [ - { - person_id: 1 - }, - { - person_id: 2 - } - ] - , - summaryStats: { - totalPoc: 4, - totalIncoming: 4, - totalBoth: 2, - totalOnlyPoc: 2, - totalOnlyIncoming: 2 - } - }; - - var actual = listCompare.fullPatientListComparison(incomingList, pocList); - - expect(actual).to.deep.equal(expectedSetDifference); - }); - - it('should transform patient ids to patient objects', - function () { - var patientObjects = [ - { - person_id: 1 - }, - { - person_id: 2 - }, - { - person_id: 3 - }, - { - person_id: 4 - } - ]; - - var patientIds = [1, 2, 3, 4]; - - var actual = listCompare.toArrayOfPatientObjects(patientIds); - - expect(actual).to.deep.equal(patientObjects); - }); - + beforeEach(function (done) { + done(); + }); + + afterEach(function () {}); + + it('should load eid-obs-compare module', function () { + expect(listCompare).to.be.defined; + }); + + it('should compare 2 patient lists and output the comparison details', function () { + var incomingList = [ + { + person_id: 1 + }, + { + person_id: 2 + }, + { + person_id: 3 + }, + { + person_id: 4 + } + ]; + + var pocList = [ + { + person_id: 3 + }, + { + person_id: 4 + }, + { + person_id: 5 + }, + { + person_id: 6 + } + ]; + + var expectedSetDifference = { + both: [ + { + person_id: 3 + }, + { + person_id: 4 + } + ], + onlyPoc: [ + { + person_id: 5 + }, + { + person_id: 6 + } + ], + onlyIncoming: [ + { + person_id: 1 + }, + { + person_id: 2 + } + ], + summaryStats: { + totalPoc: 4, + totalIncoming: 4, + totalBoth: 2, + totalOnlyPoc: 2, + totalOnlyIncoming: 2 + } + }; + + var actual = listCompare.fullPatientListComparison(incomingList, pocList); + + expect(actual).to.deep.equal(expectedSetDifference); + }); + + it('should transform patient ids to patient objects', function () { + var patientObjects = [ + { + person_id: 1 + }, + { + person_id: 2 + }, + { + person_id: 3 + }, + { + person_id: 4 + } + ]; + + var patientIds = [1, 2, 3, 4]; + + var actual = listCompare.toArrayOfPatientObjects(patientIds); + + expect(actual).to.deep.equal(patientObjects); + }); }); diff --git a/test/service/patient-reminder.service.test.js b/test/service/patient-reminder.service.test.js index 5018e3532..1bfc1b7ad 100755 --- a/test/service/patient-reminder.service.test.js +++ b/test/service/patient-reminder.service.test.js @@ -8,186 +8,184 @@ var expect = chai.expect; chai.use(sinonChai); describe('Patient Reminder Service Unit Tests', function () { + beforeEach(function (done) { + done(); + }); - beforeEach(function (done) { + afterEach(function () {}); - done(); - }); + it('should load patient reminder module', function () { + expect(patientReminder).to.be.defined; + }); - afterEach(function () { - - }); - - it('should load patient reminder module', - function () { - expect(patientReminder).to.be.defined; - }); + it('should preprocess patient reminder results', function () { + var initialResult = { + startIndex: 0, + size: 1, + result: [ + { + last_encounter_date: '2016-07-18T21:00:00.000Z', + person_id: 334192, + person_uuid: 'patient-uuid', + arv_start_date: '2012-01-23T21:00:00.000Z', + cur_arv_meds: '630 ## 633', + viral_load: 0, + vl_order_date: '2015-04-14T21:00:00.000Z', + last_vl_date: '2014-06-11T21:00:00.000Z', + vl_error: null, + vl_error_date: '2016-07-18T21:00:00.000Z', + ordered_vl_has_error: 1, + vl_error_order_date: '2016-07-18T21:00:00.000Z', + tb_prophylaxis_end_date: null, + tb_prophylaxis_start_date: null, + inh_treatment_days_remaining: null, + needs_vl_coded: 3, + overdue_vl_lab_order: 0, + new_viral_load_present: 0, + months_since_last_vl_date: 32, + is_on_inh_treatment: 0, + qualifies_enhanced: 0, + is_pregnant: 0, + is_postnatal: 0, + is_infant: 0, + dna_pcr_reminder: 0, + has_gene_xpert_result: 0, + has_dst_result: 0 + } + ] + }; - it('should preprocess patient reminder results', - function () { - var initialResult = { - "startIndex": 0, - "size": 1, - "result": [ - { - "last_encounter_date": "2016-07-18T21:00:00.000Z", - "person_id": 334192, - "person_uuid": "patient-uuid", - "arv_start_date": "2012-01-23T21:00:00.000Z", - "cur_arv_meds": "630 ## 633", - "viral_load": 0, - "vl_order_date": "2015-04-14T21:00:00.000Z", - "last_vl_date": "2014-06-11T21:00:00.000Z", - "vl_error": null, - "vl_error_date": "2016-07-18T21:00:00.000Z", - "ordered_vl_has_error": 1, - "vl_error_order_date": "2016-07-18T21:00:00.000Z", - "tb_prophylaxis_end_date": null, - "tb_prophylaxis_start_date": null, - "inh_treatment_days_remaining": null, - "needs_vl_coded": 3, - "overdue_vl_lab_order": 0, - "new_viral_load_present": 0, - "months_since_last_vl_date": 32, - "is_on_inh_treatment": 0, - "qualifies_enhanced": 0, - "is_pregnant": 0, - "is_postnatal": 0, - "is_infant": 0, - "dna_pcr_reminder": 0, - "has_gene_xpert_result": 0, - "has_dst_result": 0 - } - ] - }; + var processedResults = { + startIndex: 0, + size: 1, + result: { + person_id: 334192, + person_uuid: 'patient-uuid', + reminders: [ + { + message: + 'Viral load test that was ordered on: (19-07-2016)' + + ' resulted to an error. Please re-order.', + title: 'Lab Error Reminder', + type: 'danger', + display: { + banner: true, + toast: true + } + }, + { + message: + 'Patient requires viral load. Patients older than 25 years and on ART > 1 year' + + ' require a viral load test every year. Last viral load: LDL on' + + ' (12-06-2014) 32 months ago.', + title: 'Viral Load Reminder', + type: 'danger', + display: { + banner: true, + toast: true + } + } + ] + } + }; - var processedResults = { - "startIndex": 0, - "size": 1, - "result": { - "person_id": 334192, - "person_uuid": "patient-uuid", - "reminders": [ - { - "message": "Viral load test that was ordered on: (19-07-2016)" + - " resulted to an error. Please re-order.", - "title": "Lab Error Reminder", - "type": "danger", - "display": { - "banner": true, - "toast": true - } - }, - { - "message": "Patient requires viral load. Patients older than 25 years and on ART > 1 year" + - " require a viral load test every year. Last viral load: LDL on" + - " (12-06-2014) 32 months ago.", - "title": "Viral Load Reminder", - "type": "danger", - "display": { - "banner": true, - "toast": true - } - } - ] - } - }; - - var eidResults = { - viralLoad: [] - }; + var eidResults = { + viralLoad: [] + }; + var processedReminder = patientReminder.generateReminders( + initialResult.result, + eidResults + ); - var processedReminder = patientReminder.generateReminders(initialResult.result, eidResults); + expect(processedReminder).to.deep.equal(processedResults.result); + }); - expect(processedReminder).to.deep.equal(processedResults.result); - }); - - it('should return pending lab order when it exists in EID', - function () { - var initialResult = { - "startIndex": 0, - "size": 1, - "result": [ - { - "last_encounter_date": "2016-07-18T21:00:00.000Z", - "person_id": 334192, - "person_uuid": "patient-uuid", - "arv_start_date": "2012-01-23T21:00:00.000Z", - "cur_arv_meds": "630 ## 633", - "viral_load": 0, - "vl_order_date": "2015-04-14T21:00:00.000Z", - "last_vl_date": "2014-06-11T21:00:00.000Z", - "vl_error": null, - "vl_error_date": "2016-07-18T21:00:00.000Z", - "ordered_vl_has_error": 1, - "vl_error_order_date": "2016-07-18T21:00:00.000Z", - "tb_prophylaxis_end_date": null, - "tb_prophylaxis_start_date": null, - "inh_treatment_days_remaining": null, - "needs_vl_coded": 3, - "overdue_vl_lab_order": 0, - "new_viral_load_present": 0, - "months_since_last_vl_date": 32, - "is_on_inh_treatment": 0, - "qualifies_enhanced": 0, - "is_pregnant": 0, - "is_postnatal": 0, - "is_infant": 0, - "dna_pcr_reminder": 0, - "has_gene_xpert_result": 0, - "has_dst_result": 0 - } - ] - }; - var processedResults = { - "startIndex": 0, - "size": 1, - "result": { - "person_id": 334192, - "person_uuid": "patient-uuid", - "reminders": [ - { - "message": "Patient lab Order No. is currently being processed. Sample collected" + - " on 15-05-2017).", - "title": "Pending Lab Order Result", - "type": "info", - "display": { - "banner": true, - "toast": true - } - } - ] + it('should return pending lab order when it exists in EID', function () { + var initialResult = { + startIndex: 0, + size: 1, + result: [ + { + last_encounter_date: '2016-07-18T21:00:00.000Z', + person_id: 334192, + person_uuid: 'patient-uuid', + arv_start_date: '2012-01-23T21:00:00.000Z', + cur_arv_meds: '630 ## 633', + viral_load: 0, + vl_order_date: '2015-04-14T21:00:00.000Z', + last_vl_date: '2014-06-11T21:00:00.000Z', + vl_error: null, + vl_error_date: '2016-07-18T21:00:00.000Z', + ordered_vl_has_error: 1, + vl_error_order_date: '2016-07-18T21:00:00.000Z', + tb_prophylaxis_end_date: null, + tb_prophylaxis_start_date: null, + inh_treatment_days_remaining: null, + needs_vl_coded: 3, + overdue_vl_lab_order: 0, + new_viral_load_present: 0, + months_since_last_vl_date: 32, + is_on_inh_treatment: 0, + qualifies_enhanced: 0, + is_pregnant: 0, + is_postnatal: 0, + is_infant: 0, + dna_pcr_reminder: 0, + has_gene_xpert_result: 0, + has_dst_result: 0 } - }; - - var eidResults = { - viralLoad: [ + ] + }; + var processedResults = { + startIndex: 0, + size: 1, + result: { + person_id: 334192, + person_uuid: 'patient-uuid', + reminders: [ { - "LabID": "1", - "OrderNo": "", - "PatientID": "123", - "ProviderID": "", - "MFLCode": "1", - "AMRslocationID": "", - "AMRslocation": "", - "PatientNames": "", - "DateCollected": "15-May-2017", - "DateReceived": "17-May-2017", - "DateTested": "22-May-2017", - "Result": "Target Not Detected", - "FinalResult": "< LDL copies/ml", - "DateDispatched": "23-May-2017", - "SampleStatus": "Complete" + message: + 'Patient lab Order No. is currently being processed. Sample collected' + + ' on 15-05-2017).', + title: 'Pending Lab Order Result', + type: 'info', + display: { + banner: true, + toast: true + } } ] - }; - - var processedReminder = patientReminder.generateReminders(initialResult.result, eidResults); - - expect(processedReminder).to.deep.equal(processedResults.result); - }); + } + }; + var eidResults = { + viralLoad: [ + { + LabID: '1', + OrderNo: '', + PatientID: '123', + ProviderID: '', + MFLCode: '1', + AMRslocationID: '', + AMRslocation: '', + PatientNames: '', + DateCollected: '15-May-2017', + DateReceived: '17-May-2017', + DateTested: '22-May-2017', + Result: 'Target Not Detected', + FinalResult: '< LDL copies/ml', + DateDispatched: '23-May-2017', + SampleStatus: 'Complete' + } + ] + }; + var processedReminder = patientReminder.generateReminders( + initialResult.result, + eidResults + ); + expect(processedReminder).to.deep.equal(processedResults.result); + }); }); diff --git a/uninstall-deamon.js b/uninstall-deamon.js index 79d14761e..9f8f357bb 100755 --- a/uninstall-deamon.js +++ b/uninstall-deamon.js @@ -2,14 +2,14 @@ var Service = require('node-linux').Service; // Create a new service object var svc = new Service({ - name:'Etl Server', - script: require('path').join('/home/werick/etl-rest-server/etl-server.js') - }); + name: 'Etl Server', + script: require('path').join('/home/werick/etl-rest-server/etl-server.js') +}); // Listen for the "uninstall" event so we know when it's done. -svc.on('uninstall', function() { - console.log('Uninstall complete.'); - console.log('The service exists: ', svc.exists); - }); +svc.on('uninstall', function () { + console.log('Uninstall complete.'); + console.log('The service exists: ', svc.exists); +}); // Uninstall the service. svc.uninstall(); diff --git a/visit-type/visit-type-service.js b/visit-type/visit-type-service.js index d10a017fd..c483d5b20 100755 --- a/visit-type/visit-type-service.js +++ b/visit-type/visit-type-service.js @@ -1,110 +1,89 @@ -var Promise = require("bluebird"); +var Promise = require('bluebird'); var visitTypeDao = require('../dao/visit-type/visit-type-dao'); const _ = require('lodash'); var visitTypes = []; var visitTypeUuidIdMap = new Map(); var def = { - getAllVisitTypes: getAllVisitTypes, - mapvisitTypeUuidToId: mapvisitTypeUuidToId, - loadAndMapVisitTypeUuidToId : loadAndMapVisitTypeUuidToId, - getVisitTypeIdFromUuid: getVisitTypeIdFromUuid + getAllVisitTypes: getAllVisitTypes, + mapvisitTypeUuidToId: mapvisitTypeUuidToId, + loadAndMapVisitTypeUuidToId: loadAndMapVisitTypeUuidToId, + getVisitTypeIdFromUuid: getVisitTypeIdFromUuid }; module.exports = def; - -function getAllVisitTypes(){ - - /* +function getAllVisitTypes() { + /* returns a list of all encunter-types with their id and uuid */ return new Promise(function (resolve, reject) { - - if(visitTypes.length > 0){ - - // console.log('Visit Type length > 0'); - - resolve(visitTypes); - - }else{ - - // console.log('Visit Type length < 0'); - - visitTypeDao.getVisitTypes().then(function (result) { - if(result){ - visitTypes = result; - // console.log('All Visit Types'); - resolve(visitTypes); - }else{ - // console.log('All Visit Error'); - reject('error'); - } - }) - .catch(function (error) { - reject('error'); - }); - - - } - - - - }); - - - + if (visitTypes.length > 0) { + // console.log('Visit Type length > 0'); + + resolve(visitTypes); + } else { + // console.log('Visit Type length < 0'); + + visitTypeDao + .getVisitTypes() + .then(function (result) { + if (result) { + visitTypes = result; + // console.log('All Visit Types'); + resolve(visitTypes); + } else { + // console.log('All Visit Error'); + reject('error'); + } + }) + .catch(function (error) { + reject('error'); + }); + } + }); } -function mapvisitTypeUuidToId(visitTypes){ - // console.log('Got VisitTypes', visitTypes); +function mapvisitTypeUuidToId(visitTypes) { + // console.log('Got VisitTypes', visitTypes); - _.each(visitTypes,(visitType, index) => { - // console.log('Specific Visit Type', visitType) - visitTypeUuidIdMap.set( visitType.uuid , visitType.visit_type_id); - }); - - return visitTypeUuidIdMap; + _.each(visitTypes, (visitType, index) => { + // console.log('Specific Visit Type', visitType) + visitTypeUuidIdMap.set(visitType.uuid, visitType.visit_type_id); + }); + return visitTypeUuidIdMap; } -function getVisitTypeIdFromUuid(visitTypeUuid){ - - var visitObj = visitTypeUuidIdMap.get(visitTypeUuid); - - if(typeof visitObj === 'undefined'){ - return -1; - }else{ - return visitObj; - } +function getVisitTypeIdFromUuid(visitTypeUuid) { + var visitObj = visitTypeUuidIdMap.get(visitTypeUuid); + if (typeof visitObj === 'undefined') { + return -1; + } else { + return visitObj; + } } -function loadAndMapVisitTypeUuidToId(){ - - return new Promise(function (resolve, reject) { - - getAllVisitTypes() - .then((result) => { - if(result){ - // console.log('Got Visit TYpes'); - visitTypeUuidIdMap = mapvisitTypeUuidToId(result); - resolve(visitTypeUuidIdMap); - }else{ - // console.log('Got No Visit TYpes'); - resolve({}); - } - }) - .catch(((error) =>{ - // console.log('Got Visit TYpes Error', error); - reject('Error'); - })); - - }); - +function loadAndMapVisitTypeUuidToId() { + return new Promise(function (resolve, reject) { + getAllVisitTypes() + .then((result) => { + if (result) { + // console.log('Got Visit TYpes'); + visitTypeUuidIdMap = mapvisitTypeUuidToId(result); + resolve(visitTypeUuidIdMap); + } else { + // console.log('Got No Visit TYpes'); + resolve({}); + } + }) + .catch((error) => { + // console.log('Got Visit TYpes Error', error); + reject('Error'); + }); + }); } - - diff --git a/worker/add-location-enroll-into-hiv-program.js b/worker/add-location-enroll-into-hiv-program.js index 454846fa5..2a9989a40 100755 --- a/worker/add-location-enroll-into-hiv-program.js +++ b/worker/add-location-enroll-into-hiv-program.js @@ -1,106 +1,122 @@ -var fs = require('fs') - , util = require('util') - , stream = require('stream') - , moment = require('moment') - , curl = require('curlrequest') - , es = require('event-stream'); +var fs = require('fs'), + util = require('util'), + stream = require('stream'), + moment = require('moment'), + curl = require('curlrequest'), + es = require('event-stream'); var https = require('http'); var config = require('../conf/config'); var lineNr = 0; - var input_file = './location_enrollment.csv'; var error_file = './location_enrollment_failed.csv'; var enrollmentUuid = ''; fs.exists(error_file, function (exists) { - if (exists) { - fs.unlink(error_file, function (err) { - if (err) throw err; - console.log('successfully deleted ' + error_file); - }); - } + if (exists) { + fs.unlink(error_file, function (err) { + if (err) throw err; + console.log('successfully deleted ' + error_file); + }); + } }); function createPayload(inputLine) { - let column = inputLine.split(','); - let ampathHivProgram = { uuid: '781d85b0-1359-11df-a1f1-0026b9348838', name: 'HIV TREATMENT' }; - let payload = { - location: column[1], - uuid:column[0] - }; - enrollmentUuid = column[0]; - return payload; + let column = inputLine.split(','); + let ampathHivProgram = { + uuid: '781d85b0-1359-11df-a1f1-0026b9348838', + name: 'HIV TREATMENT' + }; + let payload = { + location: column[1], + uuid: column[0] + }; + enrollmentUuid = column[0]; + return payload; } -var s = fs.createReadStream(input_file) - .pipe(es.split()) - .pipe(es.mapSync(function (line) { +var s = fs + .createReadStream(input_file) + .pipe(es.split()) + .pipe( + es + .mapSync(function (line) { // pause the readstream s.pause(); lineNr += 1; try { - if (line && line !== '') { - console.log('Updating existing enrollment to have location: ', line); - var openmrsAppName = config.openmrs.applicationName || 'amrs'; - let payload = createPayload(line); - - var protocol = config.openmrs.https ? 'https' : 'http'; - //JSON.stringify(createPayload(line)); - var url = protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + '/' + openmrsAppName + '/ws/rest/v1/programenrollment/' + - payload.uuid; - delete payload['uuid']; - payload = JSON.stringify(payload); - console.log('url===', url); - - var usernamePass = config.eidSyncCredentials.username + ":" + config.eidSyncCredentials.password; - var auth = "Basic " + new Buffer(usernamePass).toString('base64'); - - var options = { - - url: url, - data: payload, - headers: { - 'Content-Type': 'application/json', - 'Authorization': auth - }, - method: 'POST' - }; - - curl.request(options, function (err, parts) { - - if (err || (parts && JSON.parse(parts).error)) { - console.log('error updating enrollment location to a program: ' + line, err || JSON.parse(parts).error); - fs.appendFileSync(error_file, line + '\r\n'); - } else { - console.log('updated enrollment location for program: ' + line); - } - - // resume the readstream, possibly from a callback - s.resume(); - - }); - } - - - + if (line && line !== '') { + console.log( + 'Updating existing enrollment to have location: ', + line + ); + var openmrsAppName = config.openmrs.applicationName || 'amrs'; + let payload = createPayload(line); + + var protocol = config.openmrs.https ? 'https' : 'http'; + //JSON.stringify(createPayload(line)); + var url = + protocol + + '://' + + config.openmrs.host + + ':' + + config.openmrs.port + + '/' + + openmrsAppName + + '/ws/rest/v1/programenrollment/' + + payload.uuid; + delete payload['uuid']; + payload = JSON.stringify(payload); + console.log('url===', url); + + var usernamePass = + config.eidSyncCredentials.username + + ':' + + config.eidSyncCredentials.password; + var auth = 'Basic ' + new Buffer(usernamePass).toString('base64'); + + var options = { + url: url, + data: payload, + headers: { + 'Content-Type': 'application/json', + Authorization: auth + }, + method: 'POST' + }; + + curl.request(options, function (err, parts) { + if (err || (parts && JSON.parse(parts).error)) { + console.log( + 'error updating enrollment location to a program: ' + line, + err || JSON.parse(parts).error + ); + fs.appendFileSync(error_file, line + '\r\n'); + } else { + console.log('updated enrollment location for program: ' + line); + } + + // resume the readstream, possibly from a callback + s.resume(); + }); + } } catch (error) { - console.error(error); - // resume the readstream, possibly from a callback - s.resume(); + console.error(error); + // resume the readstream, possibly from a callback + s.resume(); } - }) - .on('error', function () { - console.log('Error while reading file.'); - }) - .on('end', function () { - console.log('Read entire file.') - }) - ); + }) + .on('error', function () { + console.log('Error while reading file.'); + }) + .on('end', function () { + console.log('Read entire file.'); + }) + ); /* SELECT t1.patient_id, diff --git a/worker/auto-enroll-veremia.js b/worker/auto-enroll-veremia.js index d818318ad..f4c8496c5 100644 --- a/worker/auto-enroll-veremia.js +++ b/worker/auto-enroll-veremia.js @@ -1,5 +1,4 @@ -const - db = require('../etl-db'), +const db = require('../etl-db'), Promise = require('bluebird'), https = require('http'), config = require('../conf/config'), @@ -9,65 +8,66 @@ const program_config = require('../programs/patient-program-config'), patient_programs = require('../dao/enrollment/enrollment-patient-program-dao'), check_program_enrollment = require('../dao/enrollment/double-enrollment-check'); -const cron = require("node-cron"); - +const cron = require('node-cron'); var App = { - stateTracker: false, - start: function() { + start: function () { let _this = this; - this.loadQueueData() - .then(function(data) { - if (data.length > 0) { - App.process(data) - .then(function() { - return App.deleteProcessed(data) - }).then(function(deleted) { - - }).catch(function(err) { - console.log(err); - }) - } else { - console.log('No data in the queue', new Date()); - //process.exit(1); - } - }); + this.loadQueueData().then(function (data) { + if (data.length > 0) { + App.process(data) + .then(function () { + return App.deleteProcessed(data); + }) + .then(function (deleted) {}) + .catch(function (err) { + console.log(err); + }); + } else { + console.log('No data in the queue', new Date()); + //process.exit(1); + } + }); }, - process: function(data) { + process: function (data) { let arrayList = []; - let promise = new Promise(function(resolve, reject) { + let promise = new Promise(function (resolve, reject) { data.forEach((arrayItem) => { const key = arrayItem.program_uuid; const person_uuid = arrayItem.person_uuid; let list = []; - if (program_config[key].incompatibleWith && program_config[key].incompatibleWith.length > 0) { + if ( + program_config[key].incompatibleWith && + program_config[key].incompatibleWith.length > 0 + ) { list = program_config[key].incompatibleWith; - _.each(list, function(item) { - patient_programs.getPatientProgramEnrollment(person_uuid, list) - .then(function(rows) { + _.each(list, function (item) { + patient_programs + .getPatientProgramEnrollment(person_uuid, list) + .then(function (rows) { if (rows && rows.length !== 0) { - _.each(rows, function(row) { + _.each(rows, function (row) { App.unEnrollIfIncompatible(row.uuid); - resolve() - }) + resolve(); + }); App.enroll(person_uuid, key); } else { App.enroll(person_uuid, key); - resolve() + resolve(); } - }) - }) + }); + }); } else { App.enroll(person_uuid, key); - resolve() + resolve(); } - }) + }); }); return promise; }, - loadQueueData: function() { + loadQueueData: function () { let limit = 100; var sql = 'select * from etl.program_registration_queue limit ?'; @@ -75,14 +75,13 @@ var App = { query: sql, sqlParams: [limit] }; - return new Promise(function(resolve, reject) { - db.queryReportServer(qObject, function(data) { + return new Promise(function (resolve, reject) { + db.queryReportServer(qObject, function (data) { resolve(data.result); }); }); }, - unEnrollIfIncompatible: function(uuid) { - + unEnrollIfIncompatible: function (uuid) { let protocol = config.etl.tls ? 'https' : 'http'; let date = moment().format('YYYY-MM-DD'); @@ -91,44 +90,54 @@ var App = { let payload = { dateCompleted: date, uuid: uuid - } + }; - var url = protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + '/' + openmrsAppName + '/ws/rest/v1/programenrollment/' + + var url = + protocol + + '://' + + config.openmrs.host + + ':' + + config.openmrs.port + + '/' + + openmrsAppName + + '/ws/rest/v1/programenrollment/' + payload.uuid; delete payload['uuid']; payload = JSON.stringify(payload); - var usernamePass = config.eidSyncCredentials.username + ":" + config.eidSyncCredentials.password; - var auth = "Basic " + Buffer.from(usernamePass).toString('base64'); + var usernamePass = + config.eidSyncCredentials.username + + ':' + + config.eidSyncCredentials.password; + var auth = 'Basic ' + Buffer.from(usernamePass).toString('base64'); var options = { url: url, data: payload, headers: { 'Content-Type': 'application/json', - 'Authorization': auth + Authorization: auth }, method: 'POST' }; - return new Promise(function(resolve, reject) { - curl.request(options, function(err, parts) { + return new Promise(function (resolve, reject) { + curl.request(options, function (err, parts) { if (err || (parts && JSON.parse(parts).error)) { console.log(parts && JSON.parse(parts).error); console.log('error unenrolling to program'); - reject(err) + reject(err); //log error to file or db } else { console.log('unenrolling to program: '); - resolve('str') + resolve('str'); } }); - }) + }); }, - enroll: function(person_uuid, program_uuid) { - + enroll: function (person_uuid, program_uuid) { let dateEnrolled = moment().format('YYYY-MM-DD'); var openmrsAppName = config.openmrs.applicationName || 'amrs'; @@ -136,13 +145,23 @@ var App = { program: program_uuid, patient: person_uuid, dateEnrolled: dateEnrolled - - } + }; var protocol = config.openmrs.https ? 'https' : 'http'; - var url = protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + '/' + openmrsAppName + '/ws/rest/v1/programenrollment/'; - - var usernamePass = config.eidSyncCredentials.username + ":" + config.eidSyncCredentials.password; - var auth = "Basic " + Buffer.from(usernamePass).toString('base64'); + var url = + protocol + + '://' + + config.openmrs.host + + ':' + + config.openmrs.port + + '/' + + openmrsAppName + + '/ws/rest/v1/programenrollment/'; + + var usernamePass = + config.eidSyncCredentials.username + + ':' + + config.eidSyncCredentials.password; + var auth = 'Basic ' + Buffer.from(usernamePass).toString('base64'); payload = JSON.stringify(payload); @@ -151,43 +170,41 @@ var App = { data: payload, headers: { 'Content-Type': 'application/json', - 'Authorization': auth + Authorization: auth }, method: 'POST' }; - return new Promise(function(resolve, reject) { - - curl.request(options, function(err, parts) { - + return new Promise(function (resolve, reject) { + curl.request(options, function (err, parts) { if (err || (parts && JSON.parse(parts).error)) { - console.log((parts && JSON.parse(parts).error)); + console.log(parts && JSON.parse(parts).error); console.log('error enrolling patient into program'); //log to file or database - reject('error enrolling patient into viremia') + reject('error enrolling patient into viremia'); } else { console.log('Enrolled Patient Into Standard HIV Treatment'); resolve('Enrolled Patient Into Program'); } - }); - }) + }); }, - deleteProcessed: function(data) { + deleteProcessed: function (data) { let lst = []; for (var i = 0; i < data.length; i++) { var row = data[i]; lst.push(row.person_uuid); } - var sql = 'delete from etl.program_registration_queue where person_uuid in (?)'; + var sql = + 'delete from etl.program_registration_queue where person_uuid in (?)'; var qObject = { query: sql, sqlParams: [lst] - } - return new Promise(function(resolve, reject) { + }; + return new Promise(function (resolve, reject) { try { - db.queryReportServer(qObject, function(result) { + db.queryReportServer(qObject, function (result) { console.log(result); resolve(result); }); @@ -198,16 +215,16 @@ var App = { }); }, - init: function() { - cron.schedule('* * * * *',function(){ - try { - App.start(); - } catch (e) { - console.log(`Error occured when starting app ${e}`); - } - }) + init: function () { + cron.schedule('* * * * *', function () { + try { + App.start(); + } catch (e) { + console.log(`Error occured when starting app ${e}`); + } + }); } -} +}; App.init(); //module.exports = App; diff --git a/worker/eid-sync.js b/worker/eid-sync.js index 140a35294..5c14f9ff2 100755 --- a/worker/eid-sync.js +++ b/worker/eid-sync.js @@ -1,5 +1,4 @@ -var - db = require('../etl-db'), +var db = require('../etl-db'), Promise = require('bluebird'), https = require('http'), config = require('../conf/config'), @@ -7,7 +6,6 @@ var curl = require('curlrequest'); var Sync = { - timeout: 3000, nextSyncDateTime: moment().subtract(1, 'minute'), @@ -29,14 +27,11 @@ var Sync = { // load records from sync queue setInterval(function () { - - if (!Sync.processing) - Sync.process(); + if (!Sync.processing) Sync.process(); }, Sync.timeout); }, process: function () { - var today = new Date().getHours(); //sync records after working hours only @@ -45,9 +40,11 @@ var Sync = { // return; // } - // incase of server unavailability, postpone sync + // incase of server unavailability, postpone sync if (moment().isBefore(Sync.nextSyncDateTime)) { - console.log('Sync paused and will resume ' + Sync.nextSyncDateTime.fromNow()); + console.log( + 'Sync paused and will resume ' + Sync.nextSyncDateTime.fromNow() + ); console.log('Sync will resume at ' + Sync.nextSyncDateTime.format()); Sync.processing = false; return; @@ -63,35 +60,27 @@ var Sync = { // return; // } - this.loadDbRecords() - .then(function (data) { - - if (data.length > 0) { - - Sync.processing = true; - - Sync.sync(data) - .then(function () { - - return Sync.deleteProcessed(data); - }) - .then(function (deleted) { - - Sync.process(); - }) - .catch(function (err) { - - Sync.processing = false; - }); - - } else { - Sync.processing = false; - } - }); + this.loadDbRecords().then(function (data) { + if (data.length > 0) { + Sync.processing = true; + + Sync.sync(data) + .then(function () { + return Sync.deleteProcessed(data); + }) + .then(function (deleted) { + Sync.process(); + }) + .catch(function (err) { + Sync.processing = false; + }); + } else { + Sync.processing = false; + } + }); }, loadDbRecords: function () { - var limit = Sync.records_limit; var sql = 'select * from etl.eid_sync_queue limit ?'; @@ -109,11 +98,9 @@ var Sync = { }, sync: function (data) { - var list = []; for (var i = 0; i < data.length; i++) { - var row = data[i]; list.push(Sync.syncSingleRecord(row.person_uuid)); } @@ -122,34 +109,43 @@ var Sync = { }, syncSingleRecord: function (patientUuId) { - console.log('syncing single record. ' + patientUuId); var protocol = config.etl.tls ? 'https' : 'http'; - var url = protocol + '://' + config.etl.host + ':' + config.etl.port + '/etl/patient-lab-orders?patientUuId=' + patientUuId; - - var usernamePass = config.eidSyncCredentials.username + ":" + config.eidSyncCredentials.password; - var auth = "Basic " + new Buffer(usernamePass).toString('base64'); + var url = + protocol + + '://' + + config.etl.host + + ':' + + config.etl.port + + '/etl/patient-lab-orders?patientUuId=' + + patientUuId; + + var usernamePass = + config.eidSyncCredentials.username + + ':' + + config.eidSyncCredentials.password; + var auth = 'Basic ' + new Buffer(usernamePass).toString('base64'); var options = { url: url, headers: { - 'Authorization': auth + Authorization: auth } - } + }; return new Promise(function (resolve, reject) { - curl.request(options, function (err, parts) { - if (err) { if (err === 'Failed to connect to host.') { console.error('ETL Backend Service might be down.'); Sync.nextSyncDateTime = moment().add(10, 'minute'); } - console.log('error while syncing ' + patientUuId + '. Logging error.'); + console.log( + 'error while syncing ' + patientUuId + '. Logging error.' + ); Sync.logError(patientUuId, err) .then(function () { resolve('str'); @@ -161,14 +157,18 @@ var Sync = { console.log('syncing single record done. ' + patientUuId); resolve('str'); } - }); }); }, logError: function (patientUuId, error) { - var sql = "INSERT INTO etl.eid_sync_queue_errors(person_uuid, error, date_created)" + - " VALUES('" + patientUuId + "','" + error + "', NOW())"; + var sql = + 'INSERT INTO etl.eid_sync_queue_errors(person_uuid, error, date_created)' + + " VALUES('" + + patientUuId + + "','" + + error + + "', NOW())"; var queryObject = { query: sql, @@ -187,7 +187,6 @@ var Sync = { }, deleteProcessed: function (data) { - var lst = []; for (var i = 0; i < data.length; i++) { @@ -200,7 +199,7 @@ var Sync = { var qObject = { query: sql, sqlParams: [lst] - } + }; return new Promise(function (resolve, reject) { try { @@ -208,14 +207,13 @@ var Sync = { resolve(result); }); } catch (e) { - //TODO - ignoring delete resolve(e); } }); } -} +}; Sync.start(); -module.exports = Sync; \ No newline at end of file +module.exports = Sync; diff --git a/worker/enroll-into-hiv-program.js b/worker/enroll-into-hiv-program.js index 08134630d..dbd9b23e1 100755 --- a/worker/enroll-into-hiv-program.js +++ b/worker/enroll-into-hiv-program.js @@ -1,9 +1,9 @@ -var fs = require('fs') - , util = require('util') - , stream = require('stream') - , moment = require('moment') - , curl = require('curlrequest') - , es = require('event-stream'); +var fs = require('fs'), + util = require('util'), + stream = require('stream'), + moment = require('moment'), + curl = require('curlrequest'), + es = require('event-stream'); var https = require('http'); var config = require('../conf/config'); @@ -14,82 +14,101 @@ var input_file = './patients_not_enrolled.csv'; var error_file = './patient_enrollment_failed.csv'; fs.exists(error_file, function (exists) { - if (exists) { - fs.unlink(error_file, function (err) { - if (err) throw err; - console.log('successfully deleted ' + error_file); - }); - } + if (exists) { + fs.unlink(error_file, function (err) { + if (err) throw err; + console.log('successfully deleted ' + error_file); + }); + } }); function createPayload(inputLine) { - let column = inputLine.split(','); - let ampathHivProgram = { uuid: '781d85b0-1359-11df-a1f1-0026b9348838', name: 'Standard HIV TREATMENT' }; - let payload = { - program: ampathHivProgram.uuid, - patient: column[0], - dateEnrolled: column[1] - } - return payload; + let column = inputLine.split(','); + let ampathHivProgram = { + uuid: '781d85b0-1359-11df-a1f1-0026b9348838', + name: 'Standard HIV TREATMENT' + }; + let payload = { + program: ampathHivProgram.uuid, + patient: column[0], + dateEnrolled: column[1] + }; + return payload; } -var s = fs.createReadStream(input_file) - .pipe(es.split()) - .pipe(es.mapSync(function (line) { +var s = fs + .createReadStream(input_file) + .pipe(es.split()) + .pipe( + es + .mapSync(function (line) { // pause the readstream s.pause(); lineNr += 1; try { - if (line && line !== '') { - console.log('Enrolling a patient into Standard HIV Care Program: ', line); - var openmrsAppName = config.openmrs.applicationName || 'amrs'; - let payload = JSON.stringify(createPayload(line)); - var protocol = config.openmrs.https ? 'https' : 'http'; - var url = protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + '/' + openmrsAppName + '/ws/rest/v1/programenrollment/'; - - var usernamePass = config.eidSyncCredentials.username + ":" + config.eidSyncCredentials.password; - var auth = "Basic " + new Buffer(usernamePass).toString('base64'); - - var options = { - - url: url, - data: payload, - headers: { - 'Content-Type': 'application/json', - 'Authorization': auth - }, - method: 'POST' - }; - - curl.request(options, function (err, parts) { - - if (err || (parts && JSON.parse(parts).error)) { - console.log('error enrolling a patient into program: ' + line, err || JSON.parse(parts).error); - fs.appendFileSync(error_file, line + '\r\n'); - } else { - console.log('Enrolled Patient Into Standard HIV Treatment: ' + line); - } - - // resume the readstream, possibly from a callback - s.resume(); - - }); - } - - - + if (line && line !== '') { + console.log( + 'Enrolling a patient into Standard HIV Care Program: ', + line + ); + var openmrsAppName = config.openmrs.applicationName || 'amrs'; + let payload = JSON.stringify(createPayload(line)); + var protocol = config.openmrs.https ? 'https' : 'http'; + var url = + protocol + + '://' + + config.openmrs.host + + ':' + + config.openmrs.port + + '/' + + openmrsAppName + + '/ws/rest/v1/programenrollment/'; + + var usernamePass = + config.eidSyncCredentials.username + + ':' + + config.eidSyncCredentials.password; + var auth = 'Basic ' + new Buffer(usernamePass).toString('base64'); + + var options = { + url: url, + data: payload, + headers: { + 'Content-Type': 'application/json', + Authorization: auth + }, + method: 'POST' + }; + + curl.request(options, function (err, parts) { + if (err || (parts && JSON.parse(parts).error)) { + console.log( + 'error enrolling a patient into program: ' + line, + err || JSON.parse(parts).error + ); + fs.appendFileSync(error_file, line + '\r\n'); + } else { + console.log( + 'Enrolled Patient Into Standard HIV Treatment: ' + line + ); + } + + // resume the readstream, possibly from a callback + s.resume(); + }); + } } catch (error) { - console.error(error); - // resume the readstream, possibly from a callback - s.resume(); + console.error(error); + // resume the readstream, possibly from a callback + s.resume(); } - }) - .on('error', function () { - console.log('Error while reading file.'); - }) - .on('end', function () { - console.log('Read entire file.') - }) - ); + }) + .on('error', function () { + console.log('Error while reading file.'); + }) + .on('end', function () { + console.log('Read entire file.'); + }) + ); diff --git a/worker/extract-conflicts-script.js b/worker/extract-conflicts-script.js index 6b38dbccb..bc697e67e 100755 --- a/worker/extract-conflicts-script.js +++ b/worker/extract-conflicts-script.js @@ -1,8 +1,8 @@ -var fs = require('fs') - , util = require('util') - , stream = require('stream') - , moment = require('moment') - , es = require('event-stream'); +var fs = require('fs'), + util = require('util'), + stream = require('stream'), + moment = require('moment'), + es = require('event-stream'); var lineNr = 0; @@ -10,18 +10,20 @@ var input_file = '../conflicts.txt'; var output_file = '../processed-conflicts.csv'; fs.exists(output_file, function (exists) { - if (exists) { - fs.unlink(output_file, function (err) { - if (err) throw err; - console.log('successfully deleted ' + output_file); - }); - } + if (exists) { + fs.unlink(output_file, function (err) { + if (err) throw err; + console.log('successfully deleted ' + output_file); + }); + } }); -var s = fs.createReadStream(input_file) - .pipe(es.split()) - .pipe(es.mapSync(function (line) { - +var s = fs + .createReadStream(input_file) + .pipe(es.split()) + .pipe( + es + .mapSync(function (line) { // pause the readstream s.pause(); @@ -29,43 +31,48 @@ var s = fs.createReadStream(input_file) // if (lineNr < 20) { try { - var lineArray = JSON.parse(line); - if (Array.isArray(lineArray)) { - for (var i = 0; i < lineArray.length; i++) { - var conflict = lineArray[i]; - - if (conflict.obs.length > 0) { - for (var j = 0; j < conflict.obs.length; j++) { - var obs = conflict.obs[j]; - var toDelete = {}; - toDelete.dateCollected = conflict.eid.DateCollected; - toDelete.finalResult = conflict.eid.FinalResult; - toDelete.patientIdentifier = conflict.eid.PatientID; - toDelete.orderNo = conflict.eid.OrderNo; - toDelete.obsDatetime = moment(obs.obsDatetime).format('DD-MMM-YY'); - toDelete.uuid = obs.uuid; - toDelete.display = obs.display; - toDelete.value = obs.value && obs.value.uuid ? obs.value.uuid : obs.value; - toDelete.patientUuid = obs.person.uuid; - toDelete.encounterUuid = obs.encounter && obs.encounter.uuid ? obs.encounter.uuid : ''; - // console.log(toDelete); - var csvLine = ''; - for (var o in toDelete) { - if (csvLine !== '') { - csvLine += '\t'; - } - csvLine += toDelete[o]; - } - csvLine += '\r\n'; + var lineArray = JSON.parse(line); + if (Array.isArray(lineArray)) { + for (var i = 0; i < lineArray.length; i++) { + var conflict = lineArray[i]; - fs.appendFileSync(output_file, csvLine); - } + if (conflict.obs.length > 0) { + for (var j = 0; j < conflict.obs.length; j++) { + var obs = conflict.obs[j]; + var toDelete = {}; + toDelete.dateCollected = conflict.eid.DateCollected; + toDelete.finalResult = conflict.eid.FinalResult; + toDelete.patientIdentifier = conflict.eid.PatientID; + toDelete.orderNo = conflict.eid.OrderNo; + toDelete.obsDatetime = moment(obs.obsDatetime).format( + 'DD-MMM-YY' + ); + toDelete.uuid = obs.uuid; + toDelete.display = obs.display; + toDelete.value = + obs.value && obs.value.uuid ? obs.value.uuid : obs.value; + toDelete.patientUuid = obs.person.uuid; + toDelete.encounterUuid = + obs.encounter && obs.encounter.uuid + ? obs.encounter.uuid + : ''; + // console.log(toDelete); + var csvLine = ''; + for (var o in toDelete) { + if (csvLine !== '') { + csvLine += '\t'; } + csvLine += toDelete[o]; + } + csvLine += '\r\n'; + + fs.appendFileSync(output_file, csvLine); } + } } - + } } catch (error) { - console.error(error); + console.error(error); } // } @@ -74,11 +81,11 @@ var s = fs.createReadStream(input_file) // resume the readstream, possibly from a callback s.resume(); - }) - .on('error', function () { - console.log('Error while reading file.'); - }) - .on('end', function () { - console.log('Read entire file.') - }) - ); + }) + .on('error', function () { + console.log('Error while reading file.'); + }) + .on('end', function () { + console.log('Read entire file.'); + }) + ); diff --git a/worker/schedule-eid-sync.script.js b/worker/schedule-eid-sync.script.js index 57c9268e1..869a1d38d 100755 --- a/worker/schedule-eid-sync.script.js +++ b/worker/schedule-eid-sync.script.js @@ -1,595 +1,695 @@ -var - db = require('../etl-db'), - fs = require('fs'), - util = require('util'), - stream = require('stream'), - es = require('event-stream'), - config = require('../conf/config'), - Promise = require('bluebird'), - eidService = require('../service/eid.service.js'), - _ = require('underscore'), - format = require('date-format'), - moment = require('moment'); +var db = require('../etl-db'), + fs = require('fs'), + util = require('util'), + stream = require('stream'), + es = require('event-stream'), + config = require('../conf/config'), + Promise = require('bluebird'), + eidService = require('../service/eid.service.js'), + _ = require('underscore'), + format = require('date-format'), + moment = require('moment'); var nodemailer = require('nodemailer'); // npm install nodemailer var log_file = 'lab-sync-scheduling.log'; var error_file = 'lab-sync-scheduling-error.log'; var config = require('../conf/config'); var requestConfig = require('../request-config'); -const patientService = require('../service/openmrs-rest/patient.service') +const patientService = require('../service/openmrs-rest/patient.service'); import { LabClient } from '../app/lab-integration/utils/lab-client'; var service = { - errorQueue: [], - scheduledSuccessfully: [], - retryInterval: 20 * 60 * 1000, // Retry every 20 minutes incase of an error - maxTrialCount: 3, // maxinum number of attempts to schedule syncing incase of an error during 1st trial - currentTrialCount: 0, - lab: '', - weekly_sync: false, - schedulingInProgress: false, - start: function () { - console.info('scheduling process started'); - setInterval(function () { - if (!service.schedulingInProgress) - service.scheduleEidSync(); - }, service.retryInterval); - service.scheduleEidSync(); - }, - scheduleEidSync: function () { - console.log('Attempting to schedule ...', service.currentTrialCount); - if (service.currentTrialCount === 0) { - // first trial. - // check for date arguments. - var startDate = this.getProcessArg('--start-date'); - var endDate = this.getProcessArg('--end-date'); - var lab = this.getProcessArg('--lab'); - var weekly_sync = this.getProcessArg('--weekly'); - if (lab) { - service.lab = lab; - } else { - process.exit(1); - } - if (!startDate) { - // No dates were passed in as arguments, therefore schedule for today - startDate = new Date(); - startDate.setDate(startDate.getDate() - 1); - startDate = format('yyyy-MM-dd', startDate); - - endDate = new Date(); - endDate = format('yyyy-MM-dd', endDate); - service.startDate = startDate; - service.endDate = endDate; - } - service.weekly_sync = weekly_sync || false; - var usernamePass = config.eidSyncCredentials.username + ":" + config.eidSyncCredentials.password; - var auth = "Basic " + new Buffer(usernamePass).toString('base64'); - requestConfig.setAuthorization(auth); - service.attemptToScheduleEidSync(startDate, endDate); - service.currentTrialCount++; - return; - } - - - - if (service.currentTrialCount >= service.maxTrialCount) { - // bailing out - console.error('Bailing out...Reached maximum number of trials:', service.maxTrialCount); - - console.log('*********************************'); - console.log('Scheduled:'); - console.log('*********************************'); - console.log(service.scheduledSuccessfully); - service.logSuccessfulScheduling(service.scheduledSuccessfully); + errorQueue: [], + scheduledSuccessfully: [], + retryInterval: 20 * 60 * 1000, // Retry every 20 minutes incase of an error + maxTrialCount: 3, // maxinum number of attempts to schedule syncing incase of an error during 1st trial + currentTrialCount: 0, + lab: '', + weekly_sync: false, + schedulingInProgress: false, + start: function () { + console.info('scheduling process started'); + setInterval(function () { + if (!service.schedulingInProgress) service.scheduleEidSync(); + }, service.retryInterval); + service.scheduleEidSync(); + }, + scheduleEidSync: function () { + console.log('Attempting to schedule ...', service.currentTrialCount); + if (service.currentTrialCount === 0) { + // first trial. + // check for date arguments. + var startDate = this.getProcessArg('--start-date'); + var endDate = this.getProcessArg('--end-date'); + var lab = this.getProcessArg('--lab'); + var weekly_sync = this.getProcessArg('--weekly'); + if (lab) { + service.lab = lab; + } else { + process.exit(1); + } + if (!startDate) { + // No dates were passed in as arguments, therefore schedule for today + startDate = new Date(); + startDate.setDate(startDate.getDate() - 1); + startDate = format('yyyy-MM-dd', startDate); + + endDate = new Date(); + endDate = format('yyyy-MM-dd', endDate); + service.startDate = startDate; + service.endDate = endDate; + } + service.weekly_sync = weekly_sync || false; + var usernamePass = + config.eidSyncCredentials.username + + ':' + + config.eidSyncCredentials.password; + var auth = 'Basic ' + new Buffer(usernamePass).toString('base64'); + requestConfig.setAuthorization(auth); + service.attemptToScheduleEidSync(startDate, endDate); + service.currentTrialCount++; + return; + } + if (service.currentTrialCount >= service.maxTrialCount) { + // bailing out + console.error( + 'Bailing out...Reached maximum number of trials:', + service.maxTrialCount + ); + + console.log('*********************************'); + console.log('Scheduled:'); + console.log('*********************************'); + console.log(service.scheduledSuccessfully); + service.logSuccessfulScheduling(service.scheduledSuccessfully); + + console.log('*********************************'); + console.log('Could not schedule for:'); + console.log('*********************************'); + + _.each(service.errorQueue, function (errorItem) { + delete errorItem.apiKey; + }); + + console.log(service.errorQueue); + service.logErrorWhenScheduling(service.errorQueue); + + if ( + config && + config.emailNotification && + config.emailNotification.sourceAddress + ) { + console.log('*********************************'); + console.log('Sending email notification to maintainers..'); + service + .sendMail( + 'There was an error sheduling the eid-amrs sync: ' + + JSON.stringify(service.errorQueue, null, 4), + 'EID-AMRS sync error', + 'ampath-developers@ampath.or.ke' + ) + .then(function (info) { console.log('*********************************'); - console.log('Could not schedule for:'); + console.log('Exiting scheduler with status 1...'); + process.exit(1); + }) + .catch(function (error) { + console.log('Error sending email notification'); console.log('*********************************'); + console.log('Exiting scheduler with status 1...'); + process.exit(1); + }); + } else { + console.log('*********************************'); + console.log('Exiting scheduler with status 1...'); + process.exit(1); + } + + return; + } - _.each(service.errorQueue, function (errorItem) { - delete errorItem.apiKey; - }); - - console.log(service.errorQueue); - service.logErrorWhenScheduling(service.errorQueue); - - if (config && config.emailNotification && config.emailNotification.sourceAddress) { - console.log('*********************************'); - console.log('Sending email notification to maintainers..'); - service.sendMail('There was an error sheduling the eid-amrs sync: ' + - JSON.stringify(service.errorQueue, null, 4), 'EID-AMRS sync error', 'ampath-developers@ampath.or.ke') - .then(function (info) { - console.log('*********************************'); - console.log('Exiting scheduler with status 1...'); - process.exit(1); - }) - .catch(function (error) { - console.log('Error sending email notification'); - console.log('*********************************'); - console.log('Exiting scheduler with status 1...') - process.exit(1); - }); - } else { - console.log('*********************************'); - console.log('Exiting scheduler with status 1...') - process.exit(1); - } - - return; - } - - // check if there are items in the queue and retry to schedule them - if (service.errorQueue.length > 0) { - service.attemptToScheduleEidSync(); - } else { - process.exit(0); - return; - } - - service.currentTrialCount++; - }, - attemptToScheduleEidSync: function (startDate, endDate) { - if (service.errorQueue.length === 0) { - service.initializeQueue(startDate, endDate); - - // also pick items from previously saved error queue - } - // console.log('queue', service.errorQueue); - if (service.weekly_sync) { - let startDateVlPending = format('yyyy-MM-dd', moment(new Date()).subtract(3, 'months').toDate()); - console.log('Patients with missing vl'); - service.schedulePatientsWithMissingVlPastOneYear() - .then(function (res) { - console.log('Scheduled patients with missing vl successfully'); - service.logSuccessfulScheduling('Scheduled patients with missing vl', startDateVlPending); - console.info('*********************************'); - console.log('Exiting scheduler...'); - process.exit(0); + // check if there are items in the queue and retry to schedule them + if (service.errorQueue.length > 0) { + service.attemptToScheduleEidSync(); + } else { + process.exit(0); + return; + } - }) - .catch(function (error) { - console.error('Error scheduling patients with missing vl', error); - service.logErrorWhenScheduling('Error scheduling patients with missing VL for date ' + startDateVlPending, error); - service.sendMail('Error scheduling patients with missing vl' + error, - 'Error Scheduling EID-AMRS Sync For patients with missing VL', 'ampath-developers@ampath.or.ke'); - - console.info('*********************************'); - console.log('Exiting scheduler...'); - process.exit(1); - }); - } else { - service.scheduleQueue() - .then(function (result) { - // console.log('Queue passed',result) - // if (service.errorQueue.length === 0) { - console.info('*********************************'); - console.info('Scheduling completed successfully'); - console.info('*********************************'); - console.info(service.scheduledSuccessfully); - service.logSuccessfulScheduling(service.scheduledSuccessfully); - - // attempt for pending vl orders - // Attempt to schedule patients with pending vl orders - var startDateVlPending = format('yyyy-MM-dd', moment(new Date()).subtract(3, 'months').toDate()); - service.schedulePatientsWithPendingOrders(startDateVlPending) - .then(function (results) { - console.log('Scheduled patients with pending vl orders successfully'); - service.logSuccessfulScheduling('Scheduled patients with pending vl successfully', startDateVlPending); - // console.info('*********************************'); - // console.log('Exiting scheduler...'); - // process.exit(0); - service.rescheduleEidSyncErrors() - .then(function (res2) { - console.log('Scheduled patients in error queue successfully'); - service.logSuccessfulScheduling('Scheduled patients in error queue successfully'); - console.info('*********************************'); - console.log('Exiting scheduler...'); - process.exit(0); - }) - .catch(function (err) { - console.error('Error rescheduling patients in error queue', err); - service.logErrorWhenScheduling('Error rescheduling patients in error queue ', err); - service.sendMail('Error rescheduling patients in error queue' + err, - 'Error Scheduling EID-AMRS Sync For patients in error queue', 'ampath-developers@ampath.or.ke'); - - console.info('*********************************'); - console.log('Exiting scheduler...'); - process.exit(1); - }); - }) - .catch(function (error) { - console.error('Error scheduling patients with pending vl orders', error); - service.logErrorWhenScheduling('Error scheduling patients with pending VL order for date ' + startDateVlPending, error); - service.sendMail('Error scheduling patients with pending vl orders' + error, - 'Error Scheduling EID-AMRS Sync For patients with pending VL', 'ampath-developers@ampath.or.ke'); - - console.info('*********************************'); - console.log('Exiting scheduler...'); - process.exit(1); - }); + service.currentTrialCount++; + }, + attemptToScheduleEidSync: function (startDate, endDate) { + if (service.errorQueue.length === 0) { + service.initializeQueue(startDate, endDate); + // also pick items from previously saved error queue + } + // console.log('queue', service.errorQueue); + if (service.weekly_sync) { + let startDateVlPending = format( + 'yyyy-MM-dd', + moment(new Date()).subtract(3, 'months').toDate() + ); + console.log('Patients with missing vl'); + service + .schedulePatientsWithMissingVlPastOneYear() + .then(function (res) { + console.log('Scheduled patients with missing vl successfully'); + service.logSuccessfulScheduling( + 'Scheduled patients with missing vl', + startDateVlPending + ); + console.info('*********************************'); + console.log('Exiting scheduler...'); + process.exit(0); + }) + .catch(function (error) { + console.error('Error scheduling patients with missing vl', error); + service.logErrorWhenScheduling( + 'Error scheduling patients with missing VL for date ' + + startDateVlPending, + error + ); + service.sendMail( + 'Error scheduling patients with missing vl' + error, + 'Error Scheduling EID-AMRS Sync For patients with missing VL', + 'ampath-developers@ampath.or.ke' + ); + + console.info('*********************************'); + console.log('Exiting scheduler...'); + process.exit(1); + }); + } else { + service + .scheduleQueue() + .then(function (result) { + // console.log('Queue passed',result) + // if (service.errorQueue.length === 0) { + console.info('*********************************'); + console.info('Scheduling completed successfully'); + console.info('*********************************'); + console.info(service.scheduledSuccessfully); + service.logSuccessfulScheduling(service.scheduledSuccessfully); + + // attempt for pending vl orders + // Attempt to schedule patients with pending vl orders + var startDateVlPending = format( + 'yyyy-MM-dd', + moment(new Date()).subtract(3, 'months').toDate() + ); + service + .schedulePatientsWithPendingOrders(startDateVlPending) + .then(function (results) { + console.log( + 'Scheduled patients with pending vl orders successfully' + ); + service.logSuccessfulScheduling( + 'Scheduled patients with pending vl successfully', + startDateVlPending + ); + // console.info('*********************************'); + // console.log('Exiting scheduler...'); + // process.exit(0); + service + .rescheduleEidSyncErrors() + .then(function (res2) { + console.log('Scheduled patients in error queue successfully'); + service.logSuccessfulScheduling( + 'Scheduled patients in error queue successfully' + ); + console.info('*********************************'); + console.log('Exiting scheduler...'); + process.exit(0); }) - .catch(function (error) { - service.logErrorWhenScheduling(error); - console.log('Error', error); - console.log('An expected error happened while scheduling...'); - process.exit(1); + .catch(function (err) { + console.error( + 'Error rescheduling patients in error queue', + err + ); + service.logErrorWhenScheduling( + 'Error rescheduling patients in error queue ', + err + ); + service.sendMail( + 'Error rescheduling patients in error queue' + err, + 'Error Scheduling EID-AMRS Sync For patients in error queue', + 'ampath-developers@ampath.or.ke' + ); + + console.info('*********************************'); + console.log('Exiting scheduler...'); + process.exit(1); }); - } - - - }, - fetchAllViralLoad: function (configObj, options) { - let client = new LabClient(configObj); - return client.fetchViralLoad(options).then((result) => { - let promises = []; - let i; - for (i = 1; i <= result.last_page; i++) { - promises.push(client.fetchViralLoad(options, i)); - } - return Promise.all(promises); - }).then((results) => { - let allData = []; - for (let result of results) { - allData = allData.concat(result.data); - } - let identifiers = allData.map((result) => { - if (result) { - return result.patient; - } - return ''; + }) + .catch(function (error) { + console.error( + 'Error scheduling patients with pending vl orders', + error + ); + service.logErrorWhenScheduling( + 'Error scheduling patients with pending VL order for date ' + + startDateVlPending, + error + ); + service.sendMail( + 'Error scheduling patients with pending vl orders' + error, + 'Error Scheduling EID-AMRS Sync For patients with pending VL', + 'ampath-developers@ampath.or.ke' + ); + + console.info('*********************************'); + console.log('Exiting scheduler...'); + process.exit(1); }); - return identifiers; + }) + .catch(function (error) { + service.logErrorWhenScheduling(error); + console.log('Error', error); + console.log('An expected error happened while scheduling...'); + process.exit(1); }); - }, - fetchAllCD4: function (configObj, options) { - let client = new LabClient(configObj); - return client.fetchCD4(options).then((result) => { - let promises = []; - let i; - for (i = 1; i <= result.last_page; i++) { - promises.push(client.fetchCD4(options, i)); - } - return Promise.all(promises); - }).then((results) => { - let allData = []; - for (let result of results) { - allData = allData.concat(result.data); - } - let identifiers = allData.map((result) => { - if (result) { - return result.patient; - } - return ''; - }); - return identifiers; - }); - }, - fetchAllDNAPCR: function (configObj, options) { - let client = new LabClient(configObj); - return client.fetchDNAPCR(options).then((result) => { - let promises = []; - let i; - for (i = 1; i <= result.last_page; i++) { - promises.push(client.fetchDNAPCR(options, i)); - } - return Promise.all(promises); - }).then((results) => { - let allData = []; - for (let result of results) { - allData = allData.concat(result.data); - } - let identifiers = allData.map((result) => { - if (result) { - return result.patient; - } - return ''; - }); - return identifiers; - }); - }, - fetchAllPatientResults: function (configObj, options) { - let promises = [service.fetchAllViralLoad(configObj, options), service.fetchAllDNAPCR(configObj, options), - service.fetchAllCD4(configObj, options)]; - return Promise.all(promises).then((results) => { - let allResultTypesData = []; - for (let result of results) { - allResultTypesData = allResultTypesData.concat(result); - } - return allResultTypesData; - }); - }, - scheduleQueue: function () { - - let configObj = config.hivLabSystem[service.lab]; - let options = { - date_dispatched_start: service.startDate, - date_dispatched_end: service.endDate, dispached: 1 - }; - return service.fetchAllPatientResults(configObj, options).then((identifiers) => { - return service.insertPatientsWithEidResultsIntoSyncQueue(identifiers); + } + }, + fetchAllViralLoad: function (configObj, options) { + let client = new LabClient(configObj); + return client + .fetchViralLoad(options) + .then((result) => { + let promises = []; + let i; + for (i = 1; i <= result.last_page; i++) { + promises.push(client.fetchViralLoad(options, i)); + } + return Promise.all(promises); + }) + .then((results) => { + let allData = []; + for (let result of results) { + allData = allData.concat(result.data); + } + let identifiers = allData.map((result) => { + if (result) { + return result.patient; + } + return ''; }); - }, - scheduleEidSyncPerServerPerType: function (queueItem) { - queueItem.trial++; - return new Promise(function (resolve, reject) { - console.log('Fetching results from eid...', queueItem.host, queueItem.type); - service.getEidQueryPromise(queueItem) - .then(function (result) { - console.log('Fetching results from eid done successfully', result); - if (result && result.patientIdentifiers && - result.patientIdentifiers.length > 0) { - service.insertPatientsWithEidResultsIntoSyncQueue(result.patientIdentifiers) - .then(function (inserted) { - console.log('Inserted patients into eid sync queue'); - resolve(result); - }) - .catch(function (error) { - console.error('An error occured while inserting into eid sync queue', error); - reject(error); - }); - } else { - if (result && result.patientIdentifiers) { - resolve(result); - } else { - reject('Unkown response, ', result); - } - } - }) - .catch(function (error) { - console.error('Fetching results from eid done with an error: ', error); - reject(error); - }); + return identifiers; + }); + }, + fetchAllCD4: function (configObj, options) { + let client = new LabClient(configObj); + return client + .fetchCD4(options) + .then((result) => { + let promises = []; + let i; + for (i = 1; i <= result.last_page; i++) { + promises.push(client.fetchCD4(options, i)); + } + return Promise.all(promises); + }) + .then((results) => { + let allData = []; + for (let result of results) { + allData = allData.concat(result.data); + } + let identifiers = allData.map((result) => { + if (result) { + return result.patient; + } + return ''; }); - }, - getEidQueryPromise: function (queueItem) { - switch (queueItem.type) { - case 'vl': - return eidService.getPatientIdentifiersWithEidResultsByType(queueItem.host, queueItem.apiKey, - queueItem.startDate, queueItem.endDate, eidService.getEidViralLoadResults); - break; - case 'cd4': - return eidService.getPatientIdentifiersWithEidResultsByType(queueItem.host, queueItem.apiKey, - queueItem.startDate, queueItem.endDate, eidService.getEidCD4Results); - break; - case 'dnapcr': - return eidService.getPatientIdentifiersWithEidResultsByType(queueItem.host, queueItem.apiKey, - queueItem.startDate, queueItem.endDate, eidService.getEidDnaPcrResults); - break; - default: - throw new Error('Unknown lab type'); + return identifiers; + }); + }, + fetchAllDNAPCR: function (configObj, options) { + let client = new LabClient(configObj); + return client + .fetchDNAPCR(options) + .then((result) => { + let promises = []; + let i; + for (i = 1; i <= result.last_page; i++) { + promises.push(client.fetchDNAPCR(options, i)); } - }, - initializeQueue: function (startDate, endDate) { - _.each(config.eid.locations, function (server) { - service.errorQueue.push({ - startDate: startDate, - endDate: endDate, - host: server.host, - apiKey: server.generalApiKey, - type: 'vl', - trial: 0 - }); - - service.errorQueue.push({ - startDate: startDate, - endDate: endDate, - host: server.host, - apiKey: server.generalApiKey, - type: 'dnapcr', - trial: 0 - }); - - if (server.loadCd4 === true) { - service.errorQueue.push({ - startDate: startDate, - endDate: endDate, - host: server.host, - apiKey: server.cd4ApiKey, - type: 'cd4', - trial: 0 - }); - } + return Promise.all(promises); + }) + .then((results) => { + let allData = []; + for (let result of results) { + allData = allData.concat(result.data); + } + let identifiers = allData.map((result) => { + if (result) { + return result.patient; + } + return ''; }); - }, - insertPatientsWithEidResultsIntoSyncQueue: function (patientIdentifiers) { - - return new Promise(function (resolve, reject) { - console.log('patientIdentifiers', patientIdentifiers); - if(patientIdentifiers.length > 0){ - - var results = ''; - if (Array.isArray(patientIdentifiers)) { - results = JSON.stringify(patientIdentifiers); - } else { - results = patientIdentifiers; - } - results = results.replace('[', "").replace(']', ""); - - console.log('Results...', results); - - var sql = 'replace into etl.eid_sync_queue(person_uuid) select distinct p.uuid from amrs.person p left join amrs.patient_identifier i on p.person_id = i.patient_id where identifier in (?)'; - sql = sql.replace('?', results); - console.log('sql....', sql); - - var queryObject = { - query: sql, - sqlParams: [] - } - - db.queryReportServer(queryObject, function (response) { - if (response.error) { - reject(response); - } else { - resolve(response); - } - }); - - }else{ - resolve("No patients found"); + return identifiers; + }); + }, + fetchAllPatientResults: function (configObj, options) { + let promises = [ + service.fetchAllViralLoad(configObj, options), + service.fetchAllDNAPCR(configObj, options), + service.fetchAllCD4(configObj, options) + ]; + return Promise.all(promises).then((results) => { + let allResultTypesData = []; + for (let result of results) { + allResultTypesData = allResultTypesData.concat(result); + } + return allResultTypesData; + }); + }, + scheduleQueue: function () { + let configObj = config.hivLabSystem[service.lab]; + let options = { + date_dispatched_start: service.startDate, + date_dispatched_end: service.endDate, + dispached: 1 + }; + return service + .fetchAllPatientResults(configObj, options) + .then((identifiers) => { + return service.insertPatientsWithEidResultsIntoSyncQueue(identifiers); + }); + }, + scheduleEidSyncPerServerPerType: function (queueItem) { + queueItem.trial++; + return new Promise(function (resolve, reject) { + console.log( + 'Fetching results from eid...', + queueItem.host, + queueItem.type + ); + service + .getEidQueryPromise(queueItem) + .then(function (result) { + console.log('Fetching results from eid done successfully', result); + if ( + result && + result.patientIdentifiers && + result.patientIdentifiers.length > 0 + ) { + service + .insertPatientsWithEidResultsIntoSyncQueue( + result.patientIdentifiers + ) + .then(function (inserted) { + console.log('Inserted patients into eid sync queue'); + resolve(result); + }) + .catch(function (error) { + console.error( + 'An error occured while inserting into eid sync queue', + error + ); + reject(error); + }); + } else { + if (result && result.patientIdentifiers) { + resolve(result); + } else { + reject('Unkown response, ', result); } - - - - + } + }) + .catch(function (error) { + console.error( + 'Fetching results from eid done with an error: ', + error + ); + reject(error); }); - }, - schedulePatientsWithPendingOrders: function (startDate) { - var sql = "replace into etl.eid_sync_queue(person_uuid) (select distinct uuid from (select t3.uuid, t1.patient_id, t1.order_id, t2.order_id as obs_order_id, t1.date_activated from amrs.orders t1 inner join amrs.person t3 on t3.person_id = t1.patient_id left outer join amrs.obs t2 on t1.order_id = t2.order_id having obs_order_id is null) t where t.date_activated > date('?'))"; - sql = sql.replace('?', startDate); - // console.log(sql); - - var queryObject = { - query: sql, - sqlParams: [] - } - - return new Promise(function (resolve, reject) { - db.queryReportServer(queryObject, function (response) { - if (response.error) { - reject(response); - } else { - resolve(response); - } - }); + }); + }, + getEidQueryPromise: function (queueItem) { + switch (queueItem.type) { + case 'vl': + return eidService.getPatientIdentifiersWithEidResultsByType( + queueItem.host, + queueItem.apiKey, + queueItem.startDate, + queueItem.endDate, + eidService.getEidViralLoadResults + ); + break; + case 'cd4': + return eidService.getPatientIdentifiersWithEidResultsByType( + queueItem.host, + queueItem.apiKey, + queueItem.startDate, + queueItem.endDate, + eidService.getEidCD4Results + ); + break; + case 'dnapcr': + return eidService.getPatientIdentifiersWithEidResultsByType( + queueItem.host, + queueItem.apiKey, + queueItem.startDate, + queueItem.endDate, + eidService.getEidDnaPcrResults + ); + break; + default: + throw new Error('Unknown lab type'); + } + }, + initializeQueue: function (startDate, endDate) { + _.each(config.eid.locations, function (server) { + service.errorQueue.push({ + startDate: startDate, + endDate: endDate, + host: server.host, + apiKey: server.generalApiKey, + type: 'vl', + trial: 0 + }); + + service.errorQueue.push({ + startDate: startDate, + endDate: endDate, + host: server.host, + apiKey: server.generalApiKey, + type: 'dnapcr', + trial: 0 + }); + + if (server.loadCd4 === true) { + service.errorQueue.push({ + startDate: startDate, + endDate: endDate, + host: server.host, + apiKey: server.cd4ApiKey, + type: 'cd4', + trial: 0 }); - }, - schedulePatientsWithMissingVlPastOneYear: function () { - var sql = "replace into etl.eid_sync_queue(person_uuid) " + - "(select uuid from etl.flat_hiv_summary_v15b where timestampdiff(month, vl_1_date, now()) >= 11 and timestampdiff(month,arv_start_date,now()) >= 4 and is_clinical_encounter=1 and next_clinical_datetime_hiv is null and timestampdiff(month,encounter_datetime,now()) <= 18)"; - // sql = sql.replace('?', startDate); - // console.log(sql); - - var queryObject = { - query: sql, - sqlParams: [] + } + }); + }, + insertPatientsWithEidResultsIntoSyncQueue: function (patientIdentifiers) { + return new Promise(function (resolve, reject) { + console.log('patientIdentifiers', patientIdentifiers); + if (patientIdentifiers.length > 0) { + var results = ''; + if (Array.isArray(patientIdentifiers)) { + results = JSON.stringify(patientIdentifiers); + } else { + results = patientIdentifiers; } + results = results.replace('[', '').replace(']', ''); - return new Promise(function (resolve, reject) { - db.queryReportServer(queryObject, function (response) { - if (response.error) { - reject(response); - } else { - resolve(response); - } - }); - }); - }, - rescheduleEidSyncErrors: function () { - return new Promise(function (resolve, reject) { - service.insertEidQueueErrorsIntoEidSyncQueue() - .then(function (response) { - service.emptyEidQueueErrors() - .then(function (response2) { - resolve({ - insert: response, - delete: response2 - }); - }) - .catch(function (err) { - reject(err); - console.error('error:', err); - }); - }) - .catch(function (err) { - reject('Error occured inserting error queue back into syn queue'); - console.error('error:', err); - }); - }); - }, - insertEidQueueErrorsIntoEidSyncQueue: function () { - var sql = 'replace into etl.eid_sync_queue(person_uuid)' + - ' (select person_uuid from etl.eid_sync_queue_errors)'; - var queryObject = { - query: sql, - sqlParams: [] - }; - - return new Promise(function (resolve, reject) { - db.queryReportServer(queryObject, function (response) { - if (response.error) { - reject(response); - } else { - resolve(response); - } - }); - }); + console.log('Results...', results); - }, - emptyEidQueueErrors: function () { - var sql = 'delete from etl.eid_sync_queue_errors'; + var sql = + 'replace into etl.eid_sync_queue(person_uuid) select distinct p.uuid from amrs.person p left join amrs.patient_identifier i on p.person_id = i.patient_id where identifier in (?)'; + sql = sql.replace('?', results); + console.log('sql....', sql); var queryObject = { - query: sql, - sqlParams: [] + query: sql, + sqlParams: [] }; - return new Promise(function (resolve, reject) { - db.queryReportServer(queryObject, function (response) { - if (response.error) { - reject(response); - } else { - resolve(response); - } - }); - }); - }, - getProcessArg(arg) { - - var val = null; - - var args = process.argv; - _.each(args, function (row) { - if (row.indexOf(arg) != -1) { - val = row.split('=')[1]; - } - }); - return val; - }, - logSuccessfulScheduling: function (logMessage) { - // var s = fs.createReadStream(log_file); - fs.appendFileSync(log_file, JSON.stringify({ - date: new Date(), - log: logMessage - }) + '\r\n'); - }, - logErrorWhenScheduling: function (error) { - fs.appendFileSync(error_file, JSON.stringify({ - date: new Date(), - error: error - }) + '\r\n'); - }, - sendMail: function (message, title, destination) { - var transporter = nodemailer.createTransport({ - service: 'Gmail', - auth: { - user: config.emailNotification.sourceAddress, // Your email id - pass: config.emailNotification.sourcePassword // Your password - } + db.queryReportServer(queryObject, function (response) { + if (response.error) { + reject(response); + } else { + resolve(response); + } }); - - var mailOptions = { - from: config.emailNotification.sourceAddress, // sender address - to: destination, // list of receivers - subject: title, // Subject line - text: message //, // plaintext body - // html: 'Hello world ✔' // You can choose to send an HTML body instead - }; - - return new Promise(function (resolve, reject) { - transporter.sendMail(mailOptions, function (error, info) { - if (error) { - console.log(error); - reject(error); - } else { - console.log('Message sent: ' + info.response); - resolve(info.response); - }; + } else { + resolve('No patients found'); + } + }); + }, + schedulePatientsWithPendingOrders: function (startDate) { + var sql = + "replace into etl.eid_sync_queue(person_uuid) (select distinct uuid from (select t3.uuid, t1.patient_id, t1.order_id, t2.order_id as obs_order_id, t1.date_activated from amrs.orders t1 inner join amrs.person t3 on t3.person_id = t1.patient_id left outer join amrs.obs t2 on t1.order_id = t2.order_id having obs_order_id is null) t where t.date_activated > date('?'))"; + sql = sql.replace('?', startDate); + // console.log(sql); + + var queryObject = { + query: sql, + sqlParams: [] + }; + + return new Promise(function (resolve, reject) { + db.queryReportServer(queryObject, function (response) { + if (response.error) { + reject(response); + } else { + resolve(response); + } + }); + }); + }, + schedulePatientsWithMissingVlPastOneYear: function () { + var sql = + 'replace into etl.eid_sync_queue(person_uuid) ' + + '(select uuid from etl.flat_hiv_summary_v15b where timestampdiff(month, vl_1_date, now()) >= 11 and timestampdiff(month,arv_start_date,now()) >= 4 and is_clinical_encounter=1 and next_clinical_datetime_hiv is null and timestampdiff(month,encounter_datetime,now()) <= 18)'; + // sql = sql.replace('?', startDate); + // console.log(sql); + + var queryObject = { + query: sql, + sqlParams: [] + }; + + return new Promise(function (resolve, reject) { + db.queryReportServer(queryObject, function (response) { + if (response.error) { + reject(response); + } else { + resolve(response); + } + }); + }); + }, + rescheduleEidSyncErrors: function () { + return new Promise(function (resolve, reject) { + service + .insertEidQueueErrorsIntoEidSyncQueue() + .then(function (response) { + service + .emptyEidQueueErrors() + .then(function (response2) { + resolve({ + insert: response, + delete: response2 + }); + }) + .catch(function (err) { + reject(err); + console.error('error:', err); }); - + }) + .catch(function (err) { + reject('Error occured inserting error queue back into syn queue'); + console.error('error:', err); }); - } - + }); + }, + insertEidQueueErrorsIntoEidSyncQueue: function () { + var sql = + 'replace into etl.eid_sync_queue(person_uuid)' + + ' (select person_uuid from etl.eid_sync_queue_errors)'; + var queryObject = { + query: sql, + sqlParams: [] + }; + + return new Promise(function (resolve, reject) { + db.queryReportServer(queryObject, function (response) { + if (response.error) { + reject(response); + } else { + resolve(response); + } + }); + }); + }, + emptyEidQueueErrors: function () { + var sql = 'delete from etl.eid_sync_queue_errors'; + + var queryObject = { + query: sql, + sqlParams: [] + }; + + return new Promise(function (resolve, reject) { + db.queryReportServer(queryObject, function (response) { + if (response.error) { + reject(response); + } else { + resolve(response); + } + }); + }); + }, + getProcessArg(arg) { + var val = null; + + var args = process.argv; + _.each(args, function (row) { + if (row.indexOf(arg) != -1) { + val = row.split('=')[1]; + } + }); + return val; + }, + logSuccessfulScheduling: function (logMessage) { + // var s = fs.createReadStream(log_file); + fs.appendFileSync( + log_file, + JSON.stringify({ + date: new Date(), + log: logMessage + }) + '\r\n' + ); + }, + logErrorWhenScheduling: function (error) { + fs.appendFileSync( + error_file, + JSON.stringify({ + date: new Date(), + error: error + }) + '\r\n' + ); + }, + sendMail: function (message, title, destination) { + var transporter = nodemailer.createTransport({ + service: 'Gmail', + auth: { + user: config.emailNotification.sourceAddress, // Your email id + pass: config.emailNotification.sourcePassword // Your password + } + }); + + var mailOptions = { + from: config.emailNotification.sourceAddress, // sender address + to: destination, // list of receivers + subject: title, // Subject line + text: message //, // plaintext body + // html: 'Hello world ✔' // You can choose to send an HTML body instead + }; + + return new Promise(function (resolve, reject) { + transporter.sendMail(mailOptions, function (error, info) { + if (error) { + console.log(error); + reject(error); + } else { + console.log('Message sent: ' + info.response); + resolve(info.response); + } + }); + }); + } }; -service.start(); \ No newline at end of file +service.start(); diff --git a/worker/shared/un_enroll_hiv_call.js b/worker/shared/un_enroll_hiv_call.js index a2458764f..6ad3c40a4 100644 --- a/worker/shared/un_enroll_hiv_call.js +++ b/worker/shared/un_enroll_hiv_call.js @@ -6,20 +6,12 @@ var squel = require('squel'); var _ = require('underscore'); var moment = require('moment'); - var apiHivUnenrollCall = { unEnrollHivCall: unEnrollHivCall }; module.exports = apiHivUnenrollCall; - function unEnrollHivCall() { - - return new Promise(function (resolve, reject) { - - - - }); - -}; + return new Promise(function (resolve, reject) {}); +} diff --git a/worker/sync_cron.js b/worker/sync_cron.js index 3caa75245..309a813a3 100755 --- a/worker/sync_cron.js +++ b/worker/sync_cron.js @@ -1,5 +1,4 @@ -var - db = require('../etl-db'), +var db = require('../etl-db'), Promise = require('bluebird'), http = require('http'), config = require('../conf/config'), @@ -9,17 +8,16 @@ var etlLogger = require('../etl-file-logger'); var App = { - start: function () { - var _this = this; - var logger = etlLogger.logger(config.logging.eidPath + '/sync-cron-info.log'); + var logger = etlLogger.logger( + config.logging.eidPath + '/sync-cron-info.log' + ); this.getPatientsWithResults() .then(function (results) { return _this.savePatientsWithResults(results); }) .then(function (result) { - logger.info('sync success: %s', JSON.stringify(result)); logger.close(); process.exit(1); @@ -33,12 +31,10 @@ var App = { }, buildUrl: function () { - var startDate = this.getProcessArg('--start-date'); var endDate = this.getProcessArg('--end-date'); if (!startDate) { - startDate = new Date(); startDate.setDate(startDate.getDate() - 1); startDate = format('yyyy-MM-dd', startDate); @@ -49,29 +45,37 @@ var App = { var protocol = config.etl.tls ? 'https' : 'http'; - var url = protocol + '://' + config.etl.host + ':' + config.etl.port + - '/etl/eid/patients-with-results?startDate=' + startDate + '&endDate=' + endDate; + var url = + protocol + + '://' + + config.etl.host + + ':' + + config.etl.port + + '/etl/eid/patients-with-results?startDate=' + + startDate + + '&endDate=' + + endDate; return url; }, getPatientsWithResults: function () { - var url = this.buildUrl(); - var usernamePass = config.eidSyncCredentials.username + ":" + config.eidSyncCredentials.password; - var auth = "Basic " + new Buffer(usernamePass).toString('base64'); + var usernamePass = + config.eidSyncCredentials.username + + ':' + + config.eidSyncCredentials.password; + var auth = 'Basic ' + new Buffer(usernamePass).toString('base64'); var options = { url: url, headers: { - 'Authorization': auth + Authorization: auth } - } + }; return new Promise(function (resolve, reject) { - curl.request(options, function (err, parts) { - if (!err) { resolve(parts); } else { @@ -82,18 +86,18 @@ var App = { }, savePatientsWithResults(results) { - - results = results.replace('[', "").replace(']', ""); // TODO - use regex + results = results.replace('[', '').replace(']', ''); // TODO - use regex console.log('Results...', results); - var sql = 'replace into etl.eid_sync_queue(person_uuid) select distinct p.uuid from amrs.person p left join amrs.patient_identifier i on p.person_id = i.patient_id where identifier in (?)'; + var sql = + 'replace into etl.eid_sync_queue(person_uuid) select distinct p.uuid from amrs.person p left join amrs.patient_identifier i on p.person_id = i.patient_id where identifier in (?)'; sql = sql.replace('?', results); var queryObject = { query: sql, sqlParams: [] - } + }; return new Promise(function (resolve, reject) { db.queryReportServer(queryObject, function (result) { @@ -104,7 +108,6 @@ var App = { }, getProcessArg(arg) { - var val = null; var args = process.argv; @@ -117,4 +120,4 @@ var App = { } }; -App.start(); \ No newline at end of file +App.start(); diff --git a/worker/un_enroll-hiv-program.js b/worker/un_enroll-hiv-program.js index 76e0dd46a..0069f1cd3 100755 --- a/worker/un_enroll-hiv-program.js +++ b/worker/un_enroll-hiv-program.js @@ -1,99 +1,109 @@ -var fs = require('fs') - , util = require('util') - , stream = require('stream') - , moment = require('moment') - , curl = require('curlrequest') - , es = require('event-stream'); +var fs = require('fs'), + util = require('util'), + stream = require('stream'), + moment = require('moment'), + curl = require('curlrequest'), + es = require('event-stream'); var https = require('http'); var config = require('../conf/config'); var lineNr = 0; - var input_file = './un_enrollment_program.csv'; var error_file = './un_enrollment_program_failed.csv'; var enrollmentUuid = ''; fs.exists(error_file, function (exists) { - if (exists) { - fs.unlink(error_file, function (err) { - if (err) throw err; - console.log('successfully deleted ' + error_file); - }); - } + if (exists) { + fs.unlink(error_file, function (err) { + if (err) throw err; + console.log('successfully deleted ' + error_file); + }); + } }); function createPayload(inputLine) { - let column = inputLine.split(','); - let payload = { - dateCompleted: column[1], - uuid:column[0] - }; - enrollmentUuid = column[0]; - return payload; + let column = inputLine.split(','); + let payload = { + dateCompleted: column[1], + uuid: column[0] + }; + enrollmentUuid = column[0]; + return payload; } -var s = fs.createReadStream(input_file) - .pipe(es.split()) - .pipe(es.mapSync(function (line) { +var s = fs + .createReadStream(input_file) + .pipe(es.split()) + .pipe( + es + .mapSync(function (line) { // pause the readstream s.pause(); lineNr += 1; try { - if (line && line !== '') { - console.log('unerolling incompatible program: ', line); - var openmrsAppName = config.openmrs.applicationName || 'amrs'; - let payload = createPayload(line); - //JSON.stringify(createPayload(line)); - var url = protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + '/' + openmrsAppName + '/ws/rest/v1/programenrollment/' + - payload.uuid; - delete payload['uuid']; - payload = JSON.stringify(payload); - - var usernamePass = config.eidSyncCredentials.username + ":" + config.eidSyncCredentials.password; - var auth = "Basic " + new Buffer(usernamePass).toString('base64'); - - var options = { - - url: url, - data: payload, - headers: { - 'Content-Type': 'application/json', - 'Authorization': auth - }, - method: 'POST' - }; - - curl.request(options, function (err, parts) { - - if (err || (parts && JSON.parse(parts).error)) { - console.log('error updating enrollment location to a program: ' + line, err || JSON.parse(parts).error); - fs.appendFileSync(error_file, line + '\r\n'); - } else { - console.log('updated enrollment location for program: ' + line); - } - - // resume the readstream, possibly from a callback - s.resume(); - - }); - } - - - + if (line && line !== '') { + console.log('unerolling incompatible program: ', line); + var openmrsAppName = config.openmrs.applicationName || 'amrs'; + let payload = createPayload(line); + //JSON.stringify(createPayload(line)); + var url = + protocol + + '://' + + config.openmrs.host + + ':' + + config.openmrs.port + + '/' + + openmrsAppName + + '/ws/rest/v1/programenrollment/' + + payload.uuid; + delete payload['uuid']; + payload = JSON.stringify(payload); + + var usernamePass = + config.eidSyncCredentials.username + + ':' + + config.eidSyncCredentials.password; + var auth = 'Basic ' + new Buffer(usernamePass).toString('base64'); + + var options = { + url: url, + data: payload, + headers: { + 'Content-Type': 'application/json', + Authorization: auth + }, + method: 'POST' + }; + + curl.request(options, function (err, parts) { + if (err || (parts && JSON.parse(parts).error)) { + console.log( + 'error updating enrollment location to a program: ' + line, + err || JSON.parse(parts).error + ); + fs.appendFileSync(error_file, line + '\r\n'); + } else { + console.log('updated enrollment location for program: ' + line); + } + + // resume the readstream, possibly from a callback + s.resume(); + }); + } } catch (error) { - console.error(error); - // resume the readstream, possibly from a callback - s.resume(); + console.error(error); + // resume the readstream, possibly from a callback + s.resume(); } - }) - .on('error', function () { - console.log('Error while reading file.'); - }) - .on('end', function () { - console.log('Read entire file.') - }) - ); + }) + .on('error', function () { + console.log('Error while reading file.'); + }) + .on('end', function () { + console.log('Read entire file.'); + }) + ); diff --git a/worker/void-conflicting-obs-script.js b/worker/void-conflicting-obs-script.js index 242495562..6e6507665 100755 --- a/worker/void-conflicting-obs-script.js +++ b/worker/void-conflicting-obs-script.js @@ -1,9 +1,9 @@ -var fs = require('fs') - , util = require('util') - , stream = require('stream') - , moment = require('moment') - , curl = require('curlrequest') - , es = require('event-stream'); +var fs = require('fs'), + util = require('util'), + stream = require('stream'), + moment = require('moment'), + curl = require('curlrequest'), + es = require('event-stream'); var https = require('http'); var config = require('../conf/config'); @@ -14,67 +14,81 @@ var input_file = './obs-uuid.csv'; var error_file = './not-voided.csv'; fs.exists(error_file, function (exists) { - if (exists) { - fs.unlink(error_file, function (err) { - if (err) throw err; - console.log('successfully deleted ' + error_file); - }); - } + if (exists) { + fs.unlink(error_file, function (err) { + if (err) throw err; + console.log('successfully deleted ' + error_file); + }); + } }); -var s = fs.createReadStream(input_file) - .pipe(es.split()) - .pipe(es.mapSync(function (line) { +var s = fs + .createReadStream(input_file) + .pipe(es.split()) + .pipe( + es + .mapSync(function (line) { // pause the readstream s.pause(); lineNr += 1; try { - if (line && line !== '') { - console.log('voiding obs: ', line); - var openmrsAppName = config.openmrs.applicationName || 'amrs'; - var protocol = config.etl.tls ? 'https' : 'http'; - var url = protocol + '://' + config.openmrs.host + ':' + config.openmrs.port + '/' + openmrsAppName + '/ws/rest/v1/obs/' + line + '?!purge'; - - var usernamePass = config.eidSyncCredentials.username + ":" + config.eidSyncCredentials.password; - var auth = "Basic " + new Buffer(usernamePass).toString('base64'); - - var options = { - url: url, - headers: { - 'Authorization': auth - }, - method: 'DELETE' - }; - - curl.request(options, function (err, parts) { - - if (err || (parts && JSON.parse(parts).error)) { - console.log('error voiding: ' + line, err || JSON.parse(parts).error); - fs.appendFileSync(error_file, line + '\r\n'); - } else { - console.log('voided: ' + line); - } - - // resume the readstream, possibly from a callback - s.resume(); - - }); - } - - - + if (line && line !== '') { + console.log('voiding obs: ', line); + var openmrsAppName = config.openmrs.applicationName || 'amrs'; + var protocol = config.etl.tls ? 'https' : 'http'; + var url = + protocol + + '://' + + config.openmrs.host + + ':' + + config.openmrs.port + + '/' + + openmrsAppName + + '/ws/rest/v1/obs/' + + line + + '?!purge'; + + var usernamePass = + config.eidSyncCredentials.username + + ':' + + config.eidSyncCredentials.password; + var auth = 'Basic ' + new Buffer(usernamePass).toString('base64'); + + var options = { + url: url, + headers: { + Authorization: auth + }, + method: 'DELETE' + }; + + curl.request(options, function (err, parts) { + if (err || (parts && JSON.parse(parts).error)) { + console.log( + 'error voiding: ' + line, + err || JSON.parse(parts).error + ); + fs.appendFileSync(error_file, line + '\r\n'); + } else { + console.log('voided: ' + line); + } + + // resume the readstream, possibly from a callback + s.resume(); + }); + } } catch (error) { - console.error(error); - // resume the readstream, possibly from a callback - s.resume(); + console.error(error); + // resume the readstream, possibly from a callback + s.resume(); } - }) - .on('error', function () { - console.log('Error while reading file.'); - }) - .on('end', function () { - console.log('Read entire file.') - }) - ); + }) + .on('error', function () { + console.log('Error while reading file.'); + }) + .on('end', function () { + console.log('Read entire file.'); + }) + );