emr_ohsp_interface 2.2.4 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- require "emr_ohsp_interface/version"
1
+ require 'emr_ohsp_interface/version'
2
2
 
3
3
  module EmrOhspInterface
4
4
  module EmrOhspInterfaceService
@@ -9,7 +9,7 @@ module EmrOhspInterface
9
9
  include EmrOhspInterface::Utils
10
10
 
11
11
  def settings
12
- file = File.read(Rails.root.join("db","idsr_metadata","idsr_ohsp_settings.json"))
12
+ file = File.read(Rails.root.join('db', 'idsr_metadata', 'idsr_ohsp_settings.json'))
13
13
  config = JSON.parse(file)
14
14
  end
15
15
 
@@ -18,96 +18,95 @@ module EmrOhspInterface
18
18
  end
19
19
 
20
20
  def get_ohsp_facility_id
21
- file = File.open(Rails.root.join("db","idsr_metadata","emr_ohsp_facility_map.csv"))
22
- data = CSV.parse(file,headers: true)
21
+ file = File.open(Rails.root.join('db', 'idsr_metadata', 'emr_ohsp_facility_map.csv'))
22
+ data = CSV.parse(file, headers: true)
23
23
  emr_facility_id = Location.current_health_center.id
24
- facility = data.select{|row| row["EMR_Facility_ID"].to_i == emr_facility_id}
25
- ohsp_id = facility[0]["OrgUnit ID"]
24
+ facility = data.select { |row| row['EMR_Facility_ID'].to_i == emr_facility_id }
25
+ ohsp_id = facility[0]['OrgUnit ID']
26
26
  end
27
27
 
28
- def get_ohsp_de_ids(de,type)
29
- #this method returns an array ohsp report line ids
28
+ def get_ohsp_de_ids(de, type)
29
+ # this method returns an array ohsp report line ids
30
30
  result = []
31
- #["waoQ016uOz1", "r1AT49VBKqg", "FPN4D0s6K3m", "zE8k2BtValu"]
31
+ # ["waoQ016uOz1", "r1AT49VBKqg", "FPN4D0s6K3m", "zE8k2BtValu"]
32
32
  # ds, de_id , <5yrs , >=5yrs
33
33
  puts de
34
- if type == "weekly"
35
- file = File.open(Rails.root.join("db","idsr_metadata","idsr_weekly_ohsp_ids.csv"))
34
+ if type == 'weekly'
35
+ file = File.open(Rails.root.join('db', 'idsr_metadata', 'idsr_weekly_ohsp_ids.csv'))
36
36
  else
37
- file = File.open(Rails.root.join("db","idsr_metadata","idsr_monthly_ohsp_ids.csv"))
37
+ file = File.open(Rails.root.join('db', 'idsr_metadata', 'idsr_monthly_ohsp_ids.csv'))
38
38
  end
39
- data = CSV.parse(file,headers: true)
40
- row = data.select{|row| row["Data Element Name"].strip.downcase.eql?(de.downcase.strip)}
41
- ohsp_ds_id = row[0]["Data Set ID"]
39
+ data = CSV.parse(file, headers: true)
40
+ row = data.select { |row| row['Data Element Name'].strip.downcase.eql?(de.downcase.strip) }
41
+ ohsp_ds_id = row[0]['Data Set ID']
42
42
  result << ohsp_ds_id
43
- ohsp_de_id = row[0]["UID"]
43
+ ohsp_de_id = row[0]['UID']
44
44
  result << ohsp_de_id
45
- option1 = row[0]["<5Yrs"]
45
+ option1 = row[0]['<5Yrs']
46
46
  result << option1
47
- option2 = row[0][">=5Yrs"]
47
+ option2 = row[0]['>=5Yrs']
48
48
  result << option2
49
49
 
50
50
  return result
51
51
  end
52
52
 
53
53
  def get_data_set_id(type)
54
- if type == "weekly"
55
- file = File.open(Rails.root.join("db","idsr_metadata","idsr_weekly_ohsp_ids.csv"))
54
+ if type == 'weekly'
55
+ file = File.open(Rails.root.join('db', 'idsr_metadata', 'idsr_weekly_ohsp_ids.csv'))
56
56
  else
57
- file = File.open(Rails.root.join("db","idsr_metadata","idsr_monthly_ohsp_ids.csv"))
57
+ file = File.open(Rails.root.join('db', 'idsr_metadata', 'idsr_monthly_ohsp_ids.csv'))
58
58
  end
59
- data = CSV.parse(file,headers: true)
60
- data_set_id = data.first["Data Set ID"]
59
+ data = CSV.parse(file, headers: true)
60
+ data_set_id = data.first['Data Set ID']
61
61
  end
62
62
 
63
- def generate_weekly_idsr_report(request=nil,start_date=nil,end_date=nil)
63
+ def generate_weekly_idsr_report(request=nil, start_date=nil, end_date=nil)
64
64
 
65
- diag_map = settings["weekly_idsr_map"]
65
+ diag_map = settings['weekly_idsr_map']
66
+ site_id = Location.current.location_id
66
67
 
67
68
  epi_week = weeks_generator.last.first.strip
68
- start_date = weeks_generator.last.last.split("to")[0].strip if start_date.nil?
69
- end_date = weeks_generator.last.last.split("to")[1].strip if end_date.nil?
69
+ start_date = weeks_generator.last.last.split('to')[0].strip if start_date.nil?
70
+ end_date = weeks_generator.last.last.split('to')[1].strip if end_date.nil?
70
71
 
71
- #pull the data
72
+ # pull the data
72
73
  type = EncounterType.find_by_name 'Outpatient diagnosis'
73
74
  collection = {}
74
75
 
75
- diag_map.each do |key,value|
76
- options = {"<5yrs"=>nil,">=5yrs"=>nil}
77
- concept_ids = ConceptName.where(name: value).collect{|cn| cn.concept_id}
76
+ diag_map.each do |key, value|
77
+ options = {'<5yrs'=>nil, '>=5yrs'=>nil}
78
+ concept_ids = ConceptName.where(name: value).collect { |cn| cn.concept_id }
78
79
 
79
80
  data = Encounter.where('encounter_datetime BETWEEN ? AND ?
80
81
  AND encounter_type = ? AND value_coded IN (?)
81
- AND concept_id IN(6543, 6542)',
82
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
83
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
84
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
85
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
86
- select('encounter.encounter_type, obs.value_coded, p.*')
87
-
88
- #under_five
89
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5}.\
90
- collect{|record| record.person_id}
91
- options["<5yrs"] = under_five
92
- #above 5 years
93
- over_five = data.select{|record| calculate_age(record["birthdate"]) >=5 }.\
94
- collect{|record| record.person_id}
95
-
96
- options[">=5yrs"] = over_five
82
+ AND concept_id IN(6543, 6542) AND encounter.site_id = ?',
83
+ start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
84
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'), type.id, concept_ids, site_id)
85
+ .joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
86
+ INNER JOIN person p ON p.person_id = encounter.patient_id')
87
+ .select('encounter.encounter_type, obs.value_coded, p.*')
88
+
89
+ # under_five
90
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }
91
+ .collect { |record| record.person_id }
92
+ options['<5yrs'] = under_five
93
+ # above 5 years
94
+ over_five = data.select { |record| calculate_age(record['birthdate']) >=5 }
95
+ .collect { |record| record.person_id }
96
+
97
+ options['>=5yrs'] = over_five
97
98
 
