File: gmOrganizationWidgets.py

package info (click to toggle)
gnumed-client 1.4.12%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 164,192 kB
  • ctags: 168,531
  • sloc: python: 88,281; sh: 765; makefile: 37
file content (838 lines) | stat: -rw-r--r-- 27,095 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
"""GNUmed organization handling widgets.

copyright: authors
"""
#============================================================
__author__ = "K.Hilbert"
__license__ = "GPL v2 or later (details at http://www.gnu.org)"

import logging, sys


import wx


if __name__ == '__main__':
	sys.path.insert(0, '../../')
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmMatchProvider
from Gnumed.pycommon import gmDispatcher

from Gnumed.business import gmOrganization

from Gnumed.wxpython import gmListWidgets
from Gnumed.wxpython import gmEditArea
from Gnumed.wxpython import gmPhraseWheel
from Gnumed.wxpython import gmPersonContactWidgets
from Gnumed.wxpython import gmAddressWidgets
from Gnumed.wxpython import gmGuiHelpers


_log = logging.getLogger('gm.organization')

#============================================================
# organizational units API
#------------------------------------------------------------
def edit_org_unit(parent=None, org_unit=None, single_entry=False, org=None):
	ea = cOrgUnitEAPnl(parent = parent, id = -1)
	ea.data = org_unit
	ea.mode = gmTools.coalesce(org_unit, 'new', 'edit')
	dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = single_entry)
	if org is not None:
		ea.organization = org
	dlg.SetTitle(gmTools.coalesce(org_unit, _('Adding new organizational unit'), _('Editing organizational unit')))
	if dlg.ShowModal() == wx.ID_OK:
		dlg.Destroy()
		return True
	dlg.Destroy()
	return False

#============================================================
def select_org_unit(parent=None, msg=None, no_parent=False):

	if no_parent:
		parent = None
	else:
		if parent is None:
			parent = wx.GetApp().GetTopWindow()

	#--------------------
	def new():
		manage_orgs(parent = parent, no_parent = no_parent)
		return True
	#--------------------
	def refresh(lctrl):
		units = gmOrganization.get_org_units(order_by = 'organization, unit, l10n_unit_category')
		items = [ [
			u['organization'],
			u['unit'],
			gmTools.coalesce(u['l10n_unit_category'], u''),
			u['pk_org_unit']
		] for u in units ]

		lctrl.set_string_items(items = items)
		lctrl.set_data(data = units)
	#--------------------
	if msg is None:
		msg = _("Organizations and units thereof.\n")

	return gmListWidgets.get_choices_from_list (
		parent = parent,
		msg = msg,
		caption = _('Unit selection ...'),
		columns = [_('Organization'), _('Unit'), _('Unit type'), '#'],
		can_return_empty = False,
		single_selection = True,
		refresh_callback = refresh,
		new_callback = new
	)

#============================================================
class cOrgUnitPhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"""
	SELECT DISTINCT ON (data) * FROM (
		SELECT * FROM ((

			SELECT
				pk_org_unit
					AS data,
				unit || coalesce(' (' || l10n_unit_category || ')', '') || ': ' || organization || ' (' || l10n_organization_category || ')'
					AS list_label,
				unit || ' (' || organization || ')'
					AS field_label
			FROM
				dem.v_org_units
			WHERE
				unit %(fragment_condition)s

		) UNION ALL (

			SELECT
				pk_org_unit
					AS data,
				coalesce(l10n_unit_category || ' ', '') || '"' || unit || '": ' || organization || ' (' || l10n_organization_category || ')'
					AS list_label,
				unit || ' (' || organization || ')'
					AS field_label
			FROM
				dem.v_org_units
			WHERE
				l10n_unit_category %(fragment_condition)s
					OR
				unit_category %(fragment_condition)s

		) UNION ALL (

			SELECT
				pk_org_unit
					AS data,
				organization || ': ' || unit || coalesce(' (' || l10n_unit_category || ')', '')
					AS list_label,
				unit || ' (' || organization || ')'
					AS field_label
			FROM
				dem.v_org_units
			WHERE
				organization %(fragment_condition)s

		)) AS all_matches
		ORDER BY list_label
	) AS ordered_matches
	LIMIT 50
		"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 3, 5)
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.SetToolTipString(_("Select an organizational unit."))
		self.matcher = mp
	#--------------------------------------------------------
	def _get_data_tooltip(self):
		if self.GetData() is None:
			return None
		unit = self._data2instance()
		if unit is None:
			return None
		return u'\n'.join(unit.format(with_address = True))
	#--------------------------------------------------------
	def _data2instance(self):
		if self.GetData() is None:
			return None
		return gmOrganization.cOrgUnit(aPK_obj = self.GetData())
#============================================================
class cOrgUnitsManagerPnl(gmListWidgets.cGenericListManagerPnl):
	"""A list for managing organizational units."""

	def __init__(self, *args, **kwargs):

		try:
			self.__org = kwargs['org']
			del kwargs['org']
		except KeyError:
			self.__org = None

		gmListWidgets.cGenericListManagerPnl.__init__(self, *args, **kwargs)

		self.refresh_callback = self.refresh
		self.new_callback = self._add
		self.edit_callback = self._edit
		self.delete_callback = self._del

		self.__show_none_if_no_org = True
		self.__init_ui()
		self.__refresh()
	#--------------------------------------------------------
	# external API
	#--------------------------------------------------------
	def refresh(self, lctrl=None):
		self.__refresh()
	#--------------------------------------------------------
	# event handlers
	#--------------------------------------------------------
	def _add(self):
		return edit_org_unit(parent = self, org_unit = None, single_entry = False, org = self.__org)
	#--------------------------------------------------------
	def _edit(self, item):
		return edit_org_unit(parent = self, org_unit = item, single_entry = True)
	#--------------------------------------------------------
	def _del(self, item):
		return gmOrganization.delete_org_unit(unit = item['pk_org_unit'])
	#--------------------------------------------------------
	def _on_list_item_focused(self, event):
		pass
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __init_ui(self):
		self._LCTRL_items.set_columns(columns = [ _('Organizational Unit'), _('Unit Category'), u'#' ])
		self._LCTRL_items.SetToolTipString(_('Units (sites, parts, departments, branches, ...) of organizations registered in GNUmed.'))
		self._LCTRL_items.item_tooltip_callback = self.get_tooltip
		#self._LCTRL_items.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
	#--------------------------------------------------------
	def get_tooltip(self, unit):
		if unit is None:
			return _('Units (sites, parts, departments, branches, ...) of organizations registered in GNUmed.')
		return u'\n'.join(unit.format(with_address = True, with_org = True, with_comms = True))
	#--------------------------------------------------------
	def __refresh(self):

		msg_template = _('Units of: %s')

		if self.__org is None:
			self._BTN_add.Enable(False)
			self._BTN_edit.Enable(False)
			self._BTN_remove.Enable(False)
			pk = None
			self.message = msg_template % _('<no organization selected>')
			if self.__show_none_if_no_org:
				self._LCTRL_items.set_string_items(items = None)
				return
		else:
			self._BTN_add.Enable(True)
			pk = self.__org['pk_org']
			org_str = u'%s (%s)' % (
				self.__org['organization'],
				self.__org['l10n_category']
			)
			self.message = msg_template % org_str

		units = gmOrganization.get_org_units(order_by = 'unit, l10n_unit_category', org = pk)
		items = [ [
			u['unit'],
			gmTools.coalesce(u['l10n_unit_category'], u''),
			u['pk_org_unit']
		] for u in units ]

		self._LCTRL_items.set_string_items(items)
		self._LCTRL_items.set_data(units)

		for idx in range(len(units)):
			unit = units[idx]
			if unit['is_praxis_branch']:
				self._LCTRL_items.SetItemTextColour(idx, col=wx.NamedColour('RED'))
	#--------------------------------------------------------
	# properties
	#--------------------------------------------------------
	def _get_org(self):
		return self.__org

	def _set_org(self, org):
		self.__org = org
		self.__refresh()

	org = property(_get_org, _set_org)
	#--------------------------------------------------------
	def _get_show_none_if_no_org(self):
		return self.__show_none_if_no_org

	def _set_show_none_if_no_org(self, show_none_if_no_org):
		if show_none_if_no_org == self.__show_none_if_no_org:
			return
		if show_none_if_no_org:
			self.__show_none_if_no_org = True
		else:
			self.__show_none_if_no_org = False
		self.__refresh()

	show_none_if_no_org = property(_get_show_none_if_no_org, _set_show_none_if_no_org)

#============================================================
# org unit edit area
from Gnumed.wxGladeWidgets import wxgOrgUnitEAPnl

class cOrgUnitEAPnl(wxgOrgUnitEAPnl.wxgOrgUnitEAPnl, gmEditArea.cGenericEditAreaMixin):

	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['unit']
			del kwargs['unit']
		except KeyError:
			data = None

		wxgOrgUnitEAPnl.wxgOrgUnitEAPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

#		self.__init_ui()
	#----------------------------------------------------------------
#	def __init_ui(self):
#		pass
	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):
		validity = True

		if self._PRW_category.GetData() is not None:
			self._PRW_category.display_as_valid(True)
		else:
			if self._PRW_category.GetValue().strip() == u'':
				self._PRW_category.display_as_valid(True)
			else:
				validity = False
				self._PRW_category.display_as_valid(False)
				self._PRW_category.SetFocus()

		if self._PRW_unit.GetData() is not None:
			self._PRW_unit.display_as_valid(True)
		else:
			if self._PRW_unit.GetValue().strip() != u'':
				self._PRW_unit.display_as_valid(True)
			else:
				validity = False
				self._PRW_unit.display_as_valid(False)
				self._PRW_unit.SetFocus()

		if self._PRW_org.GetData() is None:
			validity = False
			self._PRW_org.display_as_valid(False)
			self._PRW_org.SetFocus()
		else:
			self._PRW_org.display_as_valid(True)

		return validity
	#----------------------------------------------------------------
	def _save_as_new(self):
		data = gmOrganization.create_org_unit (
			pk_organization = self._PRW_org.GetData(),
			unit = self._PRW_unit.GetValue().strip()
		)
		data['pk_category_unit'] = self._PRW_category.GetData()
		data.save()

		self.data = data
		return True
	#----------------------------------------------------------------
	def _save_as_update(self):
		self.data['pk_org'] = self._PRW_org.GetData()
		self.data['unit'] = self._PRW_unit.GetValue().strip()
		self.data['pk_category_unit'] = self._PRW_category.GetData()
		self.data.save()
		return True
	#----------------------------------------------------------------
	def _refresh_as_new(self):
		self._PRW_org.SetText(value = u'', data = None)
		self._PRW_unit.SetText(value = u'', data = None)
		self._PRW_category.SetText(value = u'', data = None)

		self._PRW_unit.SetFocus()
	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._PRW_org.SetText(value = self.data['organization'], data = self.data['pk_org'])
		self._PRW_unit.SetText(value = u'', data = None)
		self._PRW_category.SetText(value = self.data['unit_category'], data = self.data['pk_category_unit'])

		self._PRW_unit.SetFocus()
	#----------------------------------------------------------------
	def _refresh_from_existing(self):
		self._PRW_org.SetText(value = self.data['organization'], data = self.data['pk_org'])
		self._PRW_unit.SetText(value = self.data['unit'], data = self.data['pk_org_unit'])
		self._PRW_category.SetText(value = self.data['unit_category'], data = self.data['pk_category_unit'])

		self._PRW_unit.SetFocus()
	#----------------------------------------------------------------
	def _set_org(self, org):
		self._PRW_org.SetText(value = org['organization'], data = org['pk_org'])

	organization = property(lambda x:x, _set_org)
#============================================================
from Gnumed.wxGladeWidgets import wxgOrgUnitAddressPnl

class cOrgUnitAddressPnl(wxgOrgUnitAddressPnl.wxgOrgUnitAddressPnl):

	def __init__(self, *args, **kwargs):

		wxgOrgUnitAddressPnl.wxgOrgUnitAddressPnl.__init__(self, *args, **kwargs)

		self.__unit = None
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __refresh(self):
		if self.__unit is None:
			self.message = _('<no unit selected>')
			self._PRW_address_searcher.SetText(u'', None)
			self._PRW_address_searcher.Enable(False)
			self._PRW_address_searcher.display_as_disabled(True)
			self._BTN_save_picked_address.Enable(False)
			self._BTN_add_new_address.Enable(False)
		else:
			if self.__unit['l10n_unit_category'] is None:
				cat = u''
				left_delim = u''
				right_delim = u''
			else:
				cat = u'%s ' % self.__unit['l10n_unit_category']
				left_delim = gmTools.u_left_double_angle_quote
				right_delim = gmTools.u_right_double_angle_quote
			self.message = u'%s%s%s%s' % (
				cat,
				left_delim,
				self.__unit['unit'],
				right_delim
			)
			self._PRW_address_searcher.Enable(True)
			self._PRW_address_searcher.address = self.__unit['pk_address']
			self._PRW_address_searcher.Enable(True)
			self._PRW_address_searcher.display_as_disabled(False)
			self._BTN_save_picked_address.Enable(True)
			self._BTN_add_new_address.Enable(True)
	#--------------------------------------------------------
	# event handlers
	#--------------------------------------------------------
	def _on_save_picked_address_button_pressed(self, event):
		if self._PRW_address_searcher.GetData() is None:
			if self._PRW_address_searcher.GetValue().strip() != u'':
				gmDispatcher.send(signal = 'statustext', msg = _('Invalid address selection.'))
				self._PRW_address_searcher.display_as_valid(False)
				self._PRW_address_searcher.SetFocus()
				return

		self._PRW_address_searcher.display_as_valid(True)

		self.__unit['pk_address'] = self._PRW_address_searcher.GetData()
		self.__unit.save()
		self.__refresh()
	#--------------------------------------------------------
	def _on_add_new_address_button_pressed(self, event):
		ea = gmAddressWidgets.cAddressEAPnl(self, -1)
		ea.address_holder = self.__unit
		ea.type_is_editable = False
		dlg = gmEditArea.cGenericEditAreaDlg2(self, -1, edit_area = ea)
		dlg.SetTitle(_('Adding new address'))
		if dlg.ShowModal() != wx.ID_OK:
			return False
		self.__refresh()
		return True
	#--------------------------------------------------------
	def _on_manage_addresses_button_pressed(self, event):
		picked_address = gmAddressWidgets.manage_addresses(parent = self)
		if picked_address is None:
			return

		question = u'%s\n\n  %s\n' % (
			_('Link the following address to the organizational unit ?'),
			u'\n  '.join(picked_address.format())
		)

		link_it = gmGuiHelpers.gm_show_question (
			title = _('Linking selected address'),
			question = question
		)
		if not link_it:
			return

		self._PRW_address_searcher.address = picked_address['pk_address']
		self._PRW_address_searcher.display_as_valid(True)
		self.__unit['pk_address'] = self._PRW_address_searcher.GetData()
		self.__unit.save()
	#--------------------------------------------------------
	# properties
	#--------------------------------------------------------
	def _get_unit(self):
		return self.__unit

	def _set_unit(self, unit):
		self.__unit = unit
		self.__refresh()

	unit = property(_get_unit, _set_unit)
	#--------------------------------------------------------
	def _get_message(self):
		return self._LBL_message.GetLabel()

	def _set_message(self, msg):
		if msg is None:
			self._LBL_message.Hide()
			self._LBL_message.SetLabel(u'')
		else:
			self._LBL_message.SetLabel(msg)
			self._LBL_message.Show()
		self.Layout()

	message = property(_get_message, _set_message)
#============================================================
# organizations API
#------------------------------------------------------------
def manage_orgs(parent=None, no_parent=False):

	if no_parent:
		parent = None
	else:
		if parent is None:
			parent = wx.GetApp().GetTopWindow()

	dlg = cOrganizationManagerDlg(parent, -1)
	dlg.ShowModal()
	dlg.Destroy()
#============================================================
def edit_org(parent=None, org=None, single_entry=False):
	ea = cOrganizationEAPnl(parent = parent, id = -1)
	ea.data = org
	ea.mode = gmTools.coalesce(org, 'new', 'edit')
	dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = single_entry)
	dlg.SetTitle(gmTools.coalesce(org, _('Adding new organization'), _('Editing organization')))
	if dlg.ShowModal() == wx.ID_OK:
		dlg.Destroy()
		return True
	dlg.Destroy()
	return False
#============================================================
class cOrganizationPhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"""
	SELECT DISTINCT ON (data) * FROM (
		SELECT * FROM ((

			SELECT
				pk_org
					AS data,
				organization || ' (' || l10n_category || ')'
					AS list_label,
				organization || ' (' || l10n_category || ')'
					AS field_label
			FROM
				dem.v_orgs
			WHERE
				organization %(fragment_condition)s

		) UNION ALL (

			SELECT
				pk_org
					AS data,
				l10n_category || ': ' || organization
					AS list_label,
				organization || ' (' || l10n_category || ')'
					AS field_label
			FROM
				dem.v_orgs
			WHERE
				l10n_category %(fragment_condition)s
					OR
				category %(fragment_condition)s

		)) AS all_matches
		ORDER BY list_label
	) AS ordered_matches
	LIMIT 50
		"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 3, 5)
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.SetToolTipString(_("Select an organization."))
		self.matcher = mp
		self.selection_only = True

#====================================================================
from Gnumed.wxGladeWidgets import wxgOrganizationEAPnl

class cOrganizationEAPnl(wxgOrganizationEAPnl.wxgOrganizationEAPnl, gmEditArea.cGenericEditAreaMixin):

	def __init__(self, *args, **kwargs):

		try:
			data = kwargs['organization']
			del kwargs['organization']
		except KeyError:
			data = None

		wxgOrganizationEAPnl.wxgOrganizationEAPnl.__init__(self, *args, **kwargs)
		gmEditArea.cGenericEditAreaMixin.__init__(self)

		self.mode = 'new'
		self.data = data
		if data is not None:
			self.mode = 'edit'

		#self.__init_ui()
	#----------------------------------------------------------------
	def __init_ui(self):
		self._PRW_org.selection_only = False
	#----------------------------------------------------------------
	# generic Edit Area mixin API
	#----------------------------------------------------------------
	def _valid_for_save(self):
		validity = True

		if self._PRW_category.GetData() is None:
			validity = False
			self._PRW_category.display_as_valid(False)
			self._PRW_category.SetFocus()
		else:
			self._PRW_category.display_as_valid(True)

		if self._PRW_org.GetValue().strip() == u'':
			validity = False
			self._PRW_org.display_as_valid(False)
			self._PRW_org.SetFocus()
		else:
			self._PRW_org.display_as_valid(True)

#		if self.mode == 'edit':
#			if self._PRW_org.GetData() is None:
#				validity = False
#				self._PRW_org.display_as_valid(False)
#				self._PRW_org.SetFocus()
#			else:
#				self._PRW_org.display_as_valid(True)
#		else:
#			if self._PRW_org.GetValue().strip() == u'':
#				validity = False
#				self._PRW_org.display_as_valid(False)
#				self._PRW_org.SetFocus()
#			else:
#				if self._PRW_org.GetData() is not None:
#					validity = False
#					self._PRW_org.display_as_valid(False)
#					self._PRW_org.SetFocus()
#				else:
#					self._PRW_org.display_as_valid(True)

		return validity
	#----------------------------------------------------------------
	def _save_as_new(self):
		self.data = gmOrganization.create_org (
			organization = self._PRW_org.GetValue().strip(),
			category = self._PRW_category.GetData()
		)
		return True
	#----------------------------------------------------------------
	def _save_as_update(self):
		#self.data['pk_org'] = self._PRW_org.GetData()
		self.data['organization'] = self._PRW_org.GetValue().strip()
		self.data['pk_category_org'] = self._PRW_category.GetData()
		self.data.save()
		return True
	#----------------------------------------------------------------
	def _refresh_as_new(self):
		self._PRW_org.SetText(value = u'', data = None)
		self._PRW_category.SetText(value = u'', data = None)

		self._PRW_org.SetFocus()
	#----------------------------------------------------------------
	def _refresh_as_new_from_existing(self):
		self._PRW_org.SetText(value = u'', data = None)
		self._PRW_category.SetText(value = self.data['l10n_category'], data = self.data['pk_category_org'])

		self._PRW_org.SetFocus()
	#----------------------------------------------------------------
	def _refresh_from_existing(self):
		self._PRW_org.SetText(value = self.data['organization'], data = self.data['pk_org'])
		self._PRW_category.SetText(value = self.data['l10n_category'], data = self.data['pk_category_org'])

		self._PRW_category.SetFocus()

#============================================================
class cOrgCategoryPhraseWheel(gmPhraseWheel.cPhraseWheel):

	def __init__(self, *args, **kwargs):
		query = u"""
	SELECT DISTINCT ON (data)
		*
	FROM (
		SELECT
			pk
				AS data,
			_(description) || ' (' || description || ')'
				AS list_label,
			_(description)
				AS field_label
		FROM
			dem.org_category
		WHERE
			_(description) %(fragment_condition)s
				OR
			description %(fragment_condition)s
		ORDER BY list_label
		) AS ordered_matches
	LIMIT 50
		"""
		mp = gmMatchProvider.cMatchProvider_SQL2(queries=query)
		mp.setThresholds(1, 3, 5)
		gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
		self.SetToolTipString(_("Select an organizational category."))
		self.matcher = mp
		self.selection_only = True

#============================================================
class cOrganizationsManagerPnl(gmListWidgets.cGenericListManagerPnl):
	"""A list for managing organizations."""

	def __init__(self, *args, **kwargs):

		gmListWidgets.cGenericListManagerPnl.__init__(self, *args, **kwargs)

		self.refresh_callback = self.refresh
		self.new_callback = self._add
		self.edit_callback = self._edit
		self.delete_callback = self._del

		self.__init_ui()
		self.refresh()
	#--------------------------------------------------------
	# external API
	#--------------------------------------------------------
	def refresh(self, lctrl=None):
		orgs = gmOrganization.get_orgs(order_by = 'organization, l10n_category')
		items = [ [o['organization'], o['l10n_category'], o['pk_org']] for o in orgs ]
		self._LCTRL_items.set_string_items(items)
		self._LCTRL_items.set_data(orgs)

		for idx in range(len(orgs)):
			org = orgs[idx]
			if org['is_praxis']:
				self._LCTRL_items.SetItemTextColour(idx, col=wx.NamedColour('RED'))
				break
	#--------------------------------------------------------
	# event handlers
	#--------------------------------------------------------
	def _add(self):
		return edit_org(parent = self, org = None, single_entry = False)
	#--------------------------------------------------------
	def _edit(self, item):
		return edit_org(parent = self, org = item, single_entry = True)
	#--------------------------------------------------------
	def _del(self, item):
		return gmOrganization.delete_org(organization = item['pk_org'])
	#--------------------------------------------------------
	def _on_list_item_focused(self, event):
		pass
	#--------------------------------------------------------
	# internal helpers
	#--------------------------------------------------------
	def __init_ui(self):
		self._LCTRL_items.set_columns(columns = [_('Organization'), _('Category'), u'#'])
		self._LCTRL_items.SetToolTipString(_('Organizations registered in GNUmed.'))
		self._LCTRL_items.item_tooltip_callback = self.get_tooltip
		#self._LCTRL_items.set_column_widths(widths = [wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE, wx.LIST_AUTOSIZE])
	#--------------------------------------------------------
	def get_tooltip(self, org):
		if org is None:
			return _('Organizations registered in GNUmed.')
		return org.format()
#============================================================
from Gnumed.wxGladeWidgets import wxgOrganizationManagerDlg

class cOrganizationManagerDlg(wxgOrganizationManagerDlg.wxgOrganizationManagerDlg):

	def __init__(self, *args, **kwargs):

		wxgOrganizationManagerDlg.wxgOrganizationManagerDlg.__init__(self, *args, **kwargs)

		self.Centre(direction = wx.BOTH)

		self._PNL_address.type_is_editable = False
		self._PNL_orgs.select_callback = self._on_org_selected
		self._PNL_units.select_callback = self._on_unit_selected
		self._PNL_comms.message = _('Communication channels')

		# FIXME: find proper button
		#self._PNL_units.MoveAfterInTabOrder(self._PNL_orgs._BTN_)

		self._on_org_selected(None)
		self._PNL_orgs._LCTRL_items.SetFocus()
	#--------------------------------------------------------
	# event handlers
	#--------------------------------------------------------
	def _on_org_selected(self, item):
		self._PNL_units.org = item
		self._on_unit_selected(None)
	#--------------------------------------------------------
	def _on_unit_selected(self, item):
		self._PNL_address.unit = item
		self._PNL_comms.channel_owner = item
		if item is None:
			self._PNL_comms._BTN_add.Enable(False)
		else:
			self._PNL_comms._BTN_add.Enable(True)
#============================================================
# main
#------------------------------------------------------------
if __name__ == "__main__":

	if len(sys.argv) < 2:
		sys.exit()

	if sys.argv[1] != u'test':
		sys.exit()

	from Gnumed.pycommon import gmPG2
	from Gnumed.pycommon import gmI18N
	gmI18N.activate_locale()
	gmI18N.install_domain()

	#--------------------------------------------------------
	def test_org_prw():
		app = wx.PyWidgetTester(size = (200, 50))
		pw = cOrganizationPhraseWheel(app.frame, -1)
		app.frame.Show(True)
		app.MainLoop()
	#--------------------------------------------------------
	def test_org_unit_prw():
		app = wx.PyWidgetTester(size = (200, 50))
		pw = cOrgUnitPhraseWheel(app.frame, -1)
		app.frame.Show(True)
		app.MainLoop()
	#--------------------------------------------------------
	def test():
		conn = gmPG2.get_connection()
		app = wx.PyWidgetTester(size = (600, 600))
		dlg = cOrganizationManagerDlg(app.frame, -1, size = (600, 600))
		dlg.SetSize((600, 600))
		dlg.ShowModal()
	#	app.SetWidget(dlg, -1)
		app.MainLoop()
	#--------------------------------------------------------
	#test_org_unit_prw()
	#test_org_prw()
	test()

#======================================================================