Package Gnumed :: Package business :: Module gmPerson
[frames] | no frames]

Source Code for Module Gnumed.business.gmPerson

   1  # -*- coding: utf8 -*- 
   2  """GNUmed patient objects. 
   3   
   4  This is a patient object intended to let a useful client-side 
   5  API crystallize from actual use in true XP fashion. 
   6  """ 
   7  #============================================================ 
   8  __version__ = "$Revision: 1.198 $" 
   9  __author__ = "K.Hilbert <Karsten.Hilbert@gmx.net>" 
  10  __license__ = "GPL" 
  11   
  12  # std lib 
  13  import sys, os.path, time, re as regex, string, types, datetime as pyDT, codecs, threading, logging 
  14   
  15   
  16  # GNUmed 
  17  if __name__ == '__main__': 
  18          sys.path.insert(0, '../../') 
  19  from Gnumed.pycommon import gmExceptions, gmDispatcher, gmBorg, gmI18N, gmNull, gmBusinessDBObject, gmTools 
  20  from Gnumed.pycommon import gmPG2 
  21  from Gnumed.pycommon import gmDateTime 
  22  from Gnumed.pycommon import gmMatchProvider 
  23  from Gnumed.pycommon import gmLog2 
  24  from Gnumed.pycommon import gmHooks 
  25   
  26  from Gnumed.business import gmDemographicRecord 
  27  from Gnumed.business import gmClinicalRecord 
  28  from Gnumed.business import gmXdtMappings 
  29  from Gnumed.business import gmProviderInbox 
  30  from Gnumed.business.gmDocuments import cDocumentFolder 
  31   
  32   
  33  _log = logging.getLogger('gm.person') 
  34  _log.info(__version__) 
  35   
  36  __gender_list = None 
  37  __gender_idx = None 
  38   
  39  __gender2salutation_map = None 
  40  __gender2string_map = None 
  41   
  42  #============================================================ 
  43  # FIXME: make this work as a mapping type, too 