98
99
  collection[key] = options
99
100
  end
100
- if request == nil
101
- response = send_data(collection,"weekly")
102
- end
101
+ response = send_data(collection, 'weekly') if request == nil
103
102
 
104
103
  return collection
105
104
  end
106
105
 
107
- def generate_quarterly_idsr_report(request=nil,start_date=nil,end_date=nil)
106
+ def generate_quarterly_idsr_report(request=nil, start_date=nil, end_date=nil)
108
107
  epi_month = quarters_generator.first.first.strip
109
- start_date = quarters_generator.first.last[1].split("to").first.strip if start_date.nil?
110
- end_date = quarters_generator.first.last[1].split("to").last.strip if end_date.nil?
108
+ start_date = quarters_generator.first.last[1].split('to').first.strip if start_date.nil?
109
+ end_date = quarters_generator.first.last[1].split('to').last.strip if end_date.nil?
111
110
  indicators = [
112
111
  'Diabetes Mellitus',
113
112
  'Cervical Cancer',
@@ -123,11 +122,11 @@ module EmrOhspInterface
123
122
  'Psychosis'
124
123
  ]
125
124
 
126
- diagnosis_concepts = ['Primary Diagnosis','Secondary Diagnosis']
127
- encounters = ['OUTPATIENT DIAGNOSIS','ADMISSION DIAGNOSIS']
125
+ diagnosis_concepts = ['Primary Diagnosis', 'Secondary Diagnosis']
126
+ encounters = ['OUTPATIENT DIAGNOSIS', 'ADMISSION DIAGNOSIS']
128
127
 
129
128
  report_struct = indicators.each_with_object({}) do |indicator, report|
