Spaces:
Sleeping
Sleeping
File size: 71,701 Bytes
34a733e 0dc8e0f 34a733e 0dc8e0f 34a733e 0dc8e0f 34a733e ba569dd 34a733e | 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 | # -*- coding: utf-8 -*-
"""MSSH_Variable_Payout.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1Q0Jnti7rUgmbdDHK8rssozJbZXBk9HcB
"""
"""
HTML to Excel Converter for Hospital Revenue Report (Stable Version)
"""
import pandas as pd
from bs4 import BeautifulSoup
import os
def convert_html_to_excel(input_file, output_file):
# 1. Read the HTML file with verification
print(f"\n[1/6] Reading HTML file: {os.path.basename(input_file)}")
with open(input_file, 'r', encoding='utf-8', errors='ignore') as f:
html_content = f.read()
print("β File read successfully")
# 2. Parse HTML with lxml for consistency
print("[2/6] Parsing HTML content...")
soup = BeautifulSoup(html_content, 'lxml')
tables = soup.find_all('table')
print(f"β Found {len(tables)} tables in document")
# 3. Identify main table by headers
print("[3/6] Locating main data table...")
expected_headers = ['Sr.\xa0No.'] # UPDATE THESE
main_table = None
for i, table in enumerate(tables):
first_row = table.find('tr')
if first_row:
headers = [th.get_text(strip=True) for th in first_row.find_all(['th', 'td'])]
if all(h in headers for h in expected_headers):
main_table = table
print(f"β Identified table {i+1} as main data table")
print(f" Table dimensions: {len(table.find_all('tr'))} rows")
break
if not main_table:
raise ValueError("Γ ERROR: Could not find main data table with expected headers")
# 4. Extract and validate data rows
print("[4/6] Processing table rows...")
rows = main_table.find_all('tr')
header_row = rows[0]
headers = [col.get_text(strip=True) for col in header_row.find_all(['th', 'td'])]
valid_col_count = len(headers)
print(f"β Header row identified with {valid_col_count} columns:")
print(f" {headers}")
print(f"β Processing {len(rows)-1} data rows...")
# Process data rows with validation
data = []
skipped_rows = 0
for i, row in enumerate(rows[1:]): # Skip header
cols = row.find_all(['td', 'th'])
if len(cols) != valid_col_count:
skipped_rows += 1
continue
data.append([col.get_text(strip=True) for col in cols])
print(f"β Clean rows extracted: {len(data)}")
print(f" Skipped {skipped_rows} malformed rows")
# [5/6] Total Row Removal (Guaranteed Last Row + "Total Net Amount" Check)
print("[5/6] Checking for total row...")
if data:
last_row = data[-1]
# Check if "total net amount" exists in ANY cell of the last row
if any("total net amount" in cell.lower() for cell in last_row):
print("β Removed TOTAL NET AMOUNT row")
data = data[:-1]
print(f"β Final data rows: {len(data)}")
# 6. Create and save DataFrame
print("[6/6] Creating Excel file...")
df = pd.DataFrame(data, columns=headers)
# Final verification
print(f"β DataFrame created with dimensions: {df.shape}")
print(f"β First 3 columns: {df.columns.tolist()[:3]}...")
print(f"β Last 3 columns: {df.columns.tolist()[-3:]}...")
df.to_excel(output_file, index=False)
print(f"\nProcessing complete! Saved to: {output_file}")
print(f"Final verification:")
print(f"- Total rows: {len(df):,}")
print(f"- Total columns: {len(df.columns):,}")
return output_file
def process_multiple_files(file_list):
"""
Process multiple HTML files and convert them to Excel.
Args:
file_list: List of input HTML filenames to process
"""
print(f"Starting batch processing of {len(file_list)} files...")
results = []
for i, input_file in enumerate(file_list):
print(f"\n[File {i+1}/{len(file_list)}] Processing: {input_file}")
# Extract base name for output file
base_name = os.path.splitext(os.path.basename(input_file))[0]
output_file = f"processed_{base_name}.xlsx"
try:
result = convert_html_to_excel(input_file, output_file)
results.append((input_file, result, "Success"))
except Exception as e:
print(f"Γ ERROR processing {input_file}: {str(e)}")
results.append((input_file, None, f"Error: {str(e)}"))
# Print summary
print("\n" + "="*50)
print("BATCH PROCESSING SUMMARY")
print("="*50)
for input_file, output_file, status in results:
print(f"{input_file} β {output_file if output_file else 'FAILED'} ({status})")
success_count = sum(1 for _, _, status in results if status == "Success")
print(f"\nProcessed {success_count}/{len(file_list)} files successfully")
return results
if __name__ == "__main__":
file_list = [
'/content/drive/MyDrive/VarAuto/doctor_visit_report_with_package.xls',
'/content/drive/MyDrive/VarAuto/doctor_visit_report_without_package.xls',
'/content/drive/MyDrive/VarAuto/print_hospital_revenue_report.php (11).xls',
'/content/drive/MyDrive/VarAuto/print_inpatient_bill_register_report.xls'
]
process_multiple_files(file_list)
import pandas as pd
import re
def normalize_name(name):
name = re.sub(r'^dr[\.\s]*', '', str(name), flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z0-9]', '', name)
return name.lower().strip()
def filter_patient_records(file_path, search_term):
df = pd.read_excel(file_path)
df['clean_name'] = df['Name'].apply(normalize_name)
search_clean = normalize_name(search_term)
filtered = df[
(df['Patient Type'] == 'OPD') &
(df['Service Type'] == 'Consultation') &
(df['clean_name'].str.contains(search_clean, regex=False, na=False))
]
return filtered.drop(columns=['clean_name'])
if __name__ == "__main__":
excel_file = "/content/processed_print_hospital_revenue_report.php (11).xlsx"
search = 'Dr. Shashidhar Kumar'
output_file = 'processed_opd_consultations.xlsx'
results = filter_patient_records(excel_file, search)
if not results.empty:
results.to_excel(output_file, index=False)
print(f"\nFound {len(results)} matches:")
print(results[['Date', 'Patient Name', 'Name', 'Department', 'Service Name', 'Net Amount']])
else:
print("\nNo matches found")
'''
import pandas as pd
df= pd.read_excel('/content/processed_doctor_visit_report_with_package.xlsx')
df2= pd.read_excel('/content/processed_doctor_visit_report_without_package.xlsx')
base_name = 'processed_doctor_visit_report'
df['Type']='Package'
df2['Type']='Open'
# assume df has shape (1420, 13) & df2 hs shape (3635, 13)
df_final = pd.concat([df, df2], axis=0, ignore_index=True)
print(df_final.shape)
df_final.to_excel(f'final_{base_name}.xlsx', index=False)
'''
#df_cross= pd.read_excel('/content/processed_print_inpatient_bill_register_report.xlsx')
import pandas as pd
import re
def normalize_doctor_name(name):
"""Hospital-standard cleaning logic (recommended version)"""
name = re.sub(r'\(.*?\)', '', str(name))
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z]', '', name)
return name.lower().strip()
def process_reports(doctor_input, file1_path, file2_path):
df1 = pd.read_excel(file1_path)
df2 = pd.read_excel(file2_path)
norm_input = normalize_doctor_name(doctor_input)
df1['clean_doctor'] = df1['Doctor Name'].apply(normalize_doctor_name)
df2['clean_doctor'] = df2['Admiting Doctor'].apply(normalize_doctor_name)
filtered_df2 = df2[df2['clean_doctor'] == norm_input]
admission_numbers = filtered_df2['Admission No.'].unique().tolist()
df1['Consultation Type'] = pd.NA
doctor_mask = df1['clean_doctor'] == norm_input
admission_mask = df1['Admission No.'].isin(admission_numbers)
df1.loc[doctor_mask & admission_mask, 'Consultation Type'] = 'Self'
df1.loc[doctor_mask & ~admission_mask, 'Consultation Type'] = 'Cross'
df1.drop(columns=['clean_doctor'], inplace=True)
stats = {
'Total Records': len(df1),
'Target Doctor Records': doctor_mask.sum(),
'Self Consultations': (doctor_mask & admission_mask).sum(),
'Cross Consultations': (doctor_mask & ~admission_mask).sum(),
'Untagged Records': len(df1) - doctor_mask.sum()
}
return df1, stats
def main():
df = pd.read_excel('/content/final_processed_doctor_visit_report.xlsx')
df2 = pd.read_excel('processed_print_inpatient_bill_register_report.xlsx')
df['Consultation Type'] = pd.NA
doctors = [
'Dr. Shashidhar Kumar'
]
for doctor_name in doctors:
norm_input = normalize_doctor_name(doctor_name)
admissions = (
df2[df2['Admiting Doctor']
.map(normalize_doctor_name) == norm_input]
['Admission No.']
.unique()
)
mask_doc = df['Doctor Name'].map(normalize_doctor_name) == norm_input
mask_adm = df['Admission No.'].isin(admissions)
df.loc[mask_doc & mask_adm, 'Consultation Type'] = 'Self'
df.loc[mask_doc & ~mask_adm, 'Consultation Type'] = 'Cross'
total = len(df)
target_cnt = int(mask_doc.sum())
self_cnt = int((mask_doc & mask_adm).sum())
cross_cnt = int((mask_doc & ~mask_adm).sum())
untagged = total - target_cnt
print(f"\nProcessing Statistics:")
print(f"- Target Doctor: {doctor_name}")
print(f"- Total records processed: {total}")
print(f"- Target doctor's records: {target_cnt}")
print(f" ββ Self consultations: {self_cnt}")
print(f" ββ Cross consultations: {cross_cnt}")
print(f"- Untagged records (other doctors): {untagged}")
output_file = 'precision_tagged_all_consultations.xlsx'
df.to_excel(output_file, index=False)
print(f"Saved combined filtered data for all doctors to: {output_file}")
if __name__ == "__main__":
main()
# Self Open Records
import pandas as pd
import re
def normalize_doctor_name(name: str) -> str:
"""Hospitalβstandard cleaning logic."""
name = re.sub(r'\(.*?\)', '', str(name))
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z]', '', name)
return name.lower().strip()
def get_self_open_records(
input_file: str,
doctor_list: list[str]
) -> pd.DataFrame:
"""
Load the taggedβconsultations Excel, and return only those rows
for the given doctors where Type == 'open' and Consultation Type == 'Self'.
"""
df = pd.read_excel(input_file)
norm_docs = { normalize_doctor_name(d) for d in doctor_list }
df['__clean_doc'] = df['Doctor Name'].map(normalize_doctor_name)
mask = (
df['__clean_doc'].isin(norm_docs) &
df['Type'].str.lower().eq('open') &
df['Consultation Type'].eq('Self')
)
result = df.loc[mask].copy()
result.drop(columns='__clean_doc', inplace=True)
return result
def main():
doctors = [
'Dr. Shashidhar Kumar'
]
input_file = 'precision_tagged_all_consultations.xlsx'
output_file = 'self_open_for_doctors.xlsx'
filtered_df = get_self_open_records(input_file, doctors)
filtered_df.to_excel(output_file, index=False)
print(f"Extracted {len(filtered_df)} rows where Type='open' and Consultation Type='Self'")
print(f"Saved to: {output_file}")
if __name__ == "__main__":
main()
# Self Package Records
import pandas as pd
import re
def normalize_doctor_name(name: str) -> str:
"""Hospitalβstandard cleaning logic."""
name = re.sub(r'\(.*?\)', '', str(name))
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z]', '', name)
return name.lower().strip()
def get_self_package_records(
input_file: str,
doctor_list: list[str]
) -> pd.DataFrame:
"""
Load the taggedβconsultations Excel, and return only those rows
for the given doctors where Type == 'package' and Consultation Type == 'Self'.
"""
df = pd.read_excel(input_file)
norm_docs = { normalize_doctor_name(d) for d in doctor_list }
df['__clean_doc'] = df['Doctor Name'].map(normalize_doctor_name)
mask = (
df['__clean_doc'].isin(norm_docs) &
df['Type'].str.lower().eq('package') &
df['Consultation Type'].eq('Self')
)
result = df.loc[mask].copy()
result.drop(columns='__clean_doc', inplace=True)
return result
def main():
doctors = [
'Dr. Shashidhar Kumar'
]
input_file = 'precision_tagged_all_consultations.xlsx'
output_file = 'self_package_for_doctors.xlsx'
filtered_df = get_self_package_records(input_file, doctors)
filtered_df.to_excel(output_file, index=False)
print(f"Extracted {len(filtered_df)} rows where Type='package' and Consultation Type='Self'")
print(f"Saved to: {output_file}")
if __name__ == "__main__":
main()
# Cross Records
import pandas as pd
import re
def normalize_doctor_name(name: str) -> str:
"""Hospitalβstandard cleaning logic."""
name = re.sub(r'\(.*?\)', '', str(name))
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
name = re.sub(r'[^a-zA-Z]', '', name)
return name.lower().strip()
def get_cross_records(
input_file: str,
doctor_list: list[str]
) -> pd.DataFrame:
"""
Load the taggedβconsultations Excel, and return only those rows
for the given doctors where Consultation Type == 'Cross'.
"""
df = pd.read_excel(input_file)
norm_docs = { normalize_doctor_name(d) for d in doctor_list }
df['__clean_doc'] = df['Doctor Name'].map(normalize_doctor_name)
# 4) Filter:
# - rowβs doctor is one of norm_docs
# - Consultation Type is exactly 'Cross'
mask = (
df['__clean_doc'].isin(norm_docs)
& df['Consultation Type'].eq('Cross')
)
result = df.loc[mask].copy()
result.drop(columns='__clean_doc', inplace=True)
return result
def main():
doctors = [
'Dr. Shashidhar Kumar'
]
input_file = 'precision_tagged_all_consultations.xlsx'
output_file = 'cross_for_doctors.xlsx'
filtered_df = get_cross_records(input_file, doctors)
filtered_df.to_excel(output_file, index=False)
print(f"Extracted {len(filtered_df)} rows where Consultation Type='Cross'")
print(f"Saved to: {output_file}")
if __name__ == "__main__":
main()
# code for handling both surgical and medical management cases
# exclusions are only values that should be subtracted from Net Bill, it is not the final value already subtracted from the Net Bill!
# !!!if exclusions are there, the final value should be Net Bill - Exclusions Columns.
import pandas as pd
import re
def normalize_doctor_name(name: str) -> str:
"""Normalize doctor names to plain lowercase alphabetic."""
name = re.sub(r'\(.*?\)', '', str(name))
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
name = re.sub(r'[^A-Za-z]', '', name)
return name.lower().strip()
def classify_type(service_series: pd.Series) -> str:
"""Assign Type based on Service Type values in the doctorβs records."""
if service_series.str.contains(r'Package\(IPD\)', case=False, na=False).any():
return 'Surgical-Package'
if service_series.str.contains(r'OT Procedure', case=False, na=False).any():
return 'Surgical-Open'
return 'Medical'
def preprocess_revenue(
file_path: str,
doctor_name: str,
output_path: str
) -> pd.DataFrame:
# 1) Load and convert Net Amount β float
df = pd.read_excel(
file_path,
converters={'Net Amount': lambda x: float(str(x).replace(',', '') or 0)}
)
# 2) Normalize & filter by doctor + IPD
df['Clean Doctor'] = df['Name'].apply(normalize_doctor_name)
norm_doc = normalize_doctor_name(doctor_name)
df_doc = df[
(df['Clean Doctor'] == norm_doc) &
(df['Patient Type'].str.contains('IPD', case=False, na=False))
].copy()
# Handle empty DataFrame gracefully without raising error
if df_doc.empty:
print(f"Note: No IPD records found for {doctor_name}. Skipping surgical/medical management processing.")
# Create an empty Excel file (this is expected by the workflow)
# But the empty DataFrame will signal to other functions not to create sheets
empty_df = pd.DataFrame()
empty_df.to_excel(output_path, index=False)
return empty_df
# 3) Admission numbers for this doctorβs IPD cases
admission_nos = df_doc['Admission No.'].unique()
# 4) Build df_adm: all records for those admissions, excluding 'Doctors Visit'
mask_not_visit = df['Service Type'].str.strip().str.lower() != 'doctors visit'
df_adm = df[df['Admission No.'].isin(admission_nos) & mask_not_visit].copy()
# 5) net bill: sum Net Amount per admission (excl. Doctors Visit)
net_sums = (
df_adm
.groupby('Admission No.')['Net Amount']
.sum()
.rename('Net Bill')
)
# 6) Exclusions-Drugs & Implants: filter to this doctor's records, then by service type
drug_implant_sums = (
df_adm[
(df_adm['Clean Doctor'] == norm_doc) &
df_adm['Service Type'].str.contains(r'IP Pharmacy|IP Implants', case=False, na=False)
]
.groupby('Admission No.')['Net Amount']
.sum()
.rename('Exclusions-Drugs & Implants')
)
# 7) Exclusions-Other Doctors' Fees
other_fees_sums = (
df_adm[df_adm['Clean Doctor'] != norm_doc]
.groupby('Admission No.')['Net Amount']
.sum()
.rename("Exclusions-Other Doctors' Fees")
)
# 8) classify Type using only this doctorβs IPD records
type_map = (
df_doc
.groupby('Admission No.')['Service Type']
.apply(classify_type)
)
# 9) pick one row per Admission No. (cols BβI)
cols_B_to_I = df_doc.columns[2:12] # adjust if layout differs
sample = df_doc.drop_duplicates('Admission No.')[list(cols_B_to_I)].copy()
if 'Admission No.' not in sample.columns:
sample.insert(0, 'Admission No.', admission_nos)
# 10) map computed series back onto sample, filling missing with 0
sample['Net Bill'] = sample['Admission No.'].map(net_sums).fillna(0)
sample['Type'] = sample['Admission No.'].map(type_map)
sample['Exclusions-Drugs & Implants'] = (
sample['Admission No.'].map(drug_implant_sums).fillna(0)
)
sample["Exclusions-Other Doctors' Fees"] = (
sample['Admission No.'].map(other_fees_sums).fillna(0)
)
# 11) round all numeric columns to nearest integer
num_cols = sample.select_dtypes(include='number').columns
sample[num_cols] = sample[num_cols].round(0).astype(int)
# 12) swap 'Type' and 'Net Bill' using the second method
cols = sample.columns.tolist()
i, j = cols.index('Type'), cols.index('Net Bill')
cols[i], cols[j] = cols[j], cols[i]
sample = sample[cols]
# 13) now write to Excel
sample.to_excel(output_path, index=False)
return sample
if __name__ == "__main__":
file_path = '/content/processed_print_hospital_revenue_report.php (11).xlsx'
doctor_name = 'Dr. Shashidhar Kumar'
output_path = "processed_medical_and_surgical_cases_with_exclusions.xlsx"
df_summary = preprocess_revenue(file_path, doctor_name, output_path)
print(f"\nFound {len(df_summary)} matches:")
print(df_summary.head())
# Diag, Path and Daycare Reports (Simple Service Type, Patient Type and Doctor Name Matching)
import pandas as pd
import re
def normalize_doctor_name(name: str) -> str:
"""Normalize doctor names to plain lowercase alphabetic."""
name = re.sub(r'\(.*?\)', '', str(name)) # Remove anything in parentheses
name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE) # Remove 'Dr' prefix
name = re.sub(r'[^A-Za-z]', '', name) # Remove non-alphabetic characters
return name.lower().strip()
def generate_service_reports(file_path, doctor_name, service_type, output_file):
df = pd.read_excel(file_path)
# Normalize input doctor name
norm_doctor = normalize_doctor_name(doctor_name)
df['clean_doctor'] = df['Name'].apply(normalize_doctor_name)
opd_mask = df['Patient Type'] == 'OPD'
doctor_mask = df['clean_doctor'].str.contains(norm_doctor, regex=False, na=False)
service_mask = df['Service Type'] == service_type
final_mask = opd_mask & doctor_mask & service_mask
service_records = df[final_mask]
service_records = service_records.drop(columns=['clean_doctor'])
if not service_records.empty:
service_records.to_excel(output_file, index=False)
return service_records
if __name__ == "__main__":
excel_file = "/content/processed_print_hospital_revenue_report.php (11).xlsx"
doctor_name = "Dr. Shashidhar Kumar"
# Rep for Diag
diagnostic_output = 'processed_opd_diagnostics.xlsx'
diagnostic_results = generate_service_reports(excel_file, doctor_name, 'Diagnostic', diagnostic_output)
# Rep for Path
pathology_output = 'processed_opd_pathology.xlsx'
pathology_results = generate_service_reports(excel_file, doctor_name, 'Pathology', pathology_output)
# Rep for Day Care
daycare_output = 'processed_opd_daycare.xlsx'
daycare_results = generate_service_reports(excel_file, doctor_name, 'Day Care Procedure', daycare_output)
print("All reports generated successfully:")
print(f"1. Diagnostic services: {len(diagnostic_results)} records")
print(f"2. Pathology services: {len(pathology_results)} records")
print(f"3. Day Care Procedure services: {len(daycare_results)} records")
# code to dump the dictionary in .json file
import json
# Custom formatter for more compact JSON
def dump_compact_json(data, file):
"""Dump JSON in a compact format with properly aligned exclusions"""
with open(file, 'w') as f:
f.write('{\n')
items = []
for i, (doctor, config) in enumerate(data.items()):
# Format services as single-line array
services = ', '.join(str(v) for v in config['services'])
# Format exclusions with proper indentation
exclusions = []
for excl in config['exclusions']:
excl_str = ', '.join('true' if v else 'false' for v in excl)
# Add 6-space indentation for each exclusion line
exclusions.append(f' [ {excl_str} ]')
exclusions_str = ',\n'.join(exclusions)
# Create the doctor entry with consistent formatting
doctor_entry = f' "{doctor}": {{\n' \
f' "services": [ {services} ],\n' \
f' "exclusions": [\n' \
f'{exclusions_str}\n' \
f' ]\n' \
f' }}'
items.append(doctor_entry)
f.write(',\n'.join(items))
f.write('\n}')
# Save using our custom formatter
#dump_compact_json(DOCTORS, 'mssh_maatri_doctors_config.json')
'''
[OPD Consultation, IPD Consultation (Non-Package), IPD Consultation (Package),
IPD Cross Consultation, Surgery (Package cases), Surgery (Open cases), Medical Management,
OPD Diagnostics, OPD Pathology, Daycare Procedure]
[[Exclusions - Drugs & Implants, Exclusions - Other Doctor Fees]] in 2nd List
[Surgical (Package) 1, Surgical (Package) 2, Surgical Management (Non-Package) 1, Surgical Management (Non-Package) 2,
Medical Management 1, Medical Management 2]
DOCTORS = {
"Dr. Ajit Kumar": {
"services": [0.80, 0.80, 0.80, 0.80, 0, 0, 0.15, 0.20, 0.20, 0],
"exclusions": [
[False, False],
[False, False],
[False, True]
]
},
"Dr. Ashim Parwez": {
"services": [0.2, 0, 0, 0, 0, 0, 0, 0.1, 0, 0],
"exclusions": [
[False, False],
[False, False],
[False, False]
]
},
"Dr. Asif Iqbal": {
"services": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2],
"exclusions": [
[False, False],
[False, False],
[False, False]
]
},
"Dr. Avinash Kumar": {
"services": [0.8, 0, 0, 0.80, 0.15, 0.15, 0.15, 0, 0, 0],
"exclusions": [
[False, False],
[False, True],
[False, True]
]
},
"Dr. Kunal Krishna": {
"services": [0, 0, 0, 0, 0.2, 0.2, 0.2, 0.1, 0, 0],
"exclusions": [
[False, False],
[False, False],
[True, True]
]
},
"Dr. Ravikant Sinha": {
"services": [0.7, 0, 0, 0.7, 0, 0.15, 0, 0, 0, 0],
"exclusions": [
[False, False],
[False, True],
[False, False]
]
},
"Dr. S A Siddiqui": {
"services": [0.2, 0.05, 0.05, 0, 0.05, 0.05, 0, 0.10, 0, 0],
"exclusions": [
[False, False],
[False, False],
[False, False]
]
},
"Dr. Sanjay Kumar": {
"services": [0.80, 0, 0, 0, 0.8, 0.8, 0, 0.1, 0.1, 0],
"exclusions": [
[False, False],
[False, False],
[False, False]
]
},
"Dr. Shashidhar Kumar": {
"services": [0.8, 0.8, 0.8, 0, 0.25, 0.2, 0, 0, 0, 0],
"exclusions": [
[False, False],
[False, False],
[False, False]
]
},
"Dr. Vikas Singh": {
"services": [0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"exclusions": [
[False, False],
[False, False],
[False, False]
]
},
"Dr. Kumar Ashish": {
"services": [0, 0, 0, 0.8, 0.15, 0.15, 0.15, 0, 0, 0],
"exclusions": [
[False, False],
[False, False],
[False, False]
]
},
"Dr. Navneet Kumar": {
"services": [0.7, 0, 0, 0.7, 0.5, 0.5, 0.15, 0, 0, 0],
"exclusions": [
[False, False],
[False, False],
[False, True]
]
},
"Dr. Pooja Singh": {
"services": [0.8, 0, 0, 0.7, 0.15, 0.20, 0, 0, 0, 0],
"exclusions": [
[False, False],
[False, True],
[False, False]
]
},
"Dr. Rana Shamim": {
"services": [0, 0, 0, 0, 0.15, 0.15, 0, 0, 0, 0],
"exclusions": [
[False, False],
[True, True],
[False, False]
]
},
"Dr. Shilpi Kumari": {
"services": [0.7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"exclusions": [
[False, False],
[False, False],
[False, False]
]
},
"Dr. Shweta Shilpi": {
"services": [0.7, 0.8, 0.8, 0.8, 0.2, 0.2, 0, 0.15, 0.15, 0.30],
"exclusions": [
[False, False],
[False, False],
[False, False]
]
},
"Dr. Sushil Kumar Pathak": {
"services": [0.7, 0, 0, 0.7, 0.15, 0, 0.15, 0, 0, 0],
"exclusions": [
[False, False],
[False, False],
[False, True]
]
}
}
'''
# FINAL UPDATED CODE handling medical and surgical visibility with new services(diag, path and daycare)
import pandas as pd
import openpyxl
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
import os
import datetime
import json
from pathlib import Path
# Define all services in order
SERVICES = [
"OPD Consultation",
"IPD Consultation (Non-Package)",
"IPD Consultation (Package)",
"IPD Cross Consultation",
"Surgery (Package cases)",
"Surgery (Open cases)",
"Medical Management",
"OPD Diagnostics",
"OPD Pathology",
"Daycare Procedure"
]
# Define exclusions in order
EXCLUSION_TYPES = [
"Exclusions - Drugs & Implants",
"Exclusions - Other Doctor Fees"
]
# Define management types in order
MANAGEMENT_TYPES = [
"Surgical Management (Package)",
"Surgical Management (Non-Package)",
"Medical Management"
]
# SORTED ONE
# Doctor configuration - percentages for services and exclusions
# -----> DOCTORS Dictionary
# Get the directory of the current script (Variable folder)
current_dir = Path(__file__).parent.resolve()
# Construct the full path to the config file
config_path = current_dir / "mssh_maatri_doctors_config.json"
with open(config_path, 'r') as f:
DOCTORS = json.load(f)
# File mapping for each service
SERVICE_FILES = {
"OPD Consultation": "processed_opd_consultations.xlsx",
"IPD Consultation (Non-Package)": "self_open_for_doctors.xlsx",
"IPD Consultation (Package)": "self_package_for_doctors.xlsx",
"IPD Cross Consultation": "cross_for_doctors.xlsx",
"Surgery (Package cases)": "processed_medical_and_surgical_cases_with_exclusions.xlsx",
"Surgery (Open cases)": "processed_medical_and_surgical_cases_with_exclusions.xlsx",
"Medical Management": "processed_medical_and_surgical_cases_with_exclusions.xlsx",
"OPD Diagnostics": "processed_opd_diagnostics.xlsx",
"OPD Pathology": "processed_opd_pathology.xlsx",
"Daycare Procedure": "processed_opd_daycare.xlsx"
}
# Build DOCTOR_CONFIG from the simplified structure
DOCTOR_CONFIG = {
"services": {},
"exclusions": {}
}
# Build services configuration
for service in SERVICES:
DOCTOR_CONFIG["services"][service] = {
"file": SERVICE_FILES[service],
"variable_share": {
doctor: data["services"][SERVICES.index(service)]
for doctor, data in DOCTORS.items()
}
}
# Build exclusions configuration
for mgmt_type in MANAGEMENT_TYPES:
DOCTOR_CONFIG["exclusions"][mgmt_type] = {}
for excl_type in EXCLUSION_TYPES:
excl_index = EXCLUSION_TYPES.index(excl_type)
mgmt_index = MANAGEMENT_TYPES.index(mgmt_type)
DOCTOR_CONFIG["exclusions"][mgmt_type][excl_type] = {
doctor: data["exclusions"][mgmt_index][excl_index]
for doctor, data in DOCTORS.items()
}
# DOCTOR_CONFIG
current_month = datetime.datetime.now().strftime("%B")
current_year = datetime.datetime.now().year
# Helper function to clean numeric strings and convert to float
def clean_and_convert_to_float(value):
if isinstance(value, (int, float)):
return float(value)
elif isinstance(value, str):
cleaned = value.replace(",", "") # Remove commas
try:
return float(cleaned)
except ValueError:
return 0.0
else:
return 0.0
# Global styling objects
header_fill = PatternFill(start_color="92D050", end_color="92D050", fill_type="solid")
subheader_fill = PatternFill(start_color="B8CCE4", end_color="B8CCE4", fill_type="solid")
thin_border = Side(border_style="thin", color="000000")
border = Border(top=thin_border, left=thin_border, right=thin_border, bottom=thin_border)
header_font = Font(bold=True, color="FFFFFF", size=13)
subheader_font = Font(bold=True, size=12)
data_font = Font(size=11)
center_alignment = Alignment(horizontal="center", vertical="center")
left_alignment = Alignment(horizontal="left", vertical="center")
right_alignment = Alignment(horizontal="right", vertical="center")
yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
# for summary sheet
def create_summary_sheet(workbook, doctor_name, current_month, current_year):
summary_sheet = workbook.create_sheet("Summary", 0)
# Set column widths
summary_sheet.column_dimensions["A"].width = 5
summary_sheet.column_dimensions["B"].width = 55
summary_sheet.column_dimensions["C"].width = 25
summary_sheet.column_dimensions["D"].width = 30
summary_sheet.column_dimensions["E"].width = 30
# Add title row
summary_sheet.merge_cells("B2:E2")
title_cell = summary_sheet["B2"]
title_cell.value = f"[{doctor_name}] Variable Payout Summary - {current_month} {current_year}"
title_cell.fill = header_fill
title_cell.font = header_font
title_cell.alignment = center_alignment
# Add column headers
summary_sheet["B3"] = "Services"
summary_sheet["C3"] = "Total Sum"
summary_sheet["D3"] = "Variable Share"
summary_sheet["E3"] = "Final Share"
for col in ["B", "C", "D", "E"]:
cell = summary_sheet[f"{col}3"]
cell.fill = subheader_fill
cell.font = subheader_font
cell.alignment = center_alignment
cell.border = border
# List of services to skip in initial pass (will be handled later)
skip_services = ["Surgery (Package cases)", "Surgery (Open cases)", "Medical Management",
"OPD Diagnostics", "OPD Pathology", "Daycare Procedure"]
# Dynamically generate summary_rows based on DOCTOR_CONFIG and filter out 0% variable share
summary_rows = []
for service_name, service_data in DOCTOR_CONFIG["services"].items():
# Skip services that will be handled later
if service_name in skip_services:
continue
variable_share_for_doctor = service_data["variable_share"].get(doctor_name)
if variable_share_for_doctor is not None and variable_share_for_doctor != 0.00:
summary_rows.append({"service": service_name, "file": service_data["file"], "variable_share": variable_share_for_doctor})
# Initialize flags for surgery and medical management visibility
show_surgery_package = DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["variable_share"].get(doctor_name, 0.00) != 0.00
show_surgery_open = DOCTOR_CONFIG["services"]["Surgery (Open cases)"]["variable_share"].get(doctor_name, 0.00) != 0.00
show_medical_management = DOCTOR_CONFIG["services"]["Medical Management"]["variable_share"].get(doctor_name, 0.00) != 0.00
# Determine if the "Total Surgeries" line should be shown
show_total_surgeries_line = show_surgery_package or show_surgery_open
# Add specific surgical/medical management rows if applicable
surgical_rows = []
if show_total_surgeries_line:
surgical_rows.append({"service": f"Surgeries (Total {0} Surgeries in {current_month} {current_year})", "file": None, "variable_share": None})
if show_surgery_package:
surgical_rows.append({"service": " Surgery (Package cases)", "file": DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["file"], "variable_share": DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["variable_share"].get(doctor_name)})
if show_surgery_open:
surgical_rows.append({"service": " Surgery (Open cases)", "file": DOCTOR_CONFIG["services"]["Surgery (Open cases)"]["file"], "variable_share": DOCTOR_CONFIG["services"]["Surgery (Open cases)"]["variable_share"].get(doctor_name)})
if show_medical_management:
surgical_rows.append({"service": "Medical Management", "file": DOCTOR_CONFIG["services"]["Medical Management"]["file"], "variable_share": DOCTOR_CONFIG["services"]["Medical Management"]["variable_share"].get(doctor_name)})
# Append the surgical / medical block
summary_rows.extend(surgical_rows)
# Add new services after medical management
new_services = ["OPD Diagnostics", "OPD Pathology", "Daycare Procedure"]
for service_name in new_services:
service_data = DOCTOR_CONFIG["services"][service_name]
variable_share_for_doctor = service_data["variable_share"].get(doctor_name)
if variable_share_for_doctor is not None and variable_share_for_doctor != 0.00:
summary_rows.append({"service": service_name, "file": service_data["file"], "variable_share": variable_share_for_doctor})
# Add data rows
row_num = 4
for row_data in summary_rows:
summary_sheet[f"B{row_num}"] = row_data["service"]
# Apply styling to individual cells
for col in ["B", "C", "D", "E"]:
cell = summary_sheet[f"{col}{row_num}"]
cell.border = border
cell.font = data_font
if col == "B":
cell.alignment = left_alignment
else:
cell.alignment = right_alignment
row_num += 1
summary_sheet.insert_rows(row_num)
for col in ["B", "C", "D", "E"]:
summary_sheet[f"{col}{row_num}"].border = border
row_num += 1
# Add total and additional rows
total_row = row_num
summary_sheet[f"B{row_num}"] = f"Total Variable for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
row_num += 1
summary_sheet[f"B{row_num}"] = "Add: Previous Bills Realised from TPAs/Corporates"
summary_sheet[f"B{row_num}"].font = Font(size=11)
row_num += 1
summary_sheet[f"B{row_num}"] = f"Less: TPA/Corporate Dues for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(size=11)
row_num += 1
variable_payable_row = row_num
summary_sheet[f"B{row_num}"] = f"Variable Payable for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
row_num += 1
tds_row = row_num # Keep track of TDS row for highlighting later if needed
summary_sheet[f"B{row_num}"] = "Less: TDS @ 10%"
summary_sheet[f"B{row_num}"].font = Font(size=11)
row_num += 1
net_payable_row = row_num
summary_sheet[f"B{row_num}"] = f"Net Payable for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
# Highlight the net payable row with yellow color
for col in ["B", "C", "D", "E"]:
summary_sheet[f"{col}{net_payable_row}"].fill = yellow_fill
# Apply borders to all additional rows
for r in range(total_row, row_num + 1):
for col in ["B", "C", "D", "E"]:
cell = summary_sheet[f"{col}{r}"]
cell.border = border
if col != "B":
cell.alignment = right_alignment
# Add 3 blank rows before Note:
row_num += 3
# Add Exclusions table
summary_sheet[f"B{row_num}"] = "Note:"
row_num += 1
summary_sheet[f"B{row_num}"] = "Exclusions:"
row_num += 1
# Exclusions table headers
summary_sheet.merge_cells(start_row=row_num, start_column=2, end_row=row_num, end_column=3)
header_services_cell = summary_sheet["B" + str(row_num)]
header_services_cell.value = "Services"
header_services_cell.font = subheader_font
header_services_cell.alignment = center_alignment
header_services_cell.fill = subheader_fill
# Apply border to the merged Services header cell range
for col_idx in range(2, 4): # Columns B and C
summary_sheet.cell(row=row_num, column=col_idx).border = border
summary_sheet["D" + str(row_num)] = "Exclusions - Drugs & Implants"
summary_sheet["E" + str(row_num)] = "Exclusions - Other Doctor Fees"
# Adjust column widths for the exclusions table headers
summary_sheet.column_dimensions["B"].width = 60 # Adjust width for merged Services column
summary_sheet.column_dimensions["D"].width = 25 # Adjust width for Drugs & Implants column
summary_sheet.column_dimensions["E"].width = 25 # Adjust width for Other Doctor Fees column
# Apply styling to the non-merged header cells (D and E)
for col_idx in [4, 5]:
cell = summary_sheet.cell(row=row_num, column=col_idx)
cell.font = subheader_font
cell.alignment = center_alignment
cell.fill = subheader_fill
cell.border = border
row_num += 1
# Exclusions table content
exclusion_data = [
("In Surgical Management (Package)", "Surgical Management (Package)"),
("In Surgical Management (Non Package)", "Surgical Management (Non-Package)"),
("In Medical Management", "Medical Management")
]
for display_name, config_key in exclusion_data:
# Merge B and C for Services content first
summary_sheet.merge_cells(start_row=row_num, start_column=2, end_row=row_num, end_column=3)
content_services_cell = summary_sheet["B" + str(row_num)]
content_services_cell.value = display_name
content_services_cell.font = data_font
content_services_cell.alignment = left_alignment
# Apply border to the merged Services content cell range
for col_idx in range(2, 4): # Columns B and C
summary_sheet.cell(row=row_num, column=col_idx).border = border
drugs_excluded = DOCTOR_CONFIG["exclusions"][config_key]["Exclusions - Drugs & Implants"].get(doctor_name, False)
other_fees_excluded = DOCTOR_CONFIG["exclusions"][config_key]["Exclusions - Other Doctor Fees"].get(doctor_name, False)
drugs_cell = summary_sheet["D" + str(row_num)]
other_fees_cell = summary_sheet["E" + str(row_num)]
drugs_cell.value = "Yes" if drugs_excluded else "No"
other_fees_cell.value = "Yes" if other_fees_excluded else "No"
if drugs_excluded:
drugs_cell.font = Font(bold=True)
if other_fees_excluded:
other_fees_cell.font = Font(bold=True)
# Apply borders and alignment to the non-merged content cells (D and E)
for col_idx in [4, 5]:
cell = summary_sheet.cell(row=row_num, column=col_idx)
cell.alignment = center_alignment
cell.border = border
row_num += 1
return summary_sheet, summary_rows, net_payable_row, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line
# Function to populate the summary sheet with data
def populate_summary_data(summary_sheet, summary_rows, data_dir, doctor_name, net_payable_row, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line, current_month, current_year):
total_sums = {}
# Load the pre-processed surgical/medical management data once
surgical_medical_df = None
surgical_medical_file = DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["file"]
if os.path.exists(os.path.join(data_dir, surgical_medical_file)):
surgical_medical_df = pd.read_excel(os.path.join(data_dir, surgical_medical_file))
# Drop rows where all cells are NaN (blank rows)
surgical_medical_df.dropna(how='all', inplace=True)
# Ensure numeric columns are float for calculations
for col in ["Net Bill", "Exclusions-Drugs & Implants", "Exclusions-Other Doctors' Fees"]:
if col in surgical_medical_df.columns:
surgical_medical_df[col] = surgical_medical_df[col].apply(clean_and_convert_to_float)
row_num = 4
for row_data in summary_rows:
service = row_data["service"]
file = row_data.get("file")
variable_share = row_data.get("variable_share")
current_total_sum = 0.0
df_to_process = None
# HANDLE NEW SERVICES
if service in ["OPD Consultation", "OPD Diagnostics", "OPD Pathology", "Daycare Procedure"]:
if file and os.path.exists(os.path.join(data_dir, file)):
df_to_process = pd.read_excel(os.path.join(data_dir, file))
df_to_process.dropna(how='all', inplace=True)
if "Net Amount" in df_to_process.columns:
df_to_process["Net Amount"] = df_to_process["Net Amount"].apply(clean_and_convert_to_float)
current_total_sum = df_to_process["Net Amount"].sum()
elif service in ["IPD Consultation (Non-Package)", "IPD Consultation (Package)", "IPD Cross Consultation"]:
if file and os.path.exists(os.path.join(data_dir, file)):
df_to_process = pd.read_excel(os.path.join(data_dir, file))
df_to_process.dropna(how='all', inplace=True)
if "Total" in df_to_process.columns:
df_to_process["Total"] = df_to_process["Total"].apply(clean_and_convert_to_float)
current_total_sum = df_to_process["Total"].sum()
elif service == " Surgery (Package cases)":
if surgical_medical_df is not None:
df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Package"].copy()
if not df_filtered.empty and "Net Bill" in df_filtered.columns:
df_filtered["Final Bill"] = df_filtered["Net Bill"]
# Apply exclusions
if DOCTOR_CONFIG["exclusions"]["Surgical Management (Package)"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
if DOCTOR_CONFIG["exclusions"]["Surgical Management (Package)"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
current_total_sum = df_filtered["Final Bill"].sum()
# Update total surgeries count
if show_total_surgeries_line:
for i, row_data_summary in enumerate(summary_rows):
if "Surgeries (Total" in row_data_summary["service"]:
total_surgeries_count = 0
if show_surgery_package:
total_surgeries_count += surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Package"].shape[0]
if show_surgery_open:
total_surgeries_count += surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Open"].shape[0]
summary_sheet[f"B{i+4}"].value = f"Surgeries (Total {total_surgeries_count} Surgeries in {current_month} {current_year})"
break
elif service == " Surgery (Open cases)":
if surgical_medical_df is not None:
df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Open"].copy()
if not df_filtered.empty and "Net Bill" in df_filtered.columns:
df_filtered["Final Bill"] = df_filtered["Net Bill"]
# Apply exclusions
if DOCTOR_CONFIG["exclusions"]["Surgical Management (Non-Package)"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
if DOCTOR_CONFIG["exclusions"]["Surgical Management (Non-Package)"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
current_total_sum = df_filtered["Final Bill"].sum()
# Update total surgeries count
if show_total_surgeries_line:
for i, row_data_summary in enumerate(summary_rows):
if "Surgeries (Total" in row_data_summary["service"]:
total_surgeries_count = 0
if show_surgery_package:
total_surgeries_count += surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Package"].shape[0]
if show_surgery_open:
total_surgeries_count += surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Open"].shape[0]
summary_sheet[f"B{i+4}"].value = f"Surgeries (Total {total_surgeries_count} Surgeries in {current_month} {current_year})"
break
elif service == "Medical Management":
if surgical_medical_df is not None:
df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Medical"].copy()
if not df_filtered.empty and "Net Bill" in df_filtered.columns:
df_filtered["Final Bill"] = df_filtered["Net Bill"]
# Apply exclusions
if DOCTOR_CONFIG["exclusions"]["Medical Management"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
if DOCTOR_CONFIG["exclusions"]["Medical Management"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
current_total_sum = df_filtered["Final Bill"].sum()
total_sums[service] = current_total_sum
# Display Total Sum - skip the surgeries header row
if "Surgeries (Total" not in service:
summary_sheet[f"C{row_num}"] = int(current_total_sum)
summary_sheet[f"C{row_num}"].number_format = "βΉ #,##0"
# Display Variable Share and Final Share
if variable_share is not None:
if isinstance(variable_share, (int, float)) and variable_share <= 1.0:
# Percentage
summary_sheet[f"D{row_num}"] = int(variable_share * 100)
summary_sheet[f"D{row_num}"].number_format = "0\"%\""
final_share = current_total_sum * variable_share
elif isinstance(variable_share, (int, float)) and variable_share > 1.0:
# Hardcoded value (like 30000)
summary_sheet[f"D{row_num}"] = int(variable_share)
summary_sheet[f"D{row_num}"].number_format = "#,##0"
final_share = current_total_sum * variable_share # This might need adjustment based on how "Extra Cash" is calculated
else: # "variable" case for surgical/medical management
summary_sheet[f"D{row_num}"] = int(variable_share * 100) if isinstance(variable_share, float) else variable_share # Display percentage if float
summary_sheet[f"D{row_num}"].number_format = "0\"%\"" if isinstance(variable_share, float) else "General"
final_share = current_total_sum * variable_share if isinstance(variable_share, float) else 0 # Calculate if percentage
summary_sheet[f"E{row_num}"] = int(final_share)
summary_sheet[f"E{row_num}"].number_format = "βΉ #,##0"
total_sums[f"{service}_final"] = final_share
row_num += 1
row_num+=1
# Calculate and display total variable
total_final_share = sum([v for k, v in total_sums.items() if k.endswith("_final")])
total_row = row_num
summary_sheet[f"E{total_row}"] = int(total_final_share)
summary_sheet[f"E{total_row}"].number_format = "βΉ #,##0"
# The rest of the total and additional rows logic remains largely the same
# ... (omitted for brevity, as it's mostly formatting and fixed values)
row_num += 1
# ... (skip some rows for brevity)
# Removed the duplicate "Add: Previous Bills Realised from TPAs/Corporates" row
summary_sheet[f"B{row_num}"] = "Add: Previous Bills Realised from TPAs/Corporates"
summary_sheet[f"B{row_num}"].font = Font(size=11)
row_num += 1
summary_sheet[f"B{row_num}"] = f"Less: TPA/Corporate Dues for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(size=11)
# Removed the "Less: Professional Fee for Dr. Gurudeo" row
row_num += 1
variable_payable = total_final_share # Removed Dr. Gurudeo's fee subtraction here
summary_sheet[f"B{row_num}"] = f"Variable Payable for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
summary_sheet[f"E{row_num}"] = int(variable_payable)
summary_sheet[f"E{row_num}"].number_format = "βΉ #,##0"
row_num += 1
tds = variable_payable * 0.10
summary_sheet[f"B{row_num}"] = "Less: TDS @ 10%"
summary_sheet[f"B{row_num}"].font = Font(size=11)
summary_sheet[f"E{row_num}"] = int(tds)
summary_sheet[f"E{row_num}"].number_format = "βΉ #,##0"
row_num += 1
net_payable = variable_payable - tds
summary_sheet[f"B{row_num}"] = f"Net Payable for {current_month}-{current_year}"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
summary_sheet[f"E{row_num}"] = int(net_payable)
summary_sheet[f"E{row_num}"].number_format = "βΉ #,##0"
# Apply borders to all additional rows
for r in range(total_row, row_num + 1):
for col in ["B", "C", "D", "E"]:
cell = summary_sheet[f"{col}{r}"]
cell.border = border
if col != "B":
cell.alignment = right_alignment
# Highlight the net payable row with yellow color
for col in ["B", "C", "D", "E"]:
summary_sheet[f"{col}{net_payable_row}"].fill = yellow_fill
return total_sums
# Function to add individual report sheets
def add_report_sheets(workbook, summary_rows, data_dir, doctor_name, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line):
# Load the pre-processed surgical/medical management data once
surgical_medical_df = None
surgical_medical_file = DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["file"]
if os.path.exists(os.path.join(data_dir, surgical_medical_file)):
surgical_medical_df = pd.read_excel(os.path.join(data_dir, surgical_medical_file))
surgical_medical_df.dropna(how='all', inplace=True)
# Ensure numeric columns are float for calculations
for col in ["Net Bill", "Exclusions-Drugs & Implants", "Exclusions-Other Doctors' Fees"]:
if col in surgical_medical_df.columns:
surgical_medical_df[col] = surgical_medical_df[col].apply(clean_and_convert_to_float)
for row_data in summary_rows:
service = row_data["service"]
file = row_data.get("file")
df_to_add_sheet = None
sheet_name = service.replace(" ", "")[:31] # Excel sheet names are limited to 31 characters
# Check if the service should be included as a separate sheet
# This prevents creating sheets for services that were hidden in the summary
if service == "Medical Management" and not show_medical_management:
continue
if service == " Surgery (Package cases)" and not show_surgery_package:
continue
if service == " Surgery (Open cases)" and not show_surgery_open:
continue
if "Surgeries (Total" in service:
continue # Skip the total surgeries line as it's not a data sheet
if service == "OPD Consultation":
if file and os.path.exists(os.path.join(data_dir, file)):
df_to_add_sheet = pd.read_excel(os.path.join(data_dir, file))
df_to_add_sheet.dropna(how='all', inplace=True)
# HANDLE NEW SERVICES
elif service in ["OPD Diagnostics", "OPD Pathology", "Daycare Procedure"]:
if file and os.path.exists(os.path.join(data_dir, file)):
df_to_add_sheet = pd.read_excel(os.path.join(data_dir, file))
df_to_add_sheet.dropna(how='all', inplace=True)
elif service in ["IPD Consultation (Non-Package)", "IPD Consultation (Package)", "IPD Cross Consultation"]:
if file and os.path.exists(os.path.join(data_dir, file)):
df_to_add_sheet = pd.read_excel(os.path.join(data_dir, file))
df_to_add_sheet.dropna(how='all', inplace=True)
elif service == " Surgery (Package cases)":
if surgical_medical_df is not None:
df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Package"].copy()
if not df_filtered.empty:
df_filtered["Final Bill"] = df_filtered["Net Bill"]
# Apply exclusions for the sheet data as well
if DOCTOR_CONFIG["exclusions"]["Surgical Management (Package)"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
if DOCTOR_CONFIG["exclusions"]["Surgical Management (Package)"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
df_to_add_sheet = df_filtered
elif service == " Surgery (Open cases)":
if surgical_medical_df is not None:
df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Open"].copy()
if not df_filtered.empty:
df_filtered["Final Bill"] = df_filtered["Net Bill"]
# Apply exclusions for the sheet data as well
if DOCTOR_CONFIG["exclusions"]["Surgical Management (Non-Package)"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
if DOCTOR_CONFIG["exclusions"]["Surgical Management (Non-Package)"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
df_to_add_sheet = df_filtered
elif service == "Medical Management":
if surgical_medical_df is not None:
df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Medical"].copy()
if not df_filtered.empty:
df_filtered["Final Bill"] = df_filtered["Net Bill"]
# Apply exclusions for the sheet data as well
if DOCTOR_CONFIG["exclusions"]["Medical Management"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
if DOCTOR_CONFIG["exclusions"]["Medical Management"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
df_to_add_sheet = df_filtered
if df_to_add_sheet is not None and not df_to_add_sheet.empty:
sheet = workbook.create_sheet(sheet_name)
# Write the headers
for col_idx, col_name in enumerate(df_to_add_sheet.columns, 1):
sheet.cell(row=1, column=col_idx, value=col_name)
sheet.cell(row=1, column=col_idx).font = Font(bold=True)
# Write the data
for row_idx, row in df_to_add_sheet.iterrows():
for col_idx, value in enumerate(row, 1):
sheet.cell(row=row_idx+2, column=col_idx, value=value)
# Auto-adjust column widths
for col in sheet.columns:
max_length = 0
column = col[0].column_letter
for cell in col:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 2)
sheet.column_dimensions[column].width = min(adjusted_width, 30)
def create_combined_report(data_dir, output_file, doctor_name, current_month, current_year):
workbook = openpyxl.Workbook()
default_sheet = workbook.active
workbook.remove(default_sheet)
summary_sheet, summary_rows, net_payable_row, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line = create_summary_sheet(workbook, doctor_name, current_month, current_year)
total_sums = populate_summary_data(summary_sheet, summary_rows, data_dir, doctor_name, net_payable_row, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line, current_month, current_year)
add_report_sheets(workbook, summary_rows, data_dir, doctor_name, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line)
workbook.save(output_file)
return output_file, total_sums
# FINAL WRAPPER FUNCTION
import tempfile
import shutil
def generate_mssh_maatri_doctor_report(
doctor_name: str,
hospital_revenue_report_path: str,
inpatient_bill_register_path: str,
doctor_visit_with_package_path: str,
doctor_visit_without_package_path: str,
current_month: str,
current_year: str
):
"""
End-to-end processing for a single doctor's variable payout report.
Args:
doctor_name: The name of the doctor to process.
hospital_revenue_report_path: Path to the hospital revenue report HTML file.
inpatient_bill_register_path: Path to the inpatient bill register HTML file.
doctor_visit_with_package_path: Path to the doctor visit report (with package) HTML file.
doctor_visit_without_package_path: Path to the doctor visit report (without package) HTML file.
current_month: The current month as a string (e.g., \"July\").
current_year: The current year as an integer (e.g., 2025).
Returns:
Path to the final summary report or None if an error occurs.
"""
try:
with tempfile.TemporaryDirectory() as tmpdir:
print(f"--- Starting processing for {doctor_name} for {current_month} {current_year} ---")
# Step 1: Convert HTML files to Excel
print("\n[Step 1/10] Converting HTML files to Excel...")
html_files_to_convert = {
"hospital_revenue": hospital_revenue_report_path,
"inpatient_bill": inpatient_bill_register_path,
"doctor_visit_with_package": doctor_visit_with_package_path,
"doctor_visit_without_package": doctor_visit_without_package_path
}
converted_files = {}
for key, path in html_files_to_convert.items():
base_name = os.path.splitext(os.path.basename(path))[0]
output_path = os.path.join(tmpdir, f"processed_{base_name}.xlsx")
convert_html_to_excel(path, output_path)
converted_files[key] = output_path
print(f"β Converted {os.path.basename(path)} to Excel.")
# Step 2: Process OPD Consultation (if applicable)
if DOCTOR_CONFIG["services"]["OPD Consultation"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\n[Step 2/10] Processing OPD Consultations...")
opd_consultations_path = os.path.join(tmpdir, "processed_opd_consultations.xlsx")
results = filter_patient_records(converted_files["hospital_revenue"], doctor_name)
results.to_excel(opd_consultations_path, index=False)
print(f"β OPD consultations processed and saved.")
else:
print("\n[Step 2/10] Skipping OPD Consultations (0.00% variable share).")
# Step 3: Combine doctor visit reports and tag consultations
print("\n[Step 3/10] Combining and tagging IPD consultations...")
df_visit_pkg = pd.read_excel(converted_files["doctor_visit_with_package"])
df_visit_no_pkg = pd.read_excel(converted_files["doctor_visit_without_package"])
df_visit_pkg["Type"] = "Package"
df_visit_no_pkg["Type"] = "Open"
df_visit_combined = pd.concat([df_visit_pkg, df_visit_no_pkg], axis=0, ignore_index=True)
visit_combined_path = os.path.join(tmpdir, "final_processed_doctor_visit_report.xlsx")
df_visit_combined.to_excel(visit_combined_path, index=False)
df_visits = pd.read_excel(visit_combined_path)
df_admissions = pd.read_excel(converted_files['inpatient_bill'])
df_visits['Consultation Type'] = pd.NA
norm_input = normalize_doctor_name(doctor_name)
admissions = (
df_admissions[df_admissions['Admiting Doctor']
.map(normalize_doctor_name) == norm_input]
['Admission No.']
.unique()
)
mask_doc = df_visits['Doctor Name'].map(normalize_doctor_name) == norm_input
mask_adm = df_visits['Admission No.'].isin(admissions)
df_visits.loc[mask_doc & mask_adm, 'Consultation Type'] = 'Self'
df_visits.loc[mask_doc & ~mask_adm, 'Consultation Type'] = 'Cross'
tagged_consultations_path = os.path.join(tmpdir, "precision_tagged_all_consultations.xlsx")
df_visits.to_excel(tagged_consultations_path, index=False)
# Step 4: Process IPD Consultation (Non-Package) (if applicable)
if DOCTOR_CONFIG["services"]["IPD Consultation (Non-Package)"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\n[Step 4/10] Processing IPD Consultation (Non-Package)...")
self_open_path = os.path.join(tmpdir, "self_open_for_doctors.xlsx")
self_open_records = get_self_open_records(tagged_consultations_path, [doctor_name])
self_open_records.to_excel(self_open_path, index=False)
print(f"β IPD Consultation (Non-Package) processed and saved.")
else:
print("\n[Step 4/10] Skipping IPD Consultation (Non-Package) (0.00% variable share).")
# Step 5: Process IPD Consultation (Package) (if applicable)
if DOCTOR_CONFIG["services"]["IPD Consultation (Package)"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\n[Step 5/10] Processing IPD Consultation (Package)...")
self_package_path = os.path.join(tmpdir, "self_package_for_doctors.xlsx")
self_package_records = get_self_package_records(tagged_consultations_path, [doctor_name])
self_package_records.to_excel(self_package_path, index=False)
print(f"β IPD Consultation (Package) processed and saved.")
else:
print("\n[Step 5/10] Skipping IPD Consultation (Package) (0.00% variable share).")
# Step 6: Process IPD Cross Consultation (if applicable)
if DOCTOR_CONFIG["services"]["IPD Cross Consultation"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\n[Step 6/10] Processing IPD Cross Consultation...")
cross_consultation_path = os.path.join(tmpdir, "cross_for_doctors.xlsx")
cross_records = get_cross_records(tagged_consultations_path, [doctor_name])
cross_records.to_excel(cross_consultation_path, index=False)
print(f"β IPD Cross Consultation processed and saved.")
else:
print("\n[Step 6/10] Skipping IPD Cross Consultation (0.00% variable share).")
# Step 7: Process Surgical and Medical Management (if applicable)
run_surg_med_processing = (
DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["variable_share"].get(doctor_name, 0.00) != 0.00 or
DOCTOR_CONFIG["services"]["Surgery (Open cases)"]["variable_share"].get(doctor_name, 0.00) != 0.00 or
DOCTOR_CONFIG["services"]["Medical Management"]["variable_share"].get(doctor_name, 0.00) != 0.00
)
if run_surg_med_processing:
print("\n[Step 7/10] Processing Surgical and Medical Management...")
surg_med_output_path = os.path.join(tmpdir, "processed_medical_and_surgical_cases_with_exclusions.xlsx")
preprocess_revenue(converted_files["hospital_revenue"], doctor_name, surg_med_output_path)
print(f"β Surgical and Medical Management cases processed and saved.")
else:
print("\n[Step 7/10] Skipping Surgical and Medical Management (all 0.00% variable share).")
# Step 8: Process Diagnostic services (if applicable)
if DOCTOR_CONFIG["services"]["OPD Diagnostics"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\n[Step 8/10] Processing Diagnostic services...")
diagnostic_output = os.path.join(tmpdir, "processed_opd_diagnostics.xlsx")
generate_service_reports(converted_files['hospital_revenue'], doctor_name, 'Diagnostic', diagnostic_output)
print(f"β Diagnostic services processed and saved.")
else:
print("\n[Step 8/10] Skipping Diagnostic services (0.00% variable share).")
# Step 9: Process Pathology services (if applicable)
if DOCTOR_CONFIG["services"]["OPD Pathology"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\n[Step 9/10] Processing Pathology services...")
pathology_output = os.path.join(tmpdir, "processed_opd_pathology.xlsx")
generate_service_reports(converted_files['hospital_revenue'], doctor_name, 'Pathology', pathology_output)
print(f"β Pathology services processed and saved.")
else:
print("\n[Step 9/10] Skipping Pathology services (0.00% variable share).")
# Step 10: Process Day Care Procedure services (if applicable)
if DOCTOR_CONFIG["services"]["Daycare Procedure"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\n[Step 10/10] Processing Day Care Procedure services...")
daycare_output = os.path.join(tmpdir, "processed_opd_daycare.xlsx")
generate_service_reports(converted_files['hospital_revenue'], doctor_name, 'Day Care Procedure', daycare_output)
print(f"β Day Care Procedure services processed and saved.")
else:
print("\n[Step 10/10] Skipping Day Care Procedure services (0.00% variable share).")
# Final Step: Create the combined report
print("\n--- Generating Final Report ---")
# Update global variables for month/year
final_report_name = f"{doctor_name}-{current_month}-{current_year}.xlsx"
final_report_path = os.path.join(tmpdir, final_report_name)
# Create the combined report
create_combined_report(tmpdir, final_report_path, doctor_name, current_month, current_year)
# Copy final output to permanent location
permanent_output = os.path.join(os.getcwd(), final_report_name)
shutil.copy(final_report_path, permanent_output)
print(f"βββ Processing complete! Final report saved to: {permanent_output} βββ")
return permanent_output
except Exception as e:
print(f"An error occurred during processing for {doctor_name}: {str(e)}")
import traceback
traceback.print_exc()
return None
# Example usage of the wrapper function
if __name__ == "__main__":
final_report_path = generate_mssh_maatri_doctor_report(
doctor_name="Dr. Shashidhar Kumar",
hospital_revenue_report_path="/content/drive/MyDrive/VarAuto/print_hospital_revenue_report.php (11).xls",
inpatient_bill_register_path="/content/drive/MyDrive/VarAuto/print_inpatient_bill_register_report.xls",
doctor_visit_with_package_path="/content/drive/MyDrive/VarAuto/doctor_visit_report_with_package.xls",
doctor_visit_without_package_path="/content/drive/MyDrive/VarAuto/doctor_visit_report_without_package.xls",
current_month="May",
current_year="2025"
)
if final_report_path:
print(f"Report successfully generated at: {final_report_path}")
else:
print("Report generation failed.") |