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

# Source Code for Module Gnumed.business.gmPraxis

      1  """GNUmed Praxis related middleware."""
      2  #============================================================
      3  __license__ = "GPL"
      4  __author__ = "K.Hilbert <Karsten.Hilbert@gmx.net>"
      5
      6
      7  import sys
      8  import logging
      9
     10
     11  if __name__ == '__main__':
     12          sys.path.insert(0, '../../')
     13  from Gnumed.pycommon import gmPG2
     14  from Gnumed.pycommon import gmTools
     15  from Gnumed.pycommon import gmBorg
     16  from Gnumed.pycommon import gmCfg2
     17  from Gnumed.pycommon import gmBusinessDBObject
     18
     19  from Gnumed.business import gmOrganization
     20  from Gnumed.business import gmDemographicRecord
     21
     22
     23  _log = logging.getLogger('gm.praxis')
     24  _cfg = gmCfg2.gmCfgData()
     25  #============================================================
     26 -def delete_workplace(workplace=None, delete_config=False, conn=None):
     27
     28          args = {'wp': workplace}
     29
     30          # delete workplace itself (plugin load list, that is)
     31          queries = [
     32                  {'cmd': u"""
     33  delete from cfg.cfg_item
     34  where
     35          fk_template = (
     36                  select pk
     37                  from cfg.cfg_template
     38                  where name = 'horstspace.notebook.plugin_load_order'
     39          )
     40                  and
     41          workplace = %(wp)s""",
     42                  'args': args
     43                  }
     44          ]
     45
     46          # delete other config items associated with this workplace
     47          if delete_config:
     48                  queries.append ({
     49                          'cmd': u"""
     50  delete from cfg.cfg_item
     51  where
     52          workplace = %(wp)s""",
     53                          'args': args
     54                  })
     55
     56          gmPG2.run_rw_queries(link_obj = conn, queries = queries, end_tx = True)
     57
     58  #============================================================
     59  # short description
     60  #------------------------------------------------------------
     61  _SQL_get_praxis_branches = u"SELECT * FROM dem.v_praxis_branches WHERE %s"
     62
     63 -class cPraxisBranch(gmBusinessDBObject.cBusinessDBObject):
     64          """Represents a praxis branch"""
     65
     66          _cmd_fetch_payload = _SQL_get_praxis_branches % u"pk_praxis_branch = %s"
     67          _cmds_store_payload = [
     68                  u"""UPDATE dem.praxis_branch SET
     69                                  fk_org_unit = %(pk_org_unit)s
     70                          WHERE
     71                                  pk = %(pk_praxis_branch)s
     72                                          AND
     73                                  xmin = %(xmin_praxis_branch)s
     74                          RETURNING
     75                                  xmin as xmin_praxis_branch
     76                  """
     77          ]
     78          _updatable_fields = [
     79                  u'pk_org_unit'
     80          ]
     81          #--------------------------------------------------------
     82 -        def format(self):
     83                  txt = _('Praxis branch                   #%s\n') % self._payload[self._idx['pk_praxis_branch']]
     84                  txt += u' '
     85                  txt += u'\n '.join(self.org_unit.format(with_address = True, with_org = True, with_comms = True))
     86                  return txt
     87          #--------------------------------------------------------
     88 -        def lock(self, exclusive=False):
     89                  return lock_praxis_branch(pk_praxis_branch = self._payload[self._idx['pk_praxis_branch']], exclusive = exclusive)
     90          #--------------------------------------------------------
     91 -        def unlock(self, exclusive=False):
     92                  return unlock_praxis_branch(pk_praxis_branch = self._payload[self._idx['pk_praxis_branch']], exclusive = exclusive)
     93          #--------------------------------------------------------
     94 -        def get_comm_channels(self, comm_medium=None):
     95                  return self.org_unit.get_comm_channels(comm_medium = comm_medium)
     96          #--------------------------------------------------------
     97          # properties
     98          #--------------------------------------------------------
     99 -        def _get_org_unit(self):
    100                  return gmOrganization.cOrgUnit(aPK_obj = self._payload[self._idx['pk_org_unit']])
    101
    102          org_unit = property(_get_org_unit, lambda x:x)
    103          #--------------------------------------------------------
    104 -        def _get_org(self):
    105                  return gmOrganization.cOrg(aPK_obj = self._payload[self._idx['pk_org']])
    106
    107          organization = property(_get_org, lambda x:x)
    108
    109          #--------------------------------------------------------
    110 -        def _get_address(self):
    111                  return self.org_unit.address
    112
    113          address = property(_get_address, lambda x:x)
    114
    115  #       def _set_address(self, address):
    116  #               self['pk_address'] = address['pk_address']
    117  #               self.save()
    118  #       address = property(_get_address, _set_address)
    119
    120  #------------------------------------------------------------
    121 -def lock_praxis_branch(pk_praxis_branch=None, exclusive=False):
    122          return gmPG2.lock_row(table = u'dem.praxis_branch', pk = pk_praxis_branch, exclusive = exclusive)
    123
    124  #------------------------------------------------------------
    125 -def unlock_praxis_branch(pk_praxis_branch=None, exclusive=False):
    126          return gmPG2.unlock_row(table = u'dem.praxis_branch', pk = pk_praxis_branch, exclusive = exclusive)
    127
    128  #------------------------------------------------------------
    129 -def get_praxis_branches(order_by=None):
    130          if order_by is None:
    131                  order_by = u'true'
    132          else:
    133                  order_by = u'true ORDER BY %s' % order_by
    134
    135          cmd = _SQL_get_praxis_branches % order_by
    136          rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd}], get_col_idx = True)
    137          return [ cPraxisBranch(row = {'data': r, 'idx': idx, 'pk_field': 'pk_praxis_branch'}) for r in rows ]
    138
    139  #------------------------------------------------------------
    140 -def get_praxis_branch_by_org_unit(pk_org_unit=None):
    141          cmd = _SQL_get_praxis_branches % u'pk_org_unit = %(pk_ou)s'
    142          args = {'pk_ou': pk_org_unit}
    143          rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
    144          if len(rows) == 0:
    145                  return None
    146          return cPraxisBranch(row = {'data': rows[0], 'idx': idx, 'pk_field': 'pk_praxis_branch'})
    147
    148  #------------------------------------------------------------
    149 -def create_praxis_branch(pk_org_unit=None):
    150
    151          args = {u'fk_unit': pk_org_unit}
    152          cmd1 = u"""
    153                  INSERT INTO dem.praxis_branch (fk_org_unit)
    154                  SELECT %(fk_unit)s WHERE NOT EXISTS (
    155                          SELECT 1 FROM dem.praxis_branch WHERE fk_org_unit = %(fk_unit)s
    156                  )
    157          """
    158          cmd2 = u"""SELECT * from dem.v_praxis_branches WHERE pk_org_unit = %(fk_unit)s"""
    159          queries = [
    160                  {'cmd': cmd1, 'args': args},
    161                  {'cmd': cmd2, 'args': args}
    162          ]
    163          rows, idx = gmPG2.run_rw_queries(queries = queries, return_data = True, get_col_idx = True)
    164          return cPraxisBranch(row = {'data': rows[0], 'idx': idx, 'pk_field': 'pk_praxis_branch'})
    165
    166  #------------------------------------------------------------
    167 -def create_praxis_branches(pk_org_units=None):
    168          queries = []
    169          for pk in pk_org_units:
    170                  args = {u'fk_unit': pk}
    171                  cmd = u"""
    172                          INSERT INTO dem.praxis_branch (fk_org_unit)
    173                          SELECT %(fk_unit)s WHERE NOT EXISTS (
    174                                  SELECT 1 FROM dem.praxis_branch WHERE fk_org_unit = %(fk_unit)s
    175                          )
    176                  """
    177                  queries.append({'cmd': cmd, 'args': args})
    178
    179          args = {'fk_units': tuple(pk_org_units)}
    180          cmd = u"""SELECT * from dem.v_praxis_branches WHERE pk_org_unit IN %(fk_units)s"""
    181          queries.append({'cmd': cmd, 'args': args})
    182          rows, idx = gmPG2.run_rw_queries(queries = queries, return_data = True, get_col_idx = True)
    183          return [ cPraxisBranch(row = {'data': r, 'idx': idx, 'pk_field': 'pk_praxis_branch'}) for r in rows ]
    184
    185  #------------------------------------------------------------
    186 -def delete_praxis_branch(pk_praxis_branch=None):
    187          if not lock_praxis_branch(pk_praxis_branch = pk_praxis_branch, exclusive = True):
    188                  return False
    189          args = {'pk': pk_praxis_branch}
    190          cmd = u"DELETE FROM dem.praxis_branch WHERE pk = %(pk)s"
    191          gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
    192          unlock_praxis_branch(pk_praxis_branch = pk_praxis_branch, exclusive = True)
    193          return True
    194
    195  #------------------------------------------------------------
    196 -def delete_praxis_branches(pk_praxis_branches=None, except_pk_praxis_branches=None):
    197
    198          if pk_praxis_branches is None:
    199                  cmd = u'SELECT pk from dem.praxis_branch'
    200                  rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd}], get_col_idx = False)
    201                  pks_to_lock = [ r[0] for r in rows ]
    202          else:
    203                  pks_to_lock = pk_praxis_branches[:]
    204
    205          for pk in except_pk_praxis_branches:
    206                  try: pks_to_lock.remove(pk)
    207                  except ValueError: pass
    208
    209          for pk in pks_to_lock:
    210                  if not lock_praxis_branch(pk_praxis_branch = pk, exclusive = True):
    211                          return False
    212
    213          args = {}
    214          where_parts = []
    215
    216          if pk_praxis_branches is not None:
    217                  args['pks'] = tuple(pk_praxis_branches)
    218                  where_parts.append(u'pk IN %(pks)s')
    219
    220          if except_pk_praxis_branches is not None:
    221                  args['except'] = tuple(except_pk_praxis_branches)
    222                  where_parts.append(u'pk NOT IN %(except)s')
    223
    224          if len(where_parts) == 0:
    225                  cmd = u"DELETE FROM dem.praxis_branch"
    226          else:
    227                  cmd = u"DELETE FROM dem.praxis_branch WHERE %s" % u' AND '.join(where_parts)
    228
    229          gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
    230          for pk in pks_to_lock:
    231                  unlock_praxis_branch(pk_praxis_branch = pk, exclusive = True)
    232          return True
    233
    234  #============================================================
    235 -class gmCurrentPraxisBranch(gmBorg.cBorg):
    236
    237 -        def __init__(self, branch=None):
    238                  try:
    239                          self.has_been_initialized
    240                  except AttributeError:
    241                          self.branch = None
    242                          self.has_been_initialized = True
    243                          self.__helpdesk = None
    244                          self.__active_workplace = None
    245
    246                  # user wants copy of current branch
    247                  if branch is None:
    248                          return None
    249
    250                  # must be cPraxisBranch instance, then
    251                  if not isinstance(branch, cPraxisBranch):
    252                          _log.error('cannot set current praxis branch to [%s], must be a cPraxisBranch instance' % str(branch))
    253                          raise TypeError, 'gmPraxis.gmCurrentPraxisBranch.__init__(): <branch> must be a cPraxisBranch instance but is: %s' % str(branch)
    254
    255                  if self.branch is not None:
    256                          self.branch.unlock()
    257
    258                  branch.lock()
    259                  self.branch = branch
    260                  _log.debug('current praxis branch now: %s', self.branch)
    261
    262                  return None
    263          #--------------------------------------------------------
    264          # __getattr__ handling
    265          #--------------------------------------------------------
    266 -        def __getattr__(self, attribute):
    267                  if attribute == 'has_been_initialized':
    268                          raise AttributeError
    269                  if attribute in ['branch', 'waiting_list_patients', 'help_desk', 'db_logon_banner', 'active_workplace', 'workplaces', 'user_email']:
    270                          return getattr(self, attribute)
    271                  return getattr(self.branch, attribute)
    272          #--------------------------------------------------------
    273          # __get/setitem__ handling
    274          #--------------------------------------------------------
    275 -        def __getitem__(self, attribute = None):
    276                  """Return any attribute if known how to retrieve it by proxy."""
    277                  return self.branch[attribute]
    278          #--------------------------------------------------------
    279 -        def __setitem__(self, attribute, value):
    280                  self.branch[attribute] = value
    281          #--------------------------------------------------------
    282          # waiting list handling
    283          #--------------------------------------------------------
    284 -        def remove_from_waiting_list(self, pk=None):
    285                  cmd = u'delete from clin.waiting_list where pk = %(pk)s'
    286                  args = {'pk': pk}
    287                  gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
    288          #--------------------------------------------------------
    289 -        def update_in_waiting_list(self, pk = None, urgency = 0, comment = None, zone = None):
    290                  cmd = u"""
    291  update clin.waiting_list
    292  set
    293          urgency = %(urg)s,
    294          comment = %(cmt)s,
    295          area = %(zone)s
    296  where
    297          pk = %(pk)s"""
    298                  args = {
    299                          'pk': pk,
    300                          'urg': urgency,
    301                          'cmt': gmTools.none_if(comment, u''),
    302                          'zone': gmTools.none_if(zone, u'')
    303                  }
    304
    305                  gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
    306          #--------------------------------------------------------
    307 -        def raise_in_waiting_list(self, current_position=None):
    308                  if current_position == 1:
    309                          return
    310
    311                  cmd = u'select clin.move_waiting_list_entry(%(pos)s, (%(pos)s - 1))'
    312                  args = {'pos': current_position}
    313
    314                  gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
    315          #--------------------------------------------------------
    316 -        def lower_in_waiting_list(self, current_position=None):
    317                  cmd = u'select clin.move_waiting_list_entry(%(pos)s, (%(pos)s+1))'
    318                  args = {'pos': current_position}
    319
    320                  gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
    321          #--------------------------------------------------------
    322          # properties
    323          #--------------------------------------------------------
    324 -        def _get_waiting_list_patients(self):
    325                  cmd = u"""
    326                          SELECT * FROM clin.v_waiting_list
    327                          ORDER BY
    328                                  list_position
    329                  """
    330                  rows, idx = gmPG2.run_ro_queries (
    331                          queries = [{'cmd': cmd}],
    332                          get_col_idx = False
    333                  )
    334                  return rows
    335
    336          waiting_list_patients = property (_get_waiting_list_patients, lambda x:x)
    337          #--------------------------------------------------------
    338 -        def _set_helpdesk(self, helpdesk):
    339                  return
    340
    341 -        def _get_helpdesk(self):
    342
    343                  if self.__helpdesk is not None:
    344                          return self.__helpdesk
    345
    346                  self.__helpdesk = gmTools.coalesce (
    347                          _cfg.get (
    348                                  group = u'workplace',
    349                                  option = u'help desk',
    350                                  source_order = [
    351                                          ('explicit', 'return'),
    352                                          ('workbase', 'return'),
    353                                          ('local', 'return'),
    354                                          ('user', 'return'),
    355                                          ('system', 'return')
    356                                  ]
    357                          ),
    358                          u'http://wiki.gnumed.de'
    359                  )
    360
    361                  return self.__helpdesk
    362
    363          helpdesk = property(_get_helpdesk, _set_helpdesk)
    364          #--------------------------------------------------------
    365 -        def _get_db_logon_banner(self):
    366                  rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': u'select _(message) from cfg.db_logon_banner'}])
    367                  if len(rows) == 0:
    368                          return u''
    369                  return gmTools.coalesce(rows[0][0], u'').strip()
    370
    371 -        def _set_db_logon_banner(self, banner):
    372                  queries = [
    373                          {'cmd': u'delete from cfg.db_logon_banner'}
    374                  ]
    375                  if banner.strip() != u'':
    376                          queries.append ({
    377                                  'cmd': u'insert into cfg.db_logon_banner (message) values (%(msg)s)',
    378                                  'args': {'msg': banner.strip()}
    379                          })
    380                  rows, idx = gmPG2.run_rw_queries(queries = queries, end_tx = True)
    381
    382          db_logon_banner = property(_get_db_logon_banner, _set_db_logon_banner)
    383          #--------------------------------------------------------
    384 -        def _set_workplace(self, workplace):
    385                  # maybe later allow switching workplaces on the fly
    386                  return True
    387
    388 -        def _get_workplace(self):
    389                  """Return the current workplace (client profile) definition.
    390
    391                  The first occurrence counts.
    392                  """
    393                  if self.__active_workplace is not None:
    394                          return self.__active_workplace
    395
    396                  self.__active_workplace = gmTools.coalesce (
    397                          _cfg.get (
    398                                  group = u'workplace',
    399                                  option = u'name',
    400                                  source_order = [
    401                                          ('explicit', 'return'),
    402                                          ('workbase', 'return'),
    403                                          ('local', 'return'),
    404                                          ('user', 'return'),
    405                                          ('system', 'return'),
    406                                  ]
    407                          ),
    408                          u'Local Default'
    409                  )
    410
    411                  return self.__active_workplace
    412
    413          active_workplace = property(_get_workplace, _set_workplace)
    414          #--------------------------------------------------------
    415 -        def _set_workplaces(self, val):
    416                  pass
    417
    418 -        def _get_workplaces(self):
    419                  rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': u'SELECT DISTINCT workplace FROM cfg.cfg_item ORDER BY workplace'}])
    420                  return [ r[0] for r in rows ]
    421
    422          workplaces = property(_get_workplaces, _set_workplaces)
    423          #--------------------------------------------------------
    424 -        def _get_user_email(self):
    425                  # FIXME: get this from the current users staff record in the database
    426                  return _cfg.get (
    427                          group = u'preferences',
    428                          option = u'user email',
    429                          source_order = [
    430                                  ('explicit', 'return'),
    431                                  ('user', 'return'),
    432                                  ('local', 'return'),
    433                                  ('workbase', 'return'),
    434                                  ('system', 'return')
    435                          ]
    436                  )
    437
    438 -        def _set_user_email(self, val):
    439                  prefs_file = _cfg.get(option = 'user_preferences_file')
    440                  gmCfg2.set_option_in_INI_file (
    441                          filename = prefs_file,
    442                          group = u'preferences',
    443                          option = u'user email',
    444                          value = val
    445                  )
    446                  _cfg.reload_file_source(file = prefs_file)
    447
    448          user_email = property(_get_user_email, _set_user_email)
    449
    450  #============================================================
    451  if __name__ == '__main__':
    452
    453          if len(sys.argv) < 2:
    454                  sys.exit()
    455
    456          if sys.argv[1] != 'test':
    457                  sys.exit()
    458
    459          from Gnumed.pycommon import gmI18N
    460          gmI18N.install_domain()
    461
    462 -        def run_tests():
    463                  prac = gmCurrentPraxisBranch()
    464  #               print "help desk:", prac.helpdesk
    465  #               print "active workplace:", prac.active_workplace
    466
    467                  old_banner = prac.db_logon_banner
    468                  test_banner = u'a test banner'
    469                  prac.db_logon_banner = test_banner
    470                  if prac.db_logon_banner != test_banner:
    471                          print 'Cannot set logon banner to', test_banner
    472                          return False
    473                  prac.db_logon_banner = u''
    474                  if prac.db_logon_banner != u'':
    475                          print 'Cannot set logon banner to ""'
    476                          return False
    477                  prac.db_logon_banner = old_banner
    478
    479                  return True
    480
    481  #       if not run_tests():
    482  #               print "regression tests failed"
    483  #       print "regression tests succeeded"
    484
    485          for b in get_praxis_branches():
    486                  print b.format()
    487
    488  #============================================================
    489