130
- report[indicator] = ['<5 yrs','>=5 yrs'].each_with_object({}) do |group, sub_report|
129
+ report[indicator] = ['<5 yrs', '>=5 yrs'].each_with_object({}) do |group, sub_report|
131
130
  sub_report[group] = {
132
131
  outpatient_cases: [],
133
132
  inpatient_cases: [],
@@ -138,7 +137,7 @@ module EmrOhspInterface
138
137
  end
139
138
  end
140
139
 
141
- admitted_patient_died = Proc.new do |patient|
140
+ admitted_patient_died = proc do |patient|
142
141
  visit_type = patient['visit_type']
143
142
  dead = patient['dead']
144
143
 
@@ -167,351 +166,315 @@ module EmrOhspInterface
167
166
  AND DATE(e.encounter_datetime) < '#{end_date}'
168
167
  AND obs.concept_id IN (#{ConceptName.where(name: diagnosis_concepts).pluck(:concept_id).join(',')})
169
168
  AND obs.value_coded IN (#{ConceptName.where(name: indicators).pluck(:concept_id).join(',')})
169
+ AND e.site_id = #{Location.current.location_id}
170
170
  GROUP BY
171
171
  p.person_id
172
172
  SQL
173
173
 
174
174
  malaria_tests = lab_results(test_types: ['Malaria Screening'], start_date: start_date, end_date: end_date)
175
175
 
176
- tested_patient_ids = malaria_tests.map{|patient| patient['patient_id']}
176
+ tested_patient_ids = malaria_tests.map { |patient| patient['patient_id'] }
177
177
 
178
- tested_positive = Proc.new do |patient|
178
+ tested_positive = lambda do |patient|
179
179
  patient_id = patient['patient_id']
180
180
  return false unless tested_patient_ids.include?(patient_id)
181
-
182
- results = malaria_tests.find{|test| test['patient_id'] == patient_id}['results']
181
+
182
+ results = malaria_tests.find { |test| test['patient_id'] == patient_id }['results']
183
183
  ['positive', 'parasites seen'].include?(results)
184
184
  end
185
+ diagonised.each do |patient|
186
+ diagnosis = patient['diagnosis'].titleize
187
+ visit_type = patient['visit_type']
188
+ patient_id = patient['patient_id']
189
+ birthdate = patient['birthdate']
185
190
 
186
- diagonised.each do |patient|
187
- diagnosis = patient['diagnosis']
188
- visit_type = patient['visit_type']
189
- patient_id = patient['patient_id']
190
- birthdate = patient['birthdate']
191
-
192
- five_plus = '>=5 yrs'
193
- less_than_5 = '<5 yrs'
191
+ five_plus = '>=5 yrs'
192
+ less_than_5 = '<5 yrs'
194
193
 
195
- age_group = birthdate > 5.years.ago ? less_than_5 : five_plus
194
+ age_group = birthdate > 5.years.ago ? less_than_5 : five_plus
196
195
 
197
- report_struct[diagnosis][age_group][:outpatient_cases] << patient_id if visit_type == 'OUTPATIENT DIAGNOSIS'
198
- report_struct[diagnosis][age_group][:inpatient_cases] << patient_id if visit_type == 'ADMISSION DIAGNOSIS'
199
- report_struct[diagnosis][age_group][:tested_malaria] << patient_id if tested_patient_ids.include?(patient_id)
200
- report_struct[diagnosis][age_group][:tested_positive_malaria] << patient_id if tested_positive.call(patient)
201
- report_struct[diagnosis][age_group][:inpatient_cases_death] << patient_id if admitted_patient_died.call(patient)
202
- end
203
-
196
+ report_struct[diagnosis][age_group][:outpatient_cases] << patient_id if visit_type == 'OUTPATIENT DIAGNOSIS'
197
+ report_struct[diagnosis][age_group][:inpatient_cases] << patient_id if visit_type == 'ADMISSION DIAGNOSIS'
198
+ if tested_patient_ids.include?(patient_id)
199
+ report_struct[diagnosis][age_group][:tested_malaria] << patient_id
200
+ end
201
+ report_struct[diagnosis][age_group][:tested_positive_malaria] << patient_id if tested_positive.call(patient)
202
+ if admitted_patient_died.call(patient)
203
+ report_struct[diagnosis][age_group][:inpatient_cases_death] << patient_id
204
+ end
205
+ end
204
206
  report_struct
205
-
206
207
  end
207
208
 
208
- #idsr monthly report
209
- def generate_monthly_idsr_report(request=nil,start_date=nil,end_date=nil)
210
- diag_map = settings["monthly_idsr_map"]
209
+ # idsr monthly report
210
+ def generate_monthly_idsr_report(request=nil, start_date=nil, end_date=nil)
211
+ diag_map = settings['monthly_idsr_map']
211
212
  epi_month = months_generator.first.first.strip
212
- start_date = months_generator.first.last[1].split("to").first.strip if start_date.nil?
213
- end_date = months_generator.first.last[1].split("to").last.strip if end_date.nil?
213
+ start_date = months_generator.first.last[1].split('to').first.strip if start_date.nil?
214
+ end_date = months_generator.first.last[1].split('to').last.strip if end_date.nil?
214
215
  type = EncounterType.find_by_name 'Outpatient diagnosis'
215
216
  collection = {}
216
217
 
217
- special_indicators = ["Malaria in Pregnancy",
218
- "HIV New Initiated on ART",
219
- "Diarrhoea In Under 5",
220
- "Malnutrition In Under 5",
221
- "Underweight Newborns < 2500g in Under 5 Cases",
222
- "Severe Pneumonia in under 5 cases"]
218
+ special_indicators = ['Malaria in Pregnancy',
219
+ 'HIV New Initiated on ART',
220
+ 'Diarrhoea In Under 5',
221
+ 'Malnutrition In Under 5',
222
+ 'Underweight Newborns < 2500g in Under 5 Cases',
223
+ 'Severe Pneumonia in under 5 cases']
223
224
 
224
- diag_map.each do |key,value|
225
- options = {"<5yrs"=>nil,">=5yrs"=>nil}
226
- concept_ids = ConceptName.where(name: value).collect{|cn| cn.concept_id}
225
+ diag_map.each do |key, value|
226
+ options = {'<5yrs'=>nil, '>=5yrs'=>nil}
227
+ concept_ids = ConceptName.where(name: value).collect { |cn| cn.concept_id }
227
228
  if !special_indicators.include?(key)
228
229
  data = Encounter.where('encounter_datetime BETWEEN ? AND ?
229
230
  AND encounter_type = ? AND value_coded IN (?)
230
- AND concept_id IN(6543, 6542)',
231
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
232
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
233
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
234
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
235
- select('encounter.encounter_type, obs.value_coded, p.*')
236
-
237
- #under_five
238
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5}.\
239
- collect{|record| record.person_id}.uniq
240
- options["<5yrs"] = under_five
241
- #above 5 years
242
- over_five = data.select{|record| calculate_age(record["birthdate"]) >=5 }.\
243
- collect{|record| record.person_id}.uniq
244
-
245
- options[">=5yrs"] = over_five
231
+ AND concept_id IN(6543, 6542) AND encounter.site_id = ?',
232
+ start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
233
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'), type.id, concept_ids,
234
+ Location.current.location_id)
235
+ .joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
236
+ INNER JOIN person p ON p.person_id = encounter.patient_id')
237
+ .select('encounter.encounter_type, obs.value_coded, p.*')
238
+
239
+ # under_five
240
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
241
+ .collect { |record| record.person_id }.uniq
242
+ options['<5yrs'] = under_five
243
+ # above 5 years
244
+ over_five = data.select { |record| calculate_age(record['birthdate']) >=5 }\
245
+ .collect { |record| record.person_id }.uniq
246
+
247
+ options['>=5yrs'] = over_five
246
248
 
247
249
  collection[key] = options
248
250
  else
249
- if key.eql?("Malaria in Pregnancy")
251
+ if key.eql?('Malaria in Pregnancy')
250
252
  mal_patient_id = Encounter.where('encounter_datetime BETWEEN ? AND ?
251
253
  AND encounter_type = ? AND value_coded IN (?)
252
- AND concept_id IN(6543, 6542)',
253
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
254
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
255
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
256
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
257
- select('encounter.encounter_type, obs.value_coded, p.*')
258
-
259
- mal_patient_id= mal_patient_id.collect{|record| record.person_id}
260
- #find those that are pregnant
254
+ AND concept_id IN(6543, 6542) AND encounter.site_id = ?',
255
+ start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
256
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'), type.id, concept_ids,
257
+ Location.current.location_id)
258
+ .joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
259
+ INNER JOIN person p ON p.person_id = encounter.patient_id')\
260
+ .select('encounter.encounter_type, obs.value_coded, p.*')
261
+
262
+ mal_patient_id= mal_patient_id.collect { |record| record.person_id }
263
+ # find those that are pregnant
261
264
  preg = Observation.where(["concept_id = 6131 AND obs_datetime
262
265
  BETWEEN ? AND ? AND person_id IN(?)
263
266
  AND value_coded =1065",
264
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
265
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),mal_patient_id ])
267
+ start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
268
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'), mal_patient_id ])
266
269
 
267
- options[">=5yrs"] = preg.collect{|record| record.person_id} rescue 0
270
+ options['>=5yrs'] = preg.collect { |record| record.person_id } rescue 0
268
271
  collection[key] = options
269
272
  end
270
273
 
271
- if key.eql?("HIV New Initiated on ART")
272
- data = ActiveRecord::Base.connection.select_all(
274
+ if key.eql?('HIV New Initiated on ART')
275
+ data = ActiveRecord::Base.connection.select_all(
273
276
  "SELECT * FROM temp_earliest_start_date
274
277
  WHERE date_enrolled BETWEEN '#{start_date}' AND '#{end_date}'
275
278
  AND date_enrolled = earliest_start_date
276
- GROUP BY patient_id" )
279
+ AND site_id = #{Location.current.location_id}
280
+ GROUP BY patient_id" ).to_a
277
281
 
278
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5 }.\
279
- collect{|record| record["patient_id"]}
282
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
283
+ .collect { |record| record['patient_id'] }
280
284
 
281
- over_five = data.select{|record| calculate_age(record["birthdate"]) >=5 }.\
282
- collect{|record| record["patient_id"]}
285
+ over_five = data.select { |record| calculate_age(record['birthdate']) >=5 }\
286
+ .collect { |record| record['patient_id'] }
283
287
 
284
- options["<5yrs"] = under_five
285
- options[">=5yrs"] = over_five
288
+ options['<5yrs'] = under_five
289
+ options['>=5yrs'] = over_five
286
290
 
287
291
  collection[key] = options
288
292
  end
289
293
 
290
- if key.eql?("Diarrhoea In Under 5")
291
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
292
- AND encounter_type = ? AND value_coded IN (?)
293
- AND concept_id IN(6543, 6542)',
294
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
295
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
296
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
297
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
298
- select('encounter.encounter_type, obs.value_coded, p.*')
299
-
300
- #under_five
301
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5}.\
302
- collect{|record| record.person_id}
303
- options["<5yrs"] = under_five
294
+ if key.eql?('Diarrhoea In Under 5')
295
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
296
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
297
+ type.id,
298
+ concept_ids)
299
+
300
+ # under_five
301
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
302
+ .collect { |record| record.person_id }
303
+ options['<5yrs'] = under_five
304
304
  collection[key] = options
305
305
  end
306
306
 
307
307
 
308
- if key.eql?("Malnutrition In Under 5")
309
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
310
- AND encounter_type = ? AND value_coded IN (?)
311
- AND concept_id IN(6543, 6542)',
312
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
313
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
314
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
315
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
316
- select('encounter.encounter_type, obs.value_coded, p.*')
317
-
318
- #under_five
319
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5}.\
320
- collect{|record| record.person_id}
321
- options["<5yrs"] = under_five
308
+ if key.eql?('Malnutrition In Under 5')
309
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
310
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
311
+ type.id,
312
+ concept_ids)
313
+
314
+ # under_five
315
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
316
+ .collect { |record| record.person_id }
317
+ options['<5yrs'] = under_five
322
318
  collection[key] = options
