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

# Source Code for Module Gnumed.business.gmAllergy

      1  """GNUmed allergy related business object.
      2  """
      3  #============================================================
      4  __version__ = "$Revision: 1.34 $"
      5  __author__ = "Carlos Moro <cfmoro1976@yahoo.es>"
      6  __license__ = "GPL"
      7
      8  import types, sys, logging, datetime as pyDT
      9
     10
     11  if __name__ == '__main__':
     12          sys.path.insert(0, '../../')
     13  from Gnumed.pycommon import gmPG2, gmI18N, gmBusinessDBObject, gmDateTime
     14
     15
     16  _log = logging.getLogger('gm.domain')
     17  _log.info(__version__)
     18  #============================================================
     19  # allergy state related code
     20  #============================================================
     21  allergy_states = [
     22          None,           # unknown
     23          0,                      # no allergies
     24          1                       # some allergies
     25  ]
     26  #------------------------------------------------------------
     27 -def ensure_has_allergy_state(encounter=None):
     28
     29          args = {'enc': encounter}
     30
     31          cmd_create = u"""
     32                  INSERT INTO clin.allergy_state (
     33                          fk_encounter,
     34                          has_allergy
     35                  )       SELECT
     36                                  %(enc)s,
     37                                  NULL
     38                          WHERE NOT EXISTS (
     39                                  SELECT 1 FROM clin.v_pat_allergy_state
     40                                  WHERE pk_patient = (
     41                                          SELECT fk_patient FROM clin.encounter WHERE pk = %(enc)s
     42                                  )
     43                          )
     44          """
     45          cmd_search = u"""
     46  select pk_allergy_state from clin.v_pat_allergy_state
     47  where pk_patient = (
     48          select fk_patient from clin.encounter where pk = %(enc)s
     49  )"""
     50
     51          rows, idx = gmPG2.run_rw_queries (
     52                  queries = [
     53                          {'cmd': cmd_create, 'args': args},
     54                          {'cmd': cmd_search, 'args': args}
     55                  ],
     56                  return_data = True
     57          )
     58
     59          return cAllergyState(aPK_obj = rows[0][0])
     60  #------------------------------------------------------------
     61 -class cAllergyState(gmBusinessDBObject.cBusinessDBObject):
     62          """Represents the allergy state of one patient."""
     63
     64          _cmd_fetch_payload = u"select * from clin.v_pat_allergy_state where pk_allergy_state = %s"
     65          _cmds_store_payload = [
     66                  u"""update clin.allergy_state set
     67                                  last_confirmed = %(last_confirmed)s,
     68                                  has_allergy = %(has_allergy)s,
     69                                  comment = %(comment)s
     70                          where
     71                                  pk = %(pk_allergy_state)s and
     72                                  xmin = %(xmin_allergy_state)s""",
     73                  u"""select xmin_allergy_state from clin.v_pat_allergy_state where pk_allergy_state = %(pk_allergy_state)s"""
     74          ]
     75          _updatable_fields = [
     76                  'last_confirmed',               # special value u'now' will set to datetime.datetime.now() in the local time zone
     77                  'has_allergy',                  # verified against allergy_states (see above)
     78                  'comment'                               # u'' maps to None / NULL
     79          ]
     80          #--------------------------------------------------------
     81          # properties
     82          #--------------------------------------------------------
     83 -        def _get_as_string(self):
     84                  if self._payload[self._idx['has_allergy']] is None:
     85                          return _('unknown allergy state')
     86                  if self._payload[self._idx['has_allergy']] == 0:
     87                          return _('no known allergies')
     88                  if self._payload[self._idx['has_allergy']] == 1:
     89                          return _('*does* have allergies')
     90                  _log.error('unknown allergy state [%s]', self._payload[self._idx['has_allergy']])
     91                  return _('ERROR: unknown allergy state [%s]') % self._payload[self._idx['has_allergy']]
     92
     93 -        def _set_string(self, value):
     94                  raise AttributeError('invalid to set allergy state string')
     95
     96          state_string = property(_get_as_string, _set_string)
     97          #--------------------------------------------------------
     98 -        def _get_as_symbol(self):
     99                  if self._payload[self._idx['has_allergy']] is None:
    100                          if self._payload[self._idx['comment']] is None:
    101                                  return u'?'
    102                          else:
    103                                  return u'?!'
    104                  if self._payload[self._idx['has_allergy']] == 0:
    105                          if self._payload[self._idx['comment']] is None:
    106                                  return u'\u2300'
    107                          else:
    108                                  return u'\u2300!'
    109                  if self._payload[self._idx['has_allergy']] == 1:
    110                          return '!'
    111                  _log.error('unknown allergy state [%s]', self._payload[self._idx['has_allergy']])
    112                  return _('ERROR: unknown allergy state [%s]') % self._payload[self._idx['has_allergy']]
    113
    114 -        def _set_symbol(self, value):
    115                  raise AttributeError('invalid to set allergy state symbol')
    116
    117          state_symbol = property(_get_as_symbol, _set_symbol)
    118          #--------------------------------------------------------
    119 -        def __setitem__(self, attribute, value):
    120                  if attribute == u'comment':
    121                          if value is not None:
    122                                  if value.strip() == u'':
    123                                          value = None
    124
    125                  elif attribute == u'last_confirmed':
    126                          if value == u'now':
    127                                  value = pyDT.datetime.now(tz = gmDateTime.gmCurrentLocalTimezone)
    128
    129                  elif attribute == u'has_allergy':
    130                          if value not in allergy_states:
    131                                  raise ValueError('invalid allergy state [%s]' % value)
    132
    133                  gmBusinessDBObject.cBusinessDBObject.__setitem__(self, attribute, value)
    134  #============================================================
    135 -class cAllergy(gmBusinessDBObject.cBusinessDBObject):
    136          """Represents one allergy item.
    137
    138          Actually, those things are really things to *avoid*.
    139          Allergy is just one of several reasons for that.
    140          See Adrian's post on gm-dev.
    141
    142          Another word might be Therapeutic Precautions.
    143          """
    144          _cmd_fetch_payload = u"SELECT * FROM clin.v_pat_allergies WHERE pk_allergy = %s"
    145          _cmds_store_payload = [
    146                  u"""UPDATE clin.allergy SET
    147                                  clin_when = %(date)s,
    148                                  substance = %(substance)s,
    149                                  substance_code = %(substance_code)s,
    150                                  generics = %(generics)s,
    151                                  allergene = %(allergene)s,
    152                                  atc_code = %(atc_code)s,
    153                                  fk_type = %(pk_type)s,
    154                                  generic_specific = %(generic_specific)s::boolean,
    155                                  definite = %(definite)s::boolean,
    156                                  narrative = %(reaction)s
    157                          WHERE
    158                                  pk = %(pk_allergy)s AND
    159                                  xmin = %(xmin_allergy)s""",
    160                  u"""SELECT xmin_allergy FROM clin.v_pat_allergies WHERE pk_allergy=%(pk_allergy)s"""
    161          ]
    162          _updatable_fields = [
    163                  'date',
    164                  'substance',
    165                  'substance_code',
    166                  'generics',
    167                  'allergene',
    168                  'atc_code',
    169                  'pk_type',
    170                  'generic_specific',
    171                  'definite',
    172                  'reaction'
    173          ]
    174          #--------------------------------------------------------
    175 -        def __setitem__(self, attribute, value):
    176                  if attribute == 'pk_type':
    177                          if value in ['allergy', 'sensitivity']:
    178                                  cmd = u'select pk from clin._enum_allergy_type where value=%s'
    179                                  rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [value]}])
    180                                  value = rows[0][0]
    181
    182                  gmBusinessDBObject.cBusinessDBObject.__setitem__(self, attribute, value)
    183  #============================================================
    184  # convenience functions
    185  #------------------------------------------------------------
    186 -def create_allergy(allergene=None, allg_type=None, episode_id=None, encounter_id=None):
    187          """Creates a new allergy clinical item.
    188
    189          allergene - allergic substance
    190          allg_type - allergy or sensitivity, pk or string
    191          encounter_id - encounter's primary key
    192          episode_id - episode's primary key
    193          """
    194          cmd = u"""
    195                  SELECT pk_allergy
    196                  FROM clin.v_pat_allergies
    197                  WHERE
    198                          pk_patient = (SELECT fk_patient FROM clin.encounter WHERE pk = %(enc)s)
    199                                  AND
    200                          allergene = %(allergene)s
    201          """
    202          #args = {'enc': encounter_id, 'substance': substance}
    203          args = {'enc': encounter_id, 'allergene': allergene}
    204          rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])
    205          if len(rows) > 0:
    206                  # don't implicitely change existing data
    207                  return cAllergy(aPK_obj = rows[0][0])
    208
    209          # insert new allergy
    210          queries = []
    211
    212          if type(allg_type) == types.IntType:
    213                  cmd = u"""
    214                          insert into clin.allergy (fk_type, fk_encounter, fk_episode, allergene, substance)
    215                          values (%s, %s, %s, %s, %s)"""
    216          else:
    217                  cmd = u"""
    218                          insert into clin.allergy (fk_type, fk_encounter, fk_episode,  allergene, substance)
    219                          values ((select pk from clin._enum_allergy_type where value = %s), %s, %s, %s, %s)"""
    220          queries.append({'cmd': cmd, 'args': [allg_type, encounter_id, episode_id, allergene, allergene]})
    221
    222          cmd = u"select currval('clin.allergy_id_seq')"
    223          queries.append({'cmd': cmd})
    224
    225          rows, idx = gmPG2.run_rw_queries(queries=queries, return_data=True)
    226          allergy = cAllergy(aPK_obj = rows[0][0])
    227
    228          return allergy
    229  #============================================================
    230  # main - unit testing
    231  #------------------------------------------------------------
    232  if __name__ == '__main__':
    233
    234          allg = cAllergy(aPK_obj=1)
    235          print allg
    236          fields = allg.get_fields()
    237          for field in fields:
    238                  print field, ':', allg[field]
    239          print "updatable:", allg.get_updatable_fields()
    240          enc_id = allg['pk_encounter']
    241          epi_id = allg['pk_episode']
    242          status, allg = create_allergy (
    243                  allergene = 'test substance',
    244                  allg_type = 1,
    245                  episode_id = epi_id,
    246                  encounter_id = enc_id
    247          )
    248          print allg
    249          allg['reaction'] = 'hehehe'
    250          status, data = allg.save_payload()
    251          print 'status:', status
    252          print 'data:', data
    253          print allg
    254
    255  #============================================================
    256