1
2 """GNUmed clinical patient record."""
3
4 __author__ = "K.Hilbert <Karsten.Hilbert@gmx.net>"
5 __license__ = "GPL v2 or later"
6
7
8 import sys
9 import logging
10 import threading
11 import datetime as pydt
12
13 if __name__ == '__main__':
14 sys.path.insert(0, '../../')
15
16 from Gnumed.pycommon import gmI18N
17 from Gnumed.pycommon import gmDateTime
18
19 if __name__ == '__main__':
20 from Gnumed.pycommon import gmLog2
21 gmI18N.activate_locale()
22 gmI18N.install_domain()
23 gmDateTime.init()
24
25 from Gnumed.pycommon import gmExceptions
26 from Gnumed.pycommon import gmPG2
27 from Gnumed.pycommon import gmDispatcher
28 from Gnumed.pycommon import gmCfg
29 from Gnumed.pycommon import gmTools
30
31 from Gnumed.business import gmGenericEMRItem
32 from Gnumed.business import gmAllergy
33 from Gnumed.business import gmPathLab
34 from Gnumed.business import gmLOINC
35 from Gnumed.business import gmClinNarrative
36 from Gnumed.business import gmSoapDefs
37 from Gnumed.business import gmEMRStructItems
38 from Gnumed.business import gmMedication
39 from Gnumed.business import gmVaccination
40 from Gnumed.business import gmFamilyHistory
41 from Gnumed.business import gmExternalCare
42 from Gnumed.business import gmOrganization
43 from Gnumed.business import gmAutoHints
44 from Gnumed.business.gmDemographicRecord import get_occupations
45
46
47 _log = logging.getLogger('gm.emr')
48
49 _here = None
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66 from Gnumed.business.gmDocuments import cDocument
67 from Gnumed.business.gmProviderInbox import cInboxMessage
68
69 _map_table2class = {
70 'clin.encounter': gmEMRStructItems.cEncounter,
71 'clin.episode': gmEMRStructItems.cEpisode,
72 'clin.health_issue': gmEMRStructItems.cHealthIssue,
73 'clin.external_care': gmExternalCare.cExternalCareItem,
74 'clin.vaccination': gmVaccination.cVaccination,
75 'clin.clin_narrative': gmClinNarrative.cNarrative,
76 'clin.test_result': gmPathLab.cTestResult,
77 'clin.substance_intake': gmMedication.cSubstanceIntakeEntry,
78 'clin.hospital_stay': gmEMRStructItems.cHospitalStay,
79 'clin.procedure': gmEMRStructItems.cPerformedProcedure,
80 'clin.allergy': gmAllergy.cAllergy,
81 'clin.allergy_state': gmAllergy.cAllergyState,
82 'clin.family_history': gmFamilyHistory.cFamilyHistory,
83 'clin.suppressed_hint': gmAutoHints.cSuppressedHint,
84 'blobs.doc_med': cDocument,
85 'dem.message_inbox': cInboxMessage,
86 'ref.auto_hint': gmAutoHints.cDynamicHint
87 }
88
90 try:
91 item_class = _map_table2class[table]
92 except KeyError:
93 _log.error('unmapped clin_root_item entry [%s], cannot instantiate', table)
94 return None
95
96 return item_class(aPK_obj = pk)
97
98
128
129
132
133
134 _delayed_execute = __noop_delayed_execute
135
136
138 if not callable(executor):
139 raise TypeError('executor <%s> is not callable' % executor)
140 global _delayed_execute
141 _delayed_execute = executor
142 _log.debug('setting delayed executor to <%s>', executor)
143
144
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
207 _log.debug('cleaning up after clinical record for patient [%s]' % self.pk_patient)
208 if self.__encounter is not None:
209 self.__encounter.unlock(exclusive = False)
210 return True
211
212
214 if action is None:
215 action = 'EMR access for pk_identity [%s]' % self.pk_patient
216 args = {'action': action}
217 cmd = 'SELECT gm.log_access2emr(%(action)s)'
218 gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
219
220
233
234 calculator = property(_get_calculator, lambda x:x)
235
236
237
238
244
245
247
248 if kwds['table'] != 'clin.encounter':
249 return True
250 if self.current_encounter is None:
251 _log.debug('no local current-encounter, ignoring encounter modification signal')
252 return True
253 if int(kwds['pk_of_row']) != self.current_encounter['pk_encounter']:
254 _log.debug('modified encounter [%s] != local encounter [%s], ignoring signal', kwds['pk_of_row'], self.current_encounter['pk_encounter'])
255 return True
256
257 _log.debug('modification of our encounter (%s) signalled (%s)', self.current_encounter['pk_encounter'], kwds['pk_of_row'])
258
259
260
261 curr_enc_in_db = gmEMRStructItems.cEncounter(aPK_obj = self.current_encounter['pk_encounter'])
262
263
264
265
266
267
268 if curr_enc_in_db['xmin_encounter'] == self.current_encounter['xmin_encounter']:
269 _log.debug('same XMIN, no difference between DB and in-client instance of current encounter expected')
270 if self.current_encounter.is_modified():
271 _log.error('encounter modification signal from DB with same XMIN as in local in-client instance of encounter BUT local instance ALSO has .is_modified()=True')
272 _log.error('this hints at an error in .is_modified handling')
273 gmTools.compare_dict_likes(self.current_encounter.fields_as_dict(), curr_enc_in_db.fields_as_dict(), 'modified enc in client', 'enc loaded from DB')
274 return True
275
276
277
278
279
280 if self.current_encounter.is_modified():
281 gmTools.compare_dict_likes(self.current_encounter.fields_as_dict(), curr_enc_in_db.fields_as_dict(), 'modified enc in client', 'signalled enc loaded from DB')
282 raise ValueError('unsaved changes in locally active encounter [%s], cannot switch to DB state of encounter [%s]' % (
283 self.current_encounter['pk_encounter'],
284 curr_enc_in_db['pk_encounter']
285 ))
286
287
288
289
290
291
292
293
294
295
296
297
298
299 gmTools.compare_dict_likes(self.current_encounter.fields_as_dict(), curr_enc_in_db.fields_as_dict(), 'modified enc in client', 'enc loaded from DB')
300 _log.debug('active encounter modified remotely, no locally pending changes, reloading from DB and locally announcing the remote modification')
301 self.current_encounter.refetch_payload()
302 gmDispatcher.send('current_encounter_modified')
303
304 return True
305
306
308
309
310
311 curr_enc_in_db = gmEMRStructItems.cEncounter(aPK_obj = self.current_encounter['pk_encounter'])
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326 if self.current_encounter.is_modified():
327 gmTools.compare_dict_likes(self.current_encounter.fields_as_dict(), curr_enc_in_db.fields_as_dict(), 'modified enc in client', 'enc loaded from DB')
328 _log.error('current in client: %s', self.current_encounter)
329 raise ValueError('unsaved changes in active encounter [%s], cannot switch [%s]' % (
330 self.current_encounter['pk_encounter'],
331 curr_enc_in_db['pk_encounter']
332 ))
333
334 if self.current_encounter.same_payload(another_object = curr_enc_in_db):
335 _log.debug('clin.encounter_mod_db received but no change to active encounter payload')
336 return True
337
338
339
340
341
342 gmTools.compare_dict_likes(self.current_encounter.fields_as_dict(), curr_enc_in_db.fields_as_dict(), 'modified enc in client', 'enc loaded from DB')
343 _log.debug('active encounter modified remotely, reloading from DB and locally announcing the modification')
344 self.current_encounter.refetch_payload()
345 gmDispatcher.send('current_encounter_modified')
346
347 return True
348
349
350
351
352 - def get_family_history(self, episodes=None, issues=None, encounters=None):
353 fhx = gmFamilyHistory.get_family_history (
354 order_by = 'l10n_relation, condition',
355 patient = self.pk_patient
356 )
357
358 if episodes is not None:
359 fhx = [ f for f in fhx if f['pk_episode'] in episodes ]
360
361 if issues is not None:
362 fhx = [ f for f in fhx if f['pk_health_issue'] in issues ]
363
364 if encounters is not None:
365 fhx = [ f for f in fhx if f['pk_encounter'] in encounters ]
366
367 return fhx
368
369
370 - def add_family_history(self, episode=None, condition=None, relation=None):
371 return gmFamilyHistory.create_family_history (
372 encounter = self.current_encounter['pk_encounter'],
373 episode = episode,
374 condition = condition,
375 relation = relation
376 )
377
378
379
380
382 if self.__gender is not None:
383 return self.__gender
384 cmd = 'SELECT gender, dob FROM dem.v_all_persons WHERE pk_identity = %(pat)s'
385 args = {'pat': self.pk_patient}
386 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
387 self.__gender = rows[0]['gender']
388 self.__dob = rows[0]['dob']
389
392
393 gender = property(_get_gender, _set_gender)
394
395
397 if self.__dob is not None:
398 return self.__dob
399 cmd = 'SELECT gender, dob FROM dem.v_all_persons WHERE pk_identity = %(pat)s'
400 args = {'pat': self.pk_patient}
401 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
402 self.__gender = rows[0]['gender']
403 self.__dob = rows[0]['dob']
404
407
408 dob = property(_get_dob, _set_dob)
409
410
412 cmd = 'SELECT edc FROM clin.patient WHERE fk_identity = %(pat)s'
413 args = {'pat': self.pk_patient}
414 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
415 if len(rows) == 0:
416 return None
417 return rows[0]['edc']
418
420 cmd = """
421 INSERT INTO clin.patient (fk_identity, edc) SELECT
422 %(pat)s,
423 %(edc)s
424 WHERE NOT EXISTS (
425 SELECT 1 FROM clin.patient WHERE fk_identity = %(pat)s
426 )
427 RETURNING pk"""
428 args = {'pat': self.pk_patient, 'edc': edc}
429 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False, return_data = True)
430 if len(rows) == 0:
431 cmd = 'UPDATE clin.patient SET edc = %(edc)s WHERE fk_identity = %(pat)s'
432 gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
433
434 EDC = property(_get_EDC, _set_EDC)
435
436
438 edc = self.EDC
439 if edc is None:
440 return False
441 if self.gender != 'f':
442 return True
443 now = gmDateTime.pydt_now_here()
444
445 if (self.dob + pydt.timedelta(weeks = 5 * 52)) > now:
446 return True
447
448 if (self.dob + pydt.timedelta(weeks = 55 * 52)) < now:
449 return True
450
451
452 if (edc - pydt.timedelta(days = 380)) > now:
453 return True
454
455
456
457
458 if edc < (now - pydt.timedelta(days = 380)):
459 return True
460
461 EDC_is_fishy = property(_EDC_is_fishy, lambda x:x)
462
463
465 try:
466 details['quit_when']
467 except KeyError:
468 details['quit_when'] = None
469
470 try:
471 details['last_confirmed']
472 if details['last_confirmed'] is None:
473 details['last_confirmed'] = gmDateTime.pydt_now_here()
474 except KeyError:
475 details['last_confirmed'] = gmDateTime.pydt_now_here()
476
477 try:
478 details['comment']
479 if details['comment'].strip() == '':
480 details['comment'] = None
481 except KeyError:
482 details['comment'] = None
483
484 return details
485
486
492
494
495 status_flag, details = status
496 self.__harmful_substance_use = None
497 args = {
498 'pat': self.pk_patient,
499 'status': status_flag
500 }
501 if status_flag is None:
502 cmd = 'UPDATE clin.patient SET smoking_status = %(status)s, smoking_details = NULL WHERE fk_identity = %(pat)s'
503 elif status_flag == 0:
504 details['quit_when'] = None
505 args['details'] = gmTools.dict2json(self.__normalize_smoking_details(details))
506 cmd = 'UPDATE clin.patient SET smoking_status = %(status)s, smoking_details = %(details)s WHERE fk_identity = %(pat)s'
507 else:
508 args['details'] = gmTools.dict2json(self.__normalize_smoking_details(details))
509 cmd = 'UPDATE clin.patient SET smoking_status = %(status)s, smoking_details = %(details)s WHERE fk_identity = %(pat)s'
510 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
511
512 smoking_status = property(_get_smoking_status, _set_smoking_status)
513
514
520
522
523 harmful, details = status
524 self.__harmful_substance_use = None
525 args = {'pat': self.pk_patient}
526 if harmful is None:
527 cmd = 'UPDATE clin.patient SET c2_currently_harmful_use = NULL, c2_details = NULL WHERE fk_identity = %(pat)s'
528 elif harmful is False:
529 cmd = 'UPDATE clin.patient SET c2_currently_harmful_use = FALSE, c2_details = gm.nullify_empty_string(%(details)s) WHERE fk_identity = %(pat)s'
530 else:
531 cmd = 'UPDATE clin.patient SET c2_currently_harmful_use = TRUE, c2_details = gm.nullify_empty_string(%(details)s) WHERE fk_identity = %(pat)s'
532 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
533
534 alcohol_status = property(_get_alcohol_status, _set_alcohol_status)
535
536
542
544
545 harmful, details = status
546 self.__harmful_substance_use = None
547 args = {'pat': self.pk_patient}
548 if harmful is None:
549 cmd = 'UPDATE clin.patient SET drugs_currently_harmful_use = NULL, drugs_details = NULL WHERE fk_identity = %(pat)s'
550 elif harmful is False:
551 cmd = 'UPDATE clin.patient SET drugs_currently_harmful_use = FALSE, drugs_details = gm.nullify_empty_string(%(details)s) WHERE fk_identity = %(pat)s'
552 else:
553 cmd = 'UPDATE clin.patient SET drugs_currently_harmful_use = TRUE, drugs_details = gm.nullify_empty_string(%(details)s) WHERE fk_identity = %(pat)s'
554 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
555
556 drugs_status = property(_get_drugs_status, _set_drugs_status)
557
558
560
561 try:
562 self.__harmful_substance_use
563 except AttributeError:
564 self.__harmful_substance_use = None
565
566 if self.__harmful_substance_use is not None:
567 return self.__harmful_substance_use
568
569 args = {'pat': self.pk_patient}
570 cmd = """
571 SELECT
572 -- tobacco use
573 smoking_status,
574 smoking_details,
575 (smoking_details->>'last_confirmed')::timestamp with time zone
576 AS ts_last,
577 (smoking_details->>'quit_when')::timestamp with time zone
578 AS ts_quit,
579 -- c2 use
580 c2_currently_harmful_use,
581 c2_details,
582 -- other drugs use
583 drugs_currently_harmful_use,
584 drugs_details
585 FROM clin.patient
586 WHERE fk_identity = %(pat)s
587 """
588 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
589 if len(rows) == 0:
590 return None
591
592 status = rows[0]['smoking_status']
593 details = rows[0]['smoking_details']
594 if status is not None:
595 details['last_confirmed'] = rows[0]['ts_last']
596 details['quit_when'] = rows[0]['ts_quit']
597
598 self.__harmful_substance_use = {
599 'tobacco': (status, details),
600 'alcohol': (rows[0]['c2_currently_harmful_use'], rows[0]['c2_details']),
601 'drugs': (rows[0]['drugs_currently_harmful_use'], rows[0]['drugs_details'])
602 }
603
604 return self.__harmful_substance_use
605
606
608 cmd = 'SELECT * FROM clin.v_substance_intakes WHERE harmful_use_type = %s'
609
610 harmful_substance_use = property(_get_harmful_substance_use, lambda x:x)
611
612
691
692
694
695
696 use = self.harmful_substance_use
697
698 if use['alcohol'][0] is True:
699 return True
700 if use['drugs'][0] is True:
701 return True
702 if use['tobacco'][0] > 0:
703
704 if use['tobacco'][1]['quit_when'] is None:
705 return True
706
707
708 if use['alcohol'][0] is None:
709 return None
710 if use['drugs'][0] is None:
711 return None
712 if use['tobacco'][0] is None:
713 return None
714
715
716
717 return False
718
719 currently_abuses_substances = property(_get_currently_abuses_substances, lambda x:x)
720
721
722
723
735
736 performed_procedures = property(get_performed_procedures, lambda x:x)
737
740
749
751 where = 'pk_org_unit IN (SELECT DISTINCT pk_org_unit FROM clin.v_procedures_not_at_hospital WHERE pk_patient = %(pat)s)'
752 args = {'pat': self.pk_patient}
753 cmd = gmOrganization._SQL_get_org_unit % where
754 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
755 return [ gmOrganization.cOrgUnit(row = {'pk_field': 'pk_org_unit', 'data': r, 'idx': idx}) for r in rows ]
756
757
758
759
767
768 hospital_stays = property(get_hospital_stays, lambda x:x)
769
772
779
781 args = {'pat': self.pk_patient, 'range': cover_period}
782 where_parts = ['pk_patient = %(pat)s']
783 if cover_period is not None:
784 where_parts.append('discharge > (now() - %(range)s)')
785
786 cmd = """
787 SELECT hospital, count(1) AS frequency
788 FROM clin.v_hospital_stays
789 WHERE
790 %s
791 GROUP BY hospital
792 ORDER BY frequency DESC
793 """ % ' AND '.join(where_parts)
794
795 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
796 return rows
797
799 where = 'pk_org_unit IN (SELECT DISTINCT pk_org_unit FROM clin.v_hospital_stays WHERE pk_patient = %(pat)s)'
800 args = {'pat': self.pk_patient}
801 cmd = gmOrganization._SQL_get_org_unit % where
802 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
803 return [ gmOrganization.cOrgUnit(row = {'pk_field': 'pk_org_unit', 'data': r, 'idx': idx}) for r in rows ]
804
805
806
807
808 - def add_notes(self, notes=None, episode=None, encounter=None):
821
822
837
838
839 - def get_clin_narrative(self, encounters=None, episodes=None, issues=None, soap_cats=None, providers=None):
840 """Get SOAP notes pertinent to this encounter.
841
842 encounters
843 - list of encounters the narrative of which are to be retrieved
844 episodes
845 - list of episodes the narrative of which are to be retrieved
846 issues
847 - list of health issues the narrative of which are to be retrieved
848 soap_cats
849 - list of SOAP categories of the narrative to be retrieved
850 """
851 where_parts = ['pk_patient = %(pat)s']
852 args = {'pat': self.pk_patient}
853
854 if issues is not None:
855 where_parts.append('pk_health_issue IN %(issues)s')
856 if len(issues) == 0:
857 args['issues'] = tuple()
858 else:
859 if isinstance(issues[0], gmEMRStructItems.cHealthIssue):
860 args['issues'] = tuple([ i['pk_health_issue'] for i in issues ])
861 elif isinstance(issues[0], int):
862 args['issues'] = tuple(issues)
863 else:
864 raise ValueError('<issues> must be list of type int (=pk) or cHealthIssue, but 1st issue is: %s' % issues[0])
865
866 if episodes is not None:
867 where_parts.append('pk_episode IN %(epis)s')
868 if len(episodes) == 0:
869 args['epis'] = tuple()
870 else:
871 if isinstance(episodes[0], gmEMRStructItems.cEpisode):
872 args['epis'] = tuple([ e['pk_episode'] for e in episodes ])
873 elif isinstance(episodes[0], int):
874 args['epis'] = tuple(episodes)
875 else:
876 raise ValueError('<episodes> must be list of type int (=pk) or cEpisode, but 1st episode is: %s' % episodes[0])
877
878 if encounters is not None:
879 where_parts.append('pk_encounter IN %(encs)s')
880 if len(encounters) == 0:
881 args['encs'] = tuple()
882 else:
883 if isinstance(encounters[0], gmEMRStructItems.cEncounter):
884 args['encs'] = tuple([ e['pk_encounter'] for e in encounters ])
885 elif isinstance(encounters[0], int):
886 args['encs'] = tuple(encounters)
887 else:
888 raise ValueError('<encounters> must be list of type int (=pk) or cEncounter, but 1st encounter is: %s' % encounters[0])
889
890 if soap_cats is not None:
891 where_parts.append('c_vn.soap_cat IN %(cats)s')
892 args['cats'] = tuple(gmSoapDefs.soap_cats2list(soap_cats))
893
894 if providers is not None:
895 where_parts.append('c_vn.modified_by IN %(docs)s')
896 args['docs'] = tuple(providers)
897
898 cmd = """
899 SELECT
900 c_vn.*,
901 c_scr.rank AS soap_rank
902 FROM
903 clin.v_narrative c_vn
904 LEFT JOIN clin.soap_cat_ranks c_scr on c_vn.soap_cat = c_scr.soap_cat
905 WHERE %s
906 ORDER BY date, soap_rank
907 """ % ' AND '.join(where_parts)
908
909 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
910 return [ gmClinNarrative.cNarrative(row = {'pk_field': 'pk_narrative', 'idx': idx, 'data': row}) for row in rows ]
911
912
914
915 search_term = search_term.strip()
916 if search_term == '':
917 return []
918
919 cmd = """
920 SELECT
921 *,
922 coalesce((SELECT description FROM clin.episode WHERE pk = vn4s.pk_episode), vn4s.src_table)
923 as episode,
924 coalesce((SELECT description FROM clin.health_issue WHERE pk = vn4s.pk_health_issue), vn4s.src_table)
925 as health_issue,
926 (SELECT started FROM clin.encounter WHERE pk = vn4s.pk_encounter)
927 as encounter_started,
928 (SELECT last_affirmed FROM clin.encounter WHERE pk = vn4s.pk_encounter)
929 as encounter_ended,
930 (SELECT _(description) FROM clin.encounter_type WHERE pk = (SELECT fk_type FROM clin.encounter WHERE pk = vn4s.pk_encounter))
931 as encounter_type
932 from clin.v_narrative4search vn4s
933 WHERE
934 pk_patient = %(pat)s and
935 vn4s.narrative ~ %(term)s
936 order by
937 encounter_started
938 """
939 rows, idx = gmPG2.run_ro_queries(queries = [
940 {'cmd': cmd, 'args': {'pat': self.pk_patient, 'term': search_term}}
941 ])
942 return rows
943
944 - def get_text_dump(self, since=None, until=None, encounters=None, episodes=None, issues=None):
945 fields = [
946 'age',
947 "to_char(modified_when, 'YYYY-MM-DD @ HH24:MI') as modified_when",
948 'modified_by',
949 'clin_when',
950 "case is_modified when false then '%s' else '%s' end as modified_string" % (_('original entry'), _('modified entry')),
951 'pk_item',
952 'pk_encounter',
953 'pk_episode',
954 'pk_health_issue',
955 'src_table'
956 ]
957 select_from = "SELECT %s FROM clin.v_pat_items" % ', '.join(fields)
958
959 where_snippets = []
960 params = {}
961 where_snippets.append('pk_patient=%(pat_id)s')
962 params['pat_id'] = self.pk_patient
963 if not since is None:
964 where_snippets.append('clin_when >= %(since)s')
965 params['since'] = since
966 if not until is None:
967 where_snippets.append('clin_when <= %(until)s')
968 params['until'] = until
969
970
971
972 if not encounters is None and len(encounters) > 0:
973 params['enc'] = encounters
974 if len(encounters) > 1:
975 where_snippets.append('fk_encounter in %(enc)s')
976 else:
977 where_snippets.append('fk_encounter=%(enc)s')
978
979 if not episodes is None and len(episodes) > 0:
980 params['epi'] = episodes
981 if len(episodes) > 1:
982 where_snippets.append('fk_episode in %(epi)s')
983 else:
984 where_snippets.append('fk_episode=%(epi)s')
985
986 if not issues is None and len(issues) > 0:
987 params['issue'] = issues
988 if len(issues) > 1:
989 where_snippets.append('fk_health_issue in %(issue)s')
990 else:
991 where_snippets.append('fk_health_issue=%(issue)s')
992
993 where_clause = ' and '.join(where_snippets)
994 order_by = 'order by src_table, age'
995 cmd = "%s WHERE %s %s" % (select_from, where_clause, order_by)
996
997 rows, view_col_idx = gmPG.run_ro_query('historica', cmd, 1, params)
998 if rows is None:
999 _log.error('cannot load item links for patient [%s]' % self.pk_patient)
1000 return None
1001
1002
1003
1004
1005 items_by_table = {}
1006 for item in rows:
1007 src_table = item[view_col_idx['src_table']]
1008 pk_item = item[view_col_idx['pk_item']]
1009 if src_table not in items_by_table:
1010 items_by_table[src_table] = {}
1011 items_by_table[src_table][pk_item] = item
1012
1013
1014 issues = self.get_health_issues()
1015 issue_map = {}
1016 for issue in issues:
1017 issue_map[issue['pk_health_issue']] = issue['description']
1018 episodes = self.get_episodes()
1019 episode_map = {}
1020 for episode in episodes:
1021 episode_map[episode['pk_episode']] = episode['description']
1022 emr_data = {}
1023
1024 ro_conn = self._conn_pool.GetConnection('historica')
1025 curs = ro_conn.cursor()
1026 for src_table in items_by_table.keys():
1027 item_ids = items_by_table[src_table].keys()
1028
1029
1030 if len(item_ids) == 0:
1031 _log.info('no items in table [%s] ?!?' % src_table)
1032 continue
1033 elif len(item_ids) == 1:
1034 cmd = "SELECT * FROM %s WHERE pk_item=%%s order by modified_when" % src_table
1035 if not gmPG.run_query(curs, None, cmd, item_ids[0]):
1036 _log.error('cannot load items from table [%s]' % src_table)
1037
1038 continue
1039 elif len(item_ids) > 1:
1040 cmd = "SELECT * FROM %s WHERE pk_item in %%s order by modified_when" % src_table
1041 if not gmPG.run_query(curs, None, cmd, (tuple(item_ids),)):
1042 _log.error('cannot load items from table [%s]' % src_table)
1043
1044 continue
1045 rows = curs.fetchall()
1046 table_col_idx = gmPG.get_col_indices(curs)
1047
1048 for row in rows:
1049
1050 pk_item = row[table_col_idx['pk_item']]
1051 view_row = items_by_table[src_table][pk_item]
1052 age = view_row[view_col_idx['age']]
1053
1054 try:
1055 episode_name = episode_map[view_row[view_col_idx['pk_episode']]]
1056 except:
1057 episode_name = view_row[view_col_idx['pk_episode']]
1058 try:
1059 issue_name = issue_map[view_row[view_col_idx['pk_health_issue']]]
1060 except:
1061 issue_name = view_row[view_col_idx['pk_health_issue']]
1062
1063 if age not in emr_data:
1064 emr_data[age] = []
1065
1066 emr_data[age].append(
1067 _('%s: encounter (%s)') % (
1068 view_row[view_col_idx['clin_when']],
1069 view_row[view_col_idx['pk_encounter']]
1070 )
1071 )
1072 emr_data[age].append(_('health issue: %s') % issue_name)
1073 emr_data[age].append(_('episode : %s') % episode_name)
1074
1075
1076
1077 cols2ignore = [
1078 'pk_audit', 'row_version', 'modified_when', 'modified_by',
1079 'pk_item', 'id', 'fk_encounter', 'fk_episode', 'pk'
1080 ]
1081 col_data = []
1082 for col_name in table_col_idx.keys():
1083 if col_name in cols2ignore:
1084 continue
1085 emr_data[age].append("=> %s: %s" % (col_name, row[table_col_idx[col_name]]))
1086 emr_data[age].append("----------------------------------------------------")
1087 emr_data[age].append("-- %s from table %s" % (
1088 view_row[view_col_idx['modified_string']],
1089 src_table
1090 ))
1091 emr_data[age].append("-- written %s by %s" % (
1092 view_row[view_col_idx['modified_when']],
1093 view_row[view_col_idx['modified_by']]
1094 ))
1095 emr_data[age].append("----------------------------------------------------")
1096 curs.close()
1097 return emr_data
1098
1100 return self.pk_patient
1101
1103 union_query = '\n union all\n'.join ([
1104 """
1105 SELECT ((
1106 -- all relevant health issues + active episodes WITH health issue
1107 SELECT COUNT(1)
1108 FROM clin.v_problem_list
1109 WHERE
1110 pk_patient = %(pat)s
1111 AND
1112 pk_health_issue is not null
1113 ) + (
1114 -- active episodes WITHOUT health issue
1115 SELECT COUNT(1)
1116 FROM clin.v_problem_list
1117 WHERE
1118 pk_patient = %(pat)s
1119 AND
1120 pk_health_issue is null
1121 ))""",
1122 'SELECT count(1) FROM clin.encounter WHERE fk_patient = %(pat)s',
1123 'SELECT count(1) FROM clin.v_pat_items WHERE pk_patient = %(pat)s',
1124 'SELECT count(1) FROM blobs.v_doc_med WHERE pk_patient = %(pat)s',
1125 'SELECT count(1) FROM clin.v_test_results WHERE pk_patient = %(pat)s',
1126 'SELECT count(1) FROM clin.v_hospital_stays WHERE pk_patient = %(pat)s',
1127 'SELECT count(1) FROM clin.v_procedures WHERE pk_patient = %(pat)s',
1128
1129 """
1130 SELECT count(1)
1131 FROM clin.v_substance_intakes
1132 WHERE
1133 pk_patient = %(pat)s
1134 AND
1135 is_currently_active IN (null, true)
1136 AND
1137 intake_is_approved_of IN (null, true)""",
1138 'SELECT count(1) FROM clin.v_vaccinations WHERE pk_patient = %(pat)s'
1139 ])
1140
1141 rows, idx = gmPG2.run_ro_queries (
1142 queries = [{'cmd': union_query, 'args': {'pat': self.pk_patient}}],
1143 get_col_idx = False
1144 )
1145
1146 stats = dict (
1147 problems = rows[0][0],
1148 encounters = rows[1][0],
1149 items = rows[2][0],
1150 documents = rows[3][0],
1151 results = rows[4][0],
1152 stays = rows[5][0],
1153 procedures = rows[6][0],
1154 active_drugs = rows[7][0],
1155 vaccinations = rows[8][0]
1156 )
1157
1158 return stats
1159
1172
1305
1306
1327
1328
1329 - def get_as_journal(self, since=None, until=None, encounters=None, episodes=None, issues=None, soap_cats=None, providers=None, order_by=None, time_range=None):
1330 return gmClinNarrative.get_as_journal (
1331 patient = self.pk_patient,
1332 since = since,
1333 until = until,
1334 encounters = encounters,
1335 episodes = episodes,
1336 issues = issues,
1337 soap_cats = soap_cats,
1338 providers = providers,
1339 order_by = order_by,
1340 time_range = time_range,
1341 active_encounter = self.active_encounter
1342 )
1343
1344
1345 - def get_generic_emr_items(self, pk_encounters=None, pk_episodes=None, pk_health_issues=None, use_active_encounter=False, order_by=None):
1358
1359
1360
1361
1362 - def get_allergies(self, remove_sensitivities=False, since=None, until=None, encounters=None, episodes=None, issues=None, ID_list=None):
1363 """Retrieves patient allergy items.
1364
1365 remove_sensitivities
1366 - retrieve real allergies only, without sensitivities
1367 since
1368 - initial date for allergy items
1369 until
1370 - final date for allergy items
1371 encounters
1372 - list of encounters whose allergies are to be retrieved
1373 episodes
1374 - list of episodes whose allergies are to be retrieved
1375 issues
1376 - list of health issues whose allergies are to be retrieved
1377 """
1378 cmd = "SELECT * FROM clin.v_pat_allergies WHERE pk_patient=%s order by descriptor"
1379 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [self.pk_patient]}], get_col_idx = True)
1380 filtered_allergies = []
1381 for r in rows:
1382 filtered_allergies.append(gmAllergy.cAllergy(row = {'data': r, 'idx': idx, 'pk_field': 'pk_allergy'}))
1383
1384
1385 if ID_list is not None:
1386 filtered_allergies = [ allg for allg in filtered_allergies if allg['pk_allergy'] in ID_list ]
1387 if len(filtered_allergies) == 0:
1388 _log.error('no allergies of list [%s] found for patient [%s]' % (str(ID_list), self.pk_patient))
1389
1390 return None
1391 else:
1392 return filtered_allergies
1393
1394 if remove_sensitivities:
1395 filtered_allergies = [ allg for allg in filtered_allergies if allg['type'] == 'allergy' ]
1396 if since is not None:
1397 filtered_allergies = [ allg for allg in filtered_allergies if allg['date'] >= since ]
1398 if until is not None:
1399 filtered_allergies = [ allg for allg in filtered_allergies if allg['date'] < until ]
1400 if issues is not None:
1401 filtered_allergies = [ allg for allg in filtered_allergies if allg['pk_health_issue'] in issues ]
1402 if episodes is not None:
1403 filtered_allergies = [ allg for allg in filtered_allergies if allg['pk_episode'] in episodes ]
1404 if encounters is not None:
1405 filtered_allergies = [ allg for allg in filtered_allergies if allg['pk_encounter'] in encounters ]
1406
1407 return filtered_allergies
1408
1409 - def add_allergy(self, allergene=None, allg_type=None, encounter_id=None, episode_id=None):
1410 if encounter_id is None:
1411 encounter_id = self.current_encounter['pk_encounter']
1412
1413 if episode_id is None:
1414 issue = self.add_health_issue(issue_name = _('Allergies/Intolerances'))
1415 epi = self.add_episode(episode_name = _('Allergy detail: %s') % allergene, pk_health_issue = issue['pk_health_issue'])
1416 episode_id = epi['pk_episode']
1417
1418 new_allergy = gmAllergy.create_allergy (
1419 allergene = allergene,
1420 allg_type = allg_type,
1421 encounter_id = encounter_id,
1422 episode_id = episode_id
1423 )
1424
1425 return new_allergy
1426
1428 cmd = 'delete FROM clin.allergy WHERE pk=%(pk_allg)s'
1429 args = {'pk_allg': pk_allergy}
1430 gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
1431
1432
1434 """Cave: only use with one potential allergic agent
1435 otherwise you won't know which of the agents the allergy is to."""
1436
1437
1438 if self.allergy_state is None:
1439 return None
1440
1441
1442 if self.allergy_state == 0:
1443 return False
1444
1445 args = {
1446 'atcs': atcs,
1447 'inns': inns,
1448 'prod_name': product_name,
1449 'pat': self.pk_patient
1450 }
1451 allergenes = []
1452 where_parts = []
1453
1454 if len(atcs) == 0:
1455 atcs = None
1456 if atcs is not None:
1457 where_parts.append('atc_code in %(atcs)s')
1458 if len(inns) == 0:
1459 inns = None
1460 if inns is not None:
1461 where_parts.append('generics in %(inns)s')
1462 allergenes.extend(inns)
1463 if product_name is not None:
1464 where_parts.append('substance = %(prod_name)s')
1465 allergenes.append(product_name)
1466
1467 if len(allergenes) != 0:
1468 where_parts.append('allergene in %(allgs)s')
1469 args['allgs'] = tuple(allergenes)
1470
1471 cmd = """
1472 SELECT * FROM clin.v_pat_allergies
1473 WHERE
1474 pk_patient = %%(pat)s
1475 AND ( %s )""" % ' OR '.join(where_parts)
1476
1477 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
1478
1479 if len(rows) == 0:
1480 return False
1481
1482 return gmAllergy.cAllergy(row = {'data': rows[0], 'idx': idx, 'pk_field': 'pk_allergy'})
1483
1493
1496
1497 allergy_state = property(_get_allergy_state, _set_allergy_state)
1498
1499
1500
1507
1508 external_care_items = property(get_external_care_items, lambda x:x)
1509
1510
1511
1512
1513 - def get_episodes(self, id_list=None, issues=None, open_status=None, order_by=None, unlinked_only=False):
1514 """Fetches from backend patient episodes.
1515
1516 id_list - Episodes' PKs list
1517 issues - Health issues' PKs list to filter episodes by
1518 open_status - return all (None) episodes, only open (True) or closed (False) one(s)
1519 """
1520 if (unlinked_only is True) and (issues is not None):
1521 raise ValueError('<unlinked_only> cannot be TRUE if <issues> is not None')
1522
1523 if order_by is None:
1524 order_by = ''
1525 else:
1526 order_by = 'ORDER BY %s' % order_by
1527
1528 args = {
1529 'pat': self.pk_patient,
1530 'open': open_status
1531 }
1532 where_parts = ['pk_patient = %(pat)s']
1533
1534 if open_status is not None:
1535 where_parts.append('episode_open IS %(open)s')
1536
1537 if unlinked_only:
1538 where_parts.append('pk_health_issue is NULL')
1539
1540 if issues is not None:
1541 where_parts.append('pk_health_issue IN %(issues)s')
1542 args['issues'] = tuple(issues)
1543
1544 if id_list is not None:
1545 where_parts.append('pk_episode IN %(epis)s')
1546 args['epis'] = tuple(id_list)
1547
1548 cmd = "SELECT * FROM clin.v_pat_episodes WHERE %s %s" % (
1549 ' AND '.join(where_parts),
1550 order_by
1551 )
1552 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
1553
1554 return [ gmEMRStructItems.cEpisode(row = {'data': r, 'idx': idx, 'pk_field': 'pk_episode'}) for r in rows ]
1555
1556 episodes = property(get_episodes, lambda x:x)
1557
1559 return self.get_episodes(open_status = open_status, order_by = order_by, unlinked_only = True)
1560
1561 unlinked_episodes = property(get_unlinked_episodes, lambda x:x)
1562
1564 cmd = """SELECT distinct pk_episode
1565 from clin.v_pat_items
1566 WHERE pk_encounter=%(enc)s and pk_patient=%(pat)s"""
1567 args = {
1568 'enc': gmTools.coalesce(pk_encounter, self.current_encounter['pk_encounter']),
1569 'pat': self.pk_patient
1570 }
1571 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])
1572 if len(rows) == 0:
1573 return []
1574 epis = []
1575 for row in rows:
1576 epis.append(row[0])
1577 return self.get_episodes(id_list=epis)
1578
1579 - def add_episode(self, episode_name=None, pk_health_issue=None, is_open=False, allow_dupes=False, link_obj=None):
1580 """Add episode 'episode_name' for a patient's health issue.
1581
1582 - silently returns if episode already exists
1583 """
1584 episode = gmEMRStructItems.create_episode (
1585 link_obj = link_obj,
1586 pk_health_issue = pk_health_issue,
1587 episode_name = episode_name,
1588 is_open = is_open,
1589 encounter = self.current_encounter['pk_encounter'],
1590 allow_dupes = allow_dupes
1591 )
1592 return episode
1593
1595
1596
1597 issue_where = gmTools.coalesce(issue, '', 'and pk_health_issue = %(issue)s')
1598
1599 cmd = """
1600 SELECT pk
1601 from clin.episode
1602 WHERE pk = (
1603 SELECT distinct on(pk_episode) pk_episode
1604 from clin.v_pat_items
1605 WHERE
1606 pk_patient = %%(pat)s
1607 and
1608 modified_when = (
1609 SELECT max(vpi.modified_when)
1610 from clin.v_pat_items vpi
1611 WHERE vpi.pk_patient = %%(pat)s
1612 )
1613 %s
1614 -- guard against several episodes created at the same moment of time
1615 limit 1
1616 )""" % issue_where
1617 rows, idx = gmPG2.run_ro_queries(queries = [
1618 {'cmd': cmd, 'args': {'pat': self.pk_patient, 'issue': issue}}
1619 ])
1620 if len(rows) != 0:
1621 return gmEMRStructItems.cEpisode(aPK_obj=rows[0][0])
1622
1623
1624
1625 cmd = """
1626 SELECT vpe0.pk_episode
1627 from
1628 clin.v_pat_episodes vpe0
1629 WHERE
1630 vpe0.pk_patient = %%(pat)s
1631 and
1632 vpe0.episode_modified_when = (
1633 SELECT max(vpe1.episode_modified_when)
1634 from clin.v_pat_episodes vpe1
1635 WHERE vpe1.pk_episode = vpe0.pk_episode
1636 )
1637 %s""" % issue_where
1638 rows, idx = gmPG2.run_ro_queries(queries = [
1639 {'cmd': cmd, 'args': {'pat': self.pk_patient, 'issue': issue}}
1640 ])
1641 if len(rows) != 0:
1642 return gmEMRStructItems.cEpisode(aPK_obj=rows[0][0])
1643
1644 return None
1645
1648
1649
1650
1651 - def get_problems(self, episodes=None, issues=None, include_closed_episodes=False, include_irrelevant_issues=False):
1652 """Retrieve a patient's problems.
1653
1654 "Problems" are the UNION of:
1655
1656 - issues which are .clinically_relevant
1657 - episodes which are .is_open
1658
1659 Therefore, both an issue and the open episode
1660 thereof can each be listed as a problem.
1661
1662 include_closed_episodes/include_irrelevant_issues will
1663 include those -- which departs from the definition of
1664 the problem list being "active" items only ...
1665
1666 episodes - episodes' PKs to filter problems by
1667 issues - health issues' PKs to filter problems by
1668 """
1669
1670
1671 args = {'pat': self.pk_patient}
1672
1673 cmd = """SELECT pk_health_issue, pk_episode FROM clin.v_problem_list WHERE pk_patient = %(pat)s ORDER BY problem"""
1674 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
1675
1676
1677 problems = []
1678 for row in rows:
1679 pk_args = {
1680 'pk_patient': self.pk_patient,
1681 'pk_health_issue': row['pk_health_issue'],
1682 'pk_episode': row['pk_episode']
1683 }
1684 problems.append(gmEMRStructItems.cProblem(aPK_obj = pk_args, try_potential_problems = False))
1685
1686
1687 other_rows = []
1688 if include_closed_episodes:
1689 cmd = """SELECT pk_health_issue, pk_episode FROM clin.v_potential_problem_list WHERE pk_patient = %(pat)s and type = 'episode'"""
1690 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
1691 other_rows.extend(rows)
1692
1693 if include_irrelevant_issues:
1694 cmd = """SELECT pk_health_issue, pk_episode FROM clin.v_potential_problem_list WHERE pk_patient = %(pat)s and type = 'health issue'"""
1695 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
1696 other_rows.extend(rows)
1697
1698 if len(other_rows) > 0:
1699 for row in other_rows:
1700 pk_args = {
1701 'pk_patient': self.pk_patient,
1702 'pk_health_issue': row['pk_health_issue'],
1703 'pk_episode': row['pk_episode']
1704 }
1705 problems.append(gmEMRStructItems.cProblem(aPK_obj = pk_args, try_potential_problems = True))
1706
1707
1708 if issues is not None:
1709 problems = [ p for p in problems if p['pk_health_issue'] in issues ]
1710 if episodes is not None:
1711 problems = [ p for p in problems if p['pk_episode'] in episodes ]
1712
1713 return problems
1714
1715
1718
1719
1722
1723
1726
1727
1729 cmd = "SELECT * FROM clin.v_candidate_diagnoses WHERE pk_patient = %(pat)s"
1730 rows, idx = gmPG2.run_ro_queries (
1731 queries = [{'cmd': cmd, 'args': {'pat': self.pk_patient}}],
1732 get_col_idx = False
1733 )
1734 return rows
1735
1736 candidate_diagnoses = property(get_candidate_diagnoses)
1737
1738
1739
1740
1742
1743 cmd = "SELECT *, xmin_health_issue FROM clin.v_health_issues WHERE pk_patient = %(pat)s ORDER BY description"
1744 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': {'pat': self.pk_patient}}], get_col_idx = True)
1745 issues = [ gmEMRStructItems.cHealthIssue(row = {'idx': idx, 'data': r, 'pk_field': 'pk_health_issue'}) for r in rows ]
1746
1747 if id_list is None:
1748 return issues
1749
1750 if len(id_list) == 0:
1751 raise ValueError('id_list to filter by is empty, most likely a programming error')
1752
1753 filtered_issues = []
1754 for issue in issues:
1755 if issue['pk_health_issue'] in id_list:
1756 filtered_issues.append(issue)
1757
1758 return filtered_issues
1759
1760 health_issues = property(get_health_issues, lambda x:x)
1761
1762
1770
1773
1774
1775
1776 - def get_current_medications(self, include_inactive=True, include_unapproved=False, order_by=None, episodes=None, issues=None):
1777 return self._get_current_substance_intakes (
1778 include_inactive = include_inactive,
1779 include_unapproved = include_unapproved,
1780 order_by = order_by,
1781 episodes = episodes,
1782 issues = issues,
1783 exclude_medications = False,
1784 exclude_potential_abuses = True
1785 )
1786
1787
1789 return self._get_current_substance_intakes (
1790 include_inactive = True,
1791 include_unapproved = True,
1792 order_by = order_by,
1793 episodes = None,
1794 issues = None,
1795 exclude_medications = True,
1796 exclude_potential_abuses = False
1797 )
1798
1799 abused_substances = property(_get_abused_substances, lambda x:x)
1800
1801
1802 - def _get_current_substance_intakes(self, include_inactive=True, include_unapproved=False, order_by=None, episodes=None, issues=None, exclude_potential_abuses=False, exclude_medications=False):
1803
1804 where_parts = ['pk_patient = %(pat)s']
1805 args = {'pat': self.pk_patient}
1806
1807 if not include_inactive:
1808 where_parts.append('is_currently_active IN (TRUE, NULL)')
1809
1810 if not include_unapproved:
1811 where_parts.append('intake_is_approved_of IN (TRUE, NULL)')
1812
1813 if exclude_potential_abuses:
1814 where_parts.append('harmful_use_type IS NULL')
1815
1816 if exclude_medications:
1817 where_parts.append('harmful_use_type IS NOT NULL')
1818
1819 if order_by is None:
1820 order_by = ''
1821 else:
1822 order_by = 'ORDER BY %s' % order_by
1823
1824 cmd = "SELECT * FROM clin.v_substance_intakes WHERE %s %s" % (
1825 '\nAND '.join(where_parts),
1826 order_by
1827 )
1828 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
1829 intakes = [ gmMedication.cSubstanceIntakeEntry(row = {'idx': idx, 'data': r, 'pk_field': 'pk_substance_intake'}) for r in rows ]
1830
1831 if episodes is not None:
1832 intakes = [ i for i in intakes if i['pk_episode'] in episodes ]
1833
1834 if issues is not None:
1835 intakes = [ i for i in intakes if i ['pk_health_issue'] in issues ]
1836
1837 return intakes
1838
1839
1840 - def add_substance_intake(self, pk_component=None, pk_episode=None, pk_drug_product=None, pk_health_issue=None):
1853
1854
1856 return gmMedication.substance_intake_exists (
1857 pk_component = pk_component,
1858 pk_substance = pk_substance,
1859 pk_identity = self.pk_patient,
1860 pk_drug_product = pk_drug_product
1861 )
1862
1863
1864
1865
1873
1874
1876 """Returns latest given vaccination for each vaccinated indication.
1877
1878 as a dict {'l10n_indication': cVaccination instance}
1879
1880 Note that this will produce duplicate vaccination instances on combi-indication vaccines !
1881 """
1882 args = {'pat': self.pk_patient}
1883 where_parts = ['c_v_shots.pk_patient = %(pat)s']
1884
1885 if (episodes is not None) and (len(episodes) > 0):
1886 where_parts.append('c_v_shots.pk_episode IN %(epis)s')
1887 args['epis'] = tuple(episodes)
1888
1889 if (issues is not None) and (len(issues) > 0):
1890 where_parts.append('c_v_shots.pk_episode IN (select pk from clin.episode where fk_health_issue IN %(issues)s)')
1891 args['issues'] = tuple(issues)
1892
1893 if (atc_indications is not None) and (len(atc_indications) > 0):
1894 where_parts.append('c_v_plv4i.atc_indication IN %(atc_inds)s')
1895 args['atc_inds'] = tuple(atc_indications)
1896
1897
1898 cmd = """
1899 SELECT
1900 c_v_shots.*,
1901 c_v_plv4i.l10n_indication,
1902 c_v_plv4i.no_of_shots
1903 FROM
1904 clin.v_vaccinations c_v_shots
1905 JOIN clin.v_pat_last_vacc4indication c_v_plv4i ON (c_v_shots.pk_vaccination = c_v_plv4i.pk_vaccination)
1906 WHERE %s
1907 """ % '\nAND '.join(where_parts)
1908 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
1909
1910
1911 if len(rows) == 0:
1912 return {}
1913
1914
1915
1916 vaccs = {}
1917 for shot_row in rows:
1918 vaccs[shot_row['l10n_indication']] = (
1919 shot_row['no_of_shots'],
1920 gmVaccination.cVaccination(row = {'idx': idx, 'data': shot_row, 'pk_field': 'pk_vaccination'})
1921 )
1922
1923 return vaccs
1924
1925
1926 - def get_vaccinations(self, order_by=None, episodes=None, issues=None, encounters=None):
1927 return gmVaccination.get_vaccinations (
1928 pk_identity = self.pk_patient,
1929 pk_episodes = episodes,
1930 pk_health_issues = issues,
1931 pk_encounters = encounters,
1932 order_by = order_by,
1933 return_pks = False
1934 )
1935
1936 vaccinations = property(get_vaccinations, lambda x:x)
1937
1938
1939
1940
1942 """Retrieves vaccination regimes the patient is on.
1943
1944 optional:
1945 * ID - PK of the vaccination regime
1946 * indications - indications we want to retrieve vaccination
1947 regimes for, must be primary language, not l10n_indication
1948 """
1949
1950
1951 cmd = """SELECT distinct on(pk_course) pk_course
1952 FROM clin.v_vaccs_scheduled4pat
1953 WHERE pk_patient=%s"""
1954 rows = gmPG.run_ro_query('historica', cmd, None, self.pk_patient)
1955 if rows is None:
1956 _log.error('cannot retrieve scheduled vaccination courses')
1957 return None
1958
1959 for row in rows:
1960 self.__db_cache['vaccinations']['scheduled regimes'].append(gmVaccination.cVaccinationCourse(aPK_obj=row[0]))
1961
1962
1963 filtered_regimes = []
1964 filtered_regimes.extend(self.__db_cache['vaccinations']['scheduled regimes'])
1965 if ID is not None:
1966 filtered_regimes = [ r for r in filtered_regimes if r['pk_course'] == ID ]
1967 if len(filtered_regimes) == 0:
1968 _log.error('no vaccination course [%s] found for patient [%s]' % (ID, self.pk_patient))
1969 return []
1970 else:
1971 return filtered_regimes[0]
1972 if indications is not None:
1973 filtered_regimes = [ r for r in filtered_regimes if r['indication'] in indications ]
1974
1975 return filtered_regimes
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003 - def get_vaccinations_old(self, ID=None, indications=None, since=None, until=None, encounters=None, episodes=None, issues=None):
2004 """Retrieves list of vaccinations the patient has received.
2005
2006 optional:
2007 * ID - PK of a vaccination
2008 * indications - indications we want to retrieve vaccination
2009 items for, must be primary language, not l10n_indication
2010 * since - initial date for allergy items
2011 * until - final date for allergy items
2012 * encounters - list of encounters whose allergies are to be retrieved
2013 * episodes - list of episodes whose allergies are to be retrieved
2014 * issues - list of health issues whose allergies are to be retrieved
2015 """
2016 try:
2017 self.__db_cache['vaccinations']['vaccinated']
2018 except KeyError:
2019 self.__db_cache['vaccinations']['vaccinated'] = []
2020
2021 cmd= """SELECT * FROM clin.v_pat_vaccinations4indication
2022 WHERE pk_patient=%s
2023 order by indication, date"""
2024 rows, idx = gmPG.run_ro_query('historica', cmd, True, self.pk_patient)
2025 if rows is None:
2026 _log.error('cannot load given vaccinations for patient [%s]' % self.pk_patient)
2027 del self.__db_cache['vaccinations']['vaccinated']
2028 return None
2029
2030 vaccs_by_ind = {}
2031 for row in rows:
2032 vacc_row = {
2033 'pk_field': 'pk_vaccination',
2034 'idx': idx,
2035 'data': row
2036 }
2037 vacc = gmVaccination.cVaccination(row=vacc_row)
2038 self.__db_cache['vaccinations']['vaccinated'].append(vacc)
2039
2040 try:
2041 vaccs_by_ind[vacc['indication']].append(vacc)
2042 except KeyError:
2043 vaccs_by_ind[vacc['indication']] = [vacc]
2044
2045
2046 for ind in vaccs_by_ind.keys():
2047 vacc_regimes = self.get_scheduled_vaccination_regimes(indications = [ind])
2048 for vacc in vaccs_by_ind[ind]:
2049
2050
2051 seq_no = vaccs_by_ind[ind].index(vacc) + 1
2052 vacc['seq_no'] = seq_no
2053
2054
2055 if (vacc_regimes is None) or (len(vacc_regimes) == 0):
2056 continue
2057 if seq_no > vacc_regimes[0]['shots']:
2058 vacc['is_booster'] = True
2059 del vaccs_by_ind
2060
2061
2062 filtered_shots = []
2063 filtered_shots.extend(self.__db_cache['vaccinations']['vaccinated'])
2064 if ID is not None:
2065 filtered_shots = filter(lambda shot: shot['pk_vaccination'] == ID, filtered_shots)
2066 if len(filtered_shots) == 0:
2067 _log.error('no vaccination [%s] found for patient [%s]' % (ID, self.pk_patient))
2068 return None
2069 else:
2070 return filtered_shots[0]
2071 if since is not None:
2072 filtered_shots = filter(lambda shot: shot['date'] >= since, filtered_shots)
2073 if until is not None:
2074 filtered_shots = filter(lambda shot: shot['date'] < until, filtered_shots)
2075 if issues is not None:
2076 filtered_shots = filter(lambda shot: shot['pk_health_issue'] in issues, filtered_shots)
2077 if episodes is not None:
2078 filtered_shots = filter(lambda shot: shot['pk_episode'] in episodes, filtered_shots)
2079 if encounters is not None:
2080 filtered_shots = filter(lambda shot: shot['pk_encounter'] in encounters, filtered_shots)
2081 if indications is not None:
2082 filtered_shots = filter(lambda shot: shot['indication'] in indications, filtered_shots)
2083 return filtered_shots
2084
2086 """Retrieves vaccinations scheduled for a regime a patient is on.
2087
2088 The regime is referenced by its indication (not l10n)
2089
2090 * indications - List of indications (not l10n) of regimes we want scheduled
2091 vaccinations to be fetched for
2092 """
2093 try:
2094 self.__db_cache['vaccinations']['scheduled']
2095 except KeyError:
2096 self.__db_cache['vaccinations']['scheduled'] = []
2097 cmd = """SELECT * FROM clin.v_vaccs_scheduled4pat WHERE pk_patient=%s"""
2098 rows, idx = gmPG.run_ro_query('historica', cmd, True, self.pk_patient)
2099 if rows is None:
2100 _log.error('cannot load scheduled vaccinations for patient [%s]' % self.pk_patient)
2101 del self.__db_cache['vaccinations']['scheduled']
2102 return None
2103
2104 for row in rows:
2105 vacc_row = {
2106 'pk_field': 'pk_vacc_def',
2107 'idx': idx,
2108 'data': row
2109 }
2110 self.__db_cache['vaccinations']['scheduled'].append(gmVaccination.cScheduledVaccination(row = vacc_row))
2111
2112
2113 if indications is None:
2114 return self.__db_cache['vaccinations']['scheduled']
2115 filtered_shots = []
2116 filtered_shots.extend(self.__db_cache['vaccinations']['scheduled'])
2117 filtered_shots = filter(lambda shot: shot['indication'] in indications, filtered_shots)
2118 return filtered_shots
2119
2121 try:
2122 self.__db_cache['vaccinations']['missing']
2123 except KeyError:
2124 self.__db_cache['vaccinations']['missing'] = {}
2125
2126 self.__db_cache['vaccinations']['missing']['due'] = []
2127
2128 cmd = "SELECT indication, seq_no FROM clin.v_pat_missing_vaccs WHERE pk_patient=%s"
2129 rows = gmPG.run_ro_query('historica', cmd, None, self.pk_patient)
2130 if rows is None:
2131 _log.error('error loading (indication, seq_no) for due/overdue vaccinations for patient [%s]' % self.pk_patient)
2132 return None
2133 pk_args = {'pat_id': self.pk_patient}
2134 if rows is not None:
2135 for row in rows:
2136 pk_args['indication'] = row[0]
2137 pk_args['seq_no'] = row[1]
2138 self.__db_cache['vaccinations']['missing']['due'].append(gmVaccination.cMissingVaccination(aPK_obj=pk_args))
2139
2140
2141 self.__db_cache['vaccinations']['missing']['boosters'] = []
2142
2143 cmd = "SELECT indication, seq_no FROM clin.v_pat_missing_boosters WHERE pk_patient=%s"
2144 rows = gmPG.run_ro_query('historica', cmd, None, self.pk_patient)
2145 if rows is None:
2146 _log.error('error loading indications for missing boosters for patient [%s]' % self.pk_patient)
2147 return None
2148 pk_args = {'pat_id': self.pk_patient}
2149 if rows is not None:
2150 for row in rows:
2151 pk_args['indication'] = row[0]
2152 self.__db_cache['vaccinations']['missing']['boosters'].append(gmVaccination.cMissingBooster(aPK_obj=pk_args))
2153
2154
2155 if indications is None:
2156 return self.__db_cache['vaccinations']['missing']
2157 if len(indications) == 0:
2158 return self.__db_cache['vaccinations']['missing']
2159
2160 filtered_shots = {
2161 'due': [],
2162 'boosters': []
2163 }
2164 for due_shot in self.__db_cache['vaccinations']['missing']['due']:
2165 if due_shot['indication'] in indications:
2166 filtered_shots['due'].append(due_shot)
2167 for due_shot in self.__db_cache['vaccinations']['missing']['boosters']:
2168 if due_shot['indication'] in indications:
2169 filtered_shots['boosters'].append(due_shot)
2170 return filtered_shots
2171
2172
2173
2174
2176 return self.__encounter
2177
2179
2180 if self.__encounter is None:
2181 _log.debug('first setting of active encounter in this clinical record instance')
2182 encounter.lock(exclusive = False)
2183 self.__encounter = encounter
2184 gmDispatcher.send('current_encounter_switched')
2185 return True
2186
2187
2188 _log.debug('switching of active encounter')
2189
2190 if self.__encounter.is_modified():
2191 gmTools.compare_dict_likes(self.__encounter, encounter, 'modified enc in client', 'enc to switch to')
2192 _log.error('current in client: %s', self.__encounter)
2193 raise ValueError('unsaved changes in active encounter [%s], cannot switch to another one [%s]' % (
2194 self.__encounter['pk_encounter'],
2195 encounter['pk_encounter']
2196 ))
2197
2198 prev_enc = self.__encounter
2199 encounter.lock(exclusive = False)
2200 self.__encounter = encounter
2201 prev_enc.unlock(exclusive = False)
2202 gmDispatcher.send('current_encounter_switched')
2203
2204 return True
2205
2206 current_encounter = property(_get_current_encounter, _set_current_encounter)
2207 active_encounter = property(_get_current_encounter, _set_current_encounter)
2208
2209
2211 _log.debug('setting up active encounter for identity [%s]', self.pk_patient)
2212
2213
2214 _delayed_execute(self.log_access, action = 'pulling chart for identity [%s]' % self.pk_patient)
2215
2216
2217
2218 self.remove_empty_encounters()
2219
2220
2221 if self.__activate_very_recent_encounter():
2222 return
2223
2224 fairly_recent_enc = self.__get_fairly_recent_encounter()
2225
2226
2227 self.start_new_encounter()
2228
2229 if fairly_recent_enc is None:
2230 return
2231
2232
2233 gmDispatcher.send (
2234 signal = 'ask_for_encounter_continuation',
2235 new_encounter = self.__encounter,
2236 fairly_recent_encounter = fairly_recent_enc
2237 )
2238
2239
2241 """Try to attach to a "very recent" encounter if there is one.
2242
2243 returns:
2244 False: no "very recent" encounter
2245 True: success
2246 """
2247 cfg_db = gmCfg.cCfgSQL()
2248 min_ttl = cfg_db.get2 (
2249 option = 'encounter.minimum_ttl',
2250 workplace = _here.active_workplace,
2251 bias = 'user',
2252 default = '1 hour 30 minutes'
2253 )
2254 cmd = gmEMRStructItems.SQL_get_encounters % """pk_encounter = (
2255 SELECT pk_encounter
2256 FROM clin.v_most_recent_encounters
2257 WHERE
2258 pk_patient = %s
2259 and
2260 last_affirmed > (now() - %s::interval)
2261 ORDER BY
2262 last_affirmed DESC
2263 LIMIT 1
2264 )"""
2265 enc_rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [self.pk_patient, min_ttl]}], get_col_idx = True)
2266
2267
2268 if len(enc_rows) == 0:
2269 _log.debug('no <very recent> encounter (younger than [%s]) found' % min_ttl)
2270 return False
2271
2272 _log.debug('"very recent" encounter [%s] found and re-activated' % enc_rows[0]['pk_encounter'])
2273
2274
2275 self.current_encounter = gmEMRStructItems.cEncounter(row = {'data': enc_rows[0], 'idx': idx, 'pk_field': 'pk_encounter'})
2276 return True
2277
2278
2280 cfg_db = gmCfg.cCfgSQL()
2281 min_ttl = cfg_db.get2 (
2282 option = 'encounter.minimum_ttl',
2283 workplace = _here.active_workplace,
2284 bias = 'user',
2285 default = '1 hour 30 minutes'
2286 )
2287 max_ttl = cfg_db.get2 (
2288 option = 'encounter.maximum_ttl',
2289 workplace = _here.active_workplace,
2290 bias = 'user',
2291 default = '6 hours'
2292 )
2293
2294
2295 cmd = gmEMRStructItems.SQL_get_encounters % """pk_encounter = (
2296 SELECT pk_encounter
2297 FROM clin.v_most_recent_encounters
2298 WHERE
2299 pk_patient=%s
2300 AND
2301 last_affirmed BETWEEN (now() - %s::interval) AND (now() - %s::interval)
2302 ORDER BY
2303 last_affirmed DESC
2304 LIMIT 1
2305 )"""
2306 enc_rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [self.pk_patient, max_ttl, min_ttl]}], get_col_idx = True)
2307
2308
2309 if len(enc_rows) == 0:
2310 _log.debug('no <fairly recent> encounter (between [%s] and [%s] old) found' % (min_ttl, max_ttl))
2311 return None
2312
2313 _log.debug('"fairly recent" encounter [%s] found', enc_rows[0]['pk_encounter'])
2314 return gmEMRStructItems.cEncounter(row = {'data': enc_rows[0], 'idx': idx, 'pk_field': 'pk_encounter'})
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2470
2471
2472 - def get_encounters(self, since=None, until=None, id_list=None, episodes=None, issues=None, skip_empty=False, order_by=None, max_encounters=None):
2473 """Retrieves patient's encounters.
2474
2475 id_list - PKs of encounters to fetch
2476 since - initial date for encounter items, DateTime instance
2477 until - final date for encounter items, DateTime instance
2478 episodes - PKs of the episodes the encounters belong to (many-to-many relation)
2479 issues - PKs of the health issues the encounters belong to (many-to-many relation)
2480 skip_empty - do NOT return those which do not have any of documents/clinical items/RFE/AOE
2481
2482 NOTE: if you specify *both* issues and episodes
2483 you will get the *aggregate* of all encounters even
2484 if the episodes all belong to the health issues listed.
2485 IOW, the issues broaden the episode list rather than
2486 the episode list narrowing the episodes-from-issues
2487 list.
2488 Rationale: If it was the other way round it would be
2489 redundant to specify the list of issues at all.
2490 """
2491
2492 if (issues is not None) and (len(issues) > 0):
2493
2494 cmd = "SELECT distinct pk_episode FROM clin.v_pat_episodes WHERE pk_health_issue in %(issue_pks)s AND pk_patient = %(pat)s"
2495 args = {'issue_pks': tuple(issues), 'pat': self.pk_patient}
2496 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])
2497 epis4issues_pks = [ r['pk_episode'] for r in rows ]
2498 if episodes is None:
2499 episodes = []
2500 episodes.extend(epis4issues_pks)
2501
2502 if (episodes is not None) and (len(episodes) > 0):
2503
2504
2505
2506 args = {'epi_pks': tuple(episodes), 'pat': self.pk_patient}
2507 cmd = "SELECT distinct fk_encounter FROM clin.clin_root_item WHERE fk_episode IN %(epi_pks)s AND fk_encounter IN (SELECT pk FROM clin.encounter WHERE fk_patient = %(pat)s)"
2508 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])
2509 encs4epis_pks = [ r['fk_encounter'] for r in rows ]
2510 if id_list is None:
2511 id_list = []
2512 id_list.extend(encs4epis_pks)
2513
2514 where_parts = ['c_vpe.pk_patient = %(pat)s']
2515 args = {'pat': self.pk_patient}
2516
2517 if skip_empty:
2518 where_parts.append("""NOT (
2519 gm.is_null_or_blank_string(c_vpe.reason_for_encounter)
2520 AND
2521 gm.is_null_or_blank_string(c_vpe.assessment_of_encounter)
2522 AND
2523 NOT EXISTS (
2524 SELECT 1 FROM clin.v_pat_items c_vpi WHERE c_vpi.pk_patient = %(pat)s AND c_vpi.pk_encounter = c_vpe.pk_encounter
2525 UNION ALL
2526 SELECT 1 FROM blobs.v_doc_med b_vdm WHERE b_vdm.pk_patient = %(pat)s AND b_vdm.pk_encounter = c_vpe.pk_encounter
2527 ))""")
2528
2529 if since is not None:
2530 where_parts.append('c_vpe.started >= %(start)s')
2531 args['start'] = since
2532
2533 if until is not None:
2534 where_parts.append('c_vpe.last_affirmed <= %(end)s')
2535 args['end'] = since
2536
2537 if (id_list is not None) and (len(id_list) > 0):
2538 where_parts.append('c_vpe.pk_encounter IN %(enc_pks)s')
2539 args['enc_pks'] = tuple(id_list)
2540
2541 if order_by is None:
2542 order_by = 'c_vpe.started'
2543
2544 if max_encounters is None:
2545 limit = ''
2546 else:
2547 limit = 'LIMIT %s' % max_encounters
2548
2549 cmd = """
2550 SELECT * FROM clin.v_pat_encounters c_vpe
2551 WHERE
2552 %s
2553 ORDER BY %s %s
2554 """ % (
2555 ' AND '.join(where_parts),
2556 order_by,
2557 limit
2558 )
2559 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
2560 encounters = [ gmEMRStructItems.cEncounter(row = {'data': r, 'idx': idx, 'pk_field': 'pk_encounter'}) for r in rows ]
2561
2562
2563 filtered_encounters = []
2564 filtered_encounters.extend(encounters)
2565
2566 if (episodes is not None) and (len(episodes) > 0):
2567
2568
2569
2570 args = {'epi_pks': tuple(episodes), 'pat': self.pk_patient}
2571 cmd = "SELECT distinct fk_encounter FROM clin.clin_root_item WHERE fk_episode IN %(epi_pks)s AND fk_encounter IN (SELECT pk FROM clin.encounter WHERE fk_patient = %(pat)s)"
2572 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])
2573 encs4epis_pks = [ r['fk_encounter'] for r in rows ]
2574 filtered_encounters = [ enc for enc in filtered_encounters if enc['pk_encounter'] in encs4epis_pks ]
2575
2576 return filtered_encounters
2577
2578
2580 """Retrieves first encounter for a particular issue and/or episode.
2581
2582 issue_id - First encounter associated health issue
2583 episode - First encounter associated episode
2584 """
2585 if issue_id is None:
2586 issues = None
2587 else:
2588 issues = [issue_id]
2589
2590 if episode_id is None:
2591 episodes = None
2592 else:
2593 episodes = [episode_id]
2594
2595 encounters = self.get_encounters(issues = issues, episodes = episodes, order_by = 'started', max_encounters = 1)
2596 if len(encounters) == 0:
2597 return None
2598
2599 return encounters[0]
2600
2601 first_encounter = property(get_first_encounter, lambda x:x)
2602
2603
2605 args = {'pat': self.pk_patient}
2606 cmd = """
2607 SELECT MIN(earliest) FROM (
2608 (
2609 SELECT MIN(episode_modified_when) AS earliest FROM clin.v_pat_episodes WHERE pk_patient = %(pat)s
2610
2611 ) UNION ALL (
2612
2613 SELECT MIN(modified_when) AS earliest FROM clin.v_health_issues WHERE pk_patient = %(pat)s
2614
2615 ) UNION ALL (
2616
2617 SELECT MIN(modified_when) AS earliest FROM clin.encounter WHERE fk_patient = %(pat)s
2618
2619 ) UNION ALL (
2620
2621 SELECT MIN(started) AS earliest FROM clin.v_pat_encounters WHERE pk_patient = %(pat)s
2622
2623 ) UNION ALL (
2624
2625 SELECT MIN(modified_when) AS earliest FROM clin.v_pat_items WHERE pk_patient = %(pat)s
2626
2627 ) UNION ALL (
2628
2629 SELECT MIN(modified_when) AS earliest FROM clin.v_pat_allergy_state WHERE pk_patient = %(pat)s
2630
2631 ) UNION ALL (
2632
2633 SELECT MIN(last_confirmed) AS earliest FROM clin.v_pat_allergy_state WHERE pk_patient = %(pat)s
2634
2635 )
2636 ) AS candidates"""
2637 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
2638 return rows[0][0]
2639
2640 earliest_care_date = property(get_earliest_care_date, lambda x:x)
2641
2642
2644 encounters = self.get_encounters(order_by = 'started DESC', max_encounters = 1)
2645 if len(encounters) == 0:
2646 return None
2647 return encounters[0]['last_affirmed']
2648
2649 most_recent_care_date = property(get_most_recent_care_date)
2650
2651
2653 """Retrieves last encounter for a concrete issue and/or episode
2654
2655 issue_id - Last encounter associated health issue
2656 episode_id - Last encounter associated episode
2657 """
2658 if issue_id is None:
2659 issues = None
2660 else:
2661 issues = [issue_id]
2662
2663 if episode_id is None:
2664 episodes = None
2665 else:
2666 episodes = [episode_id]
2667
2668 encounters = self.get_encounters(issues = issues, episodes = episodes, order_by = 'started DESC', max_encounters = 1)
2669 if len(encounters) == 0:
2670 return None
2671
2672 return encounters[0]
2673
2674 last_encounter = property(get_last_encounter, lambda x:x)
2675
2676
2678 args = {'pat': self.pk_patient, 'range': cover_period}
2679 where_parts = ['pk_patient = %(pat)s']
2680 if cover_period is not None:
2681 where_parts.append('last_affirmed > now() - %(range)s')
2682
2683 cmd = """
2684 SELECT l10n_type, count(1) AS frequency
2685 FROM clin.v_pat_encounters
2686 WHERE
2687 %s
2688 GROUP BY l10n_type
2689 ORDER BY frequency DESC
2690 """ % ' AND '.join(where_parts)
2691 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
2692 return rows
2693
2694
2696
2697 args = {'pat': self.pk_patient}
2698
2699 if (issue_id is None) and (episode_id is None):
2700 cmd = """
2701 SELECT * FROM clin.v_pat_encounters
2702 WHERE pk_patient = %(pat)s
2703 ORDER BY started DESC
2704 LIMIT 2
2705 """
2706 else:
2707 where_parts = []
2708
2709 if issue_id is not None:
2710 where_parts.append('pk_health_issue = %(issue)s')
2711 args['issue'] = issue_id
2712
2713 if episode_id is not None:
2714 where_parts.append('pk_episode = %(epi)s')
2715 args['epi'] = episode_id
2716
2717 cmd = """
2718 SELECT *
2719 FROM clin.v_pat_encounters
2720 WHERE
2721 pk_patient = %%(pat)s
2722 AND
2723 pk_encounter IN (
2724 SELECT distinct pk_encounter
2725 FROM clin.v_narrative
2726 WHERE
2727 %s
2728 )
2729 ORDER BY started DESC
2730 LIMIT 2
2731 """ % ' AND '.join(where_parts)
2732
2733 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
2734
2735 if len(rows) == 0:
2736 return None
2737
2738
2739 if len(rows) == 1:
2740
2741 if rows[0]['pk_encounter'] == self.current_encounter['pk_encounter']:
2742
2743 return None
2744
2745 return gmEMRStructItems.cEncounter(row = {'data': rows[0], 'idx': idx, 'pk_field': 'pk_encounter'})
2746
2747
2748 if rows[0]['pk_encounter'] == self.current_encounter['pk_encounter']:
2749 return gmEMRStructItems.cEncounter(row = {'data': rows[1], 'idx': idx, 'pk_field': 'pk_encounter'})
2750
2751 return gmEMRStructItems.cEncounter(row = {'data': rows[0], 'idx': idx, 'pk_field': 'pk_encounter'})
2752
2753 last_but_one_encounter = property(get_last_but_one_encounter, lambda x:x)
2754
2755
2757 _log.debug('removing empty encounters for pk_identity [%s]', self.pk_patient)
2758 cfg_db = gmCfg.cCfgSQL()
2759 ttl = cfg_db.get2 (
2760 option = 'encounter.ttl_if_empty',
2761 workplace = _here.active_workplace,
2762 bias = 'user',
2763 default = '1 week'
2764 )
2765
2766 cmd = "SELECT clin.remove_old_empty_encounters(%(pat)s::INTEGER, %(ttl)s::INTERVAL)"
2767 args = {'pat': self.pk_patient, 'ttl': ttl}
2768 try:
2769 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], return_data = True)
2770 except:
2771 _log.exception('error deleting empty encounters')
2772 return False
2773
2774 if not rows[0][0]:
2775 _log.debug('no encounters deleted (less than 2 exist)')
2776
2777 return True
2778
2779
2780
2781
2787
2788
2796
2797
2804
2805
2811
2812
2821
2822
2829
2830
2836
2837
2840
2841
2843 if order_by is None:
2844 order_by = ''
2845 else:
2846 order_by = 'ORDER BY %s' % order_by
2847 cmd = """
2848 SELECT * FROM clin.v_test_results
2849 WHERE
2850 pk_patient = %%(pat)s
2851 AND
2852 reviewed IS FALSE
2853 %s""" % order_by
2854 args = {'pat': self.pk_patient}
2855 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
2856 return [ gmPathLab.cTestResult(row = {'pk_field': 'pk_test_result', 'idx': idx, 'data': r}) for r in rows ]
2857
2858
2859
2861 """Retrieve data about test types for which this patient has results."""
2862 if order_by is None:
2863 order_by = ''
2864 else:
2865 order_by = 'ORDER BY %s' % order_by
2866
2867 if unique_meta_types:
2868 cmd = """
2869 SELECT * FROM clin.v_test_types c_vtt
2870 WHERE c_vtt.pk_test_type IN (
2871 SELECT DISTINCT ON (c_vtr1.pk_meta_test_type) c_vtr1.pk_test_type
2872 FROM clin.v_test_results c_vtr1
2873 WHERE
2874 c_vtr1.pk_patient = %%(pat)s
2875 AND
2876 c_vtr1.pk_meta_test_type IS NOT NULL
2877 UNION ALL
2878 SELECT DISTINCT ON (c_vtr2.pk_test_type) c_vtr2.pk_test_type
2879 FROM clin.v_test_results c_vtr2
2880 WHERE
2881 c_vtr2.pk_patient = %%(pat)s
2882 AND
2883 c_vtr2.pk_meta_test_type IS NULL
2884 )
2885 %s""" % order_by
2886 else:
2887 cmd = """
2888 SELECT * FROM clin.v_test_types c_vtt
2889 WHERE c_vtt.pk_test_type IN (
2890 SELECT DISTINCT ON (c_vtr.pk_test_type) c_vtr.pk_test_type
2891 FROM clin.v_test_results c_vtr
2892 WHERE c_vtr.pk_patient = %%(pat)s
2893 )
2894 %s""" % order_by
2895
2896 args = {'pat': self.pk_patient}
2897 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
2898 return [ gmPathLab.cMeasurementType(row = {'pk_field': 'pk_test_type', 'idx': idx, 'data': r}) for r in rows ]
2899
2900
2902 """Get the dates for which we have results."""
2903 where_parts = ['pk_patient = %(pat)s']
2904 args = {'pat': self.pk_patient}
2905
2906 if tests is not None:
2907 where_parts.append('pk_test_type IN %(tests)s')
2908 args['tests'] = tuple(tests)
2909
2910 cmd = """
2911 SELECT DISTINCT ON (clin_when_day)
2912 clin_when_day,
2913 is_reviewed
2914 FROM (
2915 SELECT
2916 date_trunc('day', clin_when)
2917 AS clin_when_day,
2918 bool_and(reviewed)
2919 AS is_reviewed
2920 FROM (
2921 SELECT
2922 clin_when,
2923 reviewed,
2924 pk_patient,
2925 pk_test_result
2926 FROM clin.v_test_results
2927 WHERE %s
2928 )
2929 AS patient_tests
2930 GROUP BY clin_when_day
2931 )
2932 AS grouped_days
2933 ORDER BY clin_when_day %s
2934 """ % (
2935 ' AND '.join(where_parts),
2936 gmTools.bool2subst(reverse_chronological, 'DESC', 'ASC', 'DESC')
2937 )
2938 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
2939 return rows
2940
2941
2943 """Get the issues/episodes for which we have results."""
2944 where_parts = ['pk_patient = %(pat)s']
2945 args = {'pat': self.pk_patient}
2946
2947 if tests is not None:
2948 where_parts.append('pk_test_type IN %(tests)s')
2949 args['tests'] = tuple(tests)
2950 where = ' AND '.join(where_parts)
2951 cmd = """
2952 SELECT * FROM ((
2953 -- issues, each including all it"s episodes
2954 SELECT
2955 health_issue AS problem,
2956 pk_health_issue,
2957 NULL::integer AS pk_episode,
2958 1 AS rank
2959 FROM clin.v_test_results
2960 WHERE pk_health_issue IS NOT NULL AND %s
2961 GROUP BY pk_health_issue, problem
2962 ) UNION ALL (
2963 -- episodes w/o issue
2964 SELECT
2965 episode AS problem,
2966 NULL::integer AS pk_health_issue,
2967 pk_episode,
2968 2 AS rank
2969 FROM clin.v_test_results
2970 WHERE pk_health_issue IS NULL AND %s
2971 GROUP BY pk_episode, problem
2972 )) AS grouped_union
2973 ORDER BY rank, problem
2974 """ % (where, where)
2975 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
2976 return rows
2977
2978
2979 - def get_test_results(self, encounters=None, episodes=None, tests=None, order_by=None):
2986
2988
2989 where_parts = ['pk_patient = %(pat)s']
2990 args = {'pat': self.pk_patient}
2991
2992 if tests is not None:
2993 where_parts.append('pk_test_type IN %(tests)s')
2994 args['tests'] = tuple(tests)
2995
2996 if encounter is not None:
2997 where_parts.append('pk_encounter = %(enc)s')
2998 args['enc'] = encounter
2999
3000 if episodes is not None:
3001 where_parts.append('pk_episode IN %(epis)s')
3002 args['epis'] = tuple(episodes)
3003
3004 cmd = """
3005 SELECT * FROM clin.v_test_results
3006 WHERE %s
3007 ORDER BY clin_when %s, pk_episode, unified_name
3008 """ % (
3009 ' AND '.join(where_parts),
3010 gmTools.bool2subst(reverse_chronological, 'DESC', 'ASC', 'DESC')
3011 )
3012 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
3013
3014 tests = [ gmPathLab.cTestResult(row = {'pk_field': 'pk_test_result', 'idx': idx, 'data': r}) for r in rows ]
3015
3016 return tests
3017
3018 - def add_test_result(self, episode=None, type=None, intended_reviewer=None, val_num=None, val_alpha=None, unit=None, link_obj=None):
3019
3020 try:
3021 epi = int(episode)
3022 except:
3023 epi = episode['pk_episode']
3024
3025 try:
3026 type = int(type)
3027 except:
3028 type = type['pk_test_type']
3029
3030 tr = gmPathLab.create_test_result (
3031 link_obj = link_obj,
3032 encounter = self.current_encounter['pk_encounter'],
3033 episode = epi,
3034 type = type,
3035 intended_reviewer = intended_reviewer,
3036 val_num = val_num,
3037 val_alpha = val_alpha,
3038 unit = unit
3039 )
3040
3041 return tr
3042
3043
3045 where = 'pk_org_unit IN (%s)' % """
3046 SELECT DISTINCT fk_org_unit FROM clin.test_org WHERE pk IN (
3047 SELECT DISTINCT pk_test_org FROM clin.v_test_results where pk_patient = %(pat)s
3048 )"""
3049 args = {'pat': self.pk_patient}
3050 cmd = gmOrganization._SQL_get_org_unit % where
3051 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
3052 return [ gmOrganization.cOrgUnit(row = {'pk_field': 'pk_org_unit', 'data': r, 'idx': idx}) for r in rows ]
3053
3054
3088
3089 best_gfr_or_crea = property(_get_best_gfr_or_crea, lambda x:x)
3090
3091
3094
3095 bmi = property(_get_bmi, lambda x:x)
3096
3097
3100
3101 dynamic_hints = property(_get_dynamic_hints, lambda x:x)
3102
3103
3104
3105
3110
3111 - def add_lab_request(self, lab=None, req_id=None, encounter_id=None, episode_id=None):
3125
3126
3127
3128
3129 if __name__ == "__main__":
3130
3131 if len(sys.argv) == 1:
3132 sys.exit()
3133
3134 if sys.argv[1] != 'test':
3135 sys.exit()
3136
3137 from Gnumed.pycommon import gmLog2
3138
3139 from Gnumed.business import gmPraxis
3140 branches = gmPraxis.get_praxis_branches()
3141 praxis = gmPraxis.gmCurrentPraxisBranch(branches[0])
3142
3144 print(args)
3145 print(kwargs)
3146 args[0](*args[1:], **kwargs)
3147
3148 set_delayed_executor(_do_delayed)
3149
3150
3164
3165
3170
3171
3172
3173
3180
3181
3183 emr = cClinicalRecord(aPKey=12)
3184 rows, idx = emr.get_measurements_by_date()
3185 print("test results:")
3186 for row in rows:
3187 print(row)
3188
3189
3196
3197
3202
3203
3205 emr = cClinicalRecord(aPKey=12)
3206
3207 probs = emr.get_problems()
3208 print("normal probs (%s):" % len(probs))
3209 for p in probs:
3210 print('%s (%s)' % (p['problem'], p['type']))
3211
3212 probs = emr.get_problems(include_closed_episodes=True)
3213 print("probs + closed episodes (%s):" % len(probs))
3214 for p in probs:
3215 print('%s (%s)' % (p['problem'], p['type']))
3216
3217 probs = emr.get_problems(include_irrelevant_issues=True)
3218 print("probs + issues (%s):" % len(probs))
3219 for p in probs:
3220 print('%s (%s)' % (p['problem'], p['type']))
3221
3222 probs = emr.get_problems(include_closed_episodes=True, include_irrelevant_issues=True)
3223 print("probs + issues + epis (%s):" % len(probs))
3224 for p in probs:
3225 print('%s (%s)' % (p['problem'], p['type']))
3226
3227
3229 emr = cClinicalRecord(aPKey=12)
3230 tr = emr.add_test_result (
3231 episode = 1,
3232 intended_reviewer = 1,
3233 type = 1,
3234 val_num = 75,
3235 val_alpha = 'somewhat obese',
3236 unit = 'kg'
3237 )
3238 print(tr)
3239
3240
3244
3245
3250
3251
3256
3257
3262
3263
3268
3269
3274
3275
3280
3281
3285
3286
3288 emr = cClinicalRecord(aPKey = 12)
3289 for journal_line in emr.get_as_journal():
3290
3291 print('%(date)s %(modified_by)s %(soap_cat)s %(narrative)s' % journal_line)
3292 print("")
3293
3294
3298
3299
3304
3305
3311
3312
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350 emr = cClinicalRecord(aPKey = 12)
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369 v1 = emr.vaccinations
3370 print(v1)
3371 v2 = gmVaccination.get_vaccinations(pk_identity = 12, return_pks = True)
3372 print(v2)
3373 for v in v1:
3374 if v['pk_vaccination'] not in v2:
3375 print('ERROR')
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403