323
319
  end
324
320
 
325
321
 
326
- if key.eql?("Underweight Newborns < 2500g in Under 5 Cases")
327
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
328
- AND encounter_type = ? AND value_coded IN (?)
329
- AND concept_id IN(6543, 6542)',
330
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
331
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
332
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
333
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
334
- select('encounter.encounter_type, obs.value_coded, p.*')
335
-
336
- #under_five
337
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5}.\
338
- collect{|record| record.person_id}
339
- options["<5yrs"] = under_five
322
+ if key.eql?('Underweight Newborns < 2500g in Under 5 Cases')
323
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
324
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
325
+ type.id,
326
+ concept_ids)
327
+
328
+ # under_five
329
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
330
+ .collect { |record| record.person_id }
331
+ options['<5yrs'] = under_five
340
332
  collection[key] = options
341
333
  end
342
334
 
343
- if key.eql?("Severe Pneumonia in under 5 cases")
344
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
345
- AND encounter_type = ? AND value_coded IN (?)
346
- AND concept_id IN(6543, 6542)',
347
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
348
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
349
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
350
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
351
- select('encounter.encounter_type, obs.value_coded, p.*')
352
-
353
- #under_five
354
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5}.\
355
- collect{|record| record.person_id}
356
- options["<5yrs"] = under_five
335
+ if key.eql?('Severe Pneumonia in under 5 cases')
336
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
337
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
338
+ type.id,
339
+ concept_ids)
340
+
341
+ # under_five
342
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
343
+ .collect { |record| record.person_id }
344
+ options['<5yrs'] = under_five
357
345
  collection[key] = options
358
346
  end
359
347
  end
360
348
  end
361
- if request == nil
362
- response = send_data(collection,"monthly")
363
- end
349
+ response = send_data(collection, 'monthly') if request == nil
364
350
  return collection
365
351
  end
366
352
 
367
- def generate_hmis_15_report(start_date=nil,end_date=nil)
353
+ def fetch_encounter_data(start_date, end_date, type_id, concept_ids)
354
+ Encounter.where('encounter_datetime BETWEEN ? AND ?
355
+ AND encounter_type = ?
356
+ AND value_coded IN (?)
357
+ AND concept_id IN(6543, 6542)
358
+ AND encounter.site_id = ?',
359
+ start_date, end_date, type_id, concept_ids, Location.current.location_id)
360
+ .joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
361
+ INNER JOIN person p ON p.person_id = encounter.patient_id')
362
+ .select('encounter.encounter_type, obs.value_coded, p.*')
363
+ end
364
+
365
+ def generate_hmis_15_report(start_date=nil, end_date=nil)
368
366
 
369
- diag_map = settings["hmis_15_map"]
367
+ diag_map = settings['hmis_15_map']
370
368
 
371
- #pull the data
369
+ # pull the data
372
370
  type = EncounterType.find_by_name 'Outpatient diagnosis'
373
371
  collection = {}
374
372
 
375
- special_indicators = ["Malaria - new cases (under 5)",
376
- "Malaria - new cases (5 & over)",
377
- "HIV confirmed positive (15-49 years) new cases",
378
- "Diarrhoea non - bloody -new cases (under5)",
379
- "Malnutrition - new case (under 5)",
380
- "Acute respiratory infections - new cases (U5)"
381
- ]
373
+ special_indicators = ['Malaria - new cases (under 5)',
374
+ 'Malaria - new cases (5 & over)',
375
+ 'HIV confirmed positive (15-49 years) new cases',
376
+ 'Diarrhoea non - bloody -new cases (under5)',
377
+ 'Malnutrition - new case (under 5)',
378
+ 'Acute respiratory infections - new cases (U5)']
382
379
 
383
- diag_map.each do |key,value|
384
- options = {"ids"=>nil}
385
- concept_ids = ConceptName.where(name: value).collect{|cn| cn.concept_id}
380
+ diag_map.each do |key, value|
381
+ options = {'ids'=>nil}
382
+ concept_ids = ConceptName.where(name: value).collect { |cn| cn.concept_id }
386
383
 
387
384
  if !special_indicators.include?(key)
388
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
389
- AND encounter_type = ? AND value_coded IN (?)
390
- AND concept_id IN(6543, 6542)',
391
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
392
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
393
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
394
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
395
- select('encounter.encounter_type, obs.value_coded, p.*')
396
-
397
- # #under_five
398
- # under_five = data.select{|record| calculate_age(record["birthdate"]) < 5}.\
399
- # collect{|record| record.person_id}
400
- # options["<5yrs"] = under_five
401
- # #above 5 years
402
- # over_five = data.select{|record| calculate_age(record["birthdate"]) >=5 }.\
403
- # collect{|record| record.person_id}
385
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
386
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
387
+ type.id,
388
+ concept_ids)
389
+
390
+ all = data.collect { |record| record.person_id }
404
391
 
405
- # options[">=5yrs"] = over_five
406
392
 
407
- all = data.collect{|record| record.person_id}
408
-
409
-
410
- options["ids"] = all
393
+ options['ids'] = all
411
394
 
412
395
  collection[key] = options
413
396
  else
414
- if key.eql?("Malaria - new cases (under 5)")
415
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
416
- AND encounter_type = ? AND value_coded IN (?)
417
- AND concept_id IN(6543, 6542)',
418
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
419
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
420
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
421
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
422
- select('encounter.encounter_type, obs.value_coded, p.*')
397
+ if key.eql?('Malaria - new cases (under 5)')
398
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
399
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
400
+ type.id,
401
+ concept_ids)
423
402
 
424
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5 }.\
425
- collect{|record| record["person_id"]}
403
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
404
+ .collect { |record| record['person_id'] }
426
405
 
427
- options["ids"] = under_five
406
+ options['ids'] = under_five
428
407
 
429
408
  collection[key] = options
430
409
  end
431
410
 
432
- if key.eql?("Malaria - new cases (5 & over)")
433
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
434
- AND encounter_type = ? AND value_coded IN (?)
435
- AND concept_id IN(6543, 6542)',
436
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
437
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
438
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
439
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
440
- select('encounter.encounter_type, obs.value_coded, p.*')
411
+ if key.eql?('Malaria - new cases (5 & over)')
412
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
413
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
414
+ type.id,
415
+ concept_ids)
441
416
 
442
- over_and_five = data.select{|record| calculate_age(record["birthdate"]) >= 5 }.\
443
- collect{|record| record["person_id"]}
417
+ over_and_five = data.select { |record| calculate_age(record['birthdate']) >= 5 }\
418
+ .collect { |record| record['person_id'] }
444
419
 
445
- options["ids"] = over_and_five
420
+ options['ids'] = over_and_five
446
421
 
447
422
  collection[key] = options
448
423
  end
449
424
 
