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

# Source Code for Module Gnumed.business.gmProviderInbox

      1  # -*- coding: latin-1 -*-
      2  """GNUmed provider inbox middleware.
      3
      4  This should eventually end up in a class cPractice.
      5  """
      6  #============================================================
      7  __license__ = "GPL"
      8  __version__ = "$Revision: 1.14 $"
      9  __author__ = "K.Hilbert <Karsten.Hilbert@gmx.net>"
     10
     11
     12  import sys
     13
     14
     15  if __name__ == '__main__':
     16          sys.path.insert(0, '../../')
     17  from Gnumed.pycommon import gmPG2
     18  from Gnumed.pycommon import gmBusinessDBObject
     19  from Gnumed.pycommon import gmTools
     20  from Gnumed.pycommon import gmDateTime
     21
     22  from Gnumed.business import gmStaff
     23
     24  #============================================================
     25  # description
     26  #------------------------------------------------------------
     27  _SQL_get_inbox_messages = u"SELECT * FROM dem.v_message_inbox WHERE %s"
     28
     29 -class cInboxMessage(gmBusinessDBObject.cBusinessDBObject):
     30
     31          _cmd_fetch_payload = _SQL_get_inbox_messages % u"pk_inbox_message = %s"
     32          _cmds_store_payload = [
     33                  u"""
     34                          UPDATE dem.message_inbox SET
     35                                  fk_staff = %(pk_staff)s,
     36                                  fk_inbox_item_type = %(pk_type)s,
     37                                  comment = gm.nullify_empty_string(%(comment)s),
     38                                  data = gm.nullify_empty_string(%(data)s),
     39                                  importance = %(importance)s,
     40                                  fk_patient = %(pk_patient)s,
     41                                  ufk_context = %(pk_context)s
     42                          WHERE
     43                                  pk = %(pk_inbox_message)s
     44                                          AND
     45                                  xmin = %(xmin_message_inbox)s
     46                          RETURNING
     47                                  pk as pk_inbox_message,
     48                                  xmin as xmin_message_inbox
     49                  """
     50          ]
     51          _updatable_fields = [
     52                  u'pk_staff',
     53                  u'pk_type',
     54                  u'comment',
     55                  u'data',
     56                  u'importance',
     57                  u'pk_patient',
     58                  u'ufk_context'
     59          ]
     60          #------------------------------------------------------------
     61 -        def format(self):
     62                  tt = u'%s: %s%s\n' % (
     63                          gmDateTime.pydt_strftime (
     64                                  self._payload[self._idx['received_when']],
     65                                  format = '%A, %Y %B %d, %H:%M',
     66                                  accuracy = gmDateTime.acc_minutes
     67                          ),
     68                          gmTools.bool2subst(self._payload[self._idx['is_virtual']], _('virtual message'), _('message')),
     69                          gmTools.coalesce(self._payload[self._idx['pk_inbox_message']], u'', u' #%s ')
     70                  )
     71
     72                  tt += u'%s: %s\n' % (
     73                          self._payload[self._idx['l10n_category']],
     74                          self._payload[self._idx['l10n_type']]
     75                  )
     76
     77                  tt += u'%s %s %s\n' % (
     78                          self._payload[self._idx['modified_by']],
     79                          gmTools.u_right_arrow,
     80                          gmTools.coalesce(self._payload[self._idx['provider']], _('everyone'))
     81                  )
     82
     83                  tt += u'\n%s%s%s\n\n' % (
     84                          gmTools.u_left_double_angle_quote,
     85                          self._payload[self._idx['comment']],
     86                          gmTools.u_right_double_angle_quote
     87                  )
     88
     89                  tt += gmTools.coalesce (
     90                          self._payload[self._idx['pk_patient']],
     91                          u'',
     92                          u'%s\n\n' % _('Patient #%s')
     93                  )
     94
     95                  if self._payload[self._idx['data']] is not None:
     96                          tt += self._payload[self._idx['data']][:150]
     97                          if len(self._payload[self._idx['data']]) > 150:
     98                                  tt += gmTools.u_ellipsis
     99
    100                  return tt
    101  #------------------------------------------------------------
    102 -def get_inbox_messages(pk_staff=None, pk_patient=None, include_without_provider=False, order_by=None):
    103
    104          if order_by is None:
    105                  order_by = u'%s ORDER BY importance desc, received_when desc'
    106          else:
    107                  order_by = u'%%s ORDER BY %s' % order_by
    108
    109          args = {}
    110          where_parts = []
    111
    112          if pk_staff is not None:
    113                  if include_without_provider:
    114                          where_parts.append(u'pk_staff in (%(staff)s, NULL)')
    115                  else:
    116                          where_parts.append(u'pk_staff = %(staff)s')
    117                  args['staff'] = pk_staff
    118
    119          if pk_patient is not None:
    120                  where_parts.append(u'pk_patient = %(pat)s')
    121                  args['pat'] = pk_patient
    122
    123          cmd = _SQL_get_inbox_messages % (
    124                  order_by % u' AND '.join(where_parts)
    125          )
    126          rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
    127
    128          return [ cInboxMessage(row = {'data': r, 'idx': idx, 'pk_field': 'pk_inbox_message'}) for r in rows ]
    129  #------------------------------------------------------------
    130 -def create_inbox_message(message_type=None, subject=None, patient=None, staff=None):
    131
    132          success, pk_type = gmTools.input2int(initial = message_type)
    133          if not success:
    134                  pk_type = create_inbox_item_type(message_type = message_type)
    135
    136          cmd = u"""
    137                  INSERT INTO dem.message_inbox (
    138                          fk_staff,
    139                          fk_patient,
    140                          fk_inbox_item_type,
    141                          comment
    142                  ) VALUES (
    143                          %(staff)s,
    144                          %(pat)s,
    145                          %(type)s,
    146                          gm.nullify_empty_string(%(subject)s)
    147                  )
    148                  RETURNING pk
    149          """
    150          args = {
    151                  u'staff': staff,
    152                  u'pat': patient,
    153                  u'type': pk_type,
    154                  u'subject': subject
    155          }
    156          rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], return_data = True, get_col_idx = False)
    157
    158          return cInboxMessage(aPK_obj = rows[0]['pk'])
    159  #------------------------------------------------------------
    160 -def delete_inbox_message(inbox_message=None):
    161          args = {'pk': inbox_message}
    162          cmd = u"DELETE FROM dem.message_inbox WHERE pk = %(pk)s"
    163          gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
    164          return True
    165  #------------------------------------------------------------
    166 -def create_inbox_item_type(message_type=None, category=u'clinical'):
    167
    168          # determine category PK
    169          success, pk_cat = gmTools.input2int(initial = category)
    170          if not success:
    171                  args = {u'cat': category}
    172                  cmd = u"""SELECT COALESCE (
    173                          (SELECT pk FROM dem.inbox_item_category WHERE _(description) = %(cat)s),
    174                          (SELECT pk FROM dem.inbox_item_category WHERE description = %(cat)s)
    175                  ) AS pk"""
    176                  rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])
    177                  if rows[0]['pk'] is None:
    178                          cmd = u"INSERT INTO dem.inbox_item_category (description) VALUES (%(cat)s) RETURNING pk"
    179                          rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], return_data = True)
    180                          pk_cat = rows[0]['pk']
    181                  else:
    182                          pk_cat = rows[0]['pk']
    183
    184          # find type PK or create type
    185          args = {u'cat': pk_cat, u'type': message_type}
    186          cmd = u"""SELECT COALESCE (
    187                  (SELECT pk FROM dem.inbox_item_type where fk_inbox_item_category = %(cat)s and _(description) = %(type)s),
    188                  (SELECT pk FROM dem.inbox_item_type where fk_inbox_item_category = %(cat)s and description = %(type)s)
    189          ) AS pk"""
    190          rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])
    191          if rows[0]['pk'] is None:
    192                  cmd = u"""
    193                          INSERT INTO dem.inbox_item_type (
    194                                  fk_inbox_item_category,
    195                                  description,
    196                                  is_user
    197                          ) VALUES (
    198                                  %(cat)s,
    199                                  %(type)s,
    200                                  TRUE
    201                          ) RETURNING pk"""
    202                  rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], return_data = True)
    203
    204          return rows[0]['pk']
    205  #============================================================
    206  #============================================================
    207 -class cProviderInbox:
    208 -        def __init__(self, provider_id=None):
    209                  if provider_id is None:
    210                          self.__provider_id = gmStaff.gmCurrentProvider()['pk_staff']
    211                  else:
    212                          self.__provider_id = provider_id
    213          #--------------------------------------------------------
    214 -        def delete_message(self, pk=None):
    215                  return delete_inbox_message(inbox_message = pk)
    216          #--------------------------------------------------------
    217 -        def add_message(message_type=None, subject=None, patient=None):
    218                  return create_inbox_message (
    219                          message_type = message_type,
    220                          subject = subject,
    221                          patient = patient,
    222                          staff = self.__provider_id
    223                  )
    224          #--------------------------------------------------------
    225          # properties
    226          #--------------------------------------------------------
    227 -        def _get_messages(self):
    228                  return get_inbox_messages(pk_staff = self.__provider_id)
    229
    230 -        def _set_messages(self, messages):
    231                  return
    232
    233          messages = property(_get_messages, _set_messages)
    234  #============================================================
    235  if __name__ == '__main__':
    236
    237          if len(sys.argv) < 2:
    238                  sys.exit()
    239
    240          if sys.argv[1] != 'test':
    241                  sys.exit()
    242
    243          from Gnumed.pycommon import gmI18N
    244
    245          gmI18N.activate_locale()
    246          gmI18N.install_domain()
    247
    248          #---------------------------------------
    249 -        def test_inbox():
    250                  gmStaff.gmCurrentProvider(provider = gmStaff.cStaff())
    251                  inbox = cProviderInbox()
    252                  for msg in inbox.messages:
    253                          print msg
    254          #---------------------------------------
    255 -        def test_msg():
    256                  msg = cInboxMessage(aPK_obj = 1)
    257                  print msg
    258          #---------------------------------------
    259 -        def test_create_type():
    260                  print create_inbox_item_type(message_type = 'test')
    261          #---------------------------------------
    262          #test_inbox()
    263          #test_msg()
    264          test_create_type()
    265
    266  #============================================================
    267