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 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
|
"""GNUmed medication/substances handling widgets."""
#================================================================
__author__ = "Karsten Hilbert <Karsten.Hilbert@gmx.net>"
__license__ = "GPL v2 or later"
import logging
import sys
import os.path
import decimal
import datetime as pydt
import wx
import wx.grid
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 gmTools
from Gnumed.pycommon import gmDateTime
from Gnumed.pycommon import gmMatchProvider
from Gnumed.pycommon import gmI18N
from Gnumed.pycommon import gmPrinting
from Gnumed.pycommon import gmCfg2
from Gnumed.pycommon import gmNetworkTools
from Gnumed.business import gmPerson
from Gnumed.business import gmATC
from Gnumed.business import gmPraxis
from Gnumed.business import gmMedication
from Gnumed.business import gmForms
from Gnumed.business import gmStaff
from Gnumed.business import gmDocuments
from Gnumed.business import gmLOINC
from Gnumed.business import gmClinicalRecord
from Gnumed.business import gmClinicalCalculator
from Gnumed.business import gmPathLab
from Gnumed.wxpython import gmGuiHelpers
from Gnumed.wxpython import gmRegetMixin
from Gnumed.wxpython import gmAuthWidgets
from Gnumed.wxpython import gmEditArea
from Gnumed.wxpython import gmMacro
from Gnumed.wxpython import gmCfgWidgets
from Gnumed.wxpython import gmListWidgets
from Gnumed.wxpython import gmPhraseWheel
from Gnumed.wxpython import gmFormWidgets
from Gnumed.wxpython import gmAllergyWidgets
from Gnumed.wxpython import gmDocumentWidgets
_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 = gmMedication.drug_data_source_interfaces.keys(),
columns = [_('Drug data source')],
data = gmMedication.drug_data_source_interfaces.keys(),
caption = _('Configuring default drug data source')
)
#============================================================
def get_drug_database(parent = 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 = gmMedication.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 = gmMedication.drug_data_source_interfaces[default_db]()
except KeyError:
_log.error('still faulty default drug data source configuration: %s', default_db)
return None
pat = gmPerson.gmCurrentPatient()
if pat.connected:
drug_db.patient = pat
return drug_db
#============================================================
def jump_to_drug_database():
dbcfg = gmCfg.cCfgSQL()
drug_db = get_drug_database()
if drug_db is None:
return
drug_db.switch_to_frontend(blocking = False)
#============================================================
def jump_to_ifap(import_drugs=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 = open(transfer_file, 'w+b').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 = open(transfer_file, 'rb') # FIXME: encoding
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 = ';'
)
pat = gmPerson.gmCurrentPatient()
emr = pat.get_emr()
# 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
#============================================================
# ATC related widgets
#============================================================
def browse_atc_reference(parent=None):
if parent is None:
parent = wx.GetApp().GetTopWindow()
#------------------------------------------------------------
def refresh(lctrl):
atcs = gmATC.get_reference_atcs()
items = [ [
a['atc'],
a['term'],
gmTools.coalesce(a['unit'], u''),
gmTools.coalesce(a['administrative_route'], u''),
gmTools.coalesce(a['comment'], u''),
a['version'],
a['lang']
] for a in atcs ]
lctrl.set_string_items(items)
lctrl.set_data(atcs)
#------------------------------------------------------------
gmListWidgets.get_choices_from_list (
parent = parent,
msg = _('\nThe ATC codes as known to GNUmed.\n'),
caption = _('Showing ATC codes.'),
columns = [ u'ATC', _('Term'), _('Unit'), _(u'Route'), _('Comment'), _('Version'), _('Language') ],
single_selection = True,
refresh_callback = refresh
)
#============================================================
def update_atc_reference_data():
dlg = wx.FileDialog (
parent = None,
message = _('Choose an ATC import config file'),
defaultDir = os.path.expanduser(os.path.join('~', 'gnumed')),
defaultFile = '',
wildcard = "%s (*.conf)|*.conf|%s (*)|*" % (_('config files'), _('all files')),
style = wx.OPEN | wx.HIDE_READONLY | wx.FILE_MUST_EXIST
)
result = dlg.ShowModal()
if result == wx.ID_CANCEL:
return
cfg_file = dlg.GetPath()
dlg.Destroy()
conn = gmAuthWidgets.get_dbowner_connection(procedure = _('importing ATC reference data'))
if conn is None:
return False
wx.BeginBusyCursor()
if gmATC.atc_import(cfg_fname = cfg_file, conn = conn):
gmDispatcher.send(signal = 'statustext', msg = _('Successfully imported ATC reference data.'))
else:
gmDispatcher.send(signal = 'statustext', msg = _('Importing ATC reference data failed.'), beep = True)
wx.EndBusyCursor()
return True
#============================================================
class cATCPhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
query = u"""
SELECT DISTINCT ON (label)
atc_code,
label
FROM (
SELECT
code as atc_code,
(code || ': ' || term)
AS label
FROM ref.atc
WHERE
term %(fragment_condition)s
OR
code %(fragment_condition)s
UNION ALL
SELECT
atc_code,
(atc_code || ': ' || description)
AS label
FROM ref.consumable_substance
WHERE
description %(fragment_condition)s
OR
atc_code %(fragment_condition)s
UNION ALL
SELECT
atc_code,
(atc_code || ': ' || description || ' (' || preparation || ')')
AS label
FROM ref.branded_drug
WHERE
description %(fragment_condition)s
OR
atc_code %(fragment_condition)s
-- it would be nice to be able to include clin.vacc_indication but that's hard to do in SQL
) AS candidates
WHERE atc_code IS NOT NULL
ORDER BY label
LIMIT 50"""
mp = gmMatchProvider.cMatchProvider_SQL2(queries = query)
mp.setThresholds(1, 2, 4)
# mp.word_separators = '[ \t=+&:@]+'
self.SetToolTipString(_('Select an ATC (Anatomical-Therapeutic-Chemical) code.'))
self.matcher = mp
self.selection_only = True
#============================================================
# consumable substances widgets
#------------------------------------------------------------
def manage_consumable_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_consumable_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_consumable_substance(substance = substance['pk'])
#------------------------------------------------------------
def refresh(lctrl):
substs = gmMedication.get_consumable_substances(order_by = 'description')
items = [ [
s['description'],
s['amount'],
s['unit'],
gmTools.coalesce(s['atc_code'], u''),
s['pk']
] for s in substs ]
lctrl.set_string_items(items)
lctrl.set_data(substs)
#------------------------------------------------------------
msg = _('\nThese are the consumable substances registered with GNUmed.\n')
gmListWidgets.get_choices_from_list (
parent = parent,
msg = msg,
caption = _('Showing consumable substances.'),
columns = [_('Substance'), _('Amount'), _('Unit'), 'ATC', u'#'],
single_selection = True,
new_callback = edit,
edit_callback = edit,
delete_callback = delete,
refresh_callback = refresh,
left_extra_button = (_('Import'), _('Import consumable substances from a drug database.'), add_from_db)
)
#------------------------------------------------------------
def edit_consumable_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 = cConsumableSubstanceEAPnl(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 consumable substance'), _('Editing consumable substance')))
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
return True
dlg.Destroy()
return False
#============================================================
from Gnumed.wxGladeWidgets import wxgConsumableSubstanceEAPnl
class cConsumableSubstanceEAPnl(wxgConsumableSubstanceEAPnl.wxgConsumableSubstanceEAPnl, gmEditArea.cGenericEditAreaMixin):
def __init__(self, *args, **kwargs):
try:
data = kwargs['substance']
del kwargs['substance']
except KeyError:
data = None
wxgConsumableSubstanceEAPnl.wxgConsumableSubstanceEAPnl.__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_atc.selection_only = False
#----------------------------------------------------------------
# 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)
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._TCTRL_substance.SetFocus()
else:
self._PRW_unit.display_as_valid(valid = True)
if validity is False:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot save consumable substance. Missing essential input.'))
return validity
#----------------------------------------------------------------
def _save_as_new(self):
subst = gmMedication.create_consumable_substance (
substance = self._TCTRL_substance.GetValue().strip(),
atc = self._PRW_atc.GetData(),
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))
)
success, data = subst.save()
if not success:
err, msg = data
_log.error(err)
_log.error(msg)
gmDispatcher.send(signal = 'statustext', msg = _('Cannot save consumable substance. %s') % msg, beep = True)
return False
self.data = subst
return True
#----------------------------------------------------------------
def _save_as_update(self):
self.data['description'] = self._TCTRL_substance.GetValue().strip()
self.data['atc_code'] = self._PRW_atc.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))
success, data = self.data.save()
if not success:
err, msg = data
_log.error(err)
_log.error(msg)
gmDispatcher.send(signal = 'statustext', msg = _('Cannot save consumable substance. %s') % msg, beep = True)
return False
return True
#----------------------------------------------------------------
def _refresh_as_new(self):
self._TCTRL_substance.SetValue(u'')
self._TCTRL_amount.SetValue(u'')
self._PRW_unit.SetText(u'', None)
self._PRW_atc.SetText(u'', None)
self._TCTRL_substance.SetFocus()
#----------------------------------------------------------------
def _refresh_from_existing(self):
self._TCTRL_substance.SetValue(self.data['description'])
self._TCTRL_amount.SetValue(u'%s' % self.data['amount'])
self._PRW_unit.SetText(self.data['unit'], self.data['unit'])
self._PRW_atc.SetText(gmTools.coalesce(self.data['atc_code'], u''), self.data['atc_code'])
self._TCTRL_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 = gmMedication.cConsumableSubstance(aPK_obj = component['pk_consumable_substance'])
return edit_consumable_substance(parent = parent, substance = substance, 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(substance = component['pk_component'])
#------------------------------------------------------------
def refresh(lctrl):
comps = gmMedication.get_drug_components()
items = [ [
u'%s%s' % (c['brand'], gmTools.coalesce(c['atc_brand'], u'', u' [%s]')),
u'%s%s' % (c['substance'], gmTools.coalesce(c['atc_substance'], u'', u' [%s]')),
u'%s %s' % (c['amount'], c['unit']),
c['preparation'],
gmTools.coalesce(c['external_code_brand'], u'', u'%%s [%s]' % c['external_code_type_brand']),
c['pk_component']
] for c in comps ]
lctrl.set_string_items(items)
lctrl.set_data(comps)
#------------------------------------------------------------
msg = _('\nThese are the components in the drug brands known to GNUmed.\n')
gmListWidgets.get_choices_from_list (
parent = parent,
msg = msg,
caption = _('Showing drug brand components.'),
columns = [_('Brand'), _('Substance'), _('Strength'), _('Preparation'), _('Code'), u'#'],
single_selection = True,
#new_callback = edit,
edit_callback = edit,
delete_callback = delete,
refresh_callback = refresh
)
#------------------------------------------------------------
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']:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot edit drug component. It is in use.'), beep = True)
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:
gmDispatcher.send(signal = 'statustext', msg = _('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_consumable_substance'] = 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_brand.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_brand.SetValue(u'%s (%s)' % (self.data['brand'], self.data['preparation']))
self._TCTRL_components.SetValue(u' / '.join(self.data.containing_drug['components']))
details = []
if self.data['atc_brand'] is not None:
details.append(u'ATC: %s' % self.data['atc_brand'])
if self.data['external_code_brand'] is not None:
details.append(u'%s: %s' % (self.data['external_code_type_brand'], self.data['external_code_brand']))
self._TCTRL_codes.SetValue(u'; '.join(details))
self._PRW_substance.SetText(self.data['substance'], self.data['pk_consumable_substance'])
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_brand.SetText(u'', None)
#self._TCTRL_prep.SetValue(u'')
#self._TCTRL_brand_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))
#============================================================
#============================================================
class cSubstancePreparationPhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
query = u"""
(
SELECT DISTINCT ON (list_label)
preparation AS data,
preparation AS list_label,
preparation AS field_label
FROM ref.branded_drug
WHERE preparation %(fragment_condition)s
) UNION (
SELECT DISTINCT ON (list_label)
preparation AS data,
preparation AS list_label,
preparation AS field_label
FROM clin.substance_intake
WHERE preparation %(fragment_condition)s
)
ORDER BY list_label
LIMIT 30"""
mp = gmMatchProvider.cMatchProvider_SQL2(queries = query)
mp.setThresholds(1, 2, 4)
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
self.SetToolTipString(_('The preparation (form) of the substance or brand.'))
self.matcher = mp
self.selection_only = False
#============================================================
class cSubstancePhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
mp = gmMedication.cSubstanceMatchProvider()
mp.setThresholds(1, 2, 4)
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
self.SetToolTipString(_('The substance with optional strength.'))
self.matcher = mp
self.selection_only = False
self.phrase_separators = None
#--------------------------------------------------------
def _data2instance(self):
return gmMedication.cConsumableSubstance(aPK_obj = self.GetData(as_instance = False, can_create = False))
#============================================================
# branded drugs widgets
#------------------------------------------------------------
def manage_components_of_branded_drug(parent=None, brand=None):
if brand is not None:
if brand.is_in_use_by_patients:
gmGuiHelpers.gm_show_info (
aTitle = _('Managing components of a drug'),
aMessage = _(
'Cannot manage the components of the branded drug product\n'
'\n'
' "%s" (%s)\n'
'\n'
'because it is currently taken by patients.\n'
) % (brand['brand'], brand['preparation'])
)
return False
#--------------------------------------------------------
if parent is None:
parent = wx.GetApp().GetTopWindow()
#--------------------------------------------------------
# def manage_substances():
# pass
#--------------------------------------------------------
if brand is None:
msg = _('Pick the substances which are components of this drug.')
right_col = _('Components of drug')
comp_substs = []
else:
right_col = u'%s (%s)' % (brand['brand'], brand['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_substs = [ c.substance for c in brand.components ]
substs = gmMedication.get_consumable_substances(order_by = 'description')
choices = [ u'%s %s %s' % (s['description'], s['amount'], s['unit']) for s in substs ]
picks = [ u'%s %s %s' % (c['description'], c['amount'], c['unit']) for c in comp_substs ]
picker = gmListWidgets.cItemPickerDlg (
parent,
-1,
title = _('Managing components of a drug ...'),
msg = msg
)
picker.set_columns(['Substances'], [right_col])
picker.set_choices(choices = choices, data = substs)
picker.set_picks(picks = picks, data = comp_substs)
# picker.extra_button = (
# _('Substances'),
# _('Manage list of consumable substances'),
# manage_substances
# )
btn_pressed = picker.ShowModal()
substs = picker.get_picks()
picker.Destroy()
if btn_pressed != wx.ID_OK:
return (False, None)
if brand is not None:
brand.set_substances_as_components(substances = substs)
return (True, substs)
#------------------------------------------------------------
def manage_branded_drugs(parent=None, ignore_OK_button=False):
if parent is None:
parent = wx.GetApp().GetTopWindow()
#------------------------------------------------------------
def add_from_db(brand):
drug_db = get_drug_database(parent = parent)
if drug_db is None:
return False
drug_db.import_drugs()
return True
#------------------------------------------------------------
def get_tooltip(brand=None):
tt = u'%s %s\n' % (brand['brand'], brand['preparation'])
tt += u'\n'
tt += u'%s%s%s\n' % (
gmTools.bool2subst(brand.is_vaccine, u'%s, ' % _('Vaccine'), u''),
u'%s, ' % gmTools.bool2subst(brand.is_in_use_by_patients, _('in use'), _('not in use')),
gmTools.bool2subst(brand['is_fake_brand'], _('fake'), u'')
)
tt += gmTools.coalesce(brand['atc'], u'', _('ATC: %s\n'))
tt += gmTools.coalesce(brand['external_code'], u'', u'%s: %%s\n' % brand['external_code_type'])
if brand['components'] is not None:
tt += u'- %s' % u'\n- '.join(brand['components'])
return tt
#------------------------------------------------------------
def edit(brand):
if brand is not None:
if brand.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'
) % (brand['brand'], brand['preparation'])
)
return False
return edit_branded_drug(parent = parent, branded_drug = brand, single_entry = True)
#------------------------------------------------------------
def delete(brand):
if brand.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'
) % (brand['brand'], brand['preparation'])
)
return False
gmMedication.delete_branded_drug(brand = brand['pk_brand'])
return True
#------------------------------------------------------------
def new():
return edit_branded_drug(parent = parent, branded_drug = None, single_entry = False)
#------------------------------------------------------------
def refresh(lctrl):
drugs = gmMedication.get_branded_drugs()
items = [ [
u'%s%s' % (
d['brand'],
gmTools.bool2subst(d['is_fake_brand'], ' (%s)' % _('fake'), u'')
),
d['preparation'],
gmTools.coalesce(d['atc'], u''),
gmTools.coalesce(d['components'], u''),
gmTools.coalesce(d['external_code'], u'', u'%%s [%s]' % d['external_code_type']),
d['pk_brand']
] for d in drugs ]
lctrl.set_string_items(items)
lctrl.set_data(drugs)
#------------------------------------------------------------
msg = _('\nThese are the drug brands known to GNUmed.\n')
gmListWidgets.get_choices_from_list (
parent = parent,
msg = msg,
caption = _('Showing branded drugs.'),
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 brands 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 edit_branded_drug(parent=None, branded_drug=None, single_entry=False):
if branded_drug is not None:
if branded_drug.is_in_use_by_patients:
gmGuiHelpers.gm_show_info (
aTitle = _('Editing drug'),
aMessage = _(
'Cannot edit the branded drug product\n'
'\n'
' "%s" (%s)\n'
'\n'
'because it is currently taken by patients.\n'
) % (branded_drug['brand'], branded_drug['preparation'])
)
return False
if parent is None:
parent = wx.GetApp().GetTopWindow()
#--------------------------------------------
def manage_substances(drug):
manage_consumable_substances(parent = parent)
#--------------------------------------------
ea = cBrandedDrugEAPnl(parent = parent, id = -1)
ea.data = branded_drug
ea.mode = gmTools.coalesce(branded_drug, 'new', 'edit')
dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = single_entry)
dlg.SetTitle(gmTools.coalesce(branded_drug, _('Adding new drug brand'), _('Editing drug brand')))
dlg.left_extra_button = (
_('Substances'),
_('Manage consumable substances'),
manage_substances
)
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
return True
dlg.Destroy()
return False
#============================================================
from Gnumed.wxGladeWidgets import wxgBrandedDrugEAPnl
class cBrandedDrugEAPnl(wxgBrandedDrugEAPnl.wxgBrandedDrugEAPnl, gmEditArea.cGenericEditAreaMixin):
def __init__(self, *args, **kwargs):
try:
data = kwargs['drug']
del kwargs['drug']
except KeyError:
data = None
wxgBrandedDrugEAPnl.wxgBrandedDrugEAPnl.__init__(self, *args, **kwargs)
gmEditArea.cGenericEditAreaMixin.__init__(self)
self.mode = 'new'
self.data = data
if data is not None:
self.mode = 'edit'
self.__component_substances = data.components_as_substances
#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:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot edit drug brand. It is in use.'), beep = True)
return False
validity = True
brand_name = self._PRW_brand.GetValue().strip()
if brand_name == u'':
validity = False
self._PRW_brand.display_as_valid(False)
else:
self._PRW_brand.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_brand(brand_name = brand_name, preparation = preparation)
if drug is not None:
validity = False
self._PRW_brand.display_as_valid(False)
self._PRW_preparation.display_as_valid(False)
gmGuiHelpers.gm_show_error (
title = _('Checking brand data'),
error = _(
'The brand information you entered:\n'
'\n'
' [%s %s]\n'
'\n'
'already exists as a drug product.'
) % (brand_name, preparation)
)
else:
# lacking components ?
self._TCTRL_components.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BACKGROUND))
if len(self.__component_substances) == 0:
wants_empty = gmGuiHelpers.gm_show_question (
title = _('Checking brand 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:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot save branded drug. Invalid or missing essential input.'))
return validity
#----------------------------------------------------------------
def _save_as_new(self):
drug = gmMedication.create_branded_drug (
brand_name = self._PRW_brand.GetValue().strip(),
preparation = gmTools.coalesce (
self._PRW_preparation.GetData(),
self._PRW_preparation.GetValue()
).strip(),
return_existing = True
)
drug['is_fake_brand'] = 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_substances) > 0:
drug.set_substances_as_components(substances = self.__component_substances)
self.data = drug
return True
#----------------------------------------------------------------
def _save_as_update(self):
self.data['brand'] = self._PRW_brand.GetValue().strip()
self.data['preparation'] = gmTools.coalesce (
self._PRW_preparation.GetData(),
self._PRW_preparation.GetValue()
).strip()
self.data['is_fake_brand'] = 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_brand.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_brand.SetFocus()
self.__component_substances = []
#----------------------------------------------------------------
def _refresh_as_new_from_existing(self):
self._refresh_as_new()
#----------------------------------------------------------------
def _refresh_from_existing(self):
self._PRW_brand.SetText(self.data['brand'], self.data['pk_brand'])
self._PRW_preparation.SetText(self.data['preparation'], self.data['preparation'])
self._CHBOX_is_fake.SetValue(self.data['is_fake_brand'])
comps = u''
if self.data['components'] is not None:
comps = u'- %s' % u'\n- '.join(self.data['components'])
self._TCTRL_components.SetValue(comps)
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_brand.SetFocus()
self.__component_substances = self.data.components_as_substances
#----------------------------------------------------------------
# event handler
#----------------------------------------------------------------
def _on_manage_components_button_pressed(self, event):
event.Skip()
if self.mode == 'new_from_existing':
brand = None
else:
brand = self.data
OKed, substs = manage_components_of_branded_drug(parent = self, brand = brand)
if OKed is True:
self.__component_substances = substs
comps = u''
if len(substs) > 0:
comps = u'- %s' % u'\n- '.join([ u'%s %s %s' % (s['description'], s['amount'], s['unit']) for s in substs ])
self._TCTRL_components.SetValue(comps)
#============================================================
class cBrandedDrugPhraseWheel(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.branded_drug
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 brand name of the drug.\n'
'\n'
'Note: a brand 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
#============================================================
# current substance intake widgets
#------------------------------------------------------------
class cSubstanceSchedulePhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
query = u"""
SELECT DISTINCT ON (sched)
schedule as sched,
schedule
FROM clin.substance_intake
WHERE schedule %(fragment_condition)s
ORDER BY sched
LIMIT 50"""
mp = gmMatchProvider.cMatchProvider_SQL2(queries = query)
mp.setThresholds(1, 2, 4)
mp.word_separators = '[ \t=+&:@]+'
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
self.SetToolTipString(_('The schedule for taking this substance.'))
self.matcher = mp
self.selection_only = False
#============================================================
class cSubstanceAimPhraseWheel(gmPhraseWheel.cPhraseWheel):
def __init__(self, *args, **kwargs):
query = u"""
(
SELECT DISTINCT ON (field_label)
aim
AS data,
aim || ' (' || substance || ' ' || amount || ' ' || unit || ')'
AS list_label,
aim
AS field_label
FROM clin.v_substance_intakes
WHERE
aim %(fragment_condition)s
%(ctxt_substance)s
) UNION (
SELECT DISTINCT ON (field_label)
aim
AS data,
aim || ' (' || substance || ' ' || amount || ' ' || unit || ')'
AS list_label,
aim
AS field_label
FROM clin.v_substance_intakes
WHERE
aim %(fragment_condition)s
)
ORDER BY list_label
LIMIT 30"""
context = {'ctxt_substance': {
'where_part': u'AND substance = %(substance)s',
'placeholder': u'substance'
}}
mp = gmMatchProvider.cMatchProvider_SQL2(queries = query, context = context)
mp.setThresholds(1, 2, 4)
#mp.word_separators = '[ \t=+&:@]+'
gmPhraseWheel.cPhraseWheel.__init__(self, *args, **kwargs)
self.SetToolTipString(_('The medical aim for consuming this substance.'))
self.matcher = mp
self.selection_only = False
#============================================================
def turn_substance_intake_into_allergy(parent=None, intake=None, emr=None):
if intake['is_currently_active']:
intake['discontinued'] = gmDateTime.pydt_now_here()
if intake['discontinue_reason'] is None:
intake['discontinue_reason'] = u'%s %s' % (_('not tolerated:'), _('discontinued due to allergy or intolerance'))
else:
if not intake['discontinue_reason'].startswith(_('not tolerated:')):
intake['discontinue_reason'] = u'%s %s' % (_('not tolerated:'), intake['discontinue_reason'])
if not intake.save():
return False
allg = intake.turn_into_allergy(encounter_id = emr.active_encounter['pk_encounter'])
brand = intake.containing_drug
if brand is not None:
comps = [ c['substance'] for c in brand.components ]
if len(comps) > 1:
gmGuiHelpers.gm_show_info (
aTitle = _(u'Documented an allergy'),
aMessage = _(
u'An allergy was documented against the substance:\n'
u'\n'
u' [%s]\n'
u'\n'
u'This substance was taken with the multi-component brand:\n'
u'\n'
u' [%s (%s)]\n'
u'\n'
u'Note that ALL components of this brand were discontinued.'
) % (
intake['substance'],
intake['brand'],
u' & '.join(comps)
)
)
if parent is None:
parent = wx.GetApp().GetTopWindow()
dlg = gmAllergyWidgets.cAllergyManagerDlg(parent = parent, id = -1)
dlg.ShowModal()
return True
#============================================================
def manage_substance_intakes(parent=None, emr=None):
if parent is None:
parent = wx.GetApp().GetTopWindow()
if emr is None:
emr = gmPerson.gmCurrentPatient().emr
# #------------------------------------------------------------
# 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_consumable_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_consumable_substance(substance = substance['pk'])
#------------------------------------------------------------
def get_tooltip(intake=None):
return intake.format(one_line = False, show_all_brand_components = True)
#------------------------------------------------------------
def refresh(lctrl):
intakes = emr.get_current_substance_intakes (
include_inactive = False,
include_unapproved = True,
order_by = u'substance, brand, started'
)
items = []
for i in intakes:
started = i.medically_formatted_start
items.append ([
u'%s%s %s %s %s%s' % (
i['substance'],
gmTools.coalesce(i['brand'], u'', u' (%s)'),
i['amount'],
i['unit'],
i['preparation'],
gmTools.coalesce(i['external_code_brand'], u'', u' [%s::%s]' % (i['external_code_type_brand'], i['external_code_brand']))
),
u'%s%s%s' % (
started,
gmTools.coalesce(i['schedule'], u'', u' %%s %s' % gmTools.u_right_arrow),
gmTools.coalesce(i['duration'], u'', u' %s')
),
u'%s' % (
gmTools.bool2subst (
i['intake_is_approved_of'],
u'',
_('disapproved')
)
)
])
lctrl.set_string_items(items)
lctrl.set_data(intakes)
#------------------------------------------------------------
msg = _('Substances consumed by the patient:')
return gmListWidgets.get_choices_from_list (
parent = parent,
msg = msg,
caption = _('Showing consumable substances.'),
columns = [ _('Intake'), _('Application'), _('Status') ],
single_selection = False,
# new_callback = edit,
# edit_callback = edit,
# delete_callback = delete,
refresh_callback = refresh,
list_tooltip_callback = get_tooltip
# ,left_extra_button = (_('Import'), _('Import consumable substances from a drug database.'), add_from_db)
)
#============================================================
from Gnumed.wxGladeWidgets import wxgCurrentMedicationEAPnl
class cSubstanceIntakeEAPnl(wxgCurrentMedicationEAPnl.wxgCurrentMedicationEAPnl, gmEditArea.cGenericEditAreaMixin):
def __init__(self, *args, **kwargs):
try:
data = kwargs['substance']
del kwargs['substance']
except KeyError:
data = None
self.calc = gmClinicalCalculator.cClinicalCalculator()
wxgCurrentMedicationEAPnl.wxgCurrentMedicationEAPnl.__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_component.add_callback_on_lose_focus(callback = self._on_leave_component)
self._PRW_component.selection_only = True
self._PRW_substance.add_callback_on_lose_focus(callback = self._on_leave_substance)
self._PRW_substance.selection_only = True
self._PRW_duration.display_accuracy = gmDateTime.acc_days
self._PRW_aim.add_callback_on_set_focus(callback = self._on_enter_aim)
#----------------------------------------------------------------
def __refresh_allergies(self):
curr_pat = gmPerson.gmCurrentPatient()
emr = curr_pat.emr
state = emr.allergy_state
if state['last_confirmed'] is None:
confirmed = _('never')
else:
confirmed = gmDateTime.pydt_strftime(state['last_confirmed'], '%Y %b %d')
msg = _(u'%s, last confirmed %s\n') % (state.state_string, confirmed)
msg += gmTools.coalesce(state['comment'], u'', _('Comment (%s): %%s\n') % state['modified_by'])
tt = u''
allgs = emr.get_allergies()
if len(allgs) > 0:
msg += u'\n'
for allergy in allgs:
msg += u'%s: %s (%s)\n' % (
allergy['descriptor'],
allergy['l10n_type'],
gmTools.bool2subst(allergy['definite'], _('definite'), _('suspected'), u'?')
)
tt += u'%s: %s\n' % (
allergy['descriptor'],
gmTools.coalesce(allergy['reaction'], _('reaction not recorded'))
)
if len(allgs) > 0:
msg += u'\n'
tt += u'\n'
gfr = emr.get_most_recent_results(loinc = gmLOINC.LOINC_gfr_quantity, no_of_results = 1)
if gfr is None:
self.calc.patient = curr_pat
gfr = self.calc.eGFR
if gfr.numeric_value is None:
msg += _('GFR: unknown')
else:
msg += gfr.message
tt += gfr.format (
left_margin = 0,
width = 50,
eol = u'\n',
with_formula = True,
with_warnings = True,
with_variables = False,
with_sub_results = True,
return_list = False
)
else:
msg += u'%s: %s %s (%s)\n' % (
gfr['unified_abbrev'],
gfr['unified_val'],
gmTools.coalesce(gfr['abnormality_indicator'], u'', u' (%s)'),
gmDateTime.pydt_strftime (
gfr['clin_when'],
format = '%Y %b %d'
)
)
tt += _('GFR reported by path lab')
self._LBL_allergies.SetLabel(msg)
self._LBL_allergies.SetToolTipString(tt)
#----------------------------------------------------------------
# generic Edit Area mixin API
#----------------------------------------------------------------
def _valid_for_save(self):
validity = True
has_component = (self._PRW_component.GetData() is not None)
has_substance = (self._PRW_substance.GetValue().strip() != u'')
self._PRW_component.display_as_valid(True)
# cannot add duplicate components
if self.mode == 'new':
msg = _(
'The patient is already taking\n'
'\n'
' %s\n'
'\n'
'You will want to adjust the schedule\n'
'rather than document the intake twice.'
)
title = _('Adding substance intake entry')
if has_component:
emr = gmPerson.gmCurrentPatient().get_emr()
if emr.substance_intake_exists(pk_component = self._PRW_component.GetData()):
gmGuiHelpers.gm_show_warning (
aTitle = title,
aMessage = msg % self._PRW_component.GetValue().strip()
)
self._PRW_component.display_as_valid(False)
validity = False
pk_substance = self._PRW_substance.GetData()
if pk_substance is not None:
emr = gmPerson.gmCurrentPatient().get_emr()
if emr.substance_intake_exists(pk_substance = pk_substance):
gmGuiHelpers.gm_show_warning (
aTitle = title,
aMessage = msg % self._PRW_substance.GetValue().strip()
)
self._PRW_substance.display_as_valid(False)
validity = False
# must have either brand or substance
if (has_component is False) and (has_substance is False):
self._PRW_substance.display_as_valid(False)
self._PRW_component.display_as_valid(False)
validity = False
else:
self._PRW_substance.display_as_valid(True)
# brands already have a preparation, so only required for substances
if not has_component:
if self._PRW_preparation.GetValue().strip() == u'':
self._PRW_preparation.display_as_valid(False)
validity = False
else:
self._PRW_preparation.display_as_valid(True)
# episode must be set if intake is to be approved of
if self._CHBOX_approved.IsChecked():
if self._PRW_episode.GetValue().strip() == u'':
self._PRW_episode.display_as_valid(False)
validity = False
else:
self._PRW_episode.display_as_valid(True)
if self._PRW_duration.GetValue().strip() in [u'', gmTools.u_infinity]:
self._PRW_duration.display_as_valid(True)
else:
if self._PRW_duration.GetData() is None:
# no data ...
if gmDateTime.str2interval(self._PRW_duration.GetValue()) is None:
self._PRW_duration.display_as_valid(False)
validity = False
# ... but valid string
else:
self._PRW_duration.display_as_valid(True)
# has data
else:
self._PRW_duration.display_as_valid(True)
# started must exist
started = self._DP_started.GetData()
if started is None:
self._DP_started.display_as_valid(False)
validity = False
else:
self._DP_started.display_as_valid(True)
if validity is False:
gmDispatcher.send(signal = 'statustext', msg = _('Input incomplete/invalid for saving as substance intake.'))
# discontinued must be "< now()" AND "> started" if at all
discontinued = self._DP_discontinued.GetData()
if discontinued is not None:
now = gmDateTime.pydt_now_here().replace (
hour = 23,
minute = 59,
second = 59,
microsecond = 111111
)
# not in the future
if discontinued > now:
self._DP_discontinued.display_as_valid(False)
validity = False
gmDispatcher.send(signal = 'statustext', msg = _('Discontinued (%s) in the future (now: %s)!') % (discontinued, now))
else:
started = started.replace (
hour = 0,
minute = 0,
second = 0,
microsecond = 1
)
# and not before it was started
if started > discontinued:
self._DP_started.display_as_valid(False)
self._DP_discontinued.display_as_valid(False)
validity = False
gmDispatcher.send(signal = 'statustext', msg = _('Discontinued (%s) before started (%s) !') % (discontinued, started))
else:
self._DP_started.display_as_valid(True)
self._DP_discontinued.display_as_valid(True)
return validity
#----------------------------------------------------------------
def _save_as_new(self):
epi = self._PRW_episode.GetData()
if epi is None:
# create new episode, Jim wants it to auto-open
epi = self._PRW_episode.GetData(can_create = True, is_open = True)
emr = gmPerson.gmCurrentPatient().get_emr()
if self._PRW_substance.GetData() is None:
# auto-creates all components as intakes
intake = emr.add_substance_intake (
pk_component = self._PRW_component.GetData(),
episode = epi
)
else:
intake = emr.add_substance_intake (
pk_substance = self._PRW_substance.GetData(),
episode = epi,
preparation = self._PRW_preparation.GetValue().strip()
)
if intake is None:
gmDispatcher.send('statustext', msg = _('Cannot add duplicate of (maybe inactive) substance intake.'), beep = True)
return False
intake['started'] = self._DP_started.GetData()
intake['discontinued'] = self._DP_discontinued.GetData()
if intake['discontinued'] is None:
intake['discontinue_reason'] = None
else:
intake['discontinue_reason'] = self._PRW_discontinue_reason.GetValue().strip()
intake['schedule'] = self._PRW_schedule.GetValue().strip()
intake['aim'] = self._PRW_aim.GetValue().strip()
intake['notes'] = self._PRW_notes.GetValue().strip()
intake['is_long_term'] = self._CHBOX_long_term.IsChecked()
intake['intake_is_approved_of'] = self._CHBOX_approved.IsChecked()
if self._PRW_duration.GetValue().strip() in [u'', gmTools.u_infinity]:
intake['duration'] = None
else:
if self._PRW_duration.GetData() is None:
intake['duration'] = gmDateTime.str2interval(self._PRW_duration.GetValue())
else:
intake['duration'] = self._PRW_duration.GetData()
intake.save()
self.data = intake
return True
#----------------------------------------------------------------
def _save_as_update(self):
# auto-applies to all components of a multi-component drug if any:
self.data['started'] = self._DP_started.GetData()
self.data['discontinued'] = self._DP_discontinued.GetData()
if self.data['discontinued'] is None:
self.data['discontinue_reason'] = None
else:
self.data['discontinue_reason'] = self._PRW_discontinue_reason.GetValue().strip()
self.data['schedule'] = self._PRW_schedule.GetValue()
self.data['is_long_term'] = self._CHBOX_long_term.IsChecked()
self.data['intake_is_approved_of'] = self._CHBOX_approved.IsChecked()
if self._PRW_duration.GetValue().strip() in [u'', gmTools.u_infinity]:
self.data['duration'] = None
else:
if self._PRW_duration.GetData() is None:
self.data['duration'] = gmDateTime.str2interval(self._PRW_duration.GetValue())
else:
self.data['duration'] = self._PRW_duration.GetData()
# applies to non-component substances only
self.data['preparation'] = self._PRW_preparation.GetValue()
# per-component
self.data['aim'] = self._PRW_aim.GetValue()
self.data['notes'] = self._PRW_notes.GetValue()
epi = self._PRW_episode.GetData()
if epi is None:
# create new episode, Jim wants it to auto-open
epi = self._PRW_episode.GetData(can_create = True, is_open = True)
self.data['pk_episode'] = epi
self.data.save()
return True
#----------------------------------------------------------------
def _refresh_as_new(self):
self._PRW_component.SetText(u'', None)
self._LBL_component.Enable(True)
self._PRW_component.Enable(True)
self._TCTRL_brand_ingredients.SetValue(u'')
self._TCTRL_brand_ingredients.SetToolTipString(u'')
self._LBL_or.Enable(True)
self._PRW_substance.SetText(u'', None)
self._PRW_substance.Enable(True)
self._PRW_preparation.SetText(u'', None)
self._PRW_preparation.Enable(True)
self._PRW_schedule.SetText(u'', None)
self._PRW_duration.SetText(u'', None)
self._PRW_aim.SetText(u'', None)
self._PRW_notes.SetText(u'', None)
self._PRW_episode.SetText(u'', None)
self._CHBOX_long_term.SetValue(False)
self._CHBOX_approved.SetValue(True)
self._DP_started.SetData(gmDateTime.pydt_now_here())
self._DP_discontinued.SetData(None)
self._PRW_discontinue_reason.SetValue(u'')
self.__refresh_allergies()
self._PRW_component.SetFocus()
#----------------------------------------------------------------
def _refresh_from_existing(self):
self._TCTRL_brand_ingredients.SetValue(u'')
self._TCTRL_brand_ingredients.SetToolTipString(u'')
if self.data['pk_brand'] is None:
self.__refresh_from_existing_substance()
else:
self.__refresh_from_existing_component()
# no editing of substance or component
self._LBL_component.Enable(False)
self._PRW_component.Enable(False)
self._LBL_or.Enable(False)
self._PRW_substance.Enable(False)
if self.data['is_long_term']:
self._CHBOX_long_term.SetValue(True)
self._PRW_duration.Enable(False)
self._PRW_duration.SetText(gmTools.u_infinity, None)
self._BTN_discontinued_as_planned.Enable(False)
else:
self._CHBOX_long_term.SetValue(False)
self._PRW_duration.Enable(True)
self._BTN_discontinued_as_planned.Enable(True)
self._PRW_duration.SetData(self.data['duration'])
# if self.data['duration'] is None:
# self._PRW_duration.SetText(u'', None)
# else:
# self._PRW_duration.SetText(gmDateTime.format_interval(self.data['duration'], gmDateTime.acc_days), self.data['duration'])
self._PRW_aim.SetText(gmTools.coalesce(self.data['aim'], u''), self.data['aim'])
self._PRW_notes.SetText(gmTools.coalesce(self.data['notes'], u''), self.data['notes'])
self._PRW_episode.SetData(self.data['pk_episode'])
self._PRW_schedule.SetText(gmTools.coalesce(self.data['schedule'], u''), self.data['schedule'])
self._CHBOX_approved.SetValue(self.data['intake_is_approved_of'])
self._DP_started.SetData(self.data['started'])
self._DP_discontinued.SetData(self.data['discontinued'])
self._PRW_discontinue_reason.SetValue(gmTools.coalesce(self.data['discontinue_reason'], u''))
if self.data['discontinued'] is not None:
self._PRW_discontinue_reason.Enable()
self.__refresh_allergies()
self._PRW_schedule.SetFocus()
#----------------------------------------------------------------
def __refresh_from_existing_substance(self):
self._LBL_component.Enable(False)
self._PRW_component.Enable(False)
self._PRW_component.SetText(u'', None)
self._PRW_component.display_as_valid(True)
self._LBL_or.Enable(False)
# disable for 1.3 since we aren't saving
# the change which in combination spells
# doom for patient safety
#self._PRW_substance.Enable(True)
self._PRW_substance.Enable(False)
self._PRW_substance.SetText (
u'%s %s %s' % (self.data['substance'], self.data['amount'], self.data['unit']),
self.data['pk_substance']
)
self._PRW_preparation.SetText(self.data['preparation'], self.data['preparation'])
# see above
self._PRW_preparation.Enable(True)
self._PRW_preparation.Enable(False)
#----------------------------------------------------------------
def __refresh_from_existing_component(self):
self._LBL_component.Enable(True)
self._PRW_component.Enable(True)
self._PRW_component.SetText (
u'%s %s %s (%s)' % (self.data['substance'], self.data['amount'], self.data['unit'], self.data['brand']),
self.data['pk_drug_component']
)
brand = gmMedication.cBrandedDrug(aPK_obj = self.data['pk_brand'])
if brand['components'] is not None:
self._TCTRL_brand_ingredients.SetValue(u'; '.join(brand['components']))
tt = u'%s:\n\n- %s' % (
self.data['brand'],
u'\n- '.join(brand['components'])
)
self._TCTRL_brand_ingredients.SetToolTipString(tt)
self._LBL_or.Enable(False)
self._LBL_substance.Enable(False)
self._PRW_substance.SetText(u'', None)
self._PRW_substance.display_as_valid(True)
self._PRW_preparation.SetText(self.data['preparation'], self.data['preparation'])
self._PRW_preparation.Enable(False)
#----------------------------------------------------------------
def _refresh_as_new_from_existing(self):
self._refresh_as_new()
self._PRW_episode.SetData(self.data['pk_episode'])
self._DP_started.SetData(self.data['started'])
self._PRW_component.SetFocus()
#----------------------------------------------------------------
# event handlers
#----------------------------------------------------------------
def _on_leave_component(self):
if self._PRW_component.GetData() is None:
self._LBL_or.Enable(True)
self._PRW_component.SetText(u'', None)
self._LBL_substance.Enable(True)
self._PRW_substance.Enable(True)
self._LBL_preparation.Enable(True)
self._PRW_preparation.Enable(True)
#self._PRW_preparation.SetText(u'', None)
self._TCTRL_brand_ingredients.SetValue(u'')
self._TCTRL_brand_ingredients.SetToolTipString(u'')
else:
self._LBL_or.Enable(False)
self._LBL_substance.Enable(False)
self._PRW_substance.SetText(u'', None)
self._PRW_substance.display_as_valid(True)
self._PRW_substance.Enable(False)
self._LBL_preparation.Enable(False)
self._PRW_preparation.Enable(False)
comp = gmMedication.cDrugComponent(aPK_obj = self._PRW_component.GetData())
self._PRW_preparation.SetText(comp['preparation'], comp['preparation'])
brand = comp.containing_drug
if brand['components'] is not None:
self._TCTRL_brand_ingredients.SetValue(u'; '.join(brand['components']))
tt = u'%s:\n\n- %s' % (
brand['brand'],
u'\n- '.join(brand['components'])
)
self._TCTRL_brand_ingredients.SetToolTipString(tt)
#----------------------------------------------------------------
def _on_leave_substance(self):
if self._PRW_substance.GetData() is None:
self._LBL_or.Enable(True)
self._LBL_component.Enable(True)
self._PRW_component.Enable(True)
self._PRW_substance.SetText(u'', None)
else:
self._LBL_or.Enable(False)
self._LBL_component.Enable(False)
self._PRW_component.SetText(u'', None)
self._PRW_component.display_as_valid(True)
self._PRW_component.Enable(False)
self._LBL_preparation.Enable(True)
self._PRW_preparation.Enable(True)
self._TCTRL_brand_ingredients.SetValue(u'')
self._TCTRL_brand_ingredients.SetToolTipString(u'')
#----------------------------------------------------------------
def _on_enter_aim(self):
# when a drug component/substance is selected (that is, when .GetData()
# returns not None) then we do not want to use the GetValue().strip()
# result because that will also have amount and unit appended, hence
# create the real component or substance instance and take the canonical
# substance name from there
subst = self._PRW_component.GetValue().strip()
if subst != u'':
comp = self._PRW_component.GetData(as_instance = True)
if comp is None:
self._PRW_aim.set_context(context = u'substance', val = subst)
return
self._PRW_aim.set_context(context = u'substance', val = comp['substance'])
return
subst = self._PRW_substance.GetValue().strip()
if subst == u'':
self._PRW_aim.unset_context(context = u'substance')
return
comp = self._PRW_substance.GetData(as_instance = True)
if comp is None:
self._PRW_aim.set_context(context = u'substance', val = subst)
return
self._PRW_aim.set_context(context = u'substance', val = comp['description'])
#----------------------------------------------------------------
def _on_discontinued_date_changed(self, event):
if self._DP_discontinued.GetData() is None:
self._PRW_discontinue_reason.Enable(False)
else:
self._PRW_discontinue_reason.Enable(True)
#----------------------------------------------------------------
def _on_manage_brands_button_pressed(self, event):
manage_branded_drugs(parent = self, ignore_OK_button = True)
#----------------------------------------------------------------
def _on_manage_substances_button_pressed(self, event):
manage_consumable_substances(parent = self)
#----------------------------------------------------------------
def _on_heart_button_pressed(self, event):
gmNetworkTools.open_url_in_browser(url = u'http://qtdrugs.org')
#----------------------------------------------------------------
def _on_kidneys_button_pressed(self, event):
if self._PRW_component.GetData() is not None:
search_term = self._PRW_component.GetData(as_instance = True)
elif self._PRW_substance.GetData() is not None:
search_term = self._PRW_substance.GetData(as_instance = True)
elif self._PRW_component.GetValue().strip() != u'':
search_term = self._PRW_component.GetValue().strip()
else:
search_term = self._PRW_substance.GetValue().strip()
gmNetworkTools.open_url_in_browser(url = gmMedication.drug2renal_insufficiency_url(search_term = search_term))
#----------------------------------------------------------------
def _on_discontinued_as_planned_button_pressed(self, event):
now = gmDateTime.pydt_now_here()
self.__refresh_allergies()
if self.data is None:
return
# do we have a (full) plan ?
if None not in [self.data['started'], self.data['duration']]:
planned_end = self.data['started'] + self.data['duration']
# the plan hasn't ended so [Per plan] can't apply ;-)
if planned_end > now:
return
self._DP_discontinued.SetData(planned_end)
self._PRW_discontinue_reason.Enable(True)
self._PRW_discontinue_reason.SetValue(u'')
return
# we know started but not duration: apparently the plan is to stop today
if self.data['started'] is not None:
# but we haven't started yet so we can't stop
if self.data['started'] > now:
return
self._DP_discontinued.SetData(now)
self._PRW_discontinue_reason.Enable(True)
self._PRW_discontinue_reason.SetValue(u'')
#----------------------------------------------------------------
def _on_chbox_long_term_checked(self, event):
if self._CHBOX_long_term.IsChecked() is True:
self._PRW_duration.Enable(False)
self._BTN_discontinued_as_planned.Enable(False)
self._PRW_discontinue_reason.Enable(False)
else:
self._PRW_duration.Enable(True)
self._BTN_discontinued_as_planned.Enable(True)
self._PRW_discontinue_reason.Enable(True)
self.__refresh_allergies()
#----------------------------------------------------------------
def turn_into_allergy(self, data=None):
if not self.save():
return False
return turn_substance_intake_into_allergy (
parent = self,
intake = self.data,
emr = gmPerson.gmCurrentPatient().get_emr()
)
#============================================================
def delete_substance_intake(parent=None, substance=None):
subst = gmMedication.cSubstanceIntakeEntry(aPK_obj = substance)
msg = _(
'\n'
'[%s]\n'
'\n'
'It may be prudent to edit (before deletion) the details\n'
'of this substance intake entry so as to leave behind\n'
'some indication of why it was deleted.\n'
) % subst.format()
dlg = gmGuiHelpers.c3ButtonQuestionDlg (
parent,
-1,
caption = _('Deleting medication / substance intake'),
question = msg,
button_defs = [
{'label': _('&Edit'), 'tooltip': _('Allow editing of substance intake entry before deletion.'), 'default': True},
{'label': _('&Delete'), 'tooltip': _('Delete immediately without editing first.')},
{'label': _('&Cancel'), 'tooltip': _('Abort. Do not delete or edit substance intake entry.')}
]
)
edit_first = dlg.ShowModal()
dlg.Destroy()
if edit_first == wx.ID_CANCEL:
return
if edit_first == wx.ID_YES:
edit_intake_of_substance(parent = parent, substance = subst)
delete_it = gmGuiHelpers.gm_show_question (
aMessage = _('Now delete substance intake entry ?'),
aTitle = _('Deleting medication / substance intake')
)
else:
delete_it = True
if not delete_it:
return
gmMedication.delete_substance_intake(substance = substance)
#------------------------------------------------------------
def edit_intake_of_substance(parent = None, substance=None):
ea = cSubstanceIntakeEAPnl(parent = parent, id = -1, substance = substance)
dlg = gmEditArea.cGenericEditAreaDlg2(parent = parent, id = -1, edit_area = ea, single_entry = (substance is not None))
dlg.SetTitle(gmTools.coalesce(substance, _('Adding medication/non-medication substance intake'), _('Editing medication/non-medication substance intake')))
dlg.left_extra_button = (
_('Allergy'),
_('Document an allergy against this substance.'),
ea.turn_into_allergy
)
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
return True
dlg.Destroy()
return False
#============================================================
# current substances grid
#------------------------------------------------------------
def configure_medication_list_template(parent=None):
if parent is None:
parent = wx.GetApp().GetTopWindow()
template = gmFormWidgets.manage_form_templates (
parent = parent,
template_types = ['current medication list']
)
option = u'form_templates.medication_list'
if template is None:
gmDispatcher.send(signal = 'statustext', msg = _('No medication list template configured.'), beep = True)
return None
if template['engine'] not in [u'L', u'X', u'T']:
gmDispatcher.send(signal = 'statustext', msg = _('No medication list template configured.'), beep = True)
return None
dbcfg = gmCfg.cCfgSQL()
dbcfg.set (
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
option = option,
value = u'%s - %s' % (template['name_long'], template['external_version'])
)
return template
#------------------------------------------------------------
def print_medication_list(parent=None):
if parent is None:
parent = wx.GetApp().GetTopWindow()
# 1) get template
dbcfg = gmCfg.cCfgSQL()
option = u'form_templates.medication_list'
template = dbcfg.get2 (
option = option,
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = 'user'
)
if template is None:
template = configure_medication_list_template(parent = parent)
if template is None:
gmGuiHelpers.gm_show_error (
aMessage = _('There is no medication list template configured.'),
aTitle = _('Printing medication list')
)
return False
else:
try:
name, ver = template.split(u' - ')
except:
_log.exception('problem splitting medication list template name [%s]', template)
gmDispatcher.send(signal = 'statustext', msg = _('Problem loading medication list template.'), beep = True)
return False
template = gmForms.get_form_template(name_long = name, external_version = ver)
if template is None:
gmGuiHelpers.gm_show_error (
aMessage = _('Cannot load medication list template [%s - %s]') % (name, ver),
aTitle = _('Printing medication list')
)
return False
# 2) process template
meds_list = gmFormWidgets.generate_form_from_template (
parent = parent,
template = template,
edit = False
)
if meds_list is None:
return False
# 3) print template
return gmFormWidgets.act_on_generated_forms (
parent = parent,
forms = [meds_list],
jobtype = 'medication_list',
#episode_name = u'administrative',
episode_name = gmMedication.DEFAULT_MEDICATION_HISTORY_EPISODE,
progress_note = _('generated medication list document'),
review_copy_as_normal = True
)
#------------------------------------------------------------
def configure_prescription_template(parent=None):
if parent is None:
parent = wx.GetApp().GetTopWindow()
template = gmFormWidgets.manage_form_templates (
parent = parent,
msg = _('Select the default prescription template:'),
template_types = ['prescription', 'current medication list']
)
if template is None:
gmDispatcher.send(signal = 'statustext', msg = _('No prescription template configured.'), beep = True)
return None
if template['engine'] not in [u'L', u'X', u'T']:
gmDispatcher.send(signal = 'statustext', msg = _('No prescription template configured.'), beep = True)
return None
option = u'form_templates.prescription'
dbcfg = gmCfg.cCfgSQL()
dbcfg.set (
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
option = option,
value = u'%s - %s' % (template['name_long'], template['external_version'])
)
return template
#------------------------------------------------------------
def get_prescription_template(parent=None):
if parent is None:
parent = wx.GetApp().GetTopWindow()
dbcfg = gmCfg.cCfgSQL()
option = u'form_templates.prescription'
template_name = dbcfg.get2 (
option = option,
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = 'user'
)
if template_name is None:
template = configure_prescription_template(parent = parent)
if template is None:
gmGuiHelpers.gm_show_error (
aMessage = _('There is no prescription template configured.'),
aTitle = _('Printing prescription')
)
return None
return template
try:
name, ver = template_name.split(u' - ')
except:
_log.exception('problem splitting prescription template name [%s]', template_name)
gmDispatcher.send(signal = 'statustext', msg = _('Problem loading prescription template.'), beep = True)
return False
template = gmForms.get_form_template(name_long = name, external_version = ver)
if template is None:
gmGuiHelpers.gm_show_error (
aMessage = _('Cannot load prescription template [%s - %s]') % (name, ver),
aTitle = _('Printing prescription')
)
return None
return template
#------------------------------------------------------------
def print_prescription(parent=None, emr=None):
# 1) get template
rx_template = get_prescription_template(parent = parent)
if rx_template is None:
return False
# 2) process template
rx = gmFormWidgets.generate_form_from_template (
parent = parent,
template = rx_template,
edit = False
)
if rx is None:
return False
# 3) print template
return gmFormWidgets.act_on_generated_forms (
parent = parent,
forms = [rx],
jobtype = u'prescription',
#episode_name = u'administrative',
episode_name = gmMedication.DEFAULT_MEDICATION_HISTORY_EPISODE,
progress_note = _('generated prescription'),
review_copy_as_normal = True
)
#------------------------------------------------------------
def prescribe_drugs(parent=None, emr=None):
dbcfg = gmCfg.cCfgSQL()
rx_mode = dbcfg.get2 (
option = u'horst_space.default_prescription_mode',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = u'user',
default = u'form' # set to 'database' to access database
)
if parent is None:
parent = wx.GetApp().GetTopWindow()
if rx_mode == 'form':
return print_prescription(parent = parent, emr = emr)
if rx_mode == 'database':
drug_db = get_drug_database()
if drug_db is None:
return
drug_db.reviewer = gmStaff.gmCurrentProvider()
prescribed_drugs = drug_db.prescribe()
update_substance_intake_list_from_prescription (
parent = parent,
prescribed_drugs = prescribed_drugs,
emr = emr
)
#------------------------------------------------------------
def update_substance_intake_list_from_prescription(parent=None, prescribed_drugs=None, emr=None):
if len(prescribed_drugs) == 0:
return
curr_brands = [ i['pk_brand'] for i in emr.get_current_substance_intakes() if i['pk_brand'] is not None ]
new_drugs = []
for drug in prescribed_drugs:
if drug['pk_brand'] not in curr_brands:
new_drugs.append(drug)
if len(new_drugs) == 0:
return
if parent is None:
parent = wx.GetApp().GetTopWindow()
dlg = gmListWidgets.cItemPickerDlg (
parent,
-1,
msg = _(
'These brands have been prescribed but are not listed\n'
'in the current medication list of this patient.\n'
'\n'
'Please select those you want added to the medication list.'
)
)
dlg.set_columns (
columns = [_('Newly prescribed drugs')],
columns_right = [_('Add to medication list')]
)
choices = [ (u'%s %s (%s)' % (d['brand'], d['preparation'], u'; '.join(d['components']))) for d in new_drugs ]
dlg.set_choices (
choices = choices,
data = new_drugs
)
dlg.ShowModal()
drugs2add = dlg.get_picks()
dlg.Destroy()
if drugs2add is None:
return
if len(drugs2add) == 0:
return
for drug in drugs2add:
# only add first component since all other components get added by a trigger ...
intake = emr.add_substance_intake (
pk_component = drug['pk_components'][0],
episode = emr.add_episode(episode_name = gmMedication.DEFAULT_MEDICATION_HISTORY_EPISODE)['pk_episode'],
)
if intake is None:
continue
intake['intake_is_approved_of'] = True
intake.save()
return
#------------------------------------------------------------
class cCurrentSubstancesGrid(wx.grid.Grid):
"""A grid class for displaying current substance intake.
- does NOT listen to the currently active patient
- thereby it can display any patient at any time
"""
def __init__(self, *args, **kwargs):
wx.grid.Grid.__init__(self, *args, **kwargs)
self.__patient = None
self.__row_data = {}
self.__prev_row = None
self.__prev_tooltip_row = None
self.__prev_cell_0 = None
self.__grouping_mode = u'issue'
self.__filter_show_unapproved = True
self.__filter_show_inactive = True
self.__grouping2col_labels = {
u'issue': [
_('Health issue'),
_('Substance'),
_('Strength'),
_('Schedule'),
_('Started'),
_('Duration / Until'),
_('Brand'),
_('Advice')
],
u'brand': [
_('Brand'),
_('Schedule'),
_('Substance'),
_('Strength'),
_('Started'),
_('Duration / Until'),
_('Health issue'),
_('Advice')
],
u'episode': [
_('Episode'),
_('Substance'),
_('Strength'),
_('Schedule'),
_('Started'),
_('Duration / Until'),
_('Brand'),
_('Advice')
]
}
self.__grouping2order_by_clauses = {
u'issue': u'pk_health_issue nulls first, substance, started',
u'episode': u'pk_health_issue nulls first, episode, substance, started',
u'brand': u'brand nulls last, substance, started'
}
self.__init_ui()
self.__register_events()
#------------------------------------------------------------
# external API
#------------------------------------------------------------
def get_selected_cells(self):
sel_block_top_left = self.GetSelectionBlockTopLeft()
sel_block_bottom_right = self.GetSelectionBlockBottomRight()
sel_cols = self.GetSelectedCols()
sel_rows = self.GetSelectedRows()
selected_cells = []
# individually selected cells (ctrl-click)
selected_cells += self.GetSelectedCells()
# selected rows
selected_cells += list (
(row, col)
for row in sel_rows
for col in xrange(self.GetNumberCols())
)
# selected columns
selected_cells += list (
(row, col)
for row in xrange(self.GetNumberRows())
for col in sel_cols
)
# selection blocks
for top_left, bottom_right in zip(self.GetSelectionBlockTopLeft(), self.GetSelectionBlockBottomRight()):
selected_cells += [
(row, col)
for row in xrange(top_left[0], bottom_right[0] + 1)
for col in xrange(top_left[1], bottom_right[1] + 1)
]
return set(selected_cells)
#------------------------------------------------------------
def get_selected_rows(self):
rows = {}
for row, col in self.get_selected_cells():
rows[row] = True
return rows.keys()
#------------------------------------------------------------
def get_selected_data(self):
return [ self.__row_data[row] for row in self.get_selected_rows() ]
#------------------------------------------------------------
def repopulate_grid(self):
self.empty_grid()
if self.__patient is None:
return
emr = self.__patient.get_emr()
meds = emr.get_current_substance_intakes (
order_by = self.__grouping2order_by_clauses[self.__grouping_mode],
include_unapproved = self.__filter_show_unapproved,
include_inactive = self.__filter_show_inactive
)
if not meds:
return
self.BeginBatch()
# columns
labels = self.__grouping2col_labels[self.__grouping_mode]
if self.__filter_show_unapproved:
self.AppendCols(numCols = len(labels) + 1)
else:
self.AppendCols(numCols = len(labels))
for col_idx in range(len(labels)):
self.SetColLabelValue(col_idx, labels[col_idx])
if self.__filter_show_unapproved:
#self.SetColLabelValue(len(labels), u'OK?')
self.SetColLabelValue(len(labels), u'')
self.SetColSize(len(labels), 40)
self.AppendRows(numRows = len(meds))
# loop over data
for row_idx in range(len(meds)):
med = meds[row_idx]
self.__row_data[row_idx] = med
if med['is_currently_active'] is True:
atcs = []
if med['atc_substance'] is not None:
atcs.append(med['atc_substance'])
# if med['atc_brand'] is not None:
# atcs.append(med['atc_brand'])
# allg = emr.is_allergic_to(atcs = tuple(atcs), inns = (med['substance'],), brand = med['brand'])
allg = emr.is_allergic_to(atcs = tuple(atcs), inns = (med['substance'],))
if allg not in [None, False]:
attr = self.GetOrCreateCellAttr(row_idx, 0)
if allg['type'] == u'allergy':
attr.SetTextColour('red')
else:
#attr.SetTextColour('yellow') # too light
#attr.SetTextColour('pink') # too light
#attr.SetTextColour('dark orange') # slightly better
attr.SetTextColour('magenta')
self.SetRowAttr(row_idx, attr)
else:
attr = self.GetOrCreateCellAttr(row_idx, 0)
attr.SetTextColour('grey')
self.SetRowAttr(row_idx, attr)
if self.__grouping_mode == u'episode':
if med['pk_episode'] is None:
self.__prev_cell_0 = None
epi = gmTools.u_diameter
else:
if self.__prev_cell_0 == med['episode']:
epi = u''
else:
self.__prev_cell_0 = med['episode']
epi = gmTools.coalesce(med['episode'], u'')
self.SetCellValue(row_idx, 0, gmTools.wrap(text = epi, width = 40))
self.SetCellValue(row_idx, 1, med['substance'])
self.SetCellValue(row_idx, 2, u'%s %s' % (med['amount'], med['unit']))
self.SetCellValue(row_idx, 3, gmTools.coalesce(med['schedule'], u''))
self.SetCellValue(row_idx, 4, med.medically_formatted_start)
if med['is_long_term']:
self.SetCellValue(row_idx, 5, gmTools.u_infinity)
else:
if med['discontinued'] is None:
if med['duration'] is None:
self.SetCellValue(row_idx, 5, u'')
else:
self.SetCellValue(row_idx, 5, gmDateTime.format_interval(med['duration'], gmDateTime.acc_days))
else:
self.SetCellValue(row_idx, 5, med['discontinued'].strftime('%Y-%m-%d'))
if med['pk_brand'] is None:
brand = u'%s (%s)' % (gmTools.u_diameter, med['preparation'])
else:
if med['fake_brand']:
brand = u'%s (%s)' % (
gmTools.coalesce(med['brand'], u'', _('%s <fake>')),
med['preparation']
)
else:
brand = u'%s (%s)' % (
gmTools.coalesce(med['brand'], u''),
med['preparation']
)
self.SetCellValue(row_idx, 6, gmTools.wrap(text = brand, width = 35))
elif self.__grouping_mode == u'issue':
if med['pk_health_issue'] is None:
self.__prev_cell_0 = None
issue = u'%s%s' % (
gmTools.u_diameter,
gmTools.coalesce(med['episode'], u'', u' (%s)')
)
else:
if self.__prev_cell_0 == med['health_issue']:
issue = u''
else:
self.__prev_cell_0 = med['health_issue']
issue = med['health_issue']
self.SetCellValue(row_idx, 0, gmTools.wrap(text = issue, width = 40))
self.SetCellValue(row_idx, 1, med['substance'])
self.SetCellValue(row_idx, 2, u'%s %s' % (med['amount'], med['unit']))
self.SetCellValue(row_idx, 3, gmTools.coalesce(med['schedule'], u''))
self.SetCellValue(row_idx, 4, med.medically_formatted_start)
if med['is_long_term']:
self.SetCellValue(row_idx, 5, gmTools.u_infinity)
else:
if med['discontinued'] is None:
if med['duration'] is None:
self.SetCellValue(row_idx, 5, u'')
else:
self.SetCellValue(row_idx, 5, gmDateTime.format_interval(med['duration'], gmDateTime.acc_days))
else:
self.SetCellValue(row_idx, 5, med['discontinued'].strftime('%Y-%m-%d'))
if med['pk_brand'] is None:
brand = u'%s (%s)' % (gmTools.u_diameter, med['preparation'])
else:
if med['fake_brand']:
brand = u'%s (%s)' % (
gmTools.coalesce(med['brand'], u'', _('%s <fake>')),
med['preparation']
)
else:
brand = u'%s (%s)' % (
gmTools.coalesce(med['brand'], u''),
med['preparation']
)
self.SetCellValue(row_idx, 6, gmTools.wrap(text = brand, width = 35))
elif self.__grouping_mode == u'brand':
if med['pk_brand'] is None:
self.__prev_cell_0 = None
brand = u'%s (%s)' % (
gmTools.u_diameter,
med['preparation']
)
else:
if self.__prev_cell_0 == med['brand']:
brand = u''
else:
self.__prev_cell_0 = med['brand']
if med['fake_brand']:
brand = u'%s (%s)' % (
gmTools.coalesce(med['brand'], u'', _('%s <fake>')),
med['preparation']
)
else:
brand = u'%s (%s)' % (
gmTools.coalesce(med['brand'], u''),
med['preparation']
)
self.SetCellValue(row_idx, 0, gmTools.wrap(text = brand, width = 35))
self.SetCellValue(row_idx, 1, gmTools.coalesce(med['schedule'], u''))
self.SetCellValue(row_idx, 2, med['substance'])
self.SetCellValue(row_idx, 3, u'%s %s' % (med['amount'], med['unit']))
self.SetCellValue(row_idx, 4, med.medically_formatted_start)
if med['is_long_term']:
self.SetCellValue(row_idx, 5, gmTools.u_infinity)
else:
if med['discontinued'] is None:
if med['duration'] is None:
self.SetCellValue(row_idx, 5, u'')
else:
self.SetCellValue(row_idx, 5, gmDateTime.format_interval(med['duration'], gmDateTime.acc_days))
else:
self.SetCellValue(row_idx, 5, med['discontinued'].strftime('%Y-%m-%d'))
if med['pk_health_issue'] is None:
issue = u'%s%s' % (
gmTools.u_diameter,
gmTools.coalesce(med['episode'], u'', u' (%s)')
)
else:
issue = gmTools.coalesce(med['health_issue'], u'')
self.SetCellValue(row_idx, 6, gmTools.wrap(text = issue, width = 40))
else:
raise ValueError('unknown grouping mode [%s]' % self.__grouping_mode)
if med['notes'] is not None:
self.SetCellValue(row_idx, 7, gmTools.wrap(text = med['notes'], width = 50))
if self.__filter_show_unapproved:
self.SetCellValue (
row_idx,
len(labels),
#gmTools.bool2subst(med['intake_is_approved_of'], gmTools.u_checkmark_thin, u'', u'?')
gmTools.bool2subst(med['intake_is_approved_of'], gmTools.u_checkmark_thin, gmTools.u_frowning_face, u'?')
)
font = self.GetCellFont(row_idx, len(labels))
font.SetPointSize(font.GetPointSize() + 2)
self.SetCellFont(row_idx, len(labels), font)
#self.SetCellAlignment(row, col, horiz = wx.ALIGN_RIGHT, vert = wx.ALIGN_CENTRE)
self.AutoSize()
self.EndBatch()
#------------------------------------------------------------
def empty_grid(self):
self.BeginBatch()
self.ClearGrid()
# Windows cannot do "nothing", it rather decides to assert()
# on thinking it is supposed to do nothing
if self.GetNumberRows() > 0:
self.DeleteRows(pos = 0, numRows = self.GetNumberRows())
if self.GetNumberCols() > 0:
self.DeleteCols(pos = 0, numCols = self.GetNumberCols())
self.EndBatch()
self.__row_data = {}
self.__prev_cell_0 = None
#------------------------------------------------------------
def show_info_on_entry(self):
if len(self.__row_data) == 0:
return
sel_rows = self.get_selected_rows()
if len(sel_rows) != 1:
return
drug_db = get_drug_database()
if drug_db is None:
return
intake = self.get_selected_data()[0] # just in case
if intake['brand'] is None:
drug_db.show_info_on_substance(substance_intake = intake)
else:
drug_db.show_info_on_drug(substance_intake = intake)
#------------------------------------------------------------
def show_renal_insufficiency_info(self):
search_term = None
if len(self.__row_data) > 0:
sel_rows = self.get_selected_rows()
if len(sel_rows) == 1:
search_term = self.get_selected_data()[0]
gmNetworkTools.open_url_in_browser(url = gmMedication.drug2renal_insufficiency_url(search_term = search_term))
#------------------------------------------------------------
def show_cardiac_info(self):
gmNetworkTools.open_url_in_browser(url = u'http://qtdrugs.org')
#------------------------------------------------------------
def report_ADR(self):
dbcfg = gmCfg.cCfgSQL()
url = dbcfg.get2 (
option = u'external.urls.report_ADR',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = u'user',
default = u'https://dcgma.org/uaw/meldung.php' # http://www.akdae.de/Arzneimittelsicherheit/UAW-Meldung/UAW-Meldung-online.html
)
gmNetworkTools.open_url_in_browser(url = url)
#------------------------------------------------------------
def prescribe(self):
prescribe_drugs (
parent = self,
emr = self.__patient.emr
)
#------------------------------------------------------------
def check_interactions(self):
if len(self.__row_data) == 0:
return
drug_db = get_drug_database()
if drug_db is None:
return
if len(self.get_selected_rows()) > 1:
drug_db.check_interactions(substance_intakes = self.get_selected_data())
else:
drug_db.check_interactions(substance_intakes = self.__row_data.values())
#------------------------------------------------------------
def add_substance(self):
edit_intake_of_substance(parent = self, substance = None)
#------------------------------------------------------------
def edit_substance(self):
rows = self.get_selected_rows()
if len(rows) == 0:
return
if len(rows) > 1:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot edit more than one substance at once.'), beep = True)
return
subst = self.get_selected_data()[0]
edit_intake_of_substance(parent = self, substance = subst)
#------------------------------------------------------------
def delete_substance(self):
rows = self.get_selected_rows()
if len(rows) == 0:
return
if len(rows) > 1:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot delete more than one substance at once.'), beep = True)
return
subst = self.get_selected_data()[0]
delete_substance_intake(parent = self, substance = subst['pk_substance_intake'])
#------------------------------------------------------------
def create_allergy_from_substance(self):
rows = self.get_selected_rows()
if len(rows) == 0:
return
if len(rows) > 1:
gmDispatcher.send(signal = 'statustext', msg = _('Cannot create allergy from more than one substance at once.'), beep = True)
return
return turn_substance_intake_into_allergy (
parent = self,
intake = self.get_selected_data()[0],
emr = self.__patient.get_emr()
)
#------------------------------------------------------------
def print_medication_list(self):
# there could be some filtering/user interaction going on here
print_medication_list(parent = self)
#------------------------------------------------------------
def get_row_tooltip(self, row=None):
try:
entry = self.__row_data[row]
except KeyError:
return u' '
emr = self.__patient.get_emr()
atcs = []
if entry['atc_substance'] is not None:
atcs.append(entry['atc_substance'])
# if entry['atc_brand'] is not None:
# atcs.append(entry['atc_brand'])
# allg = emr.is_allergic_to(atcs = tuple(atcs), inns = (entry['substance'],), brand = entry['brand'])
allg = emr.is_allergic_to(atcs = tuple(atcs), inns = (entry['substance'],))
tt = _('Substance intake entry (%s, %s) [#%s] \n') % (
gmTools.bool2subst (
boolean = entry['is_currently_active'],
true_return = gmTools.bool2subst (
boolean = entry['seems_inactive'],
true_return = _('active, needs check'),
false_return = _('active'),
none_return = _('assumed active')
),
false_return = _('inactive')
),
gmTools.bool2subst (
boolean = entry['intake_is_approved_of'],
true_return = _('approved'),
false_return = _('unapproved')
),
entry['pk_substance_intake']
)
if allg not in [None, False]:
certainty = gmTools.bool2subst(allg['definite'], _('definite'), _('suspected'))
tt += u'\n'
tt += u' !! ---- Cave ---- !!\n'
tt += u' %s (%s): %s (%s)\n' % (
allg['l10n_type'],
certainty,
allg['descriptor'],
gmTools.coalesce(allg['reaction'], u'')[:40]
)
tt += u'\n'
tt += u' ' + _('Substance: %s [#%s]\n') % (entry['substance'], entry['pk_substance'])
tt += u' ' + _('Preparation: %s\n') % entry['preparation']
tt += u' ' + _('Amount per dose: %s %s') % (entry['amount'], entry['unit'])
tt += u'\n'
tt += gmTools.coalesce(entry['atc_substance'], u'', _(' ATC (substance): %s\n'))
tt += u'\n'
tt += gmTools.coalesce (
entry['brand'],
u'',
_(' Brand name: %%s [#%s]\n') % entry['pk_brand']
)
tt += gmTools.coalesce(entry['atc_brand'], u'', _(' ATC (brand): %s\n'))
tt += u'\n'
tt += gmTools.coalesce(entry['schedule'], u'', _(' Regimen: %s\n'))
if entry['is_long_term']:
duration = u' %s %s' % (gmTools.u_right_arrow, gmTools.u_infinity)
else:
if entry['duration'] is None:
duration = u''
else:
duration = u' %s %s' % (gmTools.u_right_arrow, gmDateTime.format_interval(entry['duration'], gmDateTime.acc_days))
tt += _(' Started %s%s%s\n') % (
gmDateTime.pydt_strftime(entry['started'], '%Y %b %d'),
duration,
gmTools.bool2subst(entry['is_long_term'], _(' (long-term)'), _(' (short-term)'), u'')
)
if entry['discontinued'] is not None:
tt += _(' Discontinued %s\n') % gmDateTime.pydt_strftime(entry['discontinued'], '%Y %b %d')
tt += _(' Reason: %s\n') % entry['discontinue_reason']
tt += u'\n'
tt += gmTools.coalesce(entry['aim'], u'', _(' Aim: %s\n'))
tt += gmTools.coalesce(entry['episode'], u'', _(' Episode: %s\n'))
tt += gmTools.coalesce(entry['health_issue'], u'', _(' Health issue: %s\n'))
tt += gmTools.coalesce(entry['notes'], u'', _(' Advice: %s\n'))
tt += u'\n'
tt += _(u'Revision: #%(row_ver)s, %(mod_when)s by %(mod_by)s.') % ({
'row_ver': entry['row_version'],
'mod_when': gmDateTime.pydt_strftime(entry['modified_when'], '%Y %b %d %H:%M:%S'),
'mod_by': entry['modified_by']
})
return tt
#------------------------------------------------------------
# internal helpers
#------------------------------------------------------------
def __init_ui(self):
self.CreateGrid(0, 1)
self.EnableEditing(0)
self.EnableDragGridSize(1)
self.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
self.SetColLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTER)
self.SetRowLabelSize(0)
self.SetRowLabelAlignment(horiz = wx.ALIGN_RIGHT, vert = wx.ALIGN_CENTRE)
#------------------------------------------------------------
# properties
#------------------------------------------------------------
def _get_patient(self):
return self.__patient
def _set_patient(self, patient):
self.__patient = patient
self.repopulate_grid()
patient = property(_get_patient, _set_patient)
#------------------------------------------------------------
def _get_grouping_mode(self):
return self.__grouping_mode
def _set_grouping_mode(self, mode):
self.__grouping_mode = mode
self.repopulate_grid()
grouping_mode = property(_get_grouping_mode, _set_grouping_mode)
#------------------------------------------------------------
def _get_filter_show_unapproved(self):
return self.__filter_show_unapproved
def _set_filter_show_unapproved(self, val):
self.__filter_show_unapproved = val
self.repopulate_grid()
filter_show_unapproved = property(_get_filter_show_unapproved, _set_filter_show_unapproved)
#------------------------------------------------------------
def _get_filter_show_inactive(self):
return self.__filter_show_inactive
def _set_filter_show_inactive(self, val):
self.__filter_show_inactive = val
self.repopulate_grid()
filter_show_inactive = property(_get_filter_show_inactive, _set_filter_show_inactive)
#------------------------------------------------------------
# event handling
#------------------------------------------------------------
def __register_events(self):
# dynamic tooltips: GridWindow, GridRowLabelWindow, GridColLabelWindow, GridCornerLabelWindow
self.GetGridWindow().Bind(wx.EVT_MOTION, self.__on_mouse_over_cells)
#self.GetGridRowLabelWindow().Bind(wx.EVT_MOTION, self.__on_mouse_over_row_labels)
#self.GetGridColLabelWindow().Bind(wx.EVT_MOTION, self.__on_mouse_over_col_labels)
# editing cells
self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.__on_cell_left_dclicked)
#------------------------------------------------------------
def __on_mouse_over_cells(self, evt):
"""Calculate where the mouse is and set the tooltip dynamically."""
# Use CalcUnscrolledPosition() to get the mouse position within the
# entire grid including what's offscreen
x, y = self.CalcUnscrolledPosition(evt.GetX(), evt.GetY())
# use this logic to prevent tooltips outside the actual cells
# apply to GetRowSize, too
# tot = 0
# for col in xrange(self.NumberCols):
# tot += self.GetColSize(col)
# if xpos <= tot:
# self.tool_tip.Tip = 'Tool tip for Column %s' % (
# self.GetColLabelValue(col))
# break
# else: # mouse is in label area beyond the right-most column
# self.tool_tip.Tip = ''
row, col = self.XYToCell(x, y)
if row == self.__prev_tooltip_row:
return
self.__prev_tooltip_row = row
try:
evt.GetEventObject().SetToolTipString(self.get_row_tooltip(row = row))
except KeyError:
pass
#------------------------------------------------------------
def __on_cell_left_dclicked(self, evt):
row = evt.GetRow()
data = self.__row_data[row]
edit_intake_of_substance(parent = self, substance = data)
#============================================================
def configure_default_medications_lab_panel(parent=None):
panels = gmPathLab.get_test_panels(order_by = u'description')
gmCfgWidgets.configure_string_from_list_option (
parent = parent,
message = _(
'\n'
'Select the measurements panel to show in the medications plugin.'
'\n'
),
option = u'horstspace.medications_plugin.lab_panel',
bias = 'user',
default_value = None,
choices = [ u'%s%s' % (p['description'], gmTools.coalesce(p['comment'], u'', u' (%s)')) for p in panels ],
columns = [_('Measurements panel')],
data = [ p['pk_test_panel'] for p in panels ],
caption = _('Configuring medications plugin measurements panel')
)
#============================================================
from Gnumed.wxGladeWidgets import wxgCurrentSubstancesPnl
class cCurrentSubstancesPnl(wxgCurrentSubstancesPnl.wxgCurrentSubstancesPnl, gmRegetMixin.cRegetOnPaintMixin):
"""Panel holding a grid with current substances. Used as notebook page."""
def __init__(self, *args, **kwargs):
wxgCurrentSubstancesPnl.wxgCurrentSubstancesPnl.__init__(self, *args, **kwargs)
gmRegetMixin.cRegetOnPaintMixin.__init__(self)
self.__lab_panel = None
self.__lab_default_text_color = self._TCTRL_lab.GetForegroundColour()
self.__register_interests()
#-----------------------------------------------------
# reget-on-paint mixin API
#-----------------------------------------------------
def _populate_with_data(self):
"""Populate cells with data from model."""
pat = gmPerson.gmCurrentPatient()
if pat.connected:
self._grid_substances.patient = pat
self.__refresh_gfr(pat)
self.__refresh_lab(patient = pat)
else:
self._grid_substances.patient = None
self.__clear_gfr()
self.__refresh_lab(patient = None)
return True
#--------------------------------------------------------
def __refresh_lab(self, patient):
self._TCTRL_lab.SetDefaultStyle(wx.TextAttr(self.__lab_default_text_color))
self._TCTRL_lab.SetValue(u'')
self._TCTRL_lab.Hide()
if patient is None:
self.Layout()
return
if self.__lab_panel is None:
self.Layout()
return
results = self.__lab_panel.get_most_recent_results(pk_patient = patient.ID, order_by = u'unified_abbrev')
if len(results) == 0:
self.Layout()
return
now = gmDateTime.pydt_now_here()
# look for GFR
gfr = patient.emr.get_most_recent_results(loinc = gmLOINC.LOINC_gfr_quantity, no_of_results = 1)
crea = patient.emr.get_most_recent_results(loinc = gmLOINC.LOINC_creatinine_quantity, no_of_results = 1)
if crea is None:
gfr_3_months_older_than_crea = False
elif gfr is None:
gfr_3_months_older_than_crea = True
else:
three_months = pydt.timedelta(weeks = 14)
gfr_3_months_older_than_crea = (crea['clin_when'] - gfr['clin_when']) > three_months
# if GFR not found in results or old, then calculate
if gfr_3_months_older_than_crea:
calc = gmClinicalCalculator.cClinicalCalculator()
calc.patient = patient
gfr = calc.eGFR
if gfr.numeric_value is None:
gfr_msg = u'?'
else:
gfr_msg = _(u'%.1f (%s ago)') % (
gfr.numeric_value,
gmDateTime.format_interval_medically(now - gfr.date_valid)
#gmDateTime.pydt_strftime (gfr.date_valid, format = '%b %Y')
)
self._TCTRL_lab.SetDefaultStyle(wx.TextAttr('blue'))
self._TCTRL_lab.AppendText(_('eGFR:'))
self._TCTRL_lab.SetDefaultStyle(wx.TextAttr(self.__lab_default_text_color))
self._TCTRL_lab.AppendText(u' ' + gfr_msg)
self._TCTRL_lab.AppendText(u' || ')
for most_recent in results:
if most_recent.is_considered_abnormal:
self._TCTRL_lab.SetDefaultStyle(wx.TextAttr('red'))
txt = _('%s: %s%s%s (%s ago)') % (
most_recent['unified_abbrev'],
most_recent['unified_val'],
gmTools.coalesce(most_recent['val_unit'], u'', u' %s'),
gmTools.coalesce(most_recent.formatted_abnormality_indicator, u'', u' %s'),
gmDateTime.format_interval_medically(now - most_recent['clin_when'])
)
self._TCTRL_lab.AppendText(txt)
self._TCTRL_lab.SetDefaultStyle(wx.TextAttr(self.__lab_default_text_color))
else:
self._TCTRL_lab.SetDefaultStyle(wx.TextAttr('blue'))
self._TCTRL_lab.AppendText(u'%s:' % most_recent['unified_abbrev'])
self._TCTRL_lab.SetDefaultStyle(wx.TextAttr(self.__lab_default_text_color))
txt = _(' %s%s%s (%s ago)') % (
most_recent['unified_val'],
gmTools.coalesce(most_recent['val_unit'], u'', u' %s'),
gmTools.coalesce(most_recent.formatted_abnormality_indicator, u'', u' %s'),
gmDateTime.format_interval_medically(now - most_recent['clin_when'])
)
self._TCTRL_lab.AppendText(txt)
self._TCTRL_lab.AppendText(u' || ')
self._TCTRL_lab.Show()
self.Layout()
#--------------------------------------------------------
def __refresh_gfr(self, patient):
gfr = patient.emr.get_most_recent_results(loinc = gmLOINC.LOINC_gfr_quantity, no_of_results = 1)
if gfr is None:
calc = gmClinicalCalculator.cClinicalCalculator()
calc.patient = patient
gfr = calc.eGFR
if gfr.numeric_value is None:
msg = _('GFR: ?')
tt = gfr.message
else:
msg = _('eGFR: %.1f (%s)') % (
gfr.numeric_value,
gmDateTime.pydt_strftime (
gfr.date_valid,
format = '%b %Y'
)
)
tt = gfr.format (
left_margin = 0,
width = 50,
eol = u'\n',
with_formula = True,
with_warnings = True,
with_variables = False,
with_sub_results = True,
return_list = False
)
else:
msg = u'%s: %s %s (%s)\n' % (
gfr['unified_abbrev'],
gfr['unified_val'],
gmTools.coalesce(gfr['abnormality_indicator'], u'', u' (%s)'),
gmDateTime.pydt_strftime (
gfr['clin_when'],
format = '%b %Y'
)
)
tt = _('GFR reported by path lab')
self._LBL_gfr.SetLabel(msg)
self._LBL_gfr.SetToolTipString(tt)
self._LBL_gfr.Refresh()
self.Layout()
#--------------------------------------------------------
def __clear_gfr(self):
self._LBL_gfr.SetLabel(_('GFR: ?'))
self._LBL_gfr.Refresh()
self.Layout()
#--------------------------------------------------------
# event handling
#--------------------------------------------------------
def __register_interests(self):
gmDispatcher.connect(signal = u'pre_patient_selection', receiver = self._on_pre_patient_selection)
gmDispatcher.connect(signal = u'post_patient_selection', receiver = self._on_post_patient_selection)
gmDispatcher.connect(signal = u'clin.substance_intake_mod_db', receiver = self._schedule_data_reget)
gmDispatcher.connect(signal = u'clin.test_result_mod_db', receiver = self._on_test_result_mod)
# active_substance_mod_db
# substance_brand_mod_db
#--------------------------------------------------------
def _on_test_result_mod(self):
wx.CallAfter(self.__on_test_result_mod)
#--------------------------------------------------------
def __on_test_result_mod(self):
self.__refresh_lab(patient = self._grid_substances.patient)
#--------------------------------------------------------
def _on_pre_patient_selection(self):
wx.CallAfter(self.__on_pre_patient_selection)
def __on_pre_patient_selection(self):
dbcfg = gmCfg.cCfgSQL()
pk_panel = dbcfg.get2 (
option = u'horstspace.medications_plugin.lab_panel',
workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
bias = 'user'
)
if pk_panel is None:
self.__lab_panel = None
else:
self.__lab_panel = gmPathLab.cTestPanel(aPK_obj = pk_panel)
self._grid_substances.patient = None
self.__refresh_lab(patient = None)
#--------------------------------------------------------
def _on_post_patient_selection(self):
wx.CallAfter(self.__on_post_patient_selection)
def __on_post_patient_selection(self):
self._schedule_data_reget()
#--------------------------------------------------------
def _on_add_button_pressed(self, event):
self._grid_substances.add_substance()
#--------------------------------------------------------
def _on_edit_button_pressed(self, event):
self._grid_substances.edit_substance()
#--------------------------------------------------------
def _on_delete_button_pressed(self, event):
self._grid_substances.delete_substance()
#--------------------------------------------------------
def _on_info_button_pressed(self, event):
self._grid_substances.show_info_on_entry()
#--------------------------------------------------------
def _on_interactions_button_pressed(self, event):
self._grid_substances.check_interactions()
#--------------------------------------------------------
def _on_issue_grouping_selected(self, event):
self._grid_substances.grouping_mode = 'issue'
#--------------------------------------------------------
def _on_episode_grouping_selected(self, event):
self._grid_substances.grouping_mode = 'episode'
#--------------------------------------------------------
def _on_brand_grouping_selected(self, event):
self._grid_substances.grouping_mode = 'brand'
#--------------------------------------------------------
def _on_show_unapproved_checked(self, event):
self._grid_substances.filter_show_unapproved = self._CHBOX_show_unapproved.GetValue()
#--------------------------------------------------------
def _on_show_inactive_checked(self, event):
self._grid_substances.filter_show_inactive = self._CHBOX_show_inactive.GetValue()
#--------------------------------------------------------
def _on_print_button_pressed(self, event):
self._grid_substances.print_medication_list()
#--------------------------------------------------------
def _on_allergy_button_pressed(self, event):
self._grid_substances.create_allergy_from_substance()
#--------------------------------------------------------
def _on_button_kidneys_pressed(self, event):
self._grid_substances.show_renal_insufficiency_info()
#--------------------------------------------------------
def _on_button_heart_pressed(self, event):
self._grid_substances.show_cardiac_info()
#--------------------------------------------------------
def _on_adr_button_pressed(self, event):
self._grid_substances.report_ADR()
#--------------------------------------------------------
def _on_rx_button_pressed(self, event):
self._grid_substances.prescribe()
#============================================================
# 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, 600))
# #app.SetWidget(cATCPhraseWheel, -1)
# app.SetWidget(cSubstancePhraseWheel, -1)
# app.MainLoop()
manage_substance_intakes()
#============================================================
|