450
- if key.eql?("HIV confirmed positive (15-49 years) new cases")
451
- data = ActiveRecord::Base.connection.select_all(
425
+ if key.eql?('HIV confirmed positive (15-49 years) new cases')
426
+ data = ActiveRecord::Base.connection.select_all(
452
427
  "SELECT * FROM temp_earliest_start_date
453
428
  WHERE date_enrolled BETWEEN '#{start_date}' AND '#{end_date}'
454
429
  AND date_enrolled = earliest_start_date
455
- GROUP BY patient_id" )
430
+ AND site_id = #{Location.current.location_id}
431
+ GROUP BY patient_id" ).to_a
456
432
 
457
- over_and_15_49 = data.select{|record| calculate_age(record["birthdate"]) >= 15 && calculate_age(record["birthdate"]) <=49 }.\
458
- collect{|record| record["patient_id"]}
433
+ over_and_15_49 = data.select { |record| calculate_age(record['birthdate']) >= 15 && calculate_age(record['birthdate']) <=49 }\
434
+ .collect { |record| record['patient_id'] }
459
435
 
460
- options["ids"] = over_and_15_49
436
+ options['ids'] = over_and_15_49
461
437
 
462
438
  collection[key] = options
463
439
  end
464
440
 
465
- if key.eql?("Diarrhoea non - bloody -new cases (under5)")
466
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
467
- AND encounter_type = ? AND value_coded IN (?)
468
- AND concept_id IN(6543, 6542)',
469
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
470
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
471
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
472
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
473
- select('encounter.encounter_type, obs.value_coded, p.*')
441
+ if key.eql?('Diarrhoea non - bloody -new cases (under5)')
442
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
443
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
444
+ type.id,
445
+ concept_ids)
474
446
 
475
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5 }.\
476
- collect{|record| record["person_id"]}
447
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
448
+ .collect { |record| record['person_id'] }
477
449
 
478
- options["ids"] = under_five
450
+ options['ids'] = under_five
479
451
 
480
452
  collection[key] = options
481
453
  end
482
454
 
483
- if key.eql?("Malnutrition - new case (under 5)")
484
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
485
- AND encounter_type = ? AND value_coded IN (?)
486
- AND concept_id IN(6543, 6542)',
487
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
488
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
489
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
490
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
491
- select('encounter.encounter_type, obs.value_coded, p.*')
455
+ if key.eql?('Malnutrition - new case (under 5)')
456
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
457
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
458
+ type.id,
459
+ concept_ids)
492
460
 
493
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5 }.\
494
- collect{|record| record["person_id"]}
461
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
462
+ .collect { |record| record['person_id'] }
495
463
 
496
- options["ids"] = under_five
464
+ options['ids'] = under_five
497
465
 
498
466
  collection[key] = options
499
467
  end
500
468
 
501
- if key.eql?("Acute respiratory infections - new cases (U5)")
502
- data = Encounter.where('encounter_datetime BETWEEN ? AND ?
503
- AND encounter_type = ? AND value_coded IN (?)
504
- AND concept_id IN(6543, 6542)',
505
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
506
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
507
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
508
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
509
- select('encounter.encounter_type, obs.value_coded, p.*')
469
+ if key.eql?('Acute respiratory infections - new cases (U5)')
470
+ data = fetch_encounter_data(start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
471
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'),
472
+ type.id,
473
+ concept_ids)
474
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
475
+ .collect { |record| record['person_id'] }
510
476
 
511
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5 }.\
512
- collect{|record| record["person_id"]}
513
-
514
- options["ids"] = under_five
477
+ options['ids'] = under_five
515
478
 
516
479
  collection[key] = options
517
480
  end
@@ -522,96 +485,96 @@ module EmrOhspInterface
522
485
  end
523
486
 
524
487
  def disaggregate(disaggregate_key, concept_ids, start_date, end_date, type)
525
- options = {"ids"=>nil}
488
+ options = {'ids'=>nil}
526
489
  data = Encounter.where('encounter_datetime BETWEEN ? AND ?
527
490
  AND encounter_type = ? AND value_coded IN (?)
528
491
  AND concept_id IN(6543, 6542)',
529
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
530
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
531
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
532
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
533
- select('encounter.encounter_type, obs.value_coded, p.*')
534
-
535
- if disaggregate_key == "less"
536
- options["ids"] = data.select{|record| calculate_age(record["birthdate"]) < 5 }.\
537
- collect{|record| record["person_id"]}
492
+ start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
493
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'), type.id, concept_ids)\
494
+ .joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
495
+ INNER JOIN person p ON p.person_id = encounter.patient_id')\
496
+ .select('encounter.encounter_type, obs.value_coded, p.*')
497
+
498
+ if disaggregate_key == 'less'
499
+ options['ids'] = data.select { |record| calculate_age(record['birthdate']) < 5 }\
500
+ .collect { |record| record['person_id'] }
538
501
  else
539
- if disaggregate_key == "greater"
540
- options["ids"] = data.select{|record| calculate_age(record["birthdate"]) >= 5 }.\
541
- collect{|record| record["person_id"]}
502
+ if disaggregate_key == 'greater'
503
+ options['ids'] = data.select { |record| calculate_age(record['birthdate']) >= 5 }\
504
+ .collect { |record| record['person_id'] }
542
505
  end
543
506
  end
544
507
 
545
508
  options
546
509
  end
547
510
 
548
- def generate_hmis_17_report(start_date=nil,end_date=nil)
511
+ def generate_hmis_17_report(start_date=nil, end_date=nil)
549
512
 
550
- diag_map = settings["hmis_17_map"]
513
+ diag_map = settings['hmis_17_map']
551
514
 
552
- #pull the data
515
+ # pull the data
553
516
  type = EncounterType.find_by_name 'Outpatient diagnosis'
554
517
  collection = {}
555
518
 
556
519
  special_indicators = [
557
- "Referals from other institutions",
558
- "OPD total attendance",
559
- "Referal to other institutions",
560
- "Malaria 5 years and older - new",
561
- "HIV/AIDS - new"
520
+ 'Referals from other institutions',
521
+ 'OPD total attendance',
522
+ 'Referal to other institutions',
523
+ 'Malaria 5 years and older - new',
524
+ 'HIV/AIDS - new'
562
525
  ]
563
526
 
564
527
  special_under_five_indicators = [
565
- "Measles under five years - new",
566
- "Pneumonia under 5 years- new",
567
- "Dysentery under 5 years - new",
568
- "Diarrhoea non - bloody -new cases (under5)",
569
- "Malaria under 5 years - new"
528
+ 'Measles under five years - new',
529
+ 'Pneumonia under 5 years- new',
530
+ 'Dysentery under 5 years - new',
531
+ 'Diarrhoea non - bloody -new cases (under5)',
532
+ 'Malaria under 5 years - new'
570
533
  ]
571
534
 
572
- diag_map.each do |key,value|
573
- options = {"ids"=>nil}
574
- concept_ids = ConceptName.where(name: value).collect{|cn| cn.concept_id}
535
+ diag_map.each do |key, value|
536
+ options = {'ids'=>nil}
537
+ concept_ids = ConceptName.where(name: value).collect { |cn| cn.concept_id }
575
538
 
576
539
  if !special_indicators.include?(key) && !special_under_five_indicators.include?(key)
577
540
  data = Encounter.where('encounter_datetime BETWEEN ? AND ?
578
541
  AND encounter_type = ? AND value_coded IN (?)
579
542
  AND concept_id IN(6543, 6542)',
580
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
581
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
582
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
583
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
584
- select('encounter.encounter_type, obs.value_coded, p.*')
543
+ start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
544
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'), type.id, concept_ids)\
545
+ .joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
546
+ INNER JOIN person p ON p.person_id = encounter.patient_id')\
547
+ .select('encounter.encounter_type, obs.value_coded, p.*')
585
548
 
586
- all = data.collect{|record| record.person_id}
549
+ all = data.collect { |record| record.person_id }
587
550
 
588
551
 
589
- options["ids"] = all
552
+ options['ids'] = all
590
553
 
591
554
  collection[key] = options
592
555
  else
593
- if key.eql?("Referals from other institutions")
556
+ if key.eql?('Referals from other institutions')
594
557
  _type = EncounterType.find_by_name 'PATIENT REGISTRATION'
595
558
  visit_type = ConceptName.find_by_name 'Type of visit'
596
559
 
597
560
  data = Encounter.where('encounter_datetime BETWEEN ? AND ?
598
561
  AND encounter_type = ? AND value_coded IS NOT NULL
599
562
  AND obs.concept_id = ?', start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
600
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),_type.id, visit_type.concept_id).\
601
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
563
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'), _type.id, visit_type.concept_id)\
564
+ .joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
602
565
  INNER JOIN person p ON p.person_id = encounter.patient_id
603
- INNER JOIN concept_name c ON c.concept_id = 6541').\
604
- select('encounter.encounter_type, obs.value_coded, obs.obs_datetime, p.*, c.name visit_type').\
605
- group('p.person_id, encounter.encounter_id')
566
+ INNER JOIN concept_name c ON c.concept_id = 6541')\
567
+ .select('encounter.encounter_type, obs.value_coded, obs.obs_datetime, p.*, c.name visit_type')\
568
+ .group('p.person_id, encounter.encounter_id')
606
569
 
607
- all = data.collect{|record| record.person_id}
570
+ all = data.collect { |record| record.person_id }
608
571
 
609
- options["ids"] = all
572
+ options['ids'] = all
610
573
 
611
574
  collection[key] = options
612
575
  end
613
576
 
614
- if key.eql?("OPD total attendance")
577
+ if key.eql?('OPD total attendance')
615
578
  programID = Program.find_by_name 'OPD Program'
616
579
  data = Encounter.find_by_sql(
617
580
  "SELECT patient_id, DATE_FORMAT(encounter_datetime,'%Y-%m-%d') enc_date
@@ -621,55 +584,55 @@ module EmrOhspInterface
621
584
  AND '" + end_date.to_date.strftime('%Y-%m-%d 23:59:59') + "'
622
585
  AND program_id ='" + programID.program_id.to_s + "'
623
586
  GROUP BY enc_date"
624
- ).map{|e| e. patient_id}
587
+ ).map { |e| e. patient_id }
625
588
 