44 -class cDTO_person(object):
45
46 - def __init__(self):
47 self.identity = None 48 self.external_ids = [] 49 self.comm_channels = [] 50 self.addresses = []
51 #-------------------------------------------------------- 52 # external API 53 #--------------------------------------------------------
54 - def keys(self):
55 return 'firstnames lastnames dob gender'.split()
56 #--------------------------------------------------------
57 - def delete_from_source(self):
58 pass
59 #--------------------------------------------------------
60 - def get_candidate_identities(self, can_create=False):
61 """Generate generic queries. 62 63 - not locale dependant 64 - data -> firstnames, lastnames, dob, gender 65 66 shall we mogrify name parts ? probably not as external 67 sources should know what they do 68 69 finds by inactive name, too, but then shows 70 the corresponding active name ;-) 71 72 Returns list of matching identities (may be empty) 73 or None if it was told to create an identity but couldn't. 74 """ 75 where_snippets = [] 76 args = {} 77 78 where_snippets.append(u'firstnames = %(first)s') 79 args['first'] = self.firstnames 80 81 where_snippets.append(u'lastnames = %(last)s') 82 args['last'] = self.lastnames 83 84 if self.dob is not None: 85 where_snippets.append(u"dem.date_trunc_utc('day'::text, dob) = dem.date_trunc_utc('day'::text, %(dob)s)") 86 args['dob'] = self.dob.replace(hour = 23, minute = 59, second = 59) 87 88 if self.gender is not None: 89 where_snippets.append('gender = %(sex)s') 90 args['sex'] = self.gender 91 92 cmd = u""" 93 SELECT *, '%s' AS match_type 94 FROM dem.v_basic_person 95 WHERE 96 pk_identity IN ( 97 SELECT pk_identity FROM dem.v_person_names WHERE %s 98 ) 99 ORDER BY lastnames, firstnames, dob""" % ( 100 _('external patient source (name, gender, date of birth)'), 101 ' AND '.join(where_snippets) 102 ) 103 104 try: 105 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx=True) 106 except: 107 _log.error(u'cannot get candidate identities for dto "%s"' % self) 108 _log.exception('query %s' % cmd) 109 rows = [] 110 111 if len(rows) == 0: 112 _log.debug('no candidate identity matches found') 113 if not can_create: 114 return [] 115 ident = self.import_into_database() 116 if ident is None: 117 return None 118 identities = [ident] 119 else: 120 identities = [ cIdentity(row = {'pk_field': 'pk_identity', 'data': row, 'idx': idx}) for row in rows ] 121 122 return identities
123 #--------------------------------------------------------
124 - def import_into_database(self):
125 """Imports self into the database.""" 126 127 self.identity = create_identity ( 128 firstnames = self.firstnames, 129 lastnames = self.lastnames, 130 gender = self.gender, 131 dob = self.dob 132 ) 133 134 if self.identity is None: 135 return None 136 137 for ext_id in self.external_ids: 138 try: 139 self.identity.add_external_id ( 140 type_name = ext_id['name'], 141 value = ext_id['value'], 142 issuer = ext_id['issuer'], 143 comment = ext_id['comment'] 144 ) 145 except StandardError: 146 _log.exception('cannot import <external ID> from external data source') 147 _log.log_stack_trace() 148 149 for comm in self.comm_channels: 150 try: 151 self.identity.link_comm_channel ( 152 comm_medium = comm['channel'], 153 url = comm['url'] 154 ) 155 except StandardError: 156 _log.exception('cannot import <comm channel> from external data source') 157 _log.log_stack_trace() 158 159 for adr in self.addresses: 160 try: 161 self.identity.link_address ( 162 number = adr['number'], 163 street = adr['street'], 164 postcode = adr['zip'], 165 urb = adr['urb'], 166 state = adr['region'], 167 country = adr['country'] 168 ) 169 except StandardError: 170 _log.exception('cannot import <address> from external data source') 171 _log.log_stack_trace() 172 173 return self.identity
174 #--------------------------------------------------------
175 - def import_extra_data(self, *args, **kwargs):
176 pass
177 #--------------------------------------------------------
178 - def remember_external_id(self, name=None, value=None, issuer=None, comment=None):
179 value = value.strip() 180 if value == u'': 181 return 182 name = name.strip() 183 if name == u'': 184 raise ValueError(_('<name> cannot be empty')) 185 issuer = issuer.strip() 186 if issuer == u'': 187 raise ValueError(_('<issuer> cannot be empty')) 188 self.external_ids.append({'name': name, 'value': value, 'issuer': issuer, 'comment': comment})
189 #--------------------------------------------------------
190 - def remember_comm_channel(self, channel=None, url=None):
191 url = url.strip() 192 if url == u'': 193 return 194 channel = channel.strip() 195 if channel == u'': 196 raise ValueError(_('<channel> cannot be empty')) 197 self.comm_channels.append({'channel': channel, 'url': url})
198 #--------------------------------------------------------
199 - def remember_address(self, number=None, street=None, urb=None, region=None, zip=None, country=None):
200 number = number.strip() 201 if number == u'': 202 raise ValueError(_('<number> cannot be empty')) 203 street = street.strip() 204 if street == u'': 205 raise ValueError(_('<street> cannot be empty')) 206 urb = urb.strip() 207 if urb == u'': 208 raise ValueError(_('<urb> cannot be empty')) 209 zip = zip.strip() 210 if zip == u'': 211 raise ValueError(_('<zip> cannot be empty')) 212 country = country.strip() 213 if country == u'': 214 raise ValueError(_('<country> cannot be empty')) 215 region = region.strip() 216 if region == u'': 217 region = u'??' 218 self.addresses.append ({ 219 u'number': number, 220 u'street': street, 221 u'zip': zip, 222 u'urb': urb, 223 u'region': region, 224 u'country': country 225 })
226 #-------------------------------------------------------- 227 # customizing behaviour 228 #--------------------------------------------------------
229 - def __str__(self):
230 return u'<%s @ %s: %s %s (%s) %s>' % ( 231 self.__class__.__name__, 232 id(self), 233 self.firstnames, 234 self.lastnames, 235 self.gender, 236 self.dob 237 )
238 #--------------------------------------------------------
239 - def __setattr__(self, attr, val):
240 """Do some sanity checks on self.* access.""" 241 242 if attr == 'gender': 243 glist, idx = get_gender_list() 244 for gender in glist: 245 if str(val) in [gender[0], gender[1], gender[2], gender[3]]: 246 val = gender[idx['tag']] 247 object.__setattr__(self, attr, val) 248 return 249 raise ValueError('invalid gender: [%s]' % val) 250 251 if attr == 'dob': 252 if val is not None: 253 if not isinstance(val, pyDT.datetime): 254 raise TypeError('invalid type for DOB (must be datetime.datetime): %s [%s]' % (type(val), val)) 255 if val.tzinfo is None: 256 raise ValueError('datetime.datetime instance is lacking a time zone: [%s]' % val.isoformat()) 257 258 object.__setattr__(self, attr, val) 259 return
260 #--------------------------------------------------------
261 - def __getitem__(self, attr):
262 return getattr(self, attr)
263 #============================================================
264 -class cPersonName(gmBusinessDBObject.cBusinessDBObject):
265 _cmd_fetch_payload = u"SELECT * FROM dem.v_person_names WHERE pk_name = %s" 266 _cmds_store_payload = [ 267 u"""UPDATE dem.names SET 268 active = FALSE 269 WHERE 270 %(active_name)s IS TRUE -- act only when needed and only 271 AND 272 id_identity = %(pk_identity)s -- on names of this identity 273 AND 274 active IS TRUE -- which are active 275 AND 276 id != %(pk_name)s -- but NOT *this* name 277 """, 278 u"""update dem.names set 279 active = %(active_name)s, 280 preferred = %(preferred)s, 281 comment = %(comment)s 282 where 283 id = %(pk_name)s and 284 id_identity = %(pk_identity)s and -- belt and suspenders 285 xmin = %(xmin_name)s""", 286 u"""select xmin as xmin_name from dem.names where id = %(pk_name)s""" 287 ] 288 _updatable_fields = ['active_name', 'preferred', 'comment'] 289 #--------------------------------------------------------
290 - def __setitem__(self, attribute, value):
291 if attribute == 'active_name': 292 # cannot *directly* deactivate a name, only indirectly 293 # by activating another one 294 # FIXME: should be done at DB level 295 if self._payload[self._idx['active_name']] is True: 296 return 297 gmBusinessDBObject.cBusinessDBObject.__setitem__(self, attribute, value)
298 #--------------------------------------------------------
299 - def _get_description(self):
300 return '%(last)s, %(title)s %(first)s%(nick)s' % { 301 'last': self._payload[self._idx['lastnames']], 302 'title': gmTools.coalesce ( 303 self._payload[self._idx['title']], 304 map_gender2salutation(self._payload[self._idx['gender']]) 305 ), 306 'first': self._payload[self._idx['firstnames']], 307 'nick': gmTools.coalesce(self._payload[self._idx['preferred']], u'', u" '%s'", u'%s') 308 }
309 310 description = property(_get_description, lambda x:x)
311 #============================================================
312 -class cIdentity(gmBusinessDBObject.cBusinessDBObject):
313 _cmd_fetch_payload = u"SELECT * FROM dem.v_basic_person WHERE pk_identity = %s" 314 _cmds_store_payload = [ 315 u"""UPDATE dem.identity SET 316 gender = %(gender)s, 317 dob = %(dob)s, 318 dob_is_estimated = %(dob_is_estimated)s, 319 tob = %(tob)s, 320 cob = gm.nullify_empty_string(%(cob)s), 321 title = gm.nullify_empty_string(%(title)s), 322 fk_marital_status = %(pk_marital_status)s, 323 karyotype = gm.nullify_empty_string(%(karyotype)s), 324 pupic = gm.nullify_empty_string(%(pupic)s), 325 deceased = %(deceased)s, 326 emergency_contact = gm.nullify_empty_string(%(emergency_contact)s), 327 fk_emergency_contact = %(pk_emergency_contact)s, 328 fk_primary_provider = %(pk_primary_provider)s, 329 comment = gm.nullify_empty_string(%(comment)s) 330 WHERE 331 pk = %(pk_identity)s and 332 xmin = %(xmin_identity)s 333 RETURNING 334 xmin AS xmin_identity""" 335 ] 336 _updatable_fields = [ 337 "title", 338 "dob", 339 "tob", 340 "cob", 341 "gender", 342 "pk_marital_status", 343 "karyotype", 344 "pupic", 345 'deceased', 346 'emergency_contact', 347 'pk_emergency_contact', 348 'pk_primary_provider', 349 'comment', 350 'dob_is_estimated' 351 ] 352 #--------------------------------------------------------
353 - def _get_ID(self):
354 return self._payload[self._idx['pk_identity']]
355 - def _set_ID(self, value):
356 raise AttributeError('setting ID of identity is not allowed')
357 ID = property(_get_ID, _set_ID) 358 #--------------------------------------------------------
359 - def __setitem__(self, attribute, value):
360 361 if attribute == 'dob': 362 if value is not None: 363 364 if isinstance(value, pyDT.datetime): 365 if value.tzinfo is None: 366 raise ValueError('datetime.datetime instance is lacking a time zone: [%s]' % dt.isoformat()) 367 else: 368 raise TypeError, '[%s]: type [%s] (%s) invalid for attribute [dob], must be datetime.datetime or None' % (self.__class__.__name__, type(value), value) 369 370 # compare DOB at seconds level 371 if self._payload[self._idx['dob']] is not None: 372 old_dob = gmDateTime.pydt_strftime ( 373 self._payload[self._idx['dob']], 374 format = '%Y %m %d %H %M %S', 375 accuracy = gmDateTime.acc_seconds 376 ) 377 new_dob = gmDateTime.pydt_strftime ( 378 value, 379 format = '%Y %m %d %H %M %S', 380 accuracy = gmDateTime.acc_seconds 381 ) 382 if new_dob == old_dob: 383 return 384 385 gmBusinessDBObject.cBusinessDBObject.__setitem__(self, attribute, value)
386 #--------------------------------------------------------
387 - def cleanup(self):
388 pass
389 #--------------------------------------------------------
390 - def _get_is_patient(self):
391 cmd = u""" 392 SELECT EXISTS ( 393 SELECT 1 394 FROM clin.v_emr_journal 395 WHERE 396 pk_patient = %(pat)s 397 AND 398 soap_cat IS NOT NULL 399 )""" 400 args = {'pat': self._payload[self._idx['pk_identity']]} 401 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False) 402 return rows[0][0]
403
404 - def _set_is_patient(self, value):
405 raise AttributeError('setting is_patient status of identity is not allowed')
406 407 is_patient = property(_get_is_patient, _set_is_patient) 408 #--------------------------------------------------------
409 - def _get_staff_id(self):
410 cmd = u"SELECT pk FROM dem.staff WHERE fk_identity = %(pk)s" 411 args = {'pk': self._payload[self._idx['pk_identity']]} 412 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False) 413 if len(rows) == 0: 414 return None 415 return rows[0][0]
416 417 staff_id = property(_get_staff_id, lambda x:x) 418 #-------------------------------------------------------- 419 # identity API 420 #--------------------------------------------------------
421 - def _get_gender_symbol(self):
422 return map_gender2symbol[self._payload[self._idx['gender']]]
423 424 gender_symbol = property(_get_gender_symbol, lambda x:x) 425 #--------------------------------------------------------
426 - def _get_gender_string(self):
427 return map_gender2string(gender = self._payload[self._idx['gender']])
428 429 gender_string = property(_get_gender_string, lambda x:x) 430 #--------------------------------------------------------
431 - def get_active_name(self):
432 names = self.get_names(active_only = True) 433 if len(names) == 0: 434 _log.error('cannot retrieve active name for patient [%s]', self._payload[self._idx['pk_identity']]) 435 return None 436 return names[0]
437 438 active_name = property(get_active_name, lambda x:x) 439 #--------------------------------------------------------
440 - def get_names(self, active_only=False, exclude_active=False):
441 442 args = {'pk_pat': self._payload[self._idx['pk_identity']]} 443 where_parts = [u'pk_identity = %(pk_pat)s'] 444 if active_only: 445 where_parts.append(u'active_name is True') 446 if exclude_active: 447 where_parts.append(u'active_name is False') 448 cmd = u""" 449 SELECT * 450 FROM dem.v_person_names 451 WHERE %s 452 ORDER BY active_name DESC, lastnames, firstnames 453 """ % u' AND '.join(where_parts) 454 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True) 455 456 if len(rows) == 0: 457 # no names registered for patient 458 return [] 459 460 names = [ cPersonName(row = {'idx': idx, 'data': r, 'pk_field': 'pk_name'}) for r in rows ] 461 return names
462 #--------------------------------------------------------
463 - def get_description_gender(self):
464 return _(u'%(last)s,%(title)s %(first)s%(nick)s (%(sex)s)') % { 465 'last': self._payload[self._idx['lastnames']], 466 'title': gmTools.coalesce(self._payload[self._idx['title']], u'', u' %s'), 467 'first': self._payload[self._idx['firstnames']], 468 'nick': gmTools.coalesce(self._payload[self._idx['preferred']], u'', u" '%s'"), 469 'sex': self.gender_symbol 470 }
471 #--------------------------------------------------------
472 - def get_description(self):
473 return _(u'%(last)s,%(title)s %(first)s%(nick)s') % { 474 'last': self._payload[self._idx['lastnames']], 475 'title': gmTools.coalesce(self._payload[self._idx['title']], u'', u' %s'), 476 'first': self._payload[self._idx['firstnames']], 477 'nick': gmTools.coalesce(self._payload[self._idx['preferred']], u'', u" '%s'") 478 }
479 #--------------------------------------------------------
480 - def add_name(self, firstnames, lastnames, active=True):
481 """Add a name. 482 483 @param firstnames The first names. 484 @param lastnames The last names. 485 @param active When True, the new name will become the active one (hence setting other names to inactive) 486 @type active A types.BooleanType instance 487 """ 488 name = create_name(self.ID, firstnames, lastnames, active) 489 if active: 490 self.refetch_payload() 491 return name
492 #--------------------------------------------------------
493 - def delete_name(self, name=None):
494 cmd = u"delete from dem.names where id = %(name)s and id_identity = %(pat)s" 495 args = {'name': name['pk_name'], 'pat': self.ID} 496 gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
497 # can't have been the active name as that would raise an 498 # exception (since no active name would be left) so no 499 # data refetch needed 500 #--------------------------------------------------------
501 - def set_nickname(self, nickname=None):
502 """ 503 Set the nickname. Setting the nickname only makes sense for the currently 504 active name. 505 @param nickname The preferred/nick/warrior name to set. 506 """ 507 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': u"select dem.set_nickname(%s, %s)", 'args': [self.ID, nickname]}]) 508 self.refetch_payload() 509 return True
510 #--------------------------------------------------------
511 - def get_tags(self, order_by=None):
512 if order_by is None: 513 order_by = u'' 514 else: 515 order_by = u'ORDER BY %s' % order_by 516 517 cmd = gmDemographicRecord._SQL_get_identity_tags % (u'pk_identity = %%(pat)s %s' % order_by) 518 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': {u'pat': self.ID}}], get_col_idx = True) 519 520 return [ gmDemographicRecord.cIdentityTag(row = {'data': r, 'idx': idx, 'pk_field': 'pk_identity_tag'}) for r in rows ]
521 522 tags = property(get_tags, lambda x:x) 523 #--------------------------------------------------------
524 - def add_tag(self, tag):
525 args = { 526 u'tag': tag, 527 u'identity': self.ID 528 } 529 530 # already exists ? 531 cmd = u"SELECT pk FROM dem.identity_tag WHERE fk_tag = %(tag)s AND fk_identity = %(identity)s" 532 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False) 533 if len(rows) > 0: 534 return gmDemographicRecord.cIdentityTag(aPK_obj = rows[0]['pk']) 535 536 # no, add 537 cmd = u""" 538 INSERT INTO dem.identity_tag ( 539 fk_tag, 540 fk_identity 541 ) VALUES ( 542 %(tag)s, 543 %(identity)s 544 ) 545 RETURNING pk 546 """ 547 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], return_data = True, get_col_idx = False) 548 return gmDemographicRecord.cIdentityTag(aPK_obj = rows[0]['pk'])
549 #--------------------------------------------------------
550 - def remove_tag(self, tag):
551 cmd = u"DELETE FROM dem.identity_tag WHERE pk = %(pk)s" 552 gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': {'pk': tag}}])
553 #-------------------------------------------------------- 554 # external ID API 555 # 556 # since external IDs are not treated as first class 557 # citizens (classes in their own right, that is), we 558 # handle them *entirely* within cIdentity, also they 559 # only make sense with one single person (like names) 560 # and are not reused (like addresses), so they are 561 # truly added/deleted, not just linked/unlinked 562 #--------------------------------------------------------
563 - def add_external_id(self, type_name=None, value=None, issuer=None, comment=None, pk_type=None):
564 """Adds an external ID to the patient. 565 566 creates ID type if necessary 567 """ 568 569 # check for existing ID 570 if pk_type is not None: 571 cmd = u""" 572 select * from dem.v_external_ids4identity where 573 pk_identity = %(pat)s and 574 pk_type = %(pk_type)s and 575 value = %(val)s""" 576 else: 577 # by type/value/issuer 578 if issuer is None: 579 cmd = u""" 580 select * from dem.v_external_ids4identity where 581 pk_identity = %(pat)s and 582 name = %(name)s and 583 value = %(val)s""" 584 else: 585 cmd = u""" 586 select * from dem.v_external_ids4identity where 587 pk_identity = %(pat)s and 588 name = %(name)s and 589 value = %(val)s and 590 issuer = %(issuer)s""" 591 args = { 592 'pat': self.ID, 593 'name': type_name, 594 'val': value, 595 'issuer': issuer, 596 'pk_type': pk_type 597 } 598 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}]) 599 600 # create new ID if not found 601 if len(rows) == 0: 602 603 args = { 604 'pat': self.ID, 605 'val': value, 606 'type_name': type_name, 607 'pk_type': pk_type, 608 'issuer': issuer, 609 'comment': comment 610 } 611 612 if pk_type is None: 613 cmd = u"""insert into dem.lnk_identity2ext_id (external_id, fk_origin, comment, id_identity) values ( 614 %(val)s, 615 (select dem.add_external_id_type(%(type_name)s, %(issuer)s)), 616 %(comment)s, 617 %(pat)s 618 )""" 619 else: 620 cmd = u"""insert into dem.lnk_identity2ext_id (external_id, fk_origin, comment, id_identity) values ( 621 %(val)s, 622 %(pk_type)s, 623 %(comment)s, 624 %(pat)s 625 )""" 626 627 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}]) 628 629 # or update comment of existing ID 630 else: 631 row = rows[0] 632 if comment is not None: 633 # comment not already there ? 634 if gmTools.coalesce(row['comment'], '').find(comment.strip()) == -1: 635 comment = '%s%s' % (gmTools.coalesce(row['comment'], '', '%s // '), comment.strip) 636 cmd = u"update dem.lnk_identity2ext_id set comment = %(comment)s where id=%(pk)s" 637 args = {'comment': comment, 'pk': row['pk_id']} 638 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
639 #--------------------------------------------------------
640 - def update_external_id(self, pk_id=None, type=None, value=None, issuer=None, comment=None):
641 """Edits an existing external ID. 642 643 Creates ID type if necessary. 644 """ 645 cmd = u""" 646 UPDATE dem.lnk_identity2ext_id SET 647 fk_origin = (SELECT dem.add_external_id_type(%(type)s, %(issuer)s)), 648 external_id = %(value)s, 649 comment = gm.nullify_empty_string(%(comment)s) 650 WHERE 651 id = %(pk)s 652 """ 653 args = {'pk': pk_id, 'value': value, 'type': type, 'issuer': issuer, 'comment': comment} 654 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
655 #--------------------------------------------------------
656 - def get_external_ids(self, id_type=None, issuer=None):
657 where_parts = ['pk_identity = %(pat)s'] 658 args = {'pat': self.ID} 659 660 if id_type is not None: 661 where_parts.append(u'name = %(name)s') 662 args['name'] = id_type.strip() 663 664 if issuer is not None: 665 where_parts.append(u'issuer = %(issuer)s') 666 args['issuer'] = issuer.strip() 667 668 cmd = u"SELECT * FROM dem.v_external_ids4identity WHERE %s" % ' AND '.join(where_parts) 669 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}]) 670 671 return rows
672 673 external_ids = property(get_external_ids, lambda x:x) 674 #--------------------------------------------------------
675 - def delete_external_id(self, pk_ext_id=None):
676 cmd = u""" 677 delete from dem.lnk_identity2ext_id 678 where id_identity = %(pat)s and id = %(pk)s""" 679 args = {'pat': self.ID, 'pk': pk_ext_id} 680 gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
681 #--------------------------------------------------------
682 - def assimilate_identity(self, other_identity=None, link_obj=None):
683 """Merge another identity into this one. 684 685 Keep this one. Delete other one.""" 686 687 if other_identity.ID == self.ID: 688 return True, None 689 690 curr_pat = gmCurrentPatient() 691 if curr_pat.connected: 692 if other_identity.ID == curr_pat.ID: 693 return False, _('Cannot merge active patient into another patient.') 694 695 queries = [] 696 args = {'old_pat': other_identity.ID, 'new_pat': self.ID} 697 698 # delete old allergy state 699 queries.append ({ 700 'cmd': u'delete from clin.allergy_state where pk = (select pk_allergy_state from clin.v_pat_allergy_state where pk_patient = %(old_pat)s)', 701 'args': args 702 }) 703 # FIXME: adjust allergy_state in kept patient 704 705 # deactivate all names of old patient 706 queries.append ({ 707 'cmd': u'update dem.names set active = False where id_identity = %(old_pat)s', 708 'args': args 709 }) 710 711 # find FKs pointing to identity 712 FKs = gmPG2.get_foreign_keys2column ( 713 schema = u'dem', 714 table = u'identity', 715 column = u'pk' 716 ) 717 718 # generate UPDATEs 719 cmd_template = u'update %s set %s = %%(new_pat)s where %s = %%(old_pat)s' 720 for FK in FKs: 721 queries.append ({ 722 'cmd': cmd_template % (FK['referencing_table'], FK['referencing_column'], FK['referencing_column']), 723 'args': args 724 }) 725 726 # remove old identity entry 727 queries.append ({ 728 'cmd': u'delete from dem.identity where pk = %(old_pat)s', 729 'args': args 730 }) 731 732 _log.warning('identity [%s] is about to assimilate identity [%s]', self.ID, other_identity.ID) 733 734 gmPG2.run_rw_queries(link_obj = link_obj, queries = queries, end_tx = True) 735 736 self.add_external_id ( 737 type_name = u'merged GNUmed identity primary key', 738 value = u'GNUmed::pk::%s' % other_identity.ID, 739 issuer = u'GNUmed' 740 ) 741 742 return True, None
743 #-------------------------------------------------------- 744 #--------------------------------------------------------
745 - def put_on_waiting_list(self, urgency=0, comment=None, zone=None):
746 cmd = u""" 747 insert into clin.waiting_list (fk_patient, urgency, comment, area, list_position) 748 values ( 749 %(pat)s, 750 %(urg)s, 751 %(cmt)s, 752 %(area)s, 753 (select coalesce((max(list_position) + 1), 1) from clin.waiting_list) 754 )""" 755 args = {'pat': self.ID, 'urg': urgency, 'cmt': comment, 'area': zone} 756 gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], verbose = True)
757 #--------------------------------------------------------
758 - def get_waiting_list_entry(self):
759 cmd = u"""SELECT * FROM clin.v_waiting_list WHERE pk_identity = %(pat)s""" 760 args = {'pat': self.ID} 761 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}]) 762 return rows
763 764 waiting_list_entries = property(get_waiting_list_entry, lambda x:x) 765 #--------------------------------------------------------
766 - def export_as_gdt(self, filename=None, encoding='iso-8859-15', external_id_type=None):
767 768 template = u'%s%s%s\r\n' 769 770 file = codecs.open ( 771 filename = filename, 772 mode = 'wb', 773 encoding = encoding, 774 errors = 'strict' 775 ) 776 777 file.write(template % (u'013', u'8000', u'6301')) 778 file.write(template % (u'013', u'9218', u'2.10')) 779 if external_id_type is None: 780 file.write(template % (u'%03d' % (9 + len(str(self.ID))), u'3000', self.ID)) 781 else: 782 ext_ids = self.get_external_ids(id_type = external_id_type) 783 if len(ext_ids) > 0: 784 file.write(template % (u'%03d' % (9 + len(ext_ids[0]['value'])), u'3000', ext_ids[0]['value'])) 785 file.write(template % (u'%03d' % (9 + len(self._payload[self._idx['lastnames']])), u'3101', self._payload[self._idx['lastnames']])) 786 file.write(template % (u'%03d' % (9 + len(self._payload[self._idx['firstnames']])), u'3102', self._payload[self._idx['firstnames']])) 787 file.write(template % (u'%03d' % (9 + len(self._payload[self._idx['dob']].strftime('%d%m%Y'))), u'3103', self._payload[self._idx['dob']].strftime('%d%m%Y'))) 788 file.write(template % (u'010', u'3110', gmXdtMappings.map_gender_gm2xdt[self._payload[self._idx['gender']]])) 789 file.write(template % (u'025', u'6330', 'GNUmed::9206::encoding')) 790 file.write(template % (u'%03d' % (9 + len(encoding)), u'6331', encoding)) 791 if external_id_type is None: 792 file.write(template % (u'029', u'6332', u'GNUmed::3000::source')) 793 file.write(template % (u'017', u'6333', u'internal')) 794 else: 795 if len(ext_ids) > 0: 796 file.write(template % (u'029', u'6332', u'GNUmed::3000::source')) 797 file.write(template % (u'%03d' % (9 + len(external_id_type)), u'6333', external_id_type)) 798 799 file.close()
800 #-------------------------------------------------------- 801 # occupations API 802 #--------------------------------------------------------
803 - def get_occupations(self):
804 return gmDemographicRecord.get_occupations(pk_identity = self.pk_obj)
805 #-------------------------------------------------------- 842 #-------------------------------------------------------- 850 #-------------------------------------------------------- 851 # comms API 852 #--------------------------------------------------------
853 - def get_comm_channels(self, comm_medium=None):
854 cmd = u"select * from dem.v_person_comms where pk_identity = %s" 855 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [self.pk_obj]}], get_col_idx = True) 856 857 filtered = rows 858 859 if comm_medium is not None: 860 filtered = [] 861 for row in rows: 862 if row['comm_type'] == comm_medium: 863 filtered.append(row) 864 865 return [ gmDemographicRecord.cCommChannel(row = { 866 'pk_field': 'pk_lnk_identity2comm', 867 'data': r, 868 'idx': idx 869 }) for r in filtered 870 ]
871 #-------------------------------------------------------- 889 #-------------------------------------------------------- 895 #-------------------------------------------------------- 896 # contacts API 897 #--------------------------------------------------------
898 - def get_addresses(self, address_type=None):
899 900 cmd = u"SELECT * FROM dem.v_pat_addresses WHERE pk_identity = %(pat)s" 901 args = {'pat': self.pk_obj} 902 if address_type is not None: 903 cmd = cmd + u" AND address_type = %(typ)s" 904 args['typ'] = address_type 905 906 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True) 907 908 return [ 909 gmDemographicRecord.cPatientAddress(row = {'idx': idx, 'data': r, 'pk_field': 'pk_address'}) 910 for r in rows 911 ]
912 #-------------------------------------------------------- 963 #---------------------------------------------------------------------- 976 #---------------------------------------------------------------------- 977 # relatives API 978 #----------------------------------------------------------------------
979 - def get_relatives(self):
980 cmd = u""" 981 select 982 t.description, 983 vbp.pk_identity as id, 984 title, 985 firstnames, 986 lastnames, 987 dob, 988 cob, 989 gender, 990 karyotype, 991 pupic, 992 pk_marital_status, 993 marital_status, 994 xmin_identity, 995 preferred 996 from 997 dem.v_basic_person vbp, dem.relation_types t, dem.lnk_person2relative l 998 where 999 ( 1000 l.id_identity = %(pk)s and 1001 vbp.pk_identity = l.id_relative and 1002 t.id = l.id_relation_type 1003 ) or ( 1004 l.id_relative = %(pk)s and 1005 vbp.pk_identity = l.id_identity and 1006 t.inverse = l.id_relation_type 1007 )""" 1008 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': {'pk': self.pk_obj}}]) 1009 if len(rows) == 0: 1010 return [] 1011 return [(row[0], cIdentity(row = {'data': row[1:], 'idx':idx, 'pk_field': 'pk'})) for row in rows]
1012 #-------------------------------------------------------- 1032 #----------------------------------------------------------------------
1033 - def delete_relative(self, relation):
1034 # unlink only, don't delete relative itself 1035 self.set_relative(None, relation)
1036 #--------------------------------------------------------
1038 if self._payload[self._idx['pk_emergency_contact']] is None: 1039 return None 1040 return cIdentity(aPK_obj = self._payload[self._idx['pk_emergency_contact']])
1041 1042 emergency_contact_in_database = property(_get_emergency_contact_from_database, lambda x:x) 1043 #---------------------------------------------------------------------- 1044 # age/dob related 1045 #----------------------------------------------------------------------
1046 - def get_formatted_dob(self, format='%x', encoding=None, none_string=None):
1047 return gmDateTime.format_dob ( 1048 self._payload[self._idx['dob']], 1049 format = format, 1050 encoding = encoding, 1051 none_string = none_string, 1052 dob_is_estimated = self._payload[self._idx['dob_is_estimated']] 1053 )
1054 #----------------------------------------------------------------------
1055 - def get_medical_age(self):
1056 dob = self['dob'] 1057 1058 if dob is None: 1059 return u'??' 1060 1061 if dob > gmDateTime.pydt_now_here(): 1062 return _('invalid age: DOB in the future') 1063 1064 death = self['deceased'] 1065 1066 if death is None: 1067 return u'%s%s' % ( 1068 gmTools.bool2subst ( 1069 self._payload[self._idx['dob_is_estimated']], 1070 gmTools.u_almost_equal_to, 1071 u'' 1072 ), 1073 gmDateTime.format_apparent_age_medically ( 1074 age = gmDateTime.calculate_apparent_age(start = dob) 1075 ) 1076 ) 1077 1078 if dob > death: 1079 return _('invalid age: DOB after death') 1080 1081 return u'%s%s%s' % ( 1082 gmTools.u_latin_cross, 1083 gmTools.bool2subst ( 1084 self._payload[self._idx['dob_is_estimated']], 1085 gmTools.u_almost_equal_to, 1086 u'' 1087 ), 1088 gmDateTime.format_apparent_age_medically ( 1089 age = gmDateTime.calculate_apparent_age ( 1090 start = dob, 1091 end = self['deceased'] 1092 ) 1093 ) 1094 )
1095 #----------------------------------------------------------------------
1096 - def dob_in_range(self, min_distance=u'1 week', max_distance=u'1 week'):
1097 cmd = u'select dem.dob_is_in_range(%(dob)s, %(min)s, %(max)s)' 1098 rows, idx = gmPG2.run_ro_queries ( 1099 queries = [{ 1100 'cmd': cmd, 1101 'args': {'dob': self['dob'], 'min': min_distance, 'max': max_distance} 1102 }] 1103 ) 1104 return rows[0][0]
1105 #---------------------------------------------------------------------- 1106 # practice related 1107 #----------------------------------------------------------------------
1108 - def get_last_encounter(self):
1109 cmd = u'select * from clin.v_most_recent_encounters where pk_patient=%s' 1110 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [self._payload[self._idx['pk_identity']]]}]) 1111 if len(rows) > 0: 1112 return rows[0] 1113 else: 1114 return None
1115 #--------------------------------------------------------
1116 - def _get_messages(self):
1117 return gmProviderInbox.get_inbox_messages(pk_patient = self._payload[self._idx['pk_identity']])
1118 1119 messages = property(_get_messages, lambda x:x) 1120 #--------------------------------------------------------
1121 - def _get_due_messages(self):
1122 return gmProviderInbox.get_due_messages(pk_patient = self._payload[self._idx['pk_identity']])
1123 1124 due_messages = property(_get_due_messages, lambda x:x) 1125 #--------------------------------------------------------
1126 - def delete_message(self, pk=None):
1127 return gmProviderInbox.delete_inbox_message(inbox_message = pk)
1128 #--------------------------------------------------------
1129 - def _get_dynamic_hints(self):
1130 return gmProviderInbox.get_hints_for_patient(pk_identity = self._payload[self._idx['pk_identity']])
1131 1132 dynamic_hints = property(_get_dynamic_hints, lambda x:x) 1133 #--------------------------------------------------------
1134 - def _get_primary_provider(self):
1135 if self._payload[self._idx['pk_primary_provider']] is None: 1136 return None 1137 from Gnumed.business import gmStaff 1138 return gmStaff.cStaff(aPK_obj = self._payload[self._idx['pk_primary_provider']])
1139 1140 primary_provider = property(_get_primary_provider, lambda x:x) 1141 #---------------------------------------------------------------------- 1142 # convenience 1143 #----------------------------------------------------------------------
1144 - def get_dirname(self):
1145 """Format patient demographics into patient specific path name fragment.""" 1146 return '%s-%s%s-%s' % ( 1147 self._payload[self._idx['lastnames']].replace(u' ', u'_'), 1148 self._payload[self._idx['firstnames']].replace(u' ', u'_'), 1149 gmTools.coalesce(self._payload[self._idx['preferred']], u'', template_initial = u'-(%s)'), 1150 self.get_formatted_dob(format = '%Y-%m-%d', encoding = gmI18N.get_encoding()) 1151 )
1152 #============================================================
1153 -class cPatient(cIdentity):
1154 """Represents a person which is a patient. 1155 1156 - a specializing subclass of cIdentity turning it into a patient 1157 - its use is to cache subobjects like EMR and document folder 1158 """
1159 - def __init__(self, aPK_obj=None, row=None):
1160 cIdentity.__init__(self, aPK_obj=aPK_obj, row=row) 1161 self.__db_cache = {} 1162 self.__emr_access_lock = threading.Lock()
1163 #--------------------------------------------------------
1164 - def cleanup(self):
1165 """Do cleanups before dying. 1166 1167 - note that this may be called in a thread 1168 """ 1169 if self.__db_cache.has_key('clinical record'): 1170 self.__db_cache['clinical record'].cleanup() 1171 if self.__db_cache.has_key('document folder'): 1172 self.__db_cache['document folder'].cleanup() 1173 cIdentity.cleanup(self)
1174 #----------------------------------------------------------
1175 - def get_emr(self):
1176 # attempt = 1 1177 # got_lock = self.__emr_access_lock.acquire(False) 1178 # while not got_lock: 1179 # if attempt == 100: # 100 x 500ms -> 50 seconds timeout 1180 # raise AttributeError('cannot access EMR') 1181 # attempt += 1 1182 # time.sleep(0.5) # 500ms 1183 # got_lock = self.__emr_access_lock.acquire(False) 1184 if not self.__emr_access_lock.acquire(False): 1185 raise AttributeError('cannot access EMR') 1186 try: 1187 emr = self.__db_cache['clinical record'] 1188 self.__emr_access_lock.release() 1189 return emr 1190 except KeyError: 1191 pass 1192 1193 self.__db_cache['clinical record'] = gmClinicalRecord.cClinicalRecord(aPKey = self._payload[self._idx['pk_identity']]) 1194 self.__emr_access_lock.release() 1195 return self.__db_cache['clinical record']
1196 1197 emr = property(get_emr, lambda x:x) 1198 #--------------------------------------------------------
1199 - def get_document_folder(self):
1200 try: 1201 return self.__db_cache['document folder'] 1202 except KeyError: 1203 pass 1204 1205 self.__db_cache['document folder'] = cDocumentFolder(aPKey = self._payload[self._idx['pk_identity']]) 1206 return self.__db_cache['document folder']
1207 1208 document_folder = property(get_document_folder, lambda x:x)
1209 #============================================================
1210 -class gmCurrentPatient(gmBorg.cBorg):
1211 """Patient Borg to hold currently active patient. 1212 1213 There may be many instances of this but they all share state. 1214 """
1215 - def __init__(self, patient=None, forced_reload=False):
1216 """Change or get currently active patient. 1217 1218 patient: 1219 * None: get currently active patient 1220 * -1: unset currently active patient 1221 * cPatient instance: set active patient if possible 1222 """ 1223 # make sure we do have a patient pointer 1224 try: 1225 tmp = self.patient 1226 except AttributeError: 1227 self.patient = gmNull.cNull() 1228 self.__register_interests() 1229 # set initial lock state, 1230 # this lock protects against activating another patient 1231 # when we are controlled from a remote application 1232 self.__lock_depth = 0 1233 # initialize callback state 1234 self.__pre_selection_callbacks = [] 1235 1236 # user wants copy of current patient 1237 if patient is None: 1238 return None 1239 1240 # do nothing if patient is locked 1241 if self.locked: 1242 _log.error('patient [%s] is locked, cannot change to [%s]' % (self.patient['pk_identity'], patient)) 1243 return None 1244 1245 # user wants to explicitly unset current patient 1246 if patient == -1: 1247 _log.debug('explicitly unsetting current patient') 1248 if not self.__run_pre_selection_callbacks(): 1249 _log.debug('not unsetting current patient') 1250 return None 1251 self.__send_pre_selection_notification() 1252 self.patient.cleanup() 1253 self.patient = gmNull.cNull() 1254 self.__send_selection_notification() 1255 return None 1256 1257 # must be cPatient instance, then 1258 if not isinstance(patient, cPatient): 1259 _log.error('cannot set active patient to [%s], must be either None, -1 or cPatient instance' % str(patient)) 1260 raise TypeError, 'gmPerson.gmCurrentPatient.__init__(): <patient> must be None, -1 or cPatient instance but is: %s' % str(patient) 1261 1262 # same ID, no change needed 1263 if (self.patient['pk_identity'] == patient['pk_identity']) and not forced_reload: 1264 return None 1265 1266 # user wants different patient 1267 _log.debug('patient change [%s] -> [%s] requested', self.patient['pk_identity'], patient['pk_identity']) 1268 1269 # everything seems swell 1270 if not self.__run_pre_selection_callbacks(): 1271 _log.debug('not changing current patient') 1272 return None 1273 self.__send_pre_selection_notification() 1274 self.patient.cleanup() 1275 self.patient = patient 1276 self.patient.get_emr() 1277 self.__send_selection_notification() 1278 1279 return None
1280 #--------------------------------------------------------
1281 - def __register_interests(self):
1282 gmDispatcher.connect(signal = u'identity_mod_db', receiver = self._on_identity_change) 1283 gmDispatcher.connect(signal = u'name_mod_db', receiver = self._on_identity_change)
1284 #--------------------------------------------------------
1285 - def _on_identity_change(self):
1286 """Listen for patient *data* change.""" 1287 self.patient.refetch_payload()
1288 #-------------------------------------------------------- 1289 # external API 1290 #--------------------------------------------------------
1291 - def register_pre_selection_callback(self, callback=None):
1292 if not callable(callback): 1293 raise TypeError(u'callback [%s] not callable' % callback) 1294 1295 self.__pre_selection_callbacks.append(callback)
1296 #--------------------------------------------------------
1297 - def _get_connected(self):
1298 return (not isinstance(self.patient, gmNull.cNull))
1299
1300 - def _set_connected(self):
1301 raise AttributeError(u'invalid to set <connected> state')
1302 1303 connected = property(_get_connected, _set_connected) 1304 #--------------------------------------------------------
1305 - def _get_locked(self):
1306 return (self.__lock_depth > 0)
1307
1308 - def _set_locked(self, locked):
1309 if locked: 1310 self.__lock_depth = self.__lock_depth + 1 1311 gmDispatcher.send(signal='patient_locked') 1312 else: 1313 if self.__lock_depth == 0: 1314 _log.error('lock/unlock imbalance, trying to refcount lock depth below 0') 1315 return 1316 else: 1317 self.__lock_depth = self.__lock_depth - 1 1318 gmDispatcher.send(signal='patient_unlocked')
1319 1320 locked = property(_get_locked, _set_locked) 1321 #--------------------------------------------------------
1322 - def force_unlock(self):
1323 _log.info('forced patient unlock at lock depth [%s]' % self.__lock_depth) 1324 self.__lock_depth = 0 1325 gmDispatcher.send(signal='patient_unlocked')
1326 #-------------------------------------------------------- 1327 # patient change handling 1328 #--------------------------------------------------------
1330 if isinstance(self.patient, gmNull.cNull): 1331 return True 1332 1333 for call_back in self.__pre_selection_callbacks: 1334 try: 1335 successful = call_back() 1336 except: 1337 _log.exception('callback [%s] failed', call_back) 1338 print "*** pre-selection callback failed ***" 1339 print type(call_back) 1340 print call_back 1341 return False 1342 1343 if not successful: 1344 _log.debug('callback [%s] returned False', call_back) 1345 return False 1346 1347 return True
1348 #--------------------------------------------------------
1350 """Sends signal when another patient is about to become active. 1351 1352 This does NOT wait for signal handlers to complete. 1353 """ 1354 kwargs = { 1355 'signal': u'pre_patient_selection', 1356 'sender': id(self.__class__), 1357 'pk_identity': self.patient['pk_identity'] 1358 } 1359 gmDispatcher.send(**kwargs)
1360 #--------------------------------------------------------
1362 """Sends signal when another patient has actually been made active.""" 1363 kwargs = { 1364 'signal': u'post_patient_selection', 1365 'sender': id(self.__class__), 1366 'pk_identity': self.patient['pk_identity'] 1367 } 1368 gmDispatcher.send(**kwargs)
1369 #-------------------------------------------------------- 1370 # __getattr__ handling 1371 #--------------------------------------------------------
1372 - def __getattr__(self, attribute):
1373 if attribute == 'patient': 1374 raise AttributeError 1375 if not isinstance(self.patient, gmNull.cNull): 1376 return getattr(self.patient, attribute)
1377 #-------------------------------------------------------- 1378 # __get/setitem__ handling 1379 #--------------------------------------------------------
1380 - def __getitem__(self, attribute = None):
1381 """Return any attribute if known how to retrieve it by proxy. 1382 """ 1383 return self.patient[attribute]
1384 #--------------------------------------------------------
1385 - def __setitem__(self, attribute, value):
1386 self.patient[attribute] = value
1387 #============================================================ 1388 # match providers 1389 #============================================================
1390 -class cMatchProvider_Provider(gmMatchProvider.cMatchProvider_SQL2):
1391 - def __init__(self):
1392 gmMatchProvider.cMatchProvider_SQL2.__init__( 1393 self, 1394 queries = [ 1395 u"""SELECT 1396 pk_staff AS data, 1397 short_alias || ' (' || coalesce(title, '') || ' ' || firstnames || ' ' || lastnames || ')' AS list_label, 1398 short_alias || ' (' || coalesce(title, '') || ' ' || firstnames || ' ' || lastnames || ')' AS field_label 1399 FROM dem.v_staff 1400 WHERE 1401 is_active AND ( 1402 short_alias %(fragment_condition)s OR 1403 firstnames %(fragment_condition)s OR 1404 lastnames %(fragment_condition)s OR 1405 db_user %(fragment_condition)s 1406 ) 1407 """ 1408 ] 1409 ) 1410 self.setThresholds(1, 2, 3)
1411 #============================================================ 1412 # convenience functions 1413 #============================================================
1414 -def create_name(pk_person, firstnames, lastnames, active=False):
1415 queries = [{ 1416 'cmd': u"select dem.add_name(%s, %s, %s, %s)", 1417 'args': [pk_person, firstnames, lastnames, active] 1418 }] 1419 rows, idx = gmPG2.run_rw_queries(queries=queries, return_data=True) 1420 name = cPersonName(aPK_obj = rows[0][0]) 1421 return name
1422 #============================================================
1423 -def create_identity(gender=None, dob=None, lastnames=None, firstnames=None):
1424 1425 cmd1 = u"""INSERT INTO dem.identity (gender, dob) VALUES (%s, %s)""" 1426 cmd2 = u""" 1427 INSERT INTO dem.names ( 1428 id_identity, lastnames, firstnames 1429 ) VALUES ( 1430 currval('dem.identity_pk_seq'), coalesce(%s, 'xxxDEFAULTxxx'), coalesce(%s, 'xxxDEFAULTxxx') 1431 ) RETURNING id_identity""" 1432 rows, idx = gmPG2.run_rw_queries ( 1433 queries = [ 1434 {'cmd': cmd1, 'args': [gender, dob]}, 1435 {'cmd': cmd2, 'args': [lastnames, firstnames]} 1436 ], 1437 return_data = True 1438 ) 1439 ident = cIdentity(aPK_obj=rows[0][0]) 1440 gmHooks.run_hook_script(hook = u'post_person_creation') 1441 return ident
1442 #============================================================
1443 -def create_dummy_identity():
1444 cmd = u"INSERT INTO dem.identity(gender) VALUES ('xxxDEFAULTxxx') RETURNING pk" 1445 rows, idx = gmPG2.run_rw_queries ( 1446 queries = [{'cmd': cmd}], 1447 return_data = True 1448 ) 1449 return gmDemographicRecord.cIdentity(aPK_obj = rows[0][0])
1450 #============================================================
1451 -def set_active_patient(patient=None, forced_reload=False):
1452 """Set active patient. 1453 1454 If patient is -1 the active patient will be UNset. 1455 """ 1456 if isinstance(patient, cPatient): 1457 pat = patient 1458 elif isinstance(patient, cIdentity): 1459 pat = cPatient(aPK_obj=patient['pk_identity']) 1460 # elif isinstance(patient, cStaff): 1461 # pat = cPatient(aPK_obj=patient['pk_identity']) 1462 elif isinstance(patient, gmCurrentPatient): 1463 pat = patient.patient 1464 elif patient == -1: 1465 pat = patient 1466 else: 1467 raise ValueError('<patient> must be either -1, cPatient, cIdentity or gmCurrentPatient instance, is: %s' % patient) 1468 1469 # attempt to switch 1470 try: 1471 gmCurrentPatient(patient = pat, forced_reload = forced_reload) 1472 except: 1473 _log.exception('error changing active patient to [%s]' % patient) 1474 return False 1475 1476 return True
1477 #============================================================ 1478 # gender related 1479 #------------------------------------------------------------
1480 -def get_gender_list():
1481 """Retrieves the list of known genders from the database.""" 1482 global __gender_idx 1483 global __gender_list 1484 1485 if __gender_list is None: 1486 cmd = u"select tag, l10n_tag, label, l10n_label, sort_weight from dem.v_gender_labels order by sort_weight desc" 1487 __gender_list, __gender_idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd}], get_col_idx = True) 1488 1489 return (__gender_list, __gender_idx)
1490 #------------------------------------------------------------ 1491 map_gender2mf = { 1492 'm': u'm', 1493 'f': u'f', 1494 'tf': u'f', 1495 'tm': u'm', 1496 'h': u'mf' 1497 } 1498 #------------------------------------------------------------ 1499 # Maps GNUmed related i18n-aware gender specifiers to a unicode symbol. 1500 map_gender2symbol = { 1501 'm': u'\u2642', 1502 'f': u'\u2640', 1503 'tf': u'\u26A5\u2640', 1504 'tm': u'\u26A5\u2642', 1505 'h': u'\u26A5' 1506 # 'tf': u'\u2642\u2640-\u2640', 1507 # 'tm': u'\u2642\u2640-\u2642', 1508 # 'h': u'\u2642\u2640' 1509 } 1510 #------------------------------------------------------------
1511 -def map_gender2string(gender=None):
1512 """Maps GNUmed related i18n-aware gender specifiers to a human-readable string.""" 1513 1514 global __gender2string_map 1515 1516 if __gender2string_map is None: 1517 genders, idx = get_gender_list() 1518 __gender2string_map = { 1519 'm': _('male'), 1520 'f': _('female'), 1521 'tf': u'', 1522 'tm': u'', 1523 'h': u'' 1524 } 1525 for g in genders: 1526 __gender2string_map[g[idx['l10n_tag']]] = g[idx['l10n_label']] 1527 __gender2string_map[g[idx['tag']]] = g[idx['l10n_label']] 1528 1529 return __gender2string_map[gender]
1530 #------------------------------------------------------------
1531 -def map_gender2salutation(gender=None):
1532 """Maps GNUmed related i18n-aware gender specifiers to a human-readable salutation.""" 1533 1534 global __gender2salutation_map 1535 1536 if __gender2salutation_map is None: 1537 genders, idx = get_gender_list() 1538 __gender2salutation_map = { 1539 'm': _('Mr'), 1540 'f': _('Mrs'), 1541 'tf': u'', 1542 'tm': u'', 1543 'h': u'' 1544 } 1545 for g in genders: 1546 __gender2salutation_map[g[idx['l10n_tag']]] = __gender2salutation_map[g[idx['tag']]] 1547 __gender2salutation_map[g[idx['label']]] = __gender2salutation_map[g[idx['tag']]] 1548 __gender2salutation_map[g[idx['l10n_label']]] = __gender2salutation_map[g[idx['tag']]] 1549 1550 return __gender2salutation_map[gender]
1551 #------------------------------------------------------------
1552 -def map_firstnames2gender(firstnames=None):
1553 """Try getting the gender for the given first name.""" 1554 1555 if firstnames is None: 1556 return None 1557 1558 rows, idx = gmPG2.run_ro_queries(queries = [{ 1559 'cmd': u"select gender from dem.name_gender_map where name ilike %(fn)s limit 1", 1560 'args': {'fn': firstnames} 1561 }]) 1562 1563 if len(rows) == 0: 1564 return None 1565 1566 return rows[0][0]
1567 #============================================================
1568 -def get_persons_from_pks(pks=None):
1569 return [ cIdentity(aPK_obj = pk) for pk in pks ]
1570 #============================================================
1571 -def get_person_from_xdt(filename=None, encoding=None, dob_format=None):
1572 from Gnumed.business import gmXdtObjects 1573 return gmXdtObjects.read_person_from_xdt(filename=filename, encoding=encoding, dob_format=dob_format)
1574 #============================================================
1575 -def get_persons_from_pracsoft_file(filename=None, encoding='ascii'):
1576 from Gnumed.business import gmPracSoftAU 1577 return gmPracSoftAU.read_persons_from_pracsoft_file(filename=filename, encoding=encoding)
1578 #============================================================ 1579 # main/testing 1580 #============================================================ 1581 if __name__ == '__main__': 1582 1583 if len(sys.argv) == 1: 1584 sys.exit() 1585 1586 if sys.argv[1] != 'test': 1587 sys.exit() 1588 1589 import datetime 1590 1591 gmI18N.activate_locale() 1592 gmI18N.install_domain() 1593 gmDateTime.init() 1594 1595 #--------------------------------------------------------
1596 - def test_set_active_pat():
1597 1598 ident = cIdentity(1) 1599 print "setting active patient with", ident 1600 set_active_patient(patient=ident) 1601 1602 patient = cPatient(12) 1603 print "setting active patient with", patient 1604 set_active_patient(patient=patient) 1605 1606 pat = gmCurrentPatient() 1607 print pat['dob'] 1608 #pat['dob'] = 'test' 1609 1610 # staff = cStaff() 1611 # print "setting active patient with", staff 1612 # set_active_patient(patient=staff) 1613 1614 print "setting active patient with -1" 1615 set_active_patient(patient=-1)
1616 #--------------------------------------------------------
1617 - def test_dto_person():
1618 dto = cDTO_person() 1619 dto.firstnames = 'Sepp' 1620 dto.lastnames = 'Herberger' 1621 dto.gender = 'male' 1622 dto.dob = pyDT.datetime.now(tz=gmDateTime.gmCurrentLocalTimezone) 1623 print dto 1624 1625 print dto['firstnames'] 1626 print dto['lastnames'] 1627 print dto['gender'] 1628 print dto['dob'] 1629 1630 for key in dto.keys(): 1631 print key
1632 #--------------------------------------------------------
1633 - def test_identity():
1634 # create patient 1635 print '\n\nCreating identity...' 1636 new_identity = create_identity(gender='m', dob='2005-01-01', lastnames='test lastnames', firstnames='test firstnames') 1637 print 'Identity created: %s' % new_identity 1638 1639 print '\nSetting title and gender...' 1640 new_identity['title'] = 'test title'; 1641 new_identity['gender'] = 'f'; 1642 new_identity.save_payload() 1643 print 'Refetching identity from db: %s' % cIdentity(aPK_obj=new_identity['pk_identity']) 1644 1645 print '\nGetting all names...' 1646 for a_name in new_identity.get_names(): 1647 print a_name 1648 print 'Active name: %s' % (new_identity.get_active_name()) 1649 print 'Setting nickname...' 1650 new_identity.set_nickname(nickname='test nickname') 1651 print 'Refetching all names...' 1652 for a_name in new_identity.get_names(): 1653 print a_name 1654 print 'Active name: %s' % (new_identity.get_active_name()) 1655 1656 print '\nIdentity occupations: %s' % new_identity['occupations'] 1657 print 'Creating identity occupation...' 1658 new_identity.link_occupation('test occupation') 1659 print 'Identity occupations: %s' % new_identity['occupations'] 1660 1661 print '\nIdentity addresses: %s' % new_identity.get_addresses() 1662 print 'Creating identity address...' 1663 # make sure the state exists in the backend 1664 new_identity.link_address ( 1665 number = 'test 1234', 1666 street = 'test street', 1667 postcode = 'test postcode', 1668 urb = 'test urb', 1669 state = 'SN', 1670 country = 'DE' 1671 ) 1672 print 'Identity addresses: %s' % new_identity.get_addresses() 1673 1674 print '\nIdentity communications: %s' % new_identity.get_comm_channels() 1675 print 'Creating identity communication...' 1676 new_identity.link_comm_channel('homephone', '1234566') 1677 print 'Identity communications: %s' % new_identity.get_comm_channels()
1678 #--------------------------------------------------------
1679 - def test_name():
1680 for pk in range(1,16): 1681 name = cPersonName(aPK_obj=pk) 1682 print name.description 1683 print ' ', name
1684 #--------------------------------------------------------
1685 - def test_gender_list():
1686 genders, idx = get_gender_list() 1687 print "\n\nRetrieving gender enum (tag, label, weight):" 1688 for gender in genders: 1689 print "%s, %s, %s" % (gender[idx['tag']], gender[idx['l10n_label']], gender[idx['sort_weight']])
1690 #-------------------------------------------------------- 1691 #test_dto_person() 1692 #test_identity() 1693 #test_set_active_pat() 1694 #test_search_by_dto() 1695 #test_name() 1696 test_gender_list() 1697 1698 #map_gender2salutation('m') 1699 # module functions 1700 1701 #comms = get_comm_list() 1702 #print "\n\nRetrieving communication media enum (id, description): %s" % comms 1703 1704 #============================================================ 1705