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          state_symbol = property(_get_as_symbol, lambda x:x)
    115          #--------------------------------------------------------
    116 -        def __setitem__(self, attribute, value):
    117                  if attribute == u'comment':
    118                          if value is not None:
    119                                  if value.strip() == u'':
    120                                          value = None
    121
    122                  elif attribute == u'last_confirmed':
    123                          if value == u'now':
    124                                  value = pyDT.datetime.now(tz = gmDateTime.gmCurrentLocalTimezone)
    125
    126                  elif attribute == u'has_allergy':
    127                          if value not in allergy_states:
    128                                  raise ValueError('invalid allergy state [%s]' % value)
    129
    130                  gmBusinessDBObject.cBusinessDBObject.__setitem__(self, attribute, value)
    131  #============================================================
    132 -class cAllergy(gmBusinessDBObject.cBusinessDBObject):
    133          """Represents one allergy item.
    134
    135          Actually, those things are really things to *avoid*.
    136          Allergy is just one of several reasons for that.
    137          See Adrian's post on gm-dev.
    138
    139          Another word might be Therapeutic Precautions.
    140          """
    141          _cmd_fetch_payload = u"SELECT * FROM clin.v_pat_allergies WHERE pk_allergy = %s"
    142          _cmds_store_payload = [
    143                  u"""UPDATE clin.allergy SET
    144                                  clin_when = %(date)s,
    145                                  substance = %(substance)s,
    146                                  substance_code = %(substance_code)s,
    147                                  generics = %(generics)s,
    148                                  allergene = %(allergene)s,
    149                                  atc_code = %(atc_code)s,
    150                                  fk_type = %(pk_type)s,
    151                                  generic_specific = %(generic_specific)s::boolean,
    152                                  definite = %(definite)s::boolean,
    153                                  narrative = %(reaction)s
    154                          WHERE
    155                                  pk = %(pk_allergy)s AND
    156                                  xmin = %(xmin_allergy)s""",
    157                  u"""SELECT xmin_allergy FROM clin.v_pat_allergies WHERE pk_allergy=%(pk_allergy)s"""
    158          ]
    159          _updatable_fields = [
    160                  'date',
    161                  'substance',
    162                  'substance_code',
    163                  'generics',
    164                  'allergene',
    165                  'atc_code',
    166                  'pk_type',
    167                  'generic_specific',
    168                  'definite',
    169                  'reaction'
    170          ]
    171          #--------------------------------------------------------
    172 -        def __setitem__(self, attribute, value):
    173                  if attribute == 'pk_type':
    174                          if value in ['allergy', 'sensitivity']:
    175                                  cmd = u'select pk from clin._enum_allergy_type where value=%s'
    176                                  rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [value]}])
    177                                  value = rows[0][0]
    178
    179                  gmBusinessDBObject.cBusinessDBObject.__setitem__(self, attribute, value)
    180  #============================================================
    181  # convenience functions
    182  #------------------------------------------------------------
    183 -def create_allergy(allergene=None, allg_type=None, episode_id=None, encounter_id=None):
    184          """Creates a new allergy clinical item.
    185
    186          allergene - allergic substance
    187          allg_type - allergy or sensitivity, pk or string
    188          encounter_id - encounter's primary key
    189          episode_id - episode's primary key
    190          """
    191          cmd = u"""
    192                  SELECT pk_allergy
    193                  FROM clin.v_pat_allergies
    194                  WHERE
    195                          pk_patient = (SELECT fk_patient FROM clin.encounter WHERE pk = %(enc)s)
    196                                  AND
    197                          allergene = %(allergene)s
    198          """
    199          #args = {'enc': encounter_id, 'substance': substance}
    200          args = {'enc': encounter_id, 'allergene': allergene}
    201          rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])
    202          if len(rows) > 0:
    203                  # don't implicitely change existing data
    204                  return cAllergy(aPK_obj = rows[0][0])
    205
    206          # insert new allergy
    207          queries = []
    208
    209          if type(allg_type) == types.IntType:
    210                  cmd = u"""
    211                          insert into clin.allergy (fk_type, fk_encounter, fk_episode, allergene, substance)
    212                          values (%s, %s, %s, %s, %s)"""
    213          else:
    214                  cmd = u"""
    215                          insert into clin.allergy (fk_type, fk_encounter, fk_episode,  allergene, substance)
    216                          values ((select pk from clin._enum_allergy_type where value = %s), %s, %s, %s, %s)"""
    217          queries.append({'cmd': cmd, 'args': [allg_type, encounter_id, episode_id, allergene, allergene]})
    218
    219          cmd = u"select currval('clin.allergy_id_seq')"
    220          queries.append({'cmd': cmd})
    221
    222          rows, idx = gmPG2.run_rw_queries(queries=queries, return_data=True)
    223          allergy = cAllergy(aPK_obj = rows[0][0])
    224
    225          return allergy
    226  #============================================================
    227  # main - unit testing
    228  #------------------------------------------------------------
    229  if __name__ == '__main__':
    230
    231          allg = cAllergy(aPK_obj=1)
    232          print allg
    233          fields = allg.get_fields()
    234          for field in fields:
    235                  print field, ':', allg[field]
    236          print "updatable:", allg.get_updatable_fields()
    237          enc_id = allg['pk_encounter']
    238          epi_id = allg['pk_episode']
    239          status, allg = create_allergy (
    240                  allergene = 'test substance',
    241                  allg_type = 1,
    242                  episode_id = epi_id,
    243                  encounter_id = enc_id
    244          )
    245          print allg
    246          allg['reaction'] = 'hehehe'
    247          status, data = allg.save_payload()
    248          print 'status:', status
    249          print 'data:', data
    250          print allg
    251
    252  #============================================================
    253