626
- options["ids"] = data
589
+ options['ids'] = data
627
590
  collection[key] = options
628
591
  end
629
592
 
630
- if key.eql?("Referal to other institutions")
593
+ if key.eql?('Referal to other institutions')
631
594
  data = Observation.where("obs_datetime BETWEEN ? AND ?
632
- AND concept_id = ?",start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
633
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),'7414').\
634
- joins('LEFT JOIN location l ON l.location_id = obs.value_text').\
635
- select('obs.person_id').order('obs_datetime DESC')
636
- all = data.collect{|record| record.person_id}
637
- options["ids"] = all
595
+ AND concept_id = ?", start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
596
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'), '7414')\
597
+ .joins('LEFT JOIN location l ON l.location_id = obs.value_text')\
598
+ .select('obs.person_id').order('obs_datetime DESC')
599
+ all = data.collect { |record| record.person_id }
600
+ options['ids'] = all
638
601
  collection[key] = options
639
602
  end
640
603
 
641
- if key.eql?("HIV/AIDS - new")
642
- data = ActiveRecord::Base.connection.select_all(
604
+ if key.eql?('HIV/AIDS - new')
605
+ data = ActiveRecord::Base.connection.select_all(
643
606
  "SELECT * FROM temp_earliest_start_date
644
607
  WHERE date_enrolled BETWEEN '#{start_date}' AND '#{end_date}'
645
608
  AND date_enrolled = earliest_start_date
646
- GROUP BY patient_id" )
647
- all = data.collect{|record| record["patient_id"]}
648
- options["ids"] = all
609
+ GROUP BY patient_id" ).to_hash
610
+ all = data.collect { |record| record['patient_id'] }
611
+ options['ids'] = all
649
612
  collection[key] = options
650
613
  end
651
614
 
652
- if key.eql?("Measles under five years - new")
653
- collection[key] = disaggregate('less',concept_ids, start_date, end_date, type)
615
+ if key.eql?('Measles under five years - new')
616
+ collection[key] = disaggregate('less', concept_ids, start_date, end_date, type)
654
617
  end
655
618
 
656
- if key.eql?("Pneumonia under 5 years- new")
619
+ if key.eql?('Pneumonia under 5 years- new')
657
620
  collection[key] = disaggregate('less', concept_ids, start_date, end_date, type)
658
621
  end
659
622
 
660
- if key.eql?("Malaria under 5 years - new")
623
+ if key.eql?('Malaria under 5 years - new')
661
624
  collection[key] = disaggregate('less', concept_ids, start_date, end_date, type)
662
625
  end
663
626
 
664
- if key.eql?("Malaria 5 years and older - new")
665
- collection[key] = disaggregate('greater',concept_ids, start_date, end_date, type)
627
+ if key.eql?('Malaria 5 years and older - new')
628
+ collection[key] = disaggregate('greater', concept_ids, start_date, end_date, type)
666
629
  end
667
630
 
668
- if key.eql?("Dysentery under 5 years - new")
631
+ if key.eql?('Dysentery under 5 years - new')
669
632
  collection[key] = disaggregate('less', concept_ids, start_date, end_date, type)
670
633
  end
671
634
 
672
- if key.eql?("Diarrhoea non - bloody -new cases (under5)")
635
+ if key.eql?('Diarrhoea non - bloody -new cases (under5)')
673
636
  collection[key] = disaggregate('less', concept_ids, start_date, end_date, type)
674
637
  end
675
638
 
@@ -680,38 +643,38 @@ module EmrOhspInterface
680
643
 
681
644
  end
682
645
 
683
- def generate_notifiable_disease_conditions_report(start_date=nil,end_date=nil)
684
- diag_map = settings["notifiable_disease_conditions"]
646
+ def generate_notifiable_disease_conditions_report(start_date=nil, end_date=nil)
647
+ diag_map = settings['notifiable_disease_conditions']
685
648
 
686
- start_date = Date.today.strftime("%Y-%m-%d") if start_date.nil?
687
- end_date = Date.today.strftime("%Y-%m-%d") if end_date.nil?
649
+ start_date = Date.today.strftime('%Y-%m-%d') if start_date.nil?
650
+ end_date = Date.today.strftime('%Y-%m-%d') if end_date.nil?
688
651
 
689
652
  type = EncounterType.find_by_name 'Outpatient diagnosis'
690
653
  collection = {}
691
654
  concept_name_for_sms_portal = {}
692
655
 
693
- diag_map.each do |key,value|
694
- options = {"<5yrs"=>nil,">=5yrs"=>nil}
695
- concept_ids = ConceptName.where(name: value).collect{|cn| cn.concept_id}
656
+ diag_map.each do |key, value|
657
+ options = {'<5yrs'=>nil, '>=5yrs'=>nil}
658
+ concept_ids = ConceptName.where(name: value).collect { |cn| cn.concept_id }
696
659
 
697
660
  data = Encounter.where('encounter_datetime BETWEEN ? AND ?
698
661
  AND encounter_type = ? AND value_coded IN (?)
699
662
  AND concept_id IN(6543, 6542)',
700
- start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
701
- end_date.to_date.strftime('%Y-%m-%d 23:59:59'),type.id,concept_ids).\
702
- joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
703
- INNER JOIN person p ON p.person_id = encounter.patient_id').\
704
- select('encounter.encounter_type, obs.value_coded, p.*')
705
-
706
- #under_five
707
- under_five = data.select{|record| calculate_age(record["birthdate"]) < 5}.\
708
- collect{|record| record.person_id}
709
- options["<5yrs"] = under_five
710
- #above 5 years
711
- over_five = data.select{|record| calculate_age(record["birthdate"]) >=5 }.\
712
- collect{|record| record.person_id}
713
-
714
- options[">=5yrs"] = over_five
663
+ start_date.to_date.strftime('%Y-%m-%d 00:00:00'),
664
+ end_date.to_date.strftime('%Y-%m-%d 23:59:59'), type.id, concept_ids)\
665
+ .joins('INNER JOIN obs ON obs.encounter_id = encounter.encounter_id
666
+ INNER JOIN person p ON p.person_id = encounter.patient_id')\
667
+ .select('encounter.encounter_type, obs.value_coded, p.*')
668
+
669
+ # under_five
670
+ under_five = data.select { |record| calculate_age(record['birthdate']) < 5 }\
671
+ .collect { |record| record.person_id }
672
+ options['<5yrs'] = under_five
673
+ # above 5 years
674
+ over_five = data.select { |record| calculate_age(record['birthdate']) >=5 }\
675
+ .collect { |record| record.person_id }
676
+
677
+ options['>=5yrs'] = over_five
715
678
 
716
679
  collection[key] = options
717
680
 
@@ -728,9 +691,9 @@ module EmrOhspInterface
728
691
  curr_date = Date.today
729
692
  while count < 13 do
730
693
  curr_date = curr_date - 1.month
731
- months[curr_date.strftime("%Y%m")] = [curr_date.strftime("%B-%Y"),\
732
- (curr_date.beginning_of_month.to_s+" to " + curr_date.end_of_month.to_s)]
733
- count += 1
694
+ months[curr_date.strftime('%Y%m')] = [curr_date.strftime('%B-%Y'),\
695
+ (curr_date.beginning_of_month.to_s+' to ' + curr_date.end_of_month.to_s)]
696
+ count += 1
734
697
  end
735
698
  return months.to_a
736
699
  end
@@ -745,7 +708,7 @@ module EmrOhspInterface
745
708
  init_quarter = Date.today.beginning_of_year - 2.years
746
709
 
747
710
  while init_quarter <= Date.today do
748
- quarter = init_quarter.strftime("%Y")+" Q"+to_quarter.call(init_quarter).to_s
711
+ quarter = init_quarter.strftime('%Y')+' Q'+to_quarter.call(init_quarter).to_s
749
712
  dates = "#{(init_quarter.beginning_of_quarter).to_s} to #{(init_quarter.end_of_quarter).to_s}"
750
713
  quarters[quarter] = dates
751
714
  init_quarter = init_quarter + 3.months
@@ -762,90 +725,90 @@ module EmrOhspInterface
762
725
  wk_of_first_day = first_day.cweek
763
726
 
764
727
  if wk_of_first_day > 1
765
- wk = first_day.prev_year.year.to_s+"W"+wk_of_first_day.to_s
728
+ wk = first_day.prev_year.year.to_s+'W'+wk_of_first_day.to_s
766
729
  dates = "#{(first_day-first_day.wday+1).to_s} to #{((first_day-first_day.wday+1)+6).to_s}"
767
730
  weeks[wk] = dates
768
731
  end
769
732
 
770
- #get the firt monday of the year
733
+ # get the firt monday of the year
771
734
  while !first_day.monday? do
772
735
  first_day = first_day+1
773
736
  end
774
737
  first_monday = first_day
775
- #generate week numbers and date ranges
738
+ # generate week numbers and date ranges
776
739
 
777
740
  while first_monday <= Date.today do
778
- wk = (first_monday.year).to_s+"W"+(first_monday.cweek).to_s
779
- dates = "#{first_monday.to_s} to #{(first_monday+6).to_s}"
780
- #add to the hash
741
+ wk = (first_monday.year).to_s+'W'+(first_monday.cweek).to_s
742
+ dates = "#{first_monday.to_s} to #{(first_monday+6).to_s}"
743
+ # add to the hash
781
744
  weeks[wk] = dates
782
- #step by week
745
+ # step by week
783
746
  first_monday += 7
784
747
  end
785
- #remove the last week
786
- this_wk = (Date.today.year).to_s+"W"+(Date.today.cweek).to_s
787
- weeks = weeks.delete_if{|key,value| key==this_wk}
748
+ # remove the last week
749
+ this_wk = (Date.today.year).to_s+'W'+(Date.today.cweek).to_s
750
+ weeks = weeks.delete_if { |key, value| key==this_wk }
788
751
 
789
752
  return weeks.to_a
790
753
  end
791
754
 
792
- #Age calculator
755
+ # Age calculator
793
756
  def calculate_age(dob)
794
757
  age = ((Date.today-dob.to_date).to_i)/365 rescue 0
795
758
  end
796
759
 
797
- def send_data(data,type)
760
+ def send_data(data, type)
798
761
  # method used to post data to the server
799
- #prepare payload here
762
+ # prepare payload here
800
763
  conn = server_config['ohsp']
801
764
  payload = {
802
- "dataSet" =>get_data_set_id(type),
803
- "period"=>(type.eql?("weekly") ? weeks_generator.last[0] : months_generator.first[0]),
804
- "orgUnit"=> get_ohsp_facility_id,
805
- "dataValues"=> []
765
+ 'dataSet' =>get_data_set_id(type),
766
+ 'period'=>(type.eql?('weekly') ? weeks_generator.last[0] : months_generator.first[0]),
767
+ 'orgUnit'=> get_ohsp_facility_id,
768
+ 'dataValues'=> []
806
769
  }
807
- special = ["Severe Pneumonia in under 5 cases","Malaria in Pregnancy",
808
- "Underweight Newborns < 2500g in Under 5 Cases","Diarrhoea In Under 5"]
770
+ special = ['Severe Pneumonia in under 5 cases', 'Malaria in Pregnancy',
771
+ 'Underweight Newborns < 2500g in Under 5 Cases', 'Diarrhoea In Under 5']
809
772
 
810
- data.each do |key,value|
773
+ data.each do |key, value|
811
774
  if !special.include?(key)
812
- option1 = {"dataElement"=>get_ohsp_de_ids(key,type)[1],
813
- "categoryOptionCombo"=> get_ohsp_de_ids(key,type)[2],
814
- "value"=>value["<5yrs"].size } rescue {}
775
+ option1 = {'dataElement'=>get_ohsp_de_ids(key, type)[1],
776
+ 'categoryOptionCombo'=> get_ohsp_de_ids(key, type)[2],
777
+ 'value'=>value['<5yrs'].size } rescue {}
815
778
 
816
- option2 = {"dataElement"=>get_ohsp_de_ids(key,type)[1],
817
- "categoryOptionCombo"=> get_ohsp_de_ids(key,type)[3],
818
- "value"=>value[">=5yrs"].size} rescue {}
779
+ option2 = {'dataElement'=>get_ohsp_de_ids(key, type)[1],
780
+ 'categoryOptionCombo'=> get_ohsp_de_ids(key, type)[3],
781
+ 'value'=>value['>=5yrs'].size} rescue {}
819
782
 
820
- #fill data values array
821
- payload["dataValues"] << option1
822
- payload["dataValues"] << option2
783
+ # fill data values array
784
+ payload['dataValues'] << option1
785
+ payload['dataValues'] << option2
823
786
  else
824
787
  case key
825
788
  when special[0]
826
- option1 = {"dataElement"=>get_ohsp_de_ids(key,type)[1],
827
- "categoryOptionCombo"=> get_ohsp_de_ids(key,type)[2],
828
- "value"=>value["<5yrs"].size } rescue {}
789
+ option1 = {'dataElement'=>get_ohsp_de_ids(key, type)[1],
790
+ 'categoryOptionCombo'=> get_ohsp_de_ids(key, type)[2],
791
+ 'value'=>value['<5yrs'].size } rescue {}
829
792
 
830
- payload["dataValues"] << option1
793
+ payload['dataValues'] << option1
831
794
  when special[1]
832
- option2 = {"dataElement"=>get_ohsp_de_ids(key,type)[1],
833
- "categoryOptionCombo"=> get_ohsp_de_ids(key,type)[3],
834
- "value"=>value[">=5yrs"].size } rescue {}
795
+ option2 = {'dataElement'=>get_ohsp_de_ids(key, type)[1],
796
+ 'categoryOptionCombo'=> get_ohsp_de_ids(key, type)[3],
797
+ 'value'=>value['>=5yrs'].size } rescue {}
835
798
 
836
- payload["dataValues"] << option2
799
+ payload['dataValues'] << option2
837
800
  when special[2]
838
- option1 = {"dataElement"=>get_ohsp_de_ids(key,type)[1],
839
- "categoryOptionCombo"=> get_ohsp_de_ids(key,type)[2],
840
- "value"=>value["<5yrs"].size } rescue {}
801
+ option1 = {'dataElement'=>get_ohsp_de_ids(key, type)[1],
802
+ 'categoryOptionCombo'=> get_ohsp_de_ids(key, type)[2],
803
+ 'value'=>value['<5yrs'].size } rescue {}
841
804
 
842
- payload["dataValues"] << option1
805
+ payload['dataValues'] << option1
843
806
  when special[3]
844
- option1 = {"dataElement"=>get_ohsp_de_ids(key,type)[1],
845
- "categoryOptionCombo"=> get_ohsp_de_ids(key,type)[2],
846
- "value"=>value["<5yrs"].size} rescue {}
807
+ option1 = {'dataElement'=>get_ohsp_de_ids(key, type)[1],
808
+ 'categoryOptionCombo'=> get_ohsp_de_ids(key, type)[2],
809
+ 'value'=>value['<5yrs'].size} rescue {}
847
810
 
848
- payload["dataValues"] << option1
811
+ payload['dataValues'] << option1
849
812
  end
850
813
  end
851
814
  end
@@ -855,49 +818,45 @@ module EmrOhspInterface
855
818
  puts url
856
819
  puts "pushing #{type} IDSR Reports"
857
820
  send = RestClient::Request.execute(method: :post,
858
- url: url,
859
- headers:{'Content-Type'=> 'application/json'},
860
- payload: payload.to_json,
861
- #headers: {accept: :json},
862
- user: conn["username"],
863
- password: conn["password"])
821
+ url: url,
822
+ headers:{'Content-Type'=> 'application/json'},
823
+ payload: payload.to_json,
824
+ # headers: {accept: :json},
825
+ user: conn['username'],
826
+ password: conn['password'])
864
827
 
865
828
  puts send
866
829
  end
867
830
 
868
831
  def send_data_to_sms_portal(data, concept_name_collection)
869
832
  conn2 = server_config['idsr_sms']
870
- data = data.select {|k,v| v.select {|kk,vv| vv.length > 0}.length > 0}
833
+ data = data.select { |k, v| v.select { |kk, vv| vv.length > 0 }.length > 0 }
871
834
  payload = {
872
- "email"=> conn2["username"],
873
- "password" => conn2["password"],
874
- "emr_facility_id" => Location.current_health_center.id,
875
- "emr_facility_name" => Location.current_health_center.name,
876
- "payload" => data,
877
- "concept_name_collection" => concept_name_collection
835
+ 'email'=> conn2['username'],
836
+ 'password' => conn2['password'],
837
+ 'emr_facility_id' => Location.current_health_center.id,
838
+ 'emr_facility_name' => Location.current_health_center.name,
839
+ 'payload' => data,
840
+ 'concept_name_collection' => concept_name_collection
878
841
  }
879
842
 
880
843
 
881
844
 
882
845
  begin
883
846
  response = RestClient::Request.execute(method: :post,
884
- url: conn2["url"],
885
- headers:{'Content-Type'=> 'application/json'},
886
- payload: payload.to_json
847
+ url: conn2['url'],
848
+ headers:{'Content-Type'=> 'application/json'},
849
+ payload: payload.to_json
887
850
  )
888
851
  rescue RestClient::ExceptionWithResponse => res
889
- if res.class == RestClient::Forbidden
890
- puts "error: #{res.class}"
891
- end
852
+ puts "error: #{res.class}" if res.class == RestClient::Forbidden
892
853
  end
893
854
 
894
855
  if response.class != NilClass
895
- if response.code == 200
896
- puts "success: #{response}"
897
- end
856
+ puts "success: #{response}" if response.code == 200
898
857
  end
899
858
 
900
- end
859
+ end
901
860
 
902
861
  end
903
862
  end