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
|
"""GNUmed patient creation widgets.
copyright: authors
"""
#============================================================
__author__ = "K.Hilbert"
__license__ = "GPL v2 or later (details at http://www.gnu.org)"
import logging
import sys
import datetime as pydt
import wx
if __name__ == '__main__':
sys.path.insert(0, '../../')
from Gnumed.pycommon import gmCfg
from Gnumed.pycommon import gmPG2
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmDateTime
from Gnumed.pycommon import gmDispatcher
from Gnumed.business import gmPraxis
from Gnumed.business import gmPerson
from Gnumed.business import gmStaff
from Gnumed.business import gmDemographicRecord
from Gnumed.wxpython import gmEditArea
from Gnumed.wxpython import gmGuiHelpers
from Gnumed.wxpython.gmDemographicsWidgets import _validate_dob_field, _validate_tob_field, _empty_dob_allowed
_log = logging.getLogger('gm.patient')
#============================================================
def create_new_person(parent=None, activate=False):
dbcfg = gmCfg.cCfgSQL()
def_region = dbcfg.get2 (
option = u'person.create.default_region',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = u'user'
)
def_country = None
if def_region is None:
def_country = dbcfg.get2 (
option = u'person.create.default_country',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = u'user'
)
else:
countries = gmDemographicRecord.get_country_for_region(region = def_region)
if len(countries) == 1:
def_country = countries[0]['code_country']
if parent is None:
parent = wx.GetApp().GetTopWindow()
ea = cNewPatientEAPnl(parent = parent, id = -1, country = def_country, region = def_region)
dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = True)
dlg.SetTitle(_('Adding new person'))
ea._PRW_lastname.SetFocus()
result = dlg.ShowModal()
pat = ea.data
dlg.Destroy()
if result != wx.ID_OK:
return False
_log.debug('created new person [%s]', pat.ID)
if activate:
from Gnumed.wxpython import gmPatSearchWidgets
gmPatSearchWidgets.set_active_patient(patient = pat)
gmDispatcher.send(signal = 'display_widget', name = 'gmNotebookedPatientEditionPlugin')
return True
#============================================================
from Gnumed.wxGladeWidgets import wxgNewPatientEAPnl
class cNewPatientEAPnl(wxgNewPatientEAPnl.wxgNewPatientEAPnl, gmEditArea.cGenericEditAreaMixin):
def __init__(self, *args, **kwargs):
try:
self.default_region = kwargs['region']
del kwargs['region']
except KeyError:
self.default_region = None
try:
self.default_country = kwargs['country']
del kwargs['country']
except KeyError:
self.default_country = None
wxgNewPatientEAPnl.wxgNewPatientEAPnl.__init__(self, *args, **kwargs)
gmEditArea.cGenericEditAreaMixin.__init__(self)
self.mode = 'new'
self.data = None
self._address = None
self.__init_ui()
self.__register_interests()
#----------------------------------------------------------------
# internal helpers
#----------------------------------------------------------------
def __init_ui(self):
self._PRW_lastname.final_regex = '.+'
self._PRW_firstnames.final_regex = '.+'
self._PRW_address_searcher.selection_only = False
# only if we would support None on selection_only's:
# self._PRW_external_id_type.selection_only = True
if self.default_country is not None:
match = self._PRW_country._data2match(data = self.default_country)
if match is not None:
self._PRW_country.SetText(value = match['field_label'], data = match['data'])
if self.default_region is not None:
self._PRW_region.SetText(value = self.default_region)
self._PRW_type.SetText(value = u'home')
# FIXME: only use this if member of gm-doctors,
# FIXME: other than that check fallback_primary_provider
self._PRW_primary_provider.SetData(data = gmStaff.gmCurrentProvider()['pk_staff'])
self._PRW_lastname.SetFocus()
#----------------------------------------------------------------
def _refresh_ext_id_warning(self):
id_type = self._PRW_external_id_type.GetData()
if id_type is None:
self._LBL_id_exists.SetLabel(u'')
return
val = self._TCTRL_external_id_value.GetValue().strip()
if val == u'':
self._LBL_id_exists.SetLabel(u'')
return
if gmPerson.external_id_exists(pk_issuer = id_type, value = val) > 0:
self._LBL_id_exists.SetLabel(_('ID exists !'))
else:
self._LBL_id_exists.SetLabel(u'')
#----------------------------------------------------------------
def _refresh_dupe_warning(self):
lname = self._PRW_lastname.GetValue().strip()
if lname == u'':
self._LBL_person_exists.SetLabel(u'')
return
dob = self._PRW_dob.GetData()
if dob is None:
self._LBL_person_exists.SetLabel(u'')
return
fname = gmTools.none_if(self._PRW_firstnames.GetValue().strip()[:1], u'')
no_of_dupes = gmPerson.person_exists(lastnames = lname, firstnames = fname, dob = dob)
if no_of_dupes == 0:
lbl = u''
elif no_of_dupes == 1:
lbl = _('One "%s, %s (%s)" already exists !') % (
lname,
gmTools.coalesce(fname, u'?', u'%s %%s. %s' % (gmTools.u_ellipsis, gmTools.u_ellipsis)),
gmDateTime.pydt_strftime(dob, '%Y %b %d', 'utf8')
)
else:
lbl = _('%s "%s, %s (%s)" already exist !') % (
no_of_dupes,
lname,
gmTools.coalesce(fname, u'?', u'%s %%s. %s' % (gmTools.u_ellipsis, gmTools.u_ellipsis)),
gmDateTime.pydt_strftime(dob, '%Y %b %d', 'utf8')
)
self._LBL_person_exists.SetLabel(lbl)
#----------------------------------------------------------------
def __perhaps_invalidate_address_searcher(self, ctrl=None, field=None):
adr = self._PRW_address_searcher.address
if adr is None:
return True
if ctrl.GetValue().strip() != adr[field]:
wx.CallAfter(self._PRW_address_searcher.SetText, value = u'', data = None)
return True
return False
#----------------------------------------------------------------
def __set_fields_from_address_searcher(self):
adr = self._PRW_address_searcher.address
if adr is None:
return True
self._PRW_zip.SetText(value = adr['postcode'], data = adr['postcode'])
self._PRW_street.SetText(value = adr['street'], data = adr['street'])
self._PRW_street.set_context(context = u'zip', val = adr['postcode'])
self._PRW_urb.SetText(value = adr['urb'], data = adr['urb'])
self._PRW_urb.set_context(context = u'zip', val = adr['postcode'])
self._PRW_region.SetText(value = adr['l10n_state'], data = adr['code_state'])
self._PRW_region.set_context(context = u'zip', val = adr['postcode'])
self._PRW_country.SetText(value = adr['l10n_country'], data = adr['code_country'])
self._PRW_country.set_context(context = u'zip', val = adr['postcode'])
#----------------------------------------------------------------
def __identity_valid_for_save(self):
error = False
# name fields
if self._PRW_lastname.GetValue().strip() == u'':
error = True
gmDispatcher.send(signal = 'statustext', msg = _('Must enter lastname.'))
self._PRW_lastname.display_as_valid(False)
else:
self._PRW_lastname.display_as_valid(True)
if self._PRW_firstnames.GetValue().strip() == '':
error = True
gmDispatcher.send(signal = 'statustext', msg = _('Must enter first name.'))
self._PRW_firstnames.display_as_valid(False)
else:
self._PRW_firstnames.display_as_valid(True)
# gender
if self._PRW_gender.GetData() is None:
error = True
gmDispatcher.send(signal = 'statustext', msg = _('Must select gender.'))
self._PRW_gender.display_as_valid(False)
else:
self._PRW_gender.display_as_valid(True)
# dob validation
if not _validate_dob_field(self._PRW_dob):
error = True
# TOB validation
if _validate_tob_field(self._TCTRL_tob):
self.display_ctrl_as_valid(ctrl = self._TCTRL_tob, valid = True)
else:
error = True
self.display_ctrl_as_valid(ctrl = self._TCTRL_tob, valid = False)
return (not error)
#----------------------------------------------------------------
def __address_valid_for_save(self, empty_address_is_valid=False):
# existing address ? if so set other fields
if self._PRW_address_searcher.GetData() is not None:
wx.CallAfter(self.__set_fields_from_address_searcher)
return True
# must either all contain something or none of them
fields_to_fill = (
self._TCTRL_number,
self._PRW_zip,
self._PRW_street,
self._PRW_urb,
self._PRW_type
)
no_of_filled_fields = 0
for field in fields_to_fill:
if field.GetValue().strip() != u'':
no_of_filled_fields += 1
field.display_as_valid(True)
# empty address ?
if no_of_filled_fields == 0:
if empty_address_is_valid:
return True
else:
return None
# incompletely filled address ?
if no_of_filled_fields != len(fields_to_fill):
for field in fields_to_fill:
if field.GetValue().strip() == u'':
field.display_as_valid(False)
field.SetFocus()
msg = _('To properly create an address, all the related fields must be filled in.')
gmGuiHelpers.gm_show_error(msg, _('Required fields'))
return False
# fields which must contain a selected item
# FIXME: they must also contain an *acceptable combination* which
# FIXME: can only be tested against the database itself ...
strict_fields = (
self._PRW_type,
self._PRW_region,
self._PRW_country
)
error = False
for field in strict_fields:
if field.GetData() is None:
error = True
field.display_as_valid(False)
field.SetFocus()
else:
field.display_as_valid(True)
if error:
msg = _('This field must contain an item selected from the dropdown list.')
gmGuiHelpers.gm_show_error(msg, _('Required fields'))
return False
return True
#----------------------------------------------------------------
def __register_interests(self):
# identity
self._PRW_lastname.add_callback_on_lose_focus(self._on_leaving_lastname)
self._PRW_firstnames.add_callback_on_lose_focus(self._on_leaving_firstname)
self._PRW_dob.add_callback_on_lose_focus(self._on_leaving_dob)
# address
self._PRW_address_searcher.add_callback_on_lose_focus(self._on_leaving_adress_searcher)
# invalidate address searcher when any field edited
self._PRW_street.add_callback_on_lose_focus(self._invalidate_address_searcher)
wx.EVT_KILL_FOCUS(self._TCTRL_number, self._on_leaving_number)
wx.EVT_KILL_FOCUS(self._TCTRL_unit, self._on_leaving_unit)
self._PRW_urb.add_callback_on_lose_focus(self._invalidate_address_searcher)
self._PRW_region.add_callback_on_lose_focus(self._invalidate_address_searcher)
self._PRW_zip.add_callback_on_lose_focus(self._on_leaving_zip)
self._PRW_country.add_callback_on_lose_focus(self._on_leaving_country)
self._PRW_external_id_type.add_callback_on_lose_focus(callback = self._on_leaving_ext_id_type)
self._TCTRL_external_id_value.add_callback_on_lose_focus(callback = self._on_leaving_ext_id_val)
#----------------------------------------------------------------
# event handlers
#----------------------------------------------------------------
def _on_leaving_ext_id_type(self):
wx.CallAfter(self._refresh_ext_id_warning)
#----------------------------------------------------------------
def _on_leaving_ext_id_val(self):
wx.CallAfter(self._refresh_ext_id_warning)
#----------------------------------------------------------------
def _on_leaving_lastname(self):
wx.CallAfter(self._refresh_dupe_warning)
#----------------------------------------------------------------
def _on_leaving_firstname(self):
"""Set the gender according to entered firstname.
Matches are fetched from existing records in backend.
"""
wx.CallAfter(self._refresh_dupe_warning)
# only set if not already set so as to not
# overwrite a change by the user
if self._PRW_gender.GetData() is not None:
return True
firstname = self._PRW_firstnames.GetValue().strip()
if firstname == u'':
return True
gender = gmPerson.map_firstnames2gender(firstnames = firstname)
if gender is None:
return True
wx.CallAfter(self._PRW_gender.SetData, gender)
return True
#----------------------------------------------------------------
def _on_leaving_dob(self):
wx.CallAfter(self._refresh_dupe_warning)
#----------------------------------------------------------------
def _on_leaving_zip(self):
self.__perhaps_invalidate_address_searcher(self._PRW_zip, 'postcode')
zip_code = gmTools.none_if(self._PRW_zip.GetValue().strip(), u'')
self._PRW_street.set_context(context = u'zip', val = zip_code)
self._PRW_urb.set_context(context = u'zip', val = zip_code)
self._PRW_region.set_context(context = u'zip', val = zip_code)
self._PRW_country.set_context(context = u'zip', val = zip_code)
return True
#----------------------------------------------------------------
def _on_leaving_country(self):
self.__perhaps_invalidate_address_searcher(self._PRW_country, 'l10n_country')
country = gmTools.none_if(self._PRW_country.GetValue().strip(), u'')
self._PRW_region.set_context(context = u'country', val = country)
return True
#----------------------------------------------------------------
def _on_leaving_number(self, evt):
if self._TCTRL_number.GetValue().strip() == u'':
adr = self._PRW_address_searcher.address
if adr is None:
return True
self._TCTRL_number.SetValue(adr['number'])
return True
self.__perhaps_invalidate_address_searcher(self._TCTRL_number, 'number')
return True
#----------------------------------------------------------------
def _on_leaving_unit(self, evt):
if self._TCTRL_unit.GetValue().strip() == u'':
adr = self._PRW_address_searcher.address
if adr is None:
return True
self._TCTRL_unit.SetValue(gmTools.coalesce(adr['subunit'], u''))
return True
self.__perhaps_invalidate_address_searcher(self._TCTRL_unit, 'subunit')
return True
#----------------------------------------------------------------
def _invalidate_address_searcher(self, *args, **kwargs):
mapping = [
(self._PRW_street, 'street'),
(self._PRW_urb, 'urb'),
(self._PRW_region, 'l10n_state')
]
# loop through fields and invalidate address searcher if different
for ctrl, field in mapping:
if self.__perhaps_invalidate_address_searcher(ctrl, field):
return True
return True
#----------------------------------------------------------------
def _on_leaving_adress_searcher(self):
if self._PRW_address_searcher.address is None:
return True
wx.CallAfter(self.__set_fields_from_address_searcher)
return True
#----------------------------------------------------------------
# generic Edit Area mixin API
#----------------------------------------------------------------
def _valid_for_save(self):
if self._PRW_primary_provider.GetValue().strip() == u'':
self._PRW_primary_provider.display_as_valid(True)
else:
if self._PRW_primary_provider.GetData() is None:
self._PRW_primary_provider.display_as_valid(False)
else:
self._PRW_primary_provider.display_as_valid(True)
return (self.__identity_valid_for_save() and self.__address_valid_for_save(empty_address_is_valid = True))
#----------------------------------------------------------------
def _save_as_new(self):
if self._PRW_dob.GetValue().strip() == u'':
if not _empty_dob_allowed():
self._PRW_dob.display_as_valid(False)
self._PRW_dob.SetFocus()
return False
# identity
new_identity = gmPerson.create_identity (
gender = self._PRW_gender.GetData(),
dob = self._PRW_dob.GetData(),
lastnames = self._PRW_lastname.GetValue().strip(),
firstnames = self._PRW_firstnames.GetValue().strip()
)
_log.debug('identity created: %s' % new_identity)
new_identity['dob_is_estimated'] = self._CHBOX_estimated_dob.GetValue()
val = self._TCTRL_tob.GetValue().strip()
if val != u'':
new_identity['tob'] = pydt.time(int(val[:2]), int(val[3:5]))
new_identity['title'] = gmTools.none_if(self._PRW_title.GetValue().strip())
new_identity.set_nickname(nickname = gmTools.none_if(self._PRW_nickname.GetValue().strip(), u''))
prov = self._PRW_primary_provider.GetData()
if prov is not None:
new_identity['pk_primary_provider'] = prov
new_identity['comment'] = gmTools.none_if(self._TCTRL_comment.GetValue().strip(), u'')
new_identity.save()
# address
# if we reach this the address cannot be completely empty
is_valid = self.__address_valid_for_save(empty_address_is_valid = False)
if is_valid is True:
# because we currently only check for non-emptiness
# we must still deal with database errors
try:
new_identity.link_address (
number = self._TCTRL_number.GetValue().strip(),
street = self._PRW_street.GetValue().strip(),
postcode = self._PRW_zip.GetValue().strip(),
urb = self._PRW_urb.GetValue().strip(),
state = self._PRW_region.GetData(),
country = self._PRW_country.GetData(),
subunit = gmTools.none_if(self._TCTRL_unit.GetValue().strip(), u''),
id_type = self._PRW_type.GetData()
)
except gmPG2.dbapi.InternalError:
_log.debug('number: >>%s<<', self._TCTRL_number.GetValue().strip())
_log.debug('(sub)unit: >>%s<<', self._TCTRL_unit.GetValue().strip())
_log.debug('street: >>%s<<', self._PRW_street.GetValue().strip())
_log.debug('postcode: >>%s<<', self._PRW_zip.GetValue().strip())
_log.debug('urb: >>%s<<', self._PRW_urb.GetValue().strip())
_log.debug('state: >>%s<<', self._PRW_region.GetData().strip())
_log.debug('country: >>%s<<', self._PRW_country.GetData().strip())
_log.exception('cannot link address')
gmGuiHelpers.gm_show_error (
aTitle = _('Saving address'),
aMessage = _(
'Cannot save this address.\n'
'\n'
'You will have to add it via the Demographics plugin.\n'
)
)
elif is_valid is False:
gmGuiHelpers.gm_show_error (
aTitle = _('Saving address'),
aMessage = _(
'Address not saved.\n'
'\n'
'You will have to add it via the Demographics plugin.\n'
)
)
# else it is None which means empty address which we ignore
# phone
channel_name = self._PRW_channel_type.GetValue().strip()
pk_channel_type = self._PRW_channel_type.GetData()
if pk_channel_type is None:
if channel_name == u'':
channel_name = u'homephone'
new_identity.link_comm_channel (
comm_medium = channel_name,
pk_channel_type = pk_channel_type,
url = gmTools.none_if(self._TCTRL_phone.GetValue().strip(), u''),
is_confidential = False
)
# external ID
pk_type = self._PRW_external_id_type.GetData()
id_value = self._TCTRL_external_id_value.GetValue().strip()
if (pk_type is not None) and (id_value != u''):
new_identity.add_external_id(value = id_value, pk_type = pk_type)
# occupation
new_identity.link_occupation (
occupation = gmTools.none_if(self._PRW_occupation.GetValue().strip(), u'')
)
self.data = new_identity
return True
#----------------------------------------------------------------
def _save_as_update(self):
raise NotImplementedError('[%s]: not expected to be used' % self.__class__.__name__)
#----------------------------------------------------------------
def _refresh_as_new(self):
# FIXME: button "empty out"
return
#----------------------------------------------------------------
def _refresh_from_existing(self):
return # there is no forward button so nothing to do here
#----------------------------------------------------------------
def _refresh_as_new_from_existing(self):
raise NotImplementedError('[%s]: not expected to be used' % self.__class__.__name__)
#============================================================
# 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()
#--------------------------------------------------------
#test_org_unit_prw()
|