Package Gnumed :: Package wxpython :: Module gmOrganizationWidgets |
[frames] | no frames]

# Source Code for Module Gnumed.wxpython.gmOrganizationWidgets

      1  """GNUmed organization handling widgets.
      2
      3  copyright: authors
      4  """
      5  #============================================================
      6  __author__ = "K.Hilbert"
      7  __license__ = "GPL v2 or later (details at http://www.gnu.org)"
      8
      9  import logging
     10  import sys
     11
     12
     13  import wx
     14
     15
     16  if __name__ == '__main__':
     17          sys.path.insert(0, '../../')
     18          from Gnumed.pycommon import gmI18N
     19          gmI18N.activate_locale()
     20          gmI18N.install_domain()
     21
     22  from Gnumed.pycommon import gmTools
     23  from Gnumed.pycommon import gmMatchProvider
     24  from Gnumed.pycommon import gmDispatcher
     25
     26  from Gnumed.business import gmOrganization
     27
     28  from Gnumed.wxpython import gmListWidgets
     29  from Gnumed.wxpython import gmEditArea
     30  from Gnumed.wxpython import gmPhraseWheel
     31  from Gnumed.wxpython import gmPersonContactWidgets
     32  from Gnumed.wxpython import gmAddressWidgets
     33  from Gnumed.wxpython import gmGuiHelpers
     34  from Gnumed.wxpython.gmDemographicsWidgets import cExternalIDEditAreaPnl
     35
     36
     37  _log = logging.getLogger('gm.organization')
     38
     39  #============================================================
     40  # organizational units API
     41  #------------------------------------------------------------
     42 -def edit_org_unit(parent=None, org_unit=None, single_entry=False, org=None):
     43          ea = cOrgUnitEAPnl(parent, -1)
     44          ea.data = org_unit
     45          ea.mode = gmTools.coalesce(org_unit, 'new', 'edit')
     46          dlg = gmEditArea.cGenericEditAreaDlg2(parent, -1, edit_area = ea, single_entry = single_entry)
     47          if org is not None:
     48                  ea.organization = org
     49          dlg.SetTitle(gmTools.coalesce(org_unit, _('Adding new organizational unit'), _('Editing organizational unit')))
     50          if dlg.ShowModal() == wx.ID_OK:
     51                  dlg.DestroyLater()
     52                  return True
     53          dlg.DestroyLater()
     54          return False
     55
     56  #============================================================
     57 -def select_org_unit(parent=None, msg=None, no_parent=False):
     58
     59          if no_parent:
     60                  parent = None
     61          else:
     62                  if parent is None:
     63                          parent = wx.GetApp().GetTopWindow()
     64
     65          #--------------------
     66          def new():
     67                  manage_orgs(parent = parent, no_parent = no_parent)
     68                  return True
     69          #--------------------
     70          def refresh(lctrl):
     71                  units = gmOrganization.get_org_units(order_by = 'organization, unit, l10n_unit_category')
     72                  items = [ [
     73                          u['organization'],
     74                          u['unit'],
     75                          gmTools.coalesce(u['l10n_unit_category'], ''),
     76                          u['pk_org_unit']
     77                  ] for u in units ]
     78
     79                  lctrl.set_string_items(items = items)
     80                  lctrl.set_data(data = units)
     81          #--------------------
     82          if msg is None:
     83                  msg = _("Organizations and units thereof.\n")
     84
     85          return gmListWidgets.get_choices_from_list (
     86                  parent = parent,
     87                  msg = msg,
     88                  caption = _('Unit selection ...'),
     89                  columns = [_('Organization'), _('Unit'), _('Unit type'), '#'],
     90                  can_return_empty = False,
     91                  single_selection = True,
     92                  refresh_callback = refresh,
     93                  new_callback = new
     94          )
     95
     96  #============================================================
     97 -class cOrgUnitPhraseWheel(gmPhraseWheel.cPhraseWheel):
     98
     99 -        def __init__(self, *args, **kwargs):
    100                  query = """
    101          SELECT DISTINCT ON (data) * FROM (
    102                  SELECT * FROM ((
    103
    104                          SELECT
    105                                  pk_org_unit
    106                                          AS data,
    107                                  unit || coalesce(' (' || l10n_unit_category || ')', '') || ': ' || organization || ' (' || l10n_organization_category || ')'
    108                                          AS list_label,
    109                                  unit || ' (' || organization || ')'
    110                                          AS field_label
    111                          FROM
    112                                  dem.v_org_units
    113                          WHERE
    114                                  unit %(fragment_condition)s
    115
    116                  ) UNION ALL (
    117
    118                          SELECT
    119                                  pk_org_unit
    120                                          AS data,
    121                                  coalesce(l10n_unit_category || ' ', '') || '"' || unit || '": ' || organization || ' (' || l10n_organization_category || ')'
    122                                          AS list_label,
    123                                  unit || ' (' || organization || ')'
    124                                          AS field_label
    125                          FROM
    126                                  dem.v_org_units
    127                          WHERE
    128                                  l10n_unit_category %(fragment_condition)s
    129                                          OR
    130                                  unit_category %(fragment_condition)s
    131
    132                  ) UNION ALL (
    133
    134                          SELECT
    135                                  pk_org_unit
    136                                          AS data,
    137                                  organization || ': ' || unit || coalesce(' (' || l10n_unit_category || ')', '')
    138                                          AS list_label,
    139                                  unit || ' (' || organization || ')'
    140                                          AS field_label
    141                          FROM
    142                                  dem.v_org_units
    143                          WHERE
    144                                  organization %(fragment_condition)s
    145
    146                  )) AS all_matches
    147                  ORDER BY list_label
    148          ) AS ordered_matches
    149          LIMIT 50
    150                  """
    151                  mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
    152                  mp.setThresholds(1, 3, 5)
    153                  gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
    154                  self.SetToolTip(_("Select an organizational unit."))
    155                  self.matcher = mp
    156                  self.picklist_delay = 300
    157          #--------------------------------------------------------
    158 -        def _get_data_tooltip(self):
    159                  if self.GetData() is None:
    160                          return None
    161                  unit = self._data2instance()
    162                  if unit is None:
    163                          return None
    164                  return '\n'.join(unit.format(with_address = True))
    165          #--------------------------------------------------------
    166 -        def _data2instance(self):
    167                  if self.GetData() is None:
    168                          return None
    169                  return gmOrganization.cOrgUnit(aPK_obj = self.GetData())
    170
    171  #============================================================
    172 -class cOrgUnitsManagerPnl(gmListWidgets.cGenericListManagerPnl):
    173          """A list for managing organizational units."""
    174
    175 -        def __init__(self, *args, **kwargs):
    176
    177                  try:
    178                          self.__org = kwargs['org']
    179                          del kwargs['org']
    180                  except KeyError:
    181                          self.__org = None
    182
    183                  gmListWidgets.cGenericListManagerPnl.__init__(self, *args, **kwargs)
    184
    185                  self.refresh_callback = self.refresh
    186                  self.new_callback = self._add
    187                  self.edit_callback = self._edit
    188                  self.delete_callback = self._del
    189
    190                  self.__show_none_if_no_org = True
    191                  self.__init_ui()
    192                  self.__refresh()
    193          #--------------------------------------------------------
    194          # external API
    195          #--------------------------------------------------------
    196 -        def refresh(self, lctrl=None):
    197                  self.__refresh()
    198          #--------------------------------------------------------
    199          # event handlers
    200          #--------------------------------------------------------
    201 -        def _add(self):
    202                  return edit_org_unit(parent = self, org_unit = None, single_entry = False, org = self.__org)
    203          #--------------------------------------------------------
    204 -        def _edit(self, item):
    205                  return edit_org_unit(parent = self, org_unit = item, single_entry = True)
    206          #--------------------------------------------------------
    207 -        def _del(self, item):
    208                  return gmOrganization.delete_org_unit(unit = item['pk_org_unit'])
    209          #--------------------------------------------------------
    210 -        def _on_list_item_focused(self, event):
    211                  pass
    212          #--------------------------------------------------------
    213          # internal helpers
    214          #--------------------------------------------------------
    215 -        def __init_ui(self):
    216                  self._LCTRL_items.set_columns(columns = [ _('Organizational Unit'), _('Unit Category'), '#' ])
    217                  self._LCTRL_items.SetToolTip(_('Units (sites, parts, departments, branches, ...) of organizations registered in GNUmed.'))
    218                  self._LCTRL_items.item_tooltip_callback = self.get_tooltip
    219                  #self._LCTRL_items.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
    220          #--------------------------------------------------------
    221 -        def get_tooltip(self, unit):
    222                  if unit is None:
    223                          return _('Units (sites, parts, departments, branches, ...) of organizations registered in GNUmed.')
    224                  return '\n'.join(unit.format(with_address = True, with_org = True, with_comms = True))
    225          #--------------------------------------------------------
    226 -        def __refresh(self):
    227
    228                  msg_template = _('Units of: %s')
    229
    230                  if self.__org is None:
    231                          self._BTN_add.Enable(False)
    232                          self._BTN_edit.Enable(False)
    233                          self._BTN_remove.Enable(False)
    234                          pk = None
    235                          self.message = msg_template % _('<no organization selected>')
    236                          if self.__show_none_if_no_org:
    237                                  self._LCTRL_items.set_string_items(items = None)
    238                                  return
    239                  else:
    240                          self._BTN_add.Enable(True)
    241                          pk = self.__org['pk_org']
    242                          org_str = '%s (%s)' % (
    243                                  self.__org['organization'],
    244                                  self.__org['l10n_category']
    245                          )
    246                          self.message = msg_template % org_str
    247
    248                  units = gmOrganization.get_org_units(order_by = 'unit, l10n_unit_category', org = pk)
    249                  items = [ [
    250                          u['unit'],
    251                          gmTools.coalesce(u['l10n_unit_category'], ''),
    252                          u['pk_org_unit']
    253                  ] for u in units ]
    254
    255                  self._LCTRL_items.set_string_items(items)
    256                  self._LCTRL_items.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
    257                  self._LCTRL_items.set_data(units)
    258
    259                  for idx in range(len(units)):
    260                          unit = units[idx]
    261                          if unit['is_praxis_branch']:
    262                                  self._LCTRL_items.SetItemTextColour(idx, wx.Colour('RED'))
    263          #--------------------------------------------------------
    264          # properties
    265          #--------------------------------------------------------
    266 -        def _get_org(self):
    267                  return self.__org
    268
    269 -        def _set_org(self, org):
    270                  self.__org = org
    271                  self.__refresh()
    272
    273          org = property(_get_org, _set_org)
    274          #--------------------------------------------------------
    275 -        def _get_show_none_if_no_org(self):
    276                  return self.__show_none_if_no_org
    277
    278 -        def _set_show_none_if_no_org(self, show_none_if_no_org):
    279                  if show_none_if_no_org == self.__show_none_if_no_org:
    280                          return
    281                  if show_none_if_no_org:
    282                          self.__show_none_if_no_org = True
    283                  else:
    284                          self.__show_none_if_no_org = False
    285                  self.__refresh()
    286
    287          show_none_if_no_org = property(_get_show_none_if_no_org, _set_show_none_if_no_org)
    288
    289  #============================================================
    290  # org unit edit area
    291  from Gnumed.wxGladeWidgets import wxgOrgUnitEAPnl
    292
    293 -class cOrgUnitEAPnl(wxgOrgUnitEAPnl.wxgOrgUnitEAPnl, gmEditArea.cGenericEditAreaMixin):
    294
    295 -        def __init__(self, *args, **kwargs):
    296
    297                  try:
    298                          data = kwargs['unit']
    299                          del kwargs['unit']
    300                  except KeyError:
    301                          data = None
    302
    303                  wxgOrgUnitEAPnl.wxgOrgUnitEAPnl.__init__(self, *args, **kwargs)
    304                  gmEditArea.cGenericEditAreaMixin.__init__(self)
    305
    306                  self.mode = 'new'
    307                  self.data = data
    308                  if data is not None:
    309                          self.mode = 'edit'
    310
    311  #               self.__init_ui()
    312          #----------------------------------------------------------------
    313  #       def __init_ui(self):
    314  #               pass
    315          #----------------------------------------------------------------
    316          # generic Edit Area mixin API
    317          #----------------------------------------------------------------
    318 -        def _valid_for_save(self):
    319                  validity = True
    320
    321                  if self._PRW_category.GetData() is not None:
    322                          self._PRW_category.display_as_valid(True)
    323                  else:
    324                          if self._PRW_category.GetValue().strip() == '':
    325                                  self._PRW_category.display_as_valid(True)
    326                          else:
    327                                  validity = False
    328                                  self._PRW_category.display_as_valid(False)
    329                                  self._PRW_category.SetFocus()
    330
    331                  if self._PRW_unit.GetData() is not None:
    332                          self._PRW_unit.display_as_valid(True)
    333                  else:
    334                          if self._PRW_unit.GetValue().strip() != '':
    335                                  self._PRW_unit.display_as_valid(True)
    336                          else:
    337                                  validity = False
    338                                  self._PRW_unit.display_as_valid(False)
    339                                  self._PRW_unit.SetFocus()
    340
    341                  if self._PRW_org.GetData() is None:
    342                          validity = False
    343                          self._PRW_org.display_as_valid(False)
    344                          self._PRW_org.SetFocus()
    345                  else:
    346                          self._PRW_org.display_as_valid(True)
    347
    348                  return validity
    349          #----------------------------------------------------------------
    350 -        def _save_as_new(self):
    351                  data = gmOrganization.create_org_unit (
    352                          pk_organization = self._PRW_org.GetData(),
    353                          unit = self._PRW_unit.GetValue().strip()
    354                  )
    355                  data['pk_category_unit'] = self._PRW_category.GetData()
    356                  data.save()
    357
    358                  self.data = data
    359                  return True
    360          #----------------------------------------------------------------
    361 -        def _save_as_update(self):
    362                  self.data['pk_org'] = self._PRW_org.GetData()
    363                  self.data['unit'] = self._PRW_unit.GetValue().strip()
    364                  self.data['pk_category_unit'] = self._PRW_category.GetData()
    365                  self.data.save()
    366                  return True
    367          #----------------------------------------------------------------
    368 -        def _refresh_as_new(self):
    369                  self._PRW_org.SetText(value = '', data = None)
    370                  self._PRW_unit.SetText(value = '', data = None)
    371                  self._PRW_category.SetText(value = '', data = None)
    372
    373                  self._PRW_unit.SetFocus()
    374          #----------------------------------------------------------------
    375 -        def _refresh_as_new_from_existing(self):
    376                  self._PRW_org.SetText(value = self.data['organization'], data = self.data['pk_org'])
    377                  self._PRW_unit.SetText(value = '', data = None)
    378                  self._PRW_category.SetText(value = self.data['unit_category'], data = self.data['pk_category_unit'])
    379
    380                  self._PRW_unit.SetFocus()
    381          #----------------------------------------------------------------
    382 -        def _refresh_from_existing(self):
    383                  self._PRW_org.SetText(value = self.data['organization'], data = self.data['pk_org'])
    384                  self._PRW_unit.SetText(value = self.data['unit'], data = self.data['pk_org_unit'])
    385                  self._PRW_category.SetText(value = self.data['unit_category'], data = self.data['pk_category_unit'])
    386
    387                  self._PRW_unit.SetFocus()
    388          #----------------------------------------------------------------
    389 -        def _set_org(self, org):
    390                  self._PRW_org.SetText(value = org['organization'], data = org['pk_org'])
    391
    392          organization = property(lambda x:x, _set_org)
    393
    394  #============================================================
    395  from Gnumed.wxGladeWidgets import wxgOrgUnitAddressPnl
    396
    397 -class cOrgUnitAddressPnl(wxgOrgUnitAddressPnl.wxgOrgUnitAddressPnl):
    398
    399 -        def __init__(self, *args, **kwargs):
    400
    401                  wxgOrgUnitAddressPnl.wxgOrgUnitAddressPnl.__init__(self, *args, **kwargs)
    402
    403                  self.__unit = None
    404          #--------------------------------------------------------
    405          # internal helpers
    406          #--------------------------------------------------------
    407 -        def __refresh(self):
    408                  if self.__unit is None:
    409                          self.message = _('<no unit selected>')
    410                          self._PRW_address_searcher.SetText('', None)
    411                          self._PRW_address_searcher.Enable(False)
    412                          self._BTN_save_picked_address.Enable(False)
    413                          self._BTN_add_new_address.Enable(False)
    414                  else:
    415                          if self.__unit['l10n_unit_category'] is None:
    416                                  cat = ''
    417                                  left_delim = ''
    418                                  right_delim = ''
    419                          else:
    420                                  cat = '%s ' % self.__unit['l10n_unit_category']
    421                                  left_delim = gmTools.u_left_double_angle_quote
    422                                  right_delim = gmTools.u_right_double_angle_quote
    423                          self.message = '%s%s%s%s' % (
    424                                  cat,
    425                                  left_delim,
    426                                  self.__unit['unit'],
    427                                  right_delim
    428                          )
    429                          self._PRW_address_searcher.Enable(True)
    430                          self._PRW_address_searcher.address = self.__unit['pk_address']
    431                          self._PRW_address_searcher.Enable(True)
    432                          self._BTN_save_picked_address.Enable(True)
    433                          self._BTN_add_new_address.Enable(True)
    434          #--------------------------------------------------------
    435          # event handlers
    436          #--------------------------------------------------------
    437 -        def _on_save_picked_address_button_pressed(self, event):
    438                  if self._PRW_address_searcher.GetData() is None:
    439                          if self._PRW_address_searcher.GetValue().strip() != '':
    440                                  gmDispatcher.send(signal = 'statustext', msg = _('Invalid address selection.'))
    441                                  self._PRW_address_searcher.display_as_valid(False)
    442                                  self._PRW_address_searcher.SetFocus()
    443                                  return
    444
    445                  self._PRW_address_searcher.display_as_valid(True)
    446
    447                  self.__unit['pk_address'] = self._PRW_address_searcher.GetData()
    448                  self.__unit.save()
    449                  self.__refresh()
    450          #--------------------------------------------------------
    451 -        def _on_add_new_address_button_pressed(self, event):
    452                  ea = gmAddressWidgets.cAddressEAPnl(self, -1)
    453                  ea.address_holder = self.__unit
    454                  ea.type_is_editable = False
    455                  dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea)
    456                  dlg.SetTitle(_('Adding new address'))
    457                  if dlg.ShowModal() != wx.ID_OK:
    458                          return False
    459                  self.__refresh()
    460                  return True
    461          #--------------------------------------------------------
    462 -        def _on_manage_addresses_button_pressed(self, event):
    463                  picked_address = gmAddressWidgets.manage_addresses(parent = self)
    464                  if picked_address is None:
    465                          return
    466
    467                  question = '%s\n\n  %s\n' % (
    468                          _('Link the following address to the organizational unit ?'),
    469                          '\n  '.join(picked_address.format())
    470                  )
    471
    472                  link_it = gmGuiHelpers.gm_show_question (
    473                          title = _('Linking selected address'),
    474                          question = question
    475                  )
    476                  if not link_it:
    477                          return
    478
    479                  self._PRW_address_searcher.address = picked_address['pk_address']
    480                  self._PRW_address_searcher.display_as_valid(True)
    481                  self.__unit['pk_address'] = self._PRW_address_searcher.GetData()
    482                  self.__unit.save()
    483          #--------------------------------------------------------
    484          # properties
    485          #--------------------------------------------------------
    486 -        def _get_unit(self):
    487                  return self.__unit
    488
    489 -        def _set_unit(self, unit):
    490                  self.__unit = unit
    491                  self.__refresh()
    492
    493          unit = property(_get_unit, _set_unit)
    494          #--------------------------------------------------------
    495 -        def _get_message(self):
    496                  return self._LBL_message.GetLabel()
    497
    498 -        def _set_message(self, msg):
    499                  if msg is None:
    500                          self._LBL_message.Hide()
    501                          self._LBL_message.SetLabel('')
    502                  else:
    503                          self._LBL_message.SetLabel(msg)
    504                          self._LBL_message.Show()
    505                  self.Layout()
    506
    507          message = property(_get_message, _set_message)
    508
    509  #============================================================
    510 -class cOrgUnitIDsMgrPnl(gmListWidgets.cGenericListManagerPnl):
    511          """A list for managing an org unit's external IDs.
    512
    513          Does NOT act on/listen to the current patient.
    514          """
    515 -        def __init__(self, *args, **kwargs):
    516
    517                  try:
    518                          self.__unit = kwargs['unit']
    519                          del kwargs['unit']
    520                  except KeyError:
    521                          self.__unit = None
    522
    523                  gmListWidgets.cGenericListManagerPnl.__init__(self, *args, **kwargs)
    524
    525                  self.refresh_callback = self.refresh
    526                  self.new_callback = self._add_id
    527                  self.edit_callback = self._edit_id
    528                  self.delete_callback = self._del_id
    529
    530                  self.__init_ui()
    531                  self.refresh()
    532          #--------------------------------------------------------
    533          # external API
    534          #--------------------------------------------------------
    535 -        def refresh(self, *args, **kwargs):
    536                  if self.__unit is None:
    537                          self._LCTRL_items.set_string_items()
    538                          return
    539
    540                  ids = self.__unit.external_ids
    541                  self._LCTRL_items.set_string_items (
    542                          items = [ [
    543                                          i['name'],
    544                                          i['value'],
    545                                          gmTools.coalesce(i['issuer'], ''),
    546                                          gmTools.coalesce(i['comment'], '')
    547                                  ] for i in ids
    548                          ]
    549                  )
    550                  self._LCTRL_items.set_column_widths()
    551                  self._LCTRL_items.set_data(data = ids)
    552          #--------------------------------------------------------
    553          # internal helpers
    554          #--------------------------------------------------------
    555 -        def __init_ui(self):
    556                  self._LCTRL_items.set_columns(columns = [
    557                          _('ID Type'),
    558                          _('Value'),
    559                          _('Issuer'),
    560                          _('Comment')
    561                  ])
    562          #--------------------------------------------------------
    563 -        def _add_id(self):
    564                  ea = cExternalIDEditAreaPnl(self, -1)
    565                  ea.id_holder = self.__unit
    566                  dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea)
    567                  dlg.SetTitle(_('Adding new external ID'))
    568                  if dlg.ShowModal() == wx.ID_OK:
    569                          dlg.DestroyLater()
    570                          return True
    571                  dlg.DestroyLater()
    572                  return False
    573          #--------------------------------------------------------
    574 -        def _edit_id(self, ext_id):
    575                  ea = cExternalIDEditAreaPnl(self, -1, external_id = ext_id)
    576                  ea.id_holder = self.__unit
    577                  dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea, single_entry = True)
    578                  dlg.SetTitle(_('Editing external ID'))
    579                  if dlg.ShowModal() == wx.ID_OK:
    580                          dlg.DestroyLater()
    581                          return True
    582                  dlg.DestroyLater()
    583                  return False
    584          #--------------------------------------------------------
    585 -        def _del_id(self, ext_id):
    586                  go_ahead = gmGuiHelpers.gm_show_question (
    587                          _(      'Do you really want to delete this\n'
    588                                  'external ID from the organizational unit ?'),
    589                          _('Deleting external ID')
    590                  )
    591                  if not go_ahead:
    592                          return False
    593                  self.__unit.delete_external_id(pk_ext_id = ext_id['pk_id'])
    594                  return True
    595          #--------------------------------------------------------
    596          # properties
    597          #--------------------------------------------------------
    598 -        def _get_org_unit(self):
    599                  return self.__unit
    600
    601 -        def _set_org_unit(self, org_unit):
    602                  self.__unit = org_unit
    603                  self.refresh()
    604
    605          org_unit = property(_get_org_unit, _set_org_unit)
    606
    607  #============================================================
    608  # organizations API
    609  #------------------------------------------------------------
    610 -def manage_orgs(parent=None, no_parent=False):
    611
    612          if no_parent:
    613                  parent = None
    614          else:
    615                  if parent is None:
    616                          parent = wx.GetApp().GetTopWindow()
    617
    618          dlg = cOrganizationManagerDlg(parent, -1)
    619          dlg.ShowModal()
    620          dlg.DestroyLater()
    621  #============================================================
    622 -def edit_org(parent=None, org=None, single_entry=False):
    623          ea = cOrganizationEAPnl(parent, -1)
    624          ea.data = org
    625          ea.mode = gmTools.coalesce(org, 'new', 'edit')
    626          dlg = gmEditArea.cGenericEditAreaDlg2(parent, -1, edit_area = ea, single_entry = single_entry)
    627          dlg.SetTitle(gmTools.coalesce(org, _('Adding new organization'), _('Editing organization')))
    628          if dlg.ShowModal() == wx.ID_OK:
    629                  dlg.DestroyLater()
    630                  return True
    631          dlg.DestroyLater()
    632          return False
    633  #============================================================
    634 -class cOrganizationPhraseWheel(gmPhraseWheel.cPhraseWheel):
    635
    636 -        def __init__(self, *args, **kwargs):
    637                  query = """
    638          SELECT DISTINCT ON (data) * FROM (
    639                  SELECT * FROM ((
    640
    641                          SELECT
    642                                  pk_org
    643                                          AS data,
    644                                  organization || ' (' || l10n_category || ')'
    645                                          AS list_label,
    646                                  organization || ' (' || l10n_category || ')'
    647                                          AS field_label
    648                          FROM
    649                                  dem.v_orgs
    650                          WHERE
    651                                  organization %(fragment_condition)s
    652
    653                  ) UNION ALL (
    654
    655                          SELECT
    656                                  pk_org
    657                                          AS data,
    658                                  l10n_category || ': ' || organization
    659                                          AS list_label,
    660                                  organization || ' (' || l10n_category || ')'
    661                                          AS field_label
    662                          FROM
    663                                  dem.v_orgs
    664                          WHERE
    665                                  l10n_category %(fragment_condition)s
    666                                          OR
    667                                  category %(fragment_condition)s
    668
    669                  )) AS all_matches
    670                  ORDER BY list_label
    671          ) AS ordered_matches
    672          LIMIT 50
    673                  """
    674                  mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
    675                  mp.setThresholds(1, 3, 5)
    676                  gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
    677                  self.SetToolTip(_("Select an organization."))
    678                  self.matcher = mp
    679                  self.picklist_delay = 300
    680                  self.selection_only = True
    681
    682  #====================================================================
    683  from Gnumed.wxGladeWidgets import wxgOrganizationEAPnl
    684
    685 -class cOrganizationEAPnl(wxgOrganizationEAPnl.wxgOrganizationEAPnl, gmEditArea.cGenericEditAreaMixin):
    686
    687 -        def __init__(self, *args, **kwargs):
    688
    689                  try:
    690                          data = kwargs['organization']
    691                          del kwargs['organization']
    692                  except KeyError:
    693                          data = None
    694
    695                  wxgOrganizationEAPnl.wxgOrganizationEAPnl.__init__(self, *args, **kwargs)
    696                  gmEditArea.cGenericEditAreaMixin.__init__(self)
    697
    698                  self.mode = 'new'
    699                  self.data = data
    700                  if data is not None:
    701                          self.mode = 'edit'
    702
    703                  #self.__init_ui()
    704          #----------------------------------------------------------------
    705 -        def __init_ui(self):
    706                  self._PRW_org.selection_only = False
    707          #----------------------------------------------------------------
    708          # generic Edit Area mixin API
    709          #----------------------------------------------------------------
    710 -        def _valid_for_save(self):
    711                  validity = True
    712
    713                  if self._PRW_category.GetData() is None:
    714                          validity = False
    715                          self._PRW_category.display_as_valid(False)
    716                          self._PRW_category.SetFocus()
    717                  else:
    718                          self._PRW_category.display_as_valid(True)
    719
    720                  if self._PRW_org.GetValue().strip() == '':
    721                          validity = False
    722                          self._PRW_org.display_as_valid(False)
    723                          self._PRW_org.SetFocus()
    724                  else:
    725                          self._PRW_org.display_as_valid(True)
    726
    727  #               if self.mode == 'edit':
    728  #                       if self._PRW_org.GetData() is None:
    729  #                               validity = False
    730  #                               self._PRW_org.display_as_valid(False)
    731  #                               self._PRW_org.SetFocus()
    732  #                       else:
    733  #                               self._PRW_org.display_as_valid(True)
    734  #               else:
    735  #                       if self._PRW_org.GetValue().strip() == u'':
    736  #                               validity = False
    737  #                               self._PRW_org.display_as_valid(False)
    738  #                               self._PRW_org.SetFocus()
    739  #                       else:
    740  #                               if self._PRW_org.GetData() is not None:
    741  #                                       validity = False
    742  #                                       self._PRW_org.display_as_valid(False)
    743  #                                       self._PRW_org.SetFocus()
    744  #                               else:
    745  #                                       self._PRW_org.display_as_valid(True)
    746
    747                  return validity
    748          #----------------------------------------------------------------
    749 -        def _save_as_new(self):
    750                  self.data = gmOrganization.create_org (
    751                          organization = self._PRW_org.GetValue().strip(),
    752                          category = self._PRW_category.GetData()
    753                  )
    754                  return True
    755          #----------------------------------------------------------------
    756 -        def _save_as_update(self):
    757                  #self.data['pk_org'] = self._PRW_org.GetData()
    758                  self.data['organization'] = self._PRW_org.GetValue().strip()
    759                  self.data['pk_category_org'] = self._PRW_category.GetData()
    760                  self.data.save()
    761                  return True
    762          #----------------------------------------------------------------
    763 -        def _refresh_as_new(self):
    764                  self._PRW_org.SetText(value = '', data = None)
    765                  self._PRW_category.SetText(value = '', data = None)
    766
    767                  self._PRW_org.SetFocus()
    768          #----------------------------------------------------------------
    769 -        def _refresh_as_new_from_existing(self):
    770                  self._PRW_org.SetText(value = '', data = None)
    771                  self._PRW_category.SetText(value = self.data['l10n_category'], data = self.data['pk_category_org'])
    772
    773                  self._PRW_org.SetFocus()
    774          #----------------------------------------------------------------
    775 -        def _refresh_from_existing(self):
    776                  self._PRW_org.SetText(value = self.data['organization'], data = self.data['pk_org'])
    777                  self._PRW_category.SetText(value = self.data['l10n_category'], data = self.data['pk_category_org'])
    778
    779                  self._PRW_category.SetFocus()
    780
    781  #============================================================
    782 -class cOrgCategoryPhraseWheel(gmPhraseWheel.cPhraseWheel):
    783
    784 -        def __init__(self, *args, **kwargs):
    785                  query = """
    786          SELECT DISTINCT ON (data)
    787                  *
    788          FROM (
    789                  SELECT
    790                          pk
    791                                  AS data,
    792                          _(description) || ' (' || description || ')'
    793                                  AS list_label,
    794                          _(description)
    795                                  AS field_label
    796                  FROM
    797                          dem.org_category
    798                  WHERE
    799                          _(description) %(fragment_condition)s
    800                                  OR
    801                          description %(fragment_condition)s
    802                  ORDER BY list_label
    803                  ) AS ordered_matches
    804          LIMIT 50
    805                  """
    806                  mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
    807                  mp.setThresholds(1, 3, 5)
    808                  gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
    809                  self.SetToolTip(_("Select an organizational category."))
    810                  self.matcher = mp
    811                  self.selection_only = True
    812
    813  #============================================================
    814 -class cOrganizationsManagerPnl(gmListWidgets.cGenericListManagerPnl):
    815          """A list for managing organizations."""
    816
    817 -        def __init__(self, *args, **kwargs):
    818
    819                  gmListWidgets.cGenericListManagerPnl.__init__(self, *args, **kwargs)
    820
    821                  self.refresh_callback = self.refresh
    822                  self.new_callback = self._add
    823                  self.edit_callback = self._edit
    824                  self.delete_callback = self._del
    825
    826                  self.__init_ui()
    827                  self.refresh()
    828          #--------------------------------------------------------
    829          # external API
    830          #--------------------------------------------------------
    831 -        def refresh(self, lctrl=None):
    832                  orgs = gmOrganization.get_orgs(order_by = 'organization, l10n_category')
    833                  items = [ [o['organization'], o['l10n_category'], o['pk_org']] for o in orgs ]
    834                  self._LCTRL_items.set_string_items(items)
    835                  self._LCTRL_items.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
    836                  self._LCTRL_items.set_data(orgs)
    837
    838                  for idx in range(len(orgs)):
    839                          org = orgs[idx]
    840                          if org['is_praxis']:
    841                                  self._LCTRL_items.SetItemTextColour(idx, wx.Colour('RED'))
    842                                  break
    843          #--------------------------------------------------------
    844          # event handlers
    845          #--------------------------------------------------------
    846 -        def _add(self):
    847                  return edit_org(parent = self, org = None, single_entry = False)
    848          #--------------------------------------------------------
    849 -        def _edit(self, item):
    850                  return edit_org(parent = self, org = item, single_entry = True)
    851          #--------------------------------------------------------
    852 -        def _del(self, item):
    853                  return gmOrganization.delete_org(organization = item['pk_org'])
    854          #--------------------------------------------------------
    855 -        def _on_list_item_focused(self, event):
    856                  pass
    857          #--------------------------------------------------------
    858          # internal helpers
    859          #--------------------------------------------------------
    860 -        def __init_ui(self):
    861                  self._LCTRL_items.set_columns(columns = [_('Organization'), _('Category'), '#'])
    862                  self._LCTRL_items.SetToolTip(_('Organizations registered in GNUmed.'))
    863                  self._LCTRL_items.item_tooltip_callback = self.get_tooltip
    864                  #self._LCTRL_items.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
    865          #--------------------------------------------------------
    866 -        def get_tooltip(self, org):
    867                  if org is None:
    868                          return _('Organizations registered in GNUmed.')
    869                  return org.format()
    870  #============================================================
    871  from Gnumed.wxGladeWidgets import wxgOrganizationManagerDlg
    872
    873 -class cOrganizationManagerDlg(wxgOrganizationManagerDlg.wxgOrganizationManagerDlg):
    874
    875 -        def __init__(self, *args, **kwargs):
    876
    877                  wxgOrganizationManagerDlg.wxgOrganizationManagerDlg.__init__(self, *args, **kwargs)
    878
    879                  self.Centre(direction = wx.BOTH)
    880
    881                  self._PNL_address.type_is_editable = False
    882                  self._PNL_orgs.select_callback = self._on_org_selected
    883                  self._PNL_units.select_callback = self._on_unit_selected
    884                  self._PNL_comms.message = _('Communication channels')
    885                  self._PNL_ids.message = _('External IDs')
    886
    887                  # FIXME: find proper button
    888                  #self._PNL_units.MoveAfterInTabOrder(self._PNL_orgs._BTN_)
    889
    890                  self._on_org_selected(None)
    891                  self._PNL_orgs._LCTRL_items.SetFocus()
    892          #--------------------------------------------------------
    893          # event handlers
    894          #--------------------------------------------------------
    895 -        def _on_org_selected(self, item):
    896                  self._PNL_units.org = item
    897                  self._on_unit_selected(None)
    898          #--------------------------------------------------------
    899 -        def _on_unit_selected(self, item):
    900                  self._PNL_address.unit = item
    901                  self._PNL_comms.channel_owner = item
    902                  self._PNL_ids.org_unit = item
    903                  if item is None:
    904                          self._PNL_comms._BTN_add.Enable(False)
    905                          self._PNL_ids.Enable(False)
    906                  else:
    907                          self._PNL_comms._BTN_add.Enable(True)
    908                          self._PNL_ids.Enable(True)
    909
    910  #============================================================
    911  # main
    912  #------------------------------------------------------------
    913  if __name__ == "__main__":
    914
    915          if len(sys.argv) < 2:
    916                  sys.exit()
    917
    918          if sys.argv[1] != 'test':
    919                  sys.exit()
    920
    921          from Gnumed.pycommon import gmPG2
    922
    923          #--------------------------------------------------------
    924 -        def test_org_prw():
    925                  app = wx.PyWidgetTester(size = (200, 50))
    926                  pw = cOrganizationPhraseWheel(app.frame, -1)
    927                  app.frame.Show(True)
    928                  app.MainLoop()
    929          #--------------------------------------------------------
    930 -        def test_org_unit_prw():
    931                  app = wx.PyWidgetTester(size = (200, 50))
    932                  pw = cOrgUnitPhraseWheel(app.frame, -1)
    933                  app.frame.Show(True)
    934                  app.MainLoop()
    935          #--------------------------------------------------------
    936 -        def test():
    937                  conn = gmPG2.get_connection()
    938                  app = wx.PyWidgetTester(size = (600, 600))
    939                  dlg = cOrganizationManagerDlg(app.frame, -1, size = (600, 600))
    940                  dlg.SetSize((600, 600))
    941                  dlg.ShowModal()
    942          #       app.SetWidget(dlg, -1)
    943                  app.MainLoop()
    944          #--------------------------------------------------------
    945          #test_org_unit_prw()
    946          #test_org_prw()
    947          test()
    948
    949  #======================================================================
    950