1 """GnuMed allergy related business object.
2 """
3
4
5
6 __version__ = "$Revision: 1.34 $"
7 __author__ = "Carlos Moro <cfmoro1976@yahoo.es>"
8 __license__ = "GPL"
9
10 import types, sys, logging, datetime as pyDT
11
12
13 if __name__ == '__main__':
14 sys.path.insert(0, '../../')
15 from Gnumed.pycommon import gmPG2, gmI18N, gmBusinessDBObject, gmDateTime
16
17
18 _log = logging.getLogger('gm.domain')
19 _log.info(__version__)
20
21
22
23 allergy_states = [
24 None,
25 0,
26 1
27 ]
28
30
31 args = {'enc': encounter}
32
33 cmd_create = u"""
34 insert into clin.allergy_state (fk_encounter, has_allergy)
35
36 select %(enc)s, NULL
37 where not exists (
38 select 1 from clin.v_pat_allergy_state
39 where pk_patient = (
40 select fk_patient from clin.encounter where pk = %(enc)s
41 )
42 )"""
43
44 cmd_search = u"""
45 select pk_allergy_state from clin.v_pat_allergy_state
46 where pk_patient = (
47 select fk_patient from clin.encounter where pk = %(enc)s
48 )"""
49
50 rows, idx = gmPG2.run_rw_queries (
51 queries = [
52 {'cmd': cmd_create, 'args': args},
53 {'cmd': cmd_search, 'args': args}
54 ],
55 return_data = True
56 )
57
58 return cAllergyState(aPK_obj = rows[0][0])
59
61 """Represents the allergy state of one patient."""
62
63 _cmd_fetch_payload = u"select * from clin.v_pat_allergy_state where pk_allergy_state = %s"
64 _cmds_store_payload = [
65 u"""update clin.allergy_state set
66 last_confirmed = %(last_confirmed)s,
67 has_allergy = %(has_allergy)s,
68 comment = %(comment)s
69 where
70 pk = %(pk_allergy_state)s and
71 xmin = %(xmin_allergy_state)s""",
72 u"""select xmin_allergy_state from clin.v_pat_allergy_state where pk_allergy_state = %(pk_allergy_state)s"""
73 ]
74 _updatable_fields = [
75 'last_confirmed',
76 'has_allergy',
77 'comment'
78 ]
79
80
81
83 if self._payload[self._idx['has_allergy']] is None:
84 return _('unknown allergy state')
85 if self._payload[self._idx['has_allergy']] == 0:
86 return _('no known allergies')
87 if self._payload[self._idx['has_allergy']] == 1:
88 return _('*does* have allergies')
89 _log.error('unknown allergy state [%s]', self._payload[self._idx['has_allergy']])
90 return _('ERROR: unknown allergy state [%s]') % self._payload[self._idx['has_allergy']]
91
93 raise AttributeError('invalid to set allergy state string')
94
95 state_string = property(_get_as_string, _set_string)
96
98 if self._payload[self._idx['has_allergy']] is None:
99 if self._payload[self._idx['comment']] is None:
100 return u'?'
101 else:
102 return u'?!'
103 if self._payload[self._idx['has_allergy']] == 0:
104 if self._payload[self._idx['comment']] is None:
105 return u'\u2300'
106 else:
107 return u'\u2300!'
108 if self._payload[self._idx['has_allergy']] == 1:
109 return '!'
110 _log.error('unknown allergy state [%s]', self._payload[self._idx['has_allergy']])
111 return _('ERROR: unknown allergy state [%s]') % self._payload[self._idx['has_allergy']]
112
114 raise AttributeError('invalid to set allergy state symbol')
115
116 state_symbol = property(_get_as_symbol, _set_symbol)
117
133
134 -class cAllergy(gmBusinessDBObject.cBusinessDBObject):
135 """Represents one allergy item.
136
137 Actually, those things are really things to *avoid*.
138 Allergy is just one of several reasons for that.
139 See Adrian's post on gm-dev.
140
141 Another word might be Therapeutic Precautions.
142 """
143 _cmd_fetch_payload = u"select * from clin.v_pat_allergies where pk_allergy=%s"
144 _cmds_store_payload = [
145 u"""update clin.allergy set
146 clin_when=%(date)s,
147 substance=%(substance)s,
148 substance_code=%(substance_code)s,
149 generics=%(generics)s,
150 allergene=%(allergene)s,
151 atc_code=%(atc_code)s,
152 fk_type=%(pk_type)s,
153 generic_specific=%(generic_specific)s::boolean,
154 definite=%(definite)s::boolean,
155 narrative=%(reaction)s
156 where
157 pk=%(pk_allergy)s and
158 xmin=%(xmin_allergy)s""",
159 u"""select xmin_allergy from clin.v_pat_allergies where pk_allergy=%(pk_allergy)s"""
160 ]
161 _updatable_fields = [
162 'date',
163 'substance',
164 'substance_code',
165 'generics',
166 'allergene',
167 'atc_code',
168 'pk_type',
169 'generic_specific',
170 'definite',
171 'reaction'
172 ]
173
182
183
184
185 -def create_allergy(substance=None, allg_type=None, episode_id=None, encounter_id=None):
186 """Creates a new allergy clinical item.
187
188 substance - allergic substance
189 allg_type - allergy or sensitivity, pk or string
190 encounter_id - encounter's primary key
191 episode_id - episode's primary key
192 """
193
194
195
196 cmd = u"""
197 select pk_patient from clin.v_pat_episodes where pk_episode=%s
198 union
199 select fk_patient from clin.encounter where pk=%s"""
200 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [episode_id, encounter_id]}])
201
202 if len(rows) == 0:
203 raise ValueError('error checking episode [%s] <-> encounter [%s] consistency' % (episode_id, encounter_id))
204
205 if len(rows) > 1:
206 raise ValueError('episode [%s] and encounter [%s] belong to different patients !?!' % (episode_id, encounter_id))
207
208 pat_id = rows[0][0]
209
210 cmd = u'select pk_allergy from clin.v_pat_allergies where pk_patient=%(pat)s and substance=%(substance)s'
211 args = {'pat': pat_id, 'substance': substance}
212 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}])
213 if len(rows) > 0:
214
215 return cAllergy(aPK_obj = rows[0][0])
216
217
218 queries = []
219
220 if type(allg_type) == types.IntType:
221 cmd = u"""
222 insert into clin.allergy (fk_type, fk_encounter, fk_episode, substance)
223 values (%s, %s, %s, %s)"""
224 else:
225 cmd = u"""
226 insert into clin.allergy (fk_type, fk_encounter, fk_episode, substance)
227 values ((select pk from clin._enum_allergy_type where value = %s), %s, %s, %s)"""
228 queries.append({'cmd': cmd, 'args': [allg_type, encounter_id, episode_id, substance]})
229
230 cmd = u"select currval('clin.allergy_id_seq')"
231 queries.append({'cmd': cmd})
232
233 rows, idx = gmPG2.run_rw_queries(queries=queries, return_data=True)
234 allergy = cAllergy(aPK_obj = rows[0][0])
235
236 return allergy
237
238
239
240 if __name__ == '__main__':
241
242 allg = cAllergy(aPK_obj=1)
243 print allg
244 fields = allg.get_fields()
245 for field in fields:
246 print field, ':', allg[field]
247 print "updatable:", allg.get_updatable_fields()
248 enc_id = allg['pk_encounter']
249 epi_id = allg['pk_episode']
250 status, allg = create_allergy (
251 substance = 'test substance',
252 allg_type=1,
253 episode_id = epi_id,
254 encounter_id = enc_id
255 )
256 print allg
257 allg['reaction'] = 'hehehe'
258 status, data = allg.save_payload()
259 print 'status:', status
260 print 'data:', data
261 print allg
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