| Home | Trees | Indices | Help |
|
|---|
|
|
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 #============================================================
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
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 #--------------------------------------------------------
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 #--------------------------------------------------------
89 return lock_praxis_branch(pk_praxis_branch = self._payload[self._idx['pk_praxis_branch']], exclusive = exclusive)
90 #--------------------------------------------------------
92 return unlock_praxis_branch(pk_praxis_branch = self._payload[self._idx['pk_praxis_branch']], exclusive = exclusive)
93 #--------------------------------------------------------
96 #--------------------------------------------------------
97 # properties
98 #--------------------------------------------------------
101
102 org_unit = property(_get_org_unit, lambda x:x)
103 #--------------------------------------------------------
106
107 organization = property(_get_org, lambda x:x)
108
109 #--------------------------------------------------------
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 #------------------------------------------------------------
122 return gmPG2.lock_row(table = u'dem.praxis_branch', pk = pk_praxis_branch, exclusive = exclusive)
123
124 #------------------------------------------------------------
126 return gmPG2.unlock_row(table = u'dem.praxis_branch', pk = pk_praxis_branch, exclusive = exclusive)
127
128 #------------------------------------------------------------
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 #------------------------------------------------------------
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 #------------------------------------------------------------
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 #------------------------------------------------------------
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 #------------------------------------------------------------
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 #------------------------------------------------------------
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 #============================================================
236
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 #--------------------------------------------------------
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 #--------------------------------------------------------
276 """Return any attribute if known how to retrieve it by proxy."""
277 return self.branch[attribute]
278 #--------------------------------------------------------
280 self.branch[attribute] = value
281 #--------------------------------------------------------
282 # waiting list handling
283 #--------------------------------------------------------
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 #--------------------------------------------------------
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 #--------------------------------------------------------
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 #--------------------------------------------------------
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 #--------------------------------------------------------
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 #--------------------------------------------------------
340
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 #--------------------------------------------------------
370
381
382 db_logon_banner = property(_get_db_logon_banner, _set_db_logon_banner)
383 #--------------------------------------------------------
387
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 #--------------------------------------------------------
417
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 #--------------------------------------------------------
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
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
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
| Home | Trees | Indices | Help |
|
|---|
| Generated by Epydoc 3.0.1 on Sat Oct 5 03:57:01 2013 | http://epydoc.sourceforge.net |