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 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
|
# -*- coding: utf-8 -*-
#from __future__ import print_function
__doc__ = """GNUmed drug / substance reference widgets."""
#================================================================
__author__ = "Karsten Hilbert <Karsten.Hilbert@gmx.net>"
__license__ = "GPL v2 or later"
import logging
import sys
import os.path
import decimal
import wx
if __name__ == '__main__':
sys.path.insert(0, '../../')
from Gnumed.pycommon import gmI18N
gmI18N.activate_locale()
gmI18N.install_domain(domain = 'gnumed')
from Gnumed.pycommon import gmDispatcher
from Gnumed.pycommon import gmCfg
from Gnumed.pycommon import gmShellAPI
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmMatchProvider
from Gnumed.business import gmPerson
from Gnumed.business import gmPraxis
from Gnumed.business import gmMedication
from Gnumed.business import gmDrugDataSources
from Gnumed.business import gmATC
from Gnumed.wxpython import gmGuiHelpers
from Gnumed.wxpython import gmEditArea
from Gnumed.wxpython import gmCfgWidgets
from Gnumed.wxpython import gmListWidgets
from Gnumed.wxpython import gmPhraseWheel
_log = logging.getLogger('gm.ui')
#============================================================
# generic drug database access
#------------------------------------------------------------
def configure_drug_data_source(parent=None):
gmCfgWidgets.configure_string_from_list_option (
parent = parent,
message = _(
'\n'
'Please select the default drug data source from the list below.\n'
'\n'
'Note that to actually use it you need to have the database installed, too.'
),
option = 'external.drug_data.default_source',
bias = 'user',
default_value = None,
choices = gmDrugDataSources.drug_data_source_interfaces.keys(),
columns = [_('Drug data source')],
data = gmDrugDataSources.drug_data_source_interfaces.keys(),
caption = _('Configuring default drug data source')
)
#============================================================
def get_drug_database(parent=None, patient=None):
dbcfg = gmCfg.cCfgSQL()
# load from option
default_db = dbcfg.get2 (
option = 'external.drug_data.default_source',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = 'workplace'
)
# not configured -> try to configure
if default_db is None:
gmDispatcher.send('statustext', msg = _('No default drug database configured.'), beep = True)
configure_drug_data_source(parent = parent)
default_db = dbcfg.get2 (
option = 'external.drug_data.default_source',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = 'workplace'
)
# still not configured -> return
if default_db is None:
gmGuiHelpers.gm_show_error (
aMessage = _('There is no default drug database configured.'),
aTitle = _('Jumping to drug database')
)
return None
# now it MUST be configured (either newly or previously)
# but also *validly* ?
try:
drug_db = gmDrugDataSources.drug_data_source_interfaces[default_db]()
except KeyError:
# not valid
_log.error('faulty default drug data source configuration: %s', default_db)
# try to configure
configure_drug_data_source(parent = parent)
default_db = dbcfg.get2 (
option = 'external.drug_data.default_source',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = 'workplace'
)
# deconfigured or aborted (and thusly still misconfigured) ?
try:
drug_db = gmDrugDataSources.drug_data_source_interfaces[default_db]()
except KeyError:
_log.error('still faulty default drug data source configuration: %s', default_db)
return None
if patient is not None:
drug_db.patient = patient
return drug_db
#============================================================
def jump_to_drug_database(patient=None):
drug_db = get_drug_database(patient = patient)
if drug_db is None:
return
drug_db.switch_to_frontend(blocking = False)
#============================================================
def jump_to_ifap_deprecated(import_drugs=False, emr=None):
if import_drugs and (emr is None):
gmDispatcher.send('statustext', msg = _('Cannot import drugs from IFAP into chart without chart.'))
return False
dbcfg = gmCfg.cCfgSQL()
ifap_cmd = dbcfg.get2 (
option = 'external.ifap-win.shell_command',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = 'workplace',
default = 'wine "C:\Ifapwin\WIAMDB.EXE"'
)
found, binary = gmShellAPI.detect_external_binary(ifap_cmd)
if not found:
gmDispatcher.send('statustext', msg = _('Cannot call IFAP via [%s].') % ifap_cmd)
return False
ifap_cmd = binary
if import_drugs:
transfer_file = os.path.expanduser(dbcfg.get2 (
option = 'external.ifap-win.transfer_file',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = 'workplace',
default = '~/.wine/drive_c/Ifapwin/ifap2gnumed.csv'
))
# file must exist for Ifap to write into it
try:
f = io.open(transfer_file, mode = 'wt').close()
except IOError:
_log.exception('Cannot create IFAP <-> GNUmed transfer file [%s]', transfer_file)
gmDispatcher.send('statustext', msg = _('Cannot create IFAP <-> GNUmed transfer file [%s].') % transfer_file)
return False
wx.BeginBusyCursor()
gmShellAPI.run_command_in_shell(command = ifap_cmd, blocking = import_drugs)
wx.EndBusyCursor()
if import_drugs:
# COMMENT: this file must exist PRIOR to invoking IFAP
# COMMENT: or else IFAP will not write data into it ...
try:
csv_file = io.open(transfer_file, mode = 'rt', encoding = 'latin1') # FIXME: encoding unknown
except:
_log.exception('cannot access [%s]', fname)
csv_file = None
if csv_file is not None:
import csv
csv_lines = csv.DictReader (
csv_file,
fieldnames = u'PZN Handelsname Form Abpackungsmenge Einheit Preis1 Hersteller Preis2 rezeptpflichtig Festbetrag Packungszahl Packungsgr\xf6\xdfe'.split(),
delimiter = ';'
)
# dummy episode for now
epi = emr.add_episode(episode_name = _('Current medication'))
for line in csv_lines:
narr = u'%sx %s %s %s (\u2258 %s %s) von %s (%s)' % (
line['Packungszahl'].strip(),
line['Handelsname'].strip(),
line['Form'].strip(),
line[u'Packungsgr\xf6\xdfe'].strip(),
line['Abpackungsmenge'].strip(),
line['Einheit'].strip(),
line['Hersteller'].strip(),
line['PZN'].strip()
)
emr.add_clin_narrative(note = narr, soap_cat = 's', episode = epi)
csv_file.close()
return True
#============================================================
# substances widgets
#------------------------------------------------------------
def edit_substance(parent=None, substance=None, single_entry=False):
if substance is not None:
if substance.is_in_use_by_patients:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot edit this substance. It is in use.'), beep = True)
return False
ea = cSubstanceEAPnl(parent = parent, id = -1)
ea.data = substance
ea.mode = gmTools.coalesce(substance, 'new', 'edit')
dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = single_entry)
dlg.SetTitle(gmTools.coalesce(substance, _('Adding new substance'), _('Editing substance')))
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
return True
dlg.Destroy()
return False
#------------------------------------------------------------
def manage_substances(parent=None):
if parent is None:
parent = wx.GetApp().GetTopWindow()
#------------------------------------------------------------
def add_from_db(substance):
drug_db = get_drug_database(parent = parent)
if drug_db is None:
return False
drug_db.import_drugs()
return True
#------------------------------------------------------------
def edit(substance=None):
return edit_substance(parent = parent, substance = substance, single_entry = (substance is not None))
#------------------------------------------------------------
def delete(substance):
if substance.is_in_use_by_patients:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot delete this substance. It is in use.'), beep = True)
return False
return gmMedication.delete_substance(pk_substance = substance['pk_substance'])
#------------------------------------------------------------
def get_item_tooltip(substance):
if not isinstance(substance, gmMedication.cSubstance):
return None
return substance.format()
#------------------------------------------------------------
def refresh(lctrl):
substs = gmMedication.get_substances(order_by = 'substance')
items = [ [
s['substance'],
gmTools.coalesce(s['atc'], u''),
gmTools.coalesce(s['intake_instructions'], u''),
s['pk_substance']
] for s in substs ]
lctrl.set_string_items(items)
lctrl.set_data(substs)
#------------------------------------------------------------
gmListWidgets.get_choices_from_list (
parent = parent,
caption = _('Substances registered with GNUmed.'),
columns = [_('Substance'), 'ATC', _('Instructions'), u'#'],
single_selection = True,
new_callback = edit,
edit_callback = edit,
delete_callback = delete,
refresh_callback = refresh,
left_extra_button = (_('Import'), _('Import substances from a drug database.'), add_from_db),
list_tooltip_callback = get_item_tooltip
)
#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgSubstanceEAPnl
class cSubstanceEAPnl(wxgSubstanceEAPnl.wxgSubstanceEAPnl, gmEditArea.cGenericEditAreaMixin):
def __init__(self, *args, **kwargs):
try:
data = kwargs['substance']
del kwargs['substance']
except KeyError:
data = None
wxgSubstanceEAPnl.wxgSubstanceEAPnl.__init__(self, *args, **kwargs)
gmEditArea.cGenericEditAreaMixin.__init__(self)
# Code using this mixin should set mode and data
# after instantiating the class:
self.mode = 'new'
self.data = data
if data is not None:
self.mode = 'edit'
self.__init_ui()
#----------------------------------------------------------------
def __init_ui(self):
self._LCTRL_loincs.set_columns([_(u'LOINC'), _(u'Interval'), _(u'Comment')])
#----------------------------------------------------------------
# generic Edit Area mixin API
#----------------------------------------------------------------
def _valid_for_save(self):
validity = True
if self._TCTRL_substance.GetValue().strip() == u'':
validity = False
self.display_tctrl_as_valid(tctrl = self._TCTRL_substance, valid = False)
self._TCTRL_substance.SetFocus()
else:
self.display_tctrl_as_valid(tctrl = self._TCTRL_substance, valid = True)
if validity is False:
self.status_message = _('Cannot save: Substance name missing.')
return validity
#----------------------------------------------------------------
def _save_as_new(self):
subst = gmMedication.create_substance (
substance = self._TCTRL_substance.GetValue().strip(),
atc = self._PRW_atc.GetData()
)
subst['intake_instructions'] = self._TCTRL_instructions.GetValue().strip()
success, data = subst.save()
if not success:
err, msg = data
_log.error(err)
_log.error(msg)
self.status_message = _(u'Error saving substance. %s') % msg
return False
loincs = self._LCTRL_loincs.item_data
if len(loincs) > 0:
subst.loincs = loincs
self.data = subst
return True
#----------------------------------------------------------------
def _save_as_update(self):
self.data['substance'] = self._TCTRL_substance.GetValue().strip()
self.data['atc'] = self._PRW_atc.GetData()
self.data['intake_instructions'] = self._TCTRL_instructions.GetValue().strip()
success, data = self.data.save()
if not success:
err, msg = data
_log.error(err)
_log.error(msg)
self.status_message = _(u'Error saving substance. %s') % msg
return False
loincs = self._LCTRL_loincs.item_data
if len(loincs) > 0:
self.data.loincs = loincs
return True
#----------------------------------------------------------------
def _refresh_as_new(self):
self._TCTRL_substance.SetValue(u'')
self._PRW_atc.SetText(u'', None)
self._TCTRL_instructions.SetValue(u'')
self._PRW_loinc.SetText(u'', None)
self._LCTRL_loincs.set_string_items()
self._TCTRL_substance.SetFocus()
#----------------------------------------------------------------
def _refresh_from_existing(self):
self._TCTRL_substance.SetValue(self.data['substance'])
self._PRW_atc.SetText(gmTools.coalesce(self.data['atc'], u''), self.data['atc'])
self._TCTRL_instructions.SetValue(gmTools.coalesce(self.data['intake_instructions'], u''))
self._PRW_loinc.SetText(u'', None)
if len(self.data['loincs']) == 0:
self._LCTRL_loincs.set_string_items()
else:
self._LCTRL_loincs.set_string_items([ [l['loinc'], gmTools.coalesce(l['max_age_str'], u''), gmTools.coalesce(l['comment'], u'')] for l in self.data['loincs' ]])
self._LCTRL_loincs.set_data([ l['loinc'] for l in self.data['loincs'] ])
self._TCTRL_substance.SetFocus()
#----------------------------------------------------------------
def _refresh_as_new_from_existing(self):
self._refresh_as_new()
#----------------------------------------------------------------
# event handlers
#----------------------------------------------------------------
def _on_add_loinc_button_pressed(self, event):
event.Skip()
if (self._PRW_loinc.GetData() is None) and (self._PRW_loinc.GetValue().strip() == u''):
return
if self._PRW_loinc.GetData() is None:
data = self._PRW_loinc.GetValue().strip().split(u':')[0]
item = [data, u'', u'']
else:
data = self._PRW_loinc.GetData()
item = [data, u'', u'']
self._LCTRL_loincs.append_string_items_and_data([item], new_data = [data], allow_dupes = False)
#----------------------------------------------------------------
def _on_remove_loincs_button_pressed(self, event):
event.Skip()
#------------------------------------------------------------
class cSubstancePhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
query = u"""
SELECT DISTINCT ON (list_label)
list_label,
field_label,
data
FROM (
SELECT
description AS list_label,
description AS field_label,
pk AS data
FROM ref.substance
WHERE
description %(fragment_condition)s
UNION ALL
SELECT
term AS list_label,
term AS field_label,
NULL::integer AS data
FROM ref.atc
WHERE
term %(fragment_condition)s
) AS candidates
ORDER BY list_label
LIMIT 50
"""
mp = gmMatchProvider.cMatchProvider_SQL2(queries = query)
mp.setThresholds(1, 2, 4)
# mp.word_separators = '[ \t=+&:@]+'
self.SetToolTipString(_('The substance name.'))
self.matcher = mp
self.selection_only = False
self.phrase_separators = None
#--------------------------------------------------------
def _data2instance(self):
return gmMedication.cSubstance(aPK_obj = self.GetData(as_instance = False, can_create = False))
#============================================================
# substance dose widgets
#------------------------------------------------------------
def edit_substance_dose(parent=None, substance_dose=None, single_entry=False):
if substance_dose is not None:
if substance_dose.is_in_use_by_patients:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot edit this substance. It is in use.'), beep = True)
return False
ea = cSubstanceDoseEAPnl(parent = parent, id = -1)
ea.data = substance_dose
ea.mode = gmTools.coalesce(substance_dose, 'new', 'edit')
dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = single_entry)
dlg.SetTitle(gmTools.coalesce(substance_dose, _('Adding new substance dose'), _('Editing substance dose')))
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
return True
dlg.Destroy()
return False
#------------------------------------------------------------
def manage_substance_doses(parent=None, vaccine_indications_only=False):
if parent is None:
parent = wx.GetApp().GetTopWindow()
#------------------------------------------------------------
def add_from_db(substance):
drug_db = get_drug_database(parent = parent)
if drug_db is None:
return False
drug_db.import_drugs()
return True
#------------------------------------------------------------
def edit(substance_dose=None):
return edit_substance_dose(parent = parent, substance_dose = substance_dose, single_entry = (substance_dose is not None))
#------------------------------------------------------------
def delete(substance_dose):
if substance_dose.is_in_use_by_patients:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot delete this substance. It is in use.'), beep = True)
return False
return gmMedication.delete_substance_dose(pk_dose = substance_dose['pk_dose'])
#------------------------------------------------------------
def refresh(lctrl):
if vaccine_indications_only:
substs = [ s for s in gmMedication.get_substance_doses(order_by = 'substance') if gmTools.coalesce(s['atc_substance'], u'').startswith(u'J07') ]
else:
substs = gmMedication.get_substance_doses(order_by = 'substance')
items = [ [
s['substance'],
s['amount'],
s.formatted_units,
gmTools.coalesce(s['atc_substance'], u''),
gmTools.coalesce(s['intake_instructions'], u''),
s['pk_dose']
] for s in substs ]
lctrl.set_string_items(items)
lctrl.set_data(substs)
#------------------------------------------------------------
def get_item_tooltip(substance_dose):
if not isinstance(substance_dose, gmMedication.cSubstanceDose):
return None
return substance_dose.format(include_loincs = True)
#------------------------------------------------------------
return gmListWidgets.get_choices_from_list (
parent = parent,
caption = _('Substance doses registered with GNUmed.'),
columns = [_('Substance'), _(u'Amount'), _(u'Unit'), 'ATC', _('Instructions'), u'#'],
single_selection = False,
can_return_empty = False,
new_callback = edit,
edit_callback = edit,
delete_callback = delete,
refresh_callback = refresh,
left_extra_button = (_('Import'), _('Import substance doses from a drug database.'), add_from_db),
list_tooltip_callback = get_item_tooltip
)
#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgSubstanceDoseEAPnl
class cSubstanceDoseEAPnl(wxgSubstanceDoseEAPnl.wxgSubstanceDoseEAPnl, gmEditArea.cGenericEditAreaMixin):
def __init__(self, *args, **kwargs):
try:
data = kwargs['substance']
del kwargs['substance']
except KeyError:
data = None
wxgSubstanceDoseEAPnl.wxgSubstanceDoseEAPnl.__init__(self, *args, **kwargs)
gmEditArea.cGenericEditAreaMixin.__init__(self)
# Code using this mixin should set mode and data
# after instantiating the class:
self.mode = 'new'
self.data = data
if data is not None:
self.mode = 'edit'
self.__init_ui()
#----------------------------------------------------------------
def __init_ui(self):
self._PRW_substance.add_callback_on_modified(callback = self.__refresh_info)
self._PRW_substance.add_callback_on_selection(callback = self.__refresh_info)
self._TCTRL_amount.add_callback_on_modified(callback = self.__refresh_info)
self._PRW_unit.add_callback_on_modified(callback = self.__refresh_info)
self._PRW_unit.add_callback_on_selection(callback = self.__refresh_info)
self._PRW_dose_unit.add_callback_on_modified(callback = self.__refresh_info)
self._PRW_dose_unit.add_callback_on_selection(callback = self.__refresh_info)
#----------------------------------------------------------------
def __refresh_info(self, change='dummy'):
subst = self._PRW_substance.GetValue().strip()
if subst == u'':
subst = u'?'
amount = self._TCTRL_amount.GetValue().strip()
if amount == u'':
amount = u'?'
unit = self._PRW_unit.GetValue().strip()
if unit == u'':
unit = u'?'
dose_unit = self._PRW_dose_unit.GetValue().strip()
if dose_unit == u'':
dose_unit = _(u'<delivery unit>')
self._LBL_info.SetLabel(u'%s %s %s / %s' % (subst, amount, unit, dose_unit))
self.Refresh()
#----------------------------------------------------------------
# generic Edit Area mixin API
#----------------------------------------------------------------
def _valid_for_save(self):
validity = True
if self._PRW_substance.GetValue().strip() == u'':
validity = False
self._PRW_substance.display_as_valid(valid = False)
self._PRW_substance.SetFocus()
else:
self._PRW_substance.display_as_valid(valid = True)
try:
decimal.Decimal(self._TCTRL_amount.GetValue().strip().replace(',', '.'))
self.display_tctrl_as_valid(tctrl = self._TCTRL_amount, valid = True)
except (TypeError, decimal.InvalidOperation):
validity = False
self.display_tctrl_as_valid(tctrl = self._TCTRL_amount, valid = False)
self._TCTRL_amount.SetFocus()
if self._PRW_unit.GetValue().strip() == u'':
validity = False
self._PRW_unit.display_as_valid(valid = False)
self._PRW_unit.SetFocus()
else:
self._PRW_unit.display_as_valid(valid = True)
if validity is False:
self.status_message = _('Cannot save substance dose. Missing essential input.')
return validity
#----------------------------------------------------------------
def _save_as_new(self):
dose = gmMedication.create_substance_dose (
pk_substance = self._PRW_substance.GetData(),
substance = self._PRW_substance.GetValue().strip(),
amount = decimal.Decimal(self._TCTRL_amount.GetValue().strip().replace(',', '.')),
unit = gmTools.coalesce(self._PRW_unit.GetData(), self._PRW_unit.GetValue().strip(), function_initial = ('strip', None)),
dose_unit = gmTools.coalesce(self._PRW_dose_unit.GetData(), self._PRW_dose_unit.GetValue().strip(), function_initial = ('strip', None))
)
success, data = dose.save()
if not success:
err, msg = data
_log.error(err)
_log.error(msg)
self.status_message = _('Cannot create substance dose. %s') % msg
return False
self.data = dose
return True
#----------------------------------------------------------------
def _save_as_update(self):
#self.data['pk_substance'] = self._PRW_substance.GetData()
self.data['amount'] = decimal.Decimal(self._TCTRL_amount.GetValue().strip().replace(',', '.'))
self.data['unit'] = gmTools.coalesce(self._PRW_unit.GetData(), self._PRW_unit.GetValue().strip(), function_initial = ('strip', None))
self.data['dose_unit'] = gmTools.coalesce(self._PRW_dose_unit.GetData(), self._PRW_dose_unit.GetValue().strip(), function_initial = ('strip', None))
success, data = self.data.save()
if not success:
err, msg = data
_log.error(err)
_log.error(msg)
self.status_message = _('Cannot save substance dose. %s') % msg
return False
return True
#----------------------------------------------------------------
def _refresh_as_new(self):
self._PRW_substance.SetText(u'', None)
self._TCTRL_amount.SetValue(u'')
self._PRW_unit.SetText(u'', None)
self._PRW_dose_unit.SetText(u'', None)
self._LBL_info.SetLabel(u'')
self._PRW_substance.SetFocus()
#----------------------------------------------------------------
def _refresh_from_existing(self):
self._PRW_substance.SetText(self.data['substance'], self.data['pk_substance'])
self._PRW_substance.Disable()
self._TCTRL_amount.SetValue(u'%s' % self.data['amount'])
self._PRW_unit.SetText(self.data['unit'], self.data['unit'])
self._PRW_dose_unit.SetText(gmTools.coalesce(self.data['dose_unit'], u''), self.data['dose_unit'])
self._PRW_substance.SetFocus()
#----------------------------------------------------------------
def _refresh_as_new_from_existing(self):
self._refresh_as_new()
#============================================================
# drug component widgets
#------------------------------------------------------------
def manage_drug_components(parent=None):
if parent is None:
parent = wx.GetApp().GetTopWindow()
#------------------------------------------------------------
def edit(component=None):
substance_dose = gmMedication.cSubstanceDose(aPK_obj = component['pk_dose'])
return edit_substance_dose(parent = parent, substance_dose = substance_dose, single_entry = True)
#------------------------------------------------------------
def delete(component):
if component.is_in_use_by_patients:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot remove this component from the drug. It is in use.'), beep = True)
return False
return component.containing_drug.remove_component(pk_component = component['pk_component'])
#------------------------------------------------------------
def refresh(lctrl):
comps = gmMedication.get_drug_components()
items = [ [
u'%s%s' % (c['substance'], gmTools.coalesce(c['atc_substance'], u'', u' [%s]')),
u'%s %s' % (c['amount'], c.formatted_units),
u'%s%s' % (c['product'], gmTools.coalesce(c['atc_drug'], u'', u' [%s]')),
c['l10n_preparation'],
gmTools.coalesce(c['external_code'], u'', u'%%s [%s]' % c['external_code_type']),
c['pk_component']
] for c in comps ]
lctrl.set_string_items(items)
lctrl.set_data(comps)
#------------------------------------------------------------
def get_item_tooltip(component):
if not isinstance(component, gmMedication.cDrugComponent):
return None
return component.format(include_loincs = True)
#------------------------------------------------------------
gmListWidgets.get_choices_from_list (
parent = parent,
caption = _('Drug components currently known to GNUmed'),
columns = [_('Component'), _('Strength'), _('Product name'), _('Preparation'), _('Code'), u'#'],
single_selection = True,
#new_callback = edit,
edit_callback = edit,
delete_callback = delete,
refresh_callback = refresh,
list_tooltip_callback = get_item_tooltip
)
#------------------------------------------------------------
def edit_drug_component(parent=None, drug_component=None, single_entry=False):
ea = cDrugComponentEAPnl(parent = parent, id = -1)
ea.data = drug_component
ea.mode = gmTools.coalesce(drug_component, 'new', 'edit')
dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = single_entry)
dlg.SetTitle(gmTools.coalesce(drug_component, _('Adding new drug component'), _('Editing drug component')))
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
return True
dlg.Destroy()
return False
#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgDrugComponentEAPnl
class cDrugComponentEAPnl(wxgDrugComponentEAPnl.wxgDrugComponentEAPnl, gmEditArea.cGenericEditAreaMixin):
def __init__(self, *args, **kwargs):
try:
data = kwargs['component']
del kwargs['component']
except KeyError:
data = None
wxgDrugComponentEAPnl.wxgDrugComponentEAPnl.__init__(self, *args, **kwargs)
gmEditArea.cGenericEditAreaMixin.__init__(self)
# Code using this mixin should set mode and data
# after instantiating the class:
self.mode = 'new'
self.data = data
if data is not None:
self.mode = 'edit'
#self.__init_ui()
#----------------------------------------------------------------
# def __init_ui(self):
# # adjust phrasewheels etc
#----------------------------------------------------------------
# generic Edit Area mixin API
#----------------------------------------------------------------
def _valid_for_save(self):
if self.data is not None:
if self.data['is_in_use']:
self.status_message = _('Cannot edit drug component. It is in use.')
return False
validity = True
if self._PRW_substance.GetData() is None:
validity = False
self._PRW_substance.display_as_valid(False)
else:
self._PRW_substance.display_as_valid(True)
val = self._TCTRL_amount.GetValue().strip().replace(',', u'.', 1)
try:
decimal.Decimal(val)
self.display_tctrl_as_valid(tctrl = self._TCTRL_amount, valid = True)
except:
validity = False
self.display_tctrl_as_valid(tctrl = self._TCTRL_amount, valid = False)
if self._PRW_unit.GetValue().strip() == u'':
validity = False
self._PRW_unit.display_as_valid(False)
else:
self._PRW_unit.display_as_valid(True)
if validity is False:
self.status_message = _('Cannot save drug component. Invalid or missing essential input.')
return validity
#----------------------------------------------------------------
def _save_as_new(self):
# save the data as a new instance
data = 1
data[''] = 1
data[''] = 1
# data.save()
# must be done very late or else the property access
# will refresh the display such that later field
# access will return empty values
# self.data = data
return False
return True
#----------------------------------------------------------------
def _save_as_update(self):
self.data['pk_dose'] = self._PRW_substance.GetData()
self.data['amount'] = decimal.Decimal(self._TCTRL_amount.GetValue().strip().replace(',', u'.', 1))
self.data['unit'] = self._PRW_unit.GetValue().strip()
return self.data.save()
#----------------------------------------------------------------
def _refresh_as_new(self):
self._TCTRL_product_name.SetValue(u'')
self._TCTRL_components.SetValue(u'')
self._TCTRL_codes.SetValue(u'')
self._PRW_substance.SetText(u'', None)
self._TCTRL_amount.SetValue(u'')
self._PRW_unit.SetText(u'', None)
self._PRW_substance.SetFocus()
#----------------------------------------------------------------
def _refresh_from_existing(self):
self._TCTRL_product_name.SetValue(u'%s (%s)' % (self.data['product'], self.data['l10n_preparation']))
self._TCTRL_components.SetValue(u' / '.join(self.data.containing_drug['components']))
details = []
if self.data['atc_drug'] is not None:
details.append(u'ATC: %s' % self.data['atc_drug'])
if self.data['external_code_product'] is not None:
details.append(u'%s: %s' % (self.data['external_code_type_product'], self.data['external_code_product']))
self._TCTRL_codes.SetValue(u'; '.join(details))
self._PRW_substance.SetText(self.data['substance'], self.data['pk_dose'])
self._TCTRL_amount.SetValue(u'%s' % self.data['amount'])
self._PRW_unit.SetText(self.data['unit'], self.data['unit'])
self._PRW_substance.SetFocus()
#----------------------------------------------------------------
def _refresh_as_new_from_existing(self):
#self._PRW_drug_product.SetText(u'', None)
#self._TCTRL_prep.SetValue(u'')
#self._TCTRL_product_name_details.SetValue(u'')
self._PRW_substance.SetText(u'', None)
self._TCTRL_amount.SetValue(u'')
self._PRW_unit.SetText(u'', None)
self._PRW_substance.SetFocus()
#------------------------------------------------------------
class cDrugComponentPhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
mp = gmMedication.cDrugComponentMatchProvider()
mp.setThresholds(2, 3, 4)
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
self.SetToolTipString(_('A drug component with optional strength.'))
self.matcher = mp
self.selection_only = False
#--------------------------------------------------------
def _data2instance(self):
return gmMedication.cDrugComponent(aPK_obj = self.GetData(as_instance = False, can_create = False))
#============================================================
# drug products widgets
#------------------------------------------------------------
def edit_drug_product(parent=None, drug_product=None, single_entry=False):
if drug_product is not None:
if drug_product.is_in_use_by_patients:
gmGuiHelpers.gm_show_info (
aTitle = _('Editing drug'),
aMessage = _(
'Cannot edit the drug product\n'
'\n'
' "%s" (%s)\n'
'\n'
'because it is currently taken by patients.\n'
) % (drug_product['product'], drug_product['l10n_preparation'])
)
return False
if parent is None:
parent = wx.GetApp().GetTopWindow()
#--------------------------------------------
def manage_substances(drug):
manage_substance_doses(parent = parent)
#--------------------------------------------
ea = cDrugProductEAPnl(parent = parent, id = -1)
ea.data = drug_product
ea.mode = gmTools.coalesce(drug_product, 'new', 'edit')
dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = single_entry)
dlg.SetTitle(gmTools.coalesce(drug_product, _('Adding new drug product'), _('Editing drug product')))
dlg.left_extra_button = (
_('Substances'),
_('Manage substances'),
manage_substances
)
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
return True
dlg.Destroy()
return False
#------------------------------------------------------------
def manage_drug_products(parent=None, ignore_OK_button=False):
if parent is None:
parent = wx.GetApp().GetTopWindow()
#------------------------------------------------------------
def add_from_db(drug):
drug_db = get_drug_database(parent = parent)
if drug_db is None:
return False
drug_db.import_drugs()
return True
#------------------------------------------------------------
def get_tooltip(product=None):
return product.format(include_component_details = True)
#------------------------------------------------------------
def edit(product):
if product is not None:
if product.is_in_use_as_vaccine:
gmGuiHelpers.gm_show_info (
aTitle = _('Editing medication'),
aMessage = _(
'Cannot edit the vaccine product\n'
'\n'
' "%s" (%s)\n'
'\n'
'because it is in use.'
) % (product['product'], product['l10n_preparation'])
)
return False
return edit_drug_product(parent = parent, drug_product = product, single_entry = True)
#------------------------------------------------------------
def delete(product):
if not product.delete_associated_vaccine():
gmGuiHelpers.gm_show_info (
aTitle = _('Deleting vaccine'),
aMessage = _(
'Cannot delete the vaccine product\n'
'\n'
' "%s" (%s)\n'
'\n'
'because it is in use.'
) % (product['product'], product['l10n_preparation'])
)
return False
gmMedication.delete_drug_product(pk_drug_product = product['pk_drug_product'])
return True
#------------------------------------------------------------
def new():
return edit_drug_product(parent = parent, drug_product = None, single_entry = False)
#------------------------------------------------------------
def refresh(lctrl):
drugs = gmMedication.get_drug_products()
items = [ [
u'%s%s' % (
d['product'],
gmTools.bool2subst(d['is_fake_product'], ' (%s)' % _('fake'), u'')
),
d['l10n_preparation'],
gmTools.coalesce(d['atc'], u''),
u'; '.join([ u'%s %s%s' % (
c['substance'],
c['amount'],
gmMedication.format_units(c['unit'], c['dose_unit'])
) for c in d['components']]),
gmTools.coalesce(d['external_code'], u'', u'%%s [%s]' % d['external_code_type']),
d['pk_drug_product']
] for d in drugs ]
lctrl.set_string_items(items)
lctrl.set_data(drugs)
#------------------------------------------------------------
gmListWidgets.get_choices_from_list (
parent = parent,
caption = _('Drug products currently known to GNUmed.'),
columns = [_('Name'), _('Preparation'), _('ATC'), _('Components'), _('Code'), u'#'],
single_selection = True,
ignore_OK_button = ignore_OK_button,
refresh_callback = refresh,
new_callback = new,
edit_callback = edit,
delete_callback = delete,
list_tooltip_callback = get_tooltip,
left_extra_button = (_('Import'), _('Import substances and products from a drug database.'), add_from_db)
#, middle_extra_button = (_('Clone'), _('Clone selected drug into a new entry for editing.'), clone_from_existing)
#, right_extra_button = (_('Reassign'), _('Reassign all patients taking the selected drug to another drug.'), reassign_patients)
)
#------------------------------------------------------------
def manage_components_of_drug_product(parent=None, product=None):
if product is not None:
if product.is_in_use_by_patients:
gmGuiHelpers.gm_show_info (
aTitle = _('Managing components of a drug'),
aMessage = _(
'Cannot manage the components of the drug product\n'
'\n'
' "%s" (%s)\n'
'\n'
'because it is currently taken by patients.\n'
) % (product['product'], product['l10n_preparation'])
)
return False
#--------------------------------------------------------
if parent is None:
parent = wx.GetApp().GetTopWindow()
#--------------------------------------------------------
# def manage_substances():
# pass
#--------------------------------------------------------
if product is None:
msg = _('Pick the substance doses which are components of this drug.')
right_col = _('Components of drug')
comp_doses = []
else:
right_col = u'%s (%s)' % (product['product'], product['l10n_preparation'])
msg = _(
'Adjust the components of "%s"\n'
'\n'
'The drug must contain at least one component. Any given\n'
'substance can only be included once per drug.'
) % right_col
comp_doses = [ comp.substance_dose for comp in product.components ]
doses = gmMedication.get_substance_doses(order_by = 'substance')
choices = [ u'%s %s %s' % (d['substance'], d['amount'], d.formatted_units) for d in doses ]
picks = [ u'%s %s %s' % (d['substance'], d['amount'], d.formatted_units) for d in comp_doses ]
picker = gmListWidgets.cItemPickerDlg (
parent,
-1,
title = _('Managing components of a drug ...'),
msg = msg
)
picker.set_columns(['Substance doses'], [right_col])
picker.set_choices(choices = choices, data = doses)
picker.set_picks(picks = picks, data = comp_doses)
# picker.extra_button = (
# _('Substances'),
# _('Manage list of substances'),
# manage_substances
# )
btn_pressed = picker.ShowModal()
doses2set = picker.get_picks()
picker.Destroy()
if btn_pressed != wx.ID_OK:
return (False, None)
if product is not None:
product.set_substance_doses_as_components(substance_doses = doses2set)
return (True, doses2set)
#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgDrugProductEAPnl
class cDrugProductEAPnl(wxgDrugProductEAPnl.wxgDrugProductEAPnl, gmEditArea.cGenericEditAreaMixin):
def __init__(self, *args, **kwargs):
try:
data = kwargs['drug']
del kwargs['drug']
except KeyError:
data = None
wxgDrugProductEAPnl.wxgDrugProductEAPnl.__init__(self, *args, **kwargs)
gmEditArea.cGenericEditAreaMixin.__init__(self)
self.mode = 'new'
self.data = data
if data is not None:
self.mode = 'edit'
self.__component_doses = data.components_as_doses
#self.__init_ui()
#----------------------------------------------------------------
# def __init_ui(self):
# adjust external type PRW
#----------------------------------------------------------------
# generic Edit Area mixin API
#----------------------------------------------------------------
def _valid_for_save(self):
if self.data is not None:
if self.data.is_in_use_by_patients:
self.status_message = _('Cannot edit drug product. It is in use.')
return False
validity = True
product_name = self._PRW_product_name.GetValue().strip()
if product_name == u'':
validity = False
self._PRW_product_name.display_as_valid(False)
else:
self._PRW_product_name.display_as_valid(True)
preparation = self._PRW_preparation.GetValue().strip()
if preparation == u'':
validity = False
self._PRW_preparation.display_as_valid(False)
else:
self._PRW_preparation.display_as_valid(True)
if validity is True:
# dupe ?
drug = gmMedication.get_drug_by_name(product_name = product_name, preparation = preparation)
if drug is not None:
if self.mode != 'edit':
validity = False
self._PRW_product_name.display_as_valid(False)
self._PRW_preparation.display_as_valid(False)
gmGuiHelpers.gm_show_error (
title = _('Checking product data'),
error = _(
'The information you entered:\n'
'\n'
' [%s %s]\n'
'\n'
'already exists as a drug product.'
) % (product_name, preparation)
)
else:
# lacking components ?
self._TCTRL_components.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BACKGROUND))
if len(self.__component_doses) == 0:
wants_empty = gmGuiHelpers.gm_show_question (
title = _('Checking product data'),
question = _(
'You have not selected any substances\n'
'as drug components.\n'
'\n'
'Without components you will not be able to\n'
'use this drug for documenting patient care.\n'
'\n'
'Are you sure you want to save\n'
'it without components ?'
)
)
if not wants_empty:
validity = False
self.display_ctrl_as_valid(ctrl = self._TCTRL_components, valid = False)
if validity is False:
self.status_message = _('Cannot save drug product. Invalid or missing essential input.')
return validity
#----------------------------------------------------------------
def _save_as_new(self):
drug = gmMedication.create_drug_product (
product_name = self._PRW_product_name.GetValue().strip(),
preparation = gmTools.coalesce (
self._PRW_preparation.GetData(),
self._PRW_preparation.GetValue()
).strip(),
return_existing = True
)
drug['is_fake_product'] = self._CHBOX_is_fake.GetValue()
drug['atc'] = self._PRW_atc.GetData()
code = self._TCTRL_external_code.GetValue().strip()
if code != u'':
drug['external_code'] = code
drug['external_code_type'] = self._PRW_external_code_type.GetData().strip()
drug.save()
if len(self.__component_doses) > 0:
drug.set_substance_doses_as_components(substance_doses = self.__component_doses)
self.data = drug
return True
#----------------------------------------------------------------
def _save_as_update(self):
self.data['product'] = self._PRW_product_name.GetValue().strip()
self.data['preparation'] = gmTools.coalesce (
self._PRW_preparation.GetData(),
self._PRW_preparation.GetValue()
).strip()
self.data['is_fake_product'] = self._CHBOX_is_fake.GetValue()
self.data['atc'] = self._PRW_atc.GetData()
code = self._TCTRL_external_code.GetValue().strip()
if code != u'':
self.data['external_code'] = code
self.data['external_code_type'] = self._PRW_external_code_type.GetData().strip()
success, data = self.data.save()
if not success:
err, msg = data
_log.error('problem saving')
_log.error('%s', err)
_log.error('%s', msg)
return (success is True)
#----------------------------------------------------------------
def _refresh_as_new(self):
self._PRW_product_name.SetText(u'', None)
self._PRW_preparation.SetText(u'', None)
self._CHBOX_is_fake.SetValue(False)
self._TCTRL_components.SetValue(u'')
self._PRW_atc.SetText(u'', None)
self._TCTRL_external_code.SetValue(u'')
self._PRW_external_code_type.SetText(u'', None)
self._PRW_product_name.SetFocus()
self.__component_substances = []
#----------------------------------------------------------------
def _refresh_as_new_from_existing(self):
self._refresh_as_new()
#----------------------------------------------------------------
def _refresh_from_existing(self):
self._PRW_product_name.SetText(self.data['product'], self.data['pk_drug_product'])
self._PRW_preparation.SetText(self.data['preparation'], self.data['preparation'])
self._CHBOX_is_fake.SetValue(self.data['is_fake_product'])
comp_str = u''
if len(self.data['components']) > 0:
comp_str = u'- %s' % u'\n- '.join([ u'%s %s%s' % (c['substance'], c['amount'], gmMedication.format_units(c['unit'], c['dose_unit'])) for c in self.data['components'] ])
self._TCTRL_components.SetValue(comp_str)
self._PRW_atc.SetText(gmTools.coalesce(self.data['atc'], u''), self.data['atc'])
self._TCTRL_external_code.SetValue(gmTools.coalesce(self.data['external_code'], u''))
t = gmTools.coalesce(self.data['external_code_type'], u'')
self._PRW_external_code_type.SetText(t, t)
self._PRW_product_name.SetFocus()
self.__component_doses = self.data.components_as_doses
#----------------------------------------------------------------
# event handler
#----------------------------------------------------------------
def _on_manage_components_button_pressed(self, event):
event.Skip()
if self.mode == 'new_from_existing':
product = None
else:
product = self.data
OKed, doses = manage_components_of_drug_product(parent = self, product = product)
if OKed is True:
self.__component_doses = doses
comp_str = u''
if len(doses) > 0:
comp_str = u'- %s' % u'\n- '.join([ u'%s %s%s' % (d['substance'], d['amount'], gmMedication.format_units(d['unit'], d['dose_unit'])) for d in doses ])
self._TCTRL_components.SetValue(comp_str)
#------------------------------------------------------------
class cDrugProductPhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
query = u"""
SELECT
pk
AS data,
(description || ' (' || preparation || ')' || coalesce(' [' || atc_code || ']', ''))
AS list_label,
(description || ' (' || preparation || ')' || coalesce(' [' || atc_code || ']', ''))
AS field_label
FROM ref.drug_product
WHERE description %(fragment_condition)s
ORDER BY list_label
LIMIT 50"""
mp = gmMatchProvider.cMatchProvider_SQL2(queries = query)
mp.setThresholds(2, 3, 4)
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
self.SetToolTipString(_(
'The product name of the drug.\n'
'\n'
'Note: a product name will need to be linked to\n'
'one or more components before it can be used,\n'
'except in the case of fake (generic) vaccines.'
))
self.matcher = mp
self.selection_only = False
#============================================================
# single-component generic drugs
# drug name is forced to substance + amount + unit + dose_unit
#------------------------------------------------------------
def edit_single_component_generic_drug(parent=None, drug=None, single_entry=False, fields=None, return_drug=False):
# if drug is not None:
# if drug.is_in_use_by_patients:
# gmGuiHelpers.gm_show_info (
# aTitle = _('Editing single-component generic drug'),
# aMessage = _(
# 'Cannot edit the single-component generic drug\n'
# '\n'
# ' "%s" (%s)\n'
# '\n'
# 'because it is currently taken by patients.\n'
# ) % (drug['product'], drug['l10n_preparation'])
# )
# return False
if parent is None:
parent = wx.GetApp().GetTopWindow()
# #--------------------------------------------
# def manage_substances(drug):
# manage_substance_doses(parent = parent)
#--------------------------------------------
ea = cSingleComponentGenericDrugEAPnl(parent = parent, id = -1)
ea.data = drug
ea.mode = gmTools.coalesce(drug, 'new', 'edit')
dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = single_entry)
if fields is not None:
ea.set_fields(fields)
dlg.SetTitle(gmTools.coalesce(drug, _('Adding new single-component generic drug'), _('Editing single-component generic drug')))
# dlg.left_extra_button = (
# _('Substances'),
# _('Manage substances'),
# manage_substances
# )
if dlg.ShowModal() == wx.ID_OK:
drug = ea.data
dlg.Destroy()
if return_drug:
return drug
return True
dlg.Destroy()
if return_drug:
return None
return False
#------------------------------------------------------------
def manage_single_component_generic_drugs(parent=None, ignore_OK_button=False):
if parent is None:
parent = wx.GetApp().GetTopWindow()
#------------------------------------------------------------
def add_from_db(drug):
drug_db = get_drug_database(parent = parent)
if drug_db is None:
return False
drug_db.import_drugs()
return True
#------------------------------------------------------------
def get_tooltip(product=None):
return product.format(include_component_details = True)
#------------------------------------------------------------
def edit(product):
if product is not None:
if product.is_vaccine:
gmGuiHelpers.gm_show_info (
aTitle = _('Editing medication'),
aMessage = _(
'Cannot edit the medication\n'
'\n'
' "%s" (%s)\n'
'\n'
'because it is a vaccine. Please edit it\n'
'from the vaccine management section !\n'
) % (product['product'], product['l10n_preparation'])
)
return False
return edit_drug_product(parent = parent, drug_product = product, single_entry = True)
#------------------------------------------------------------
def delete(product):
if product.is_vaccine:
gmGuiHelpers.gm_show_info (
aTitle = _('Deleting medication'),
aMessage = _(
'Cannot delete the medication\n'
'\n'
' "%s" (%s)\n'
'\n'
'because it is a vaccine. Please delete it\n'
'from the vaccine management section !\n'
) % (product['product'], product['l10n_preparation'])
)
return False
gmMedication.delete_drug_product(pk_drug_product = product['pk_drug_product'])
return True
#------------------------------------------------------------
def new():
return edit_drug_product(parent = parent, drug_product = None, single_entry = False)
#------------------------------------------------------------
def refresh(lctrl):
drugs = gmMedication.get_drug_products()
items = [ [
u'%s%s' % (
d['product'],
gmTools.bool2subst(d['is_fake_product'], ' (%s)' % _('fake'), u'')
),
d['l10n_preparation'],
gmTools.coalesce(d['atc'], u''),
u'; '.join([ u'%s %s%s' % (
c['substance'],
c['amount'],
gmMedication.format_units(c['unit'], c['dose_unit'])
) for c in d['components']]),
gmTools.coalesce(d['external_code'], u'', u'%%s [%s]' % d['external_code_type']),
d['pk_drug_product']
] for d in drugs ]
lctrl.set_string_items(items)
lctrl.set_data(drugs)
#------------------------------------------------------------
gmListWidgets.get_choices_from_list (
parent = parent,
caption = _('Drug products currently known to GNUmed.'),
columns = [_('Name'), _('Preparation'), _('ATC'), _('Components'), _('Code'), u'#'],
single_selection = True,
ignore_OK_button = ignore_OK_button,
refresh_callback = refresh,
new_callback = new,
edit_callback = edit,
delete_callback = delete,
list_tooltip_callback = get_tooltip,
#left_extra_button = (_('Import'), _('Import substances and products from a drug database.'), add_from_db)
#, middle_extra_button = (_('Clone'), _('Clone selected drug into a new entry for editing.'), clone_from_existing)
#, right_extra_button = (_('Reassign'), _('Reassign all patients taking the selected drug to another drug.'), reassign_patients)
)
#------------------------------------------------------------
from Gnumed.wxGladeWidgets import wxgSingleComponentGenericDrugEAPnl
class cSingleComponentGenericDrugEAPnl(wxgSingleComponentGenericDrugEAPnl.wxgSingleComponentGenericDrugEAPnl, gmEditArea.cGenericEditAreaMixin):
def __init__(self, *args, **kwargs):
try:
data = kwargs['drug']
del kwargs['drug']
except KeyError:
data = None
wxgSingleComponentGenericDrugEAPnl.wxgSingleComponentGenericDrugEAPnl.__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_substance.add_callback_on_modified(callback = self._on_name_field_modified)
self._PRW_substance.add_callback_on_selection(callback = self._on_name_field_modified)
self._TCTRL_amount.add_callback_on_modified(callback = self._on_name_field_modified)
self._PRW_unit.add_callback_on_modified(callback = self._on_name_field_modified)
self._PRW_unit.add_callback_on_selection(callback = self._on_name_field_modified)
self._PRW_dose_unit.add_callback_on_modified(callback = self._on_name_field_modified)
self._PRW_dose_unit.add_callback_on_selection(callback = self._on_name_field_modified)
#----------------------------------------------------------------
# generic Edit Area mixin API
#----------------------------------------------------------------
def _valid_for_save(self):
validity = True
if self._PRW_preparation.Value.strip() == u'':
validity = False
self._PRW_preparation.display_as_valid(False)
self.status_message = _('Drug form is missing.')
self._PRW_preparation.SetFocus()
else:
self._PRW_preparation.display_as_valid(True)
if self._PRW_unit.GetData() is None:
validity = False
self._PRW_unit.display_as_valid(False)
self.status_message = _('Unit for amount is missing.')
self._PRW_unit.SetFocus()
else:
self._PRW_unit.display_as_valid(True)
if self._TCTRL_amount.GetValue().strip() == u'':
validity = False
self.display_tctrl_as_valid(tctrl = self._TCTRL_amount, valid = False)
self.status_message = _('Amount is missing.')
self._TCTRL_amount.SetFocus()
else:
self.display_tctrl_as_valid(tctrl = self._TCTRL_amount, valid = True)
if self._PRW_substance.GetData() is None:
val = self._PRW_substance.Value.strip()
if val != u'' and gmATC.exists_as_atc(val):
subst = gmMedication.create_substance(substance = val)
self._PRW_substance.SetText(subst['substance'], subst['pk_substance'])
self._PRW_substance.display_as_valid(True)
else:
validity = False
self._PRW_substance.display_as_valid(False)
self.status_message = _('Substance is missing.')
self._PRW_substance.SetFocus()
else:
self._PRW_substance.display_as_valid(True)
return validity
#----------------------------------------------------------------
def _save_as_new(self):
dose = gmMedication.create_substance_dose (
pk_substance = self._PRW_substance.GetData(),
amount = self._TCTRL_amount.Value.strip(),
unit = self._PRW_unit.GetData(),
dose_unit = self._PRW_dose_unit.GetData()
)
dose_unit = self._PRW_dose_unit.GetValue().strip()
if dose_unit != u'':
dose_unit = u'/' + dose_unit
name = u'%s %s%s%s' % (
self._PRW_substance.GetValue().strip(),
self._TCTRL_amount.Value.strip(),
self._PRW_unit.GetValue().strip(),
dose_unit
)
drug = gmMedication.create_drug_product (
product_name = name,
preparation = self._PRW_preparation.GetValue().strip(),
return_existing = True
)
drug['is_fake_product'] = True
drug.save()
drug.set_substance_doses_as_components(substance_doses = [dose])
self.data = drug
return True
#----------------------------------------------------------------
def _save_as_update(self):
return False
# self.data[''] = self._CHBOX_xxx.GetValue()
# self.data.save()
# return True
#----------------------------------------------------------------
def _refresh_as_new(self):
self._LBL_drug_name.SetLabel(u'')
self._PRW_substance.SetText(u'', None)
self._TCTRL_amount.SetValue(u'')
self._PRW_unit.SetText(u'', None)
self._PRW_dose_unit.SetText(u'', None)
self._PRW_preparation.SetText(u'', None)
#----------------------------------------------------------------
def _refresh_as_new_from_existing(self):
self._refresh_as_new()
#----------------------------------------------------------------
def _refresh_from_existing(self):
pass
#----------------------------------------------------------------
def set_fields(self, fields):
try:
self._PRW_substance.SetText(fields['substance']['value'], fields['substance']['data'])
except KeyError:
_log.error('cannot set field [substance] from <%s>', fields)
#----------------------------------------------------------------
def _on_name_field_modified(self, data=None):
dose_unit = self._PRW_dose_unit.GetValue().strip()
if dose_unit != u'':
dose_unit = u'/' + dose_unit
name = u'%s %s%s%s' % (
self._PRW_substance.GetValue().strip(),
self._TCTRL_amount.Value.strip(),
self._PRW_unit.GetValue().strip(),
dose_unit
)
self._LBL_drug_name.SetLabel(u'"%s"' % name.strip())
#============================================================
# main
#------------------------------------------------------------
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.exit()
if sys.argv[1] != 'test':
sys.exit()
from Gnumed.business import gmPersonSearch
pat = gmPersonSearch.ask_for_patient()
if pat is None:
sys.exit()
gmPerson.set_active_patient(patient = pat)
#----------------------------------------
app = wx.PyWidgetTester(size = (600, 300))
app.SetWidget(cSubstancePhraseWheel, -1)
app.MainLoop()
#manage_substance_intakes()
edit_single_component_generic_drug (
single_entry = True,
fields = {u'substance': {u'value': val, 'data': None}},
return_drug = True
)
|