Spaces:
Sleeping
Sleeping
Download variable/mhs_variable.py from mhpl/rr_payout_test: direct link, hf CLI and curl.
- Browser
- Download file 71.7 kB
-
https://huggingface.co/spaces/mhpl/rr_payout_test/resolve/main/variable/mhs_variable.py
- Command line
-
hf download hf://spaces/mhpl/rr_payout_test/variable/mhs_variable.py
-
curl -L -o mhs_variable.py https://huggingface.co/spaces/mhpl/rr_payout_test/resolve/main/variable/mhs_variable.py
71.7 kB
# -*- coding: utf-8 -*-
"""MHS_Variable_Payout.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1I5F6Yxj8GpAhw_AEF-u-SijO3rBOa6yi
"""
"""
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/mhs_print_hospital_revenue_report.php (16).xls',
'/content/drive/MyDrive/VarAuto/maatri_print_hospital_revenue_report.php (16).xls',
'/content/drive/MyDrive/VarAuto/print_hospital_revenue_report.php (11).xls',
'/content/drive/MyDrive/VarAuto/doctor_visit_report_without_package.xls',
'/content/drive/MyDrive/VarAuto/doctor_visit_report_with_package.xls',
'/content/drive/MyDrive/VarAuto/maatri_doctor_visit_report_with_package.xls',
'/content/drive/MyDrive/VarAuto/maatri_doctor_visit_report_without_package.xls',
'/content/drive/MyDrive/VarAuto/print_inpatient_bill_register_report.xls',
'/content/drive/MyDrive/VarAuto/maatri_print_inpatient_bill_register_report.xls'
]
process_multiple_files(file_list)
# OPD Consultations
import pandas as pd
import re
def normalize_name(name):
"""Clean doctor names for robust matching"""
# Remove 'Dr' prefixes with any formatting
name = re.sub(r'^dr[\.\s]*', '', str(name), flags=re.IGNORECASE)
# Remove all non-alphanumeric characters and spaces
name = re.sub(r'[^a-zA-Z0-9]', '', name)
return name.lower().strip()
def filter_patient_records(file_path, search_term):
# Load Excel data
df = pd.read_excel(file_path)
# Preprocess doctor names in dataframe
df['clean_name'] = df['Dr. Name'].apply(normalize_name)
# Preprocess search term
search_clean = normalize_name(search_term)
# Apply filters
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'])
# Example usage
if __name__ == "__main__":
excel_file = "/content/processed_mhs_print_hospital_revenue_report.php (16).xlsx"
search = 'Dr. Amit 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', 'Dr. Name', 'Dr. Department', 'Service Name', 'Net Amount']])
else:
print("\nNo matches found")
# Diag and Path Cases
import pandas as pd
import re
def normalize_name(name):
"""Clean doctor names for robust matching"""
# Remove 'Dr' prefixes with any formatting
name = re.sub(r'^dr[\.\s]*', '', str(name), flags=re.IGNORECASE)
# Remove all non-alphanumeric characters and spaces
name = re.sub(r'[^a-zA-Z0-9]', '', name)
return name.lower().strip()
def filter_diag_path_records(file_path, search_term):
# Load Excel data
df = pd.read_excel(file_path)
# Preprocess doctor names in dataframe
df['clean_name'] = df['Dr. Name'].apply(normalize_name)
# Preprocess search term
search_clean = normalize_name(search_term)
# Apply filters: Patient Type OPD, Service Type Diagnostic OR Pathology, and doctor match
filtered = df[
(df['Patient Type'].str.strip().str.upper() == 'OPD')
&
df['Service Type']
.str.contains(r'Diagnostic|Pathology', case=False, na=False)
&
df['clean_name'].str.contains(search_clean, regex=False, na=False)
]
return filtered.drop(columns=['clean_name'])
# Example usage
if __name__ == "__main__":
excel_file = "/content/processed_mhs_print_hospital_revenue_report.php (16).xlsx"
search = 'Dr. Amit Kumar'
output_file = 'processed_diag_and_path.xlsx'
results = filter_diag_path_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', 'Dr. Name', 'Dr. Department', 'Service Name', 'Net Amount']])
else:
print("\nNo matches found")
# Enhanced Day Care Procedure Cases with Additional Service Types
# Day Care and Other Charges
import pandas as pd
import re
def normalize_name(name):
"""Clean doctor names for robust matching"""
# Handle missing values
if pd.isna(name):
return ""
# Remove 'Dr' prefixes with any formatting
name = re.sub(r'^dr[\.\s]*', '', str(name), flags=re.IGNORECASE)
# Remove all non-alphanumeric characters and spaces
name = re.sub(r'[^a-zA-Z0-9]', '', name)
return name.lower().strip()
def normalize_service_type(service_type):
"""Normalize service type for consistent matching"""
if pd.isna(service_type):
return ""
# Convert to lowercase and remove special characters/extra spaces
service_type = str(service_type).lower().strip()
service_type = re.sub(r'[^a-z0-9\s]', '', service_type)
# Consolidate variations
service_type = re.sub(r'\s+', ' ', service_type) # Collapse multiple spaces
return service_type
def filter_daycare_records(file_path, search_term):
# Load Excel data
df = pd.read_excel(file_path)
# Preprocess doctor names in dataframe
df['clean_name'] = df['Dr. Name'].apply(normalize_name)
# Preprocess service types
df['clean_service'] = df['Service Type'].apply(normalize_service_type)
# Preprocess search term
search_clean = normalize_name(search_term)
# Define valid service types after normalization
valid_services = ['day care procedure', 'other charges']
# Apply filters
filtered = df[
(df['Patient Type'] == 'OPD') &
(df['clean_service'].isin(valid_services)) &
(df['clean_name'].str.contains(search_clean, regex=False, na=False))
]
return filtered.drop(columns=['clean_name', 'clean_service'])
# Example usage
if __name__ == "__main__":
excel_file = "/content/processed_mhs_print_hospital_revenue_report.php (16).xlsx"
search = 'Dr. Amit Kumar'
output_file = 'processed_daycare.xlsx'
results = filter_daycare_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', 'Dr. Name', 'Dr. Department',
'Service Type', 'Service Name', 'Net Amount']])
else:
print("\nNo matches found")
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 combine_doctor_visit_reports(
with_pkg_path: str,
without_pkg_path: str,
output_path: str
) -> pd.DataFrame:
"""Combine package and non-package visit reports, add Type column."""
df_with = pd.read_excel(with_pkg_path)
df_without = pd.read_excel(without_pkg_path)
df_with['Type'] = 'Package'
df_without['Type'] = 'Open'
combined = pd.concat([df_with, df_without], axis=0, ignore_index=True)
combined.to_excel(output_path, index=False)
print(f"Saved combined visit report: {output_path}")
return combined
def get_cross_consultations(
visit_file: str,
bill_file: str,
doctor_list: list[str],
unit_name: str # New parameter for hospital/unit name
) -> pd.DataFrame:
"""
Process one hospital's reports and extract only Cross consultations
for the specified doctors. Adds a 'Unit' column.
"""
df_visit = pd.read_excel(visit_file)
df_bill = pd.read_excel(bill_file)
# Add Consultation Type column
df_visit['Consultation Type'] = pd.NA
# Normalize admitting doctor names and map admissions
df_bill['clean_admit'] = df_bill['Admiting Doctor'].map(normalize_doctor_name)
admission_map = (
df_bill[['clean_admit', 'Admission No.']]
.groupby('clean_admit')['Admission No.']
.unique()
)
# Normalize doctor names in visit report
df_visit['clean_doc'] = df_visit['Doctor Name'].map(normalize_doctor_name)
# Prepare normalized doctor set
norm_docs = {normalize_doctor_name(d) for d in doctor_list}
# With this corrected logic:
for norm_doc in norm_docs:
mask_doc = df_visit['clean_doc'] == norm_doc
if norm_doc not in admission_map:
# No admissions for this doctor β all visits are Cross
df_visit.loc[mask_doc, 'Consultation Type'] = 'Cross'
else:
mask_adm = df_visit['Admission No.'].isin(admission_map[norm_doc])
df_visit.loc[mask_doc & mask_adm, 'Consultation Type'] = 'Self'
df_visit.loc[mask_doc & ~mask_adm, 'Consultation Type'] = 'Cross'
# Filter only Cross consults for target doctors
result = df_visit[df_visit['clean_doc'].isin(norm_docs) &
(df_visit['Consultation Type'] == 'Cross')].copy()
result.drop(columns='clean_doc', inplace=True)
# Add Unit column
result['Unit'] = unit_name
return result
def main():
# Doctors to analyze
doctors = [
'Dr. Amit Kumar'
]
# Maatri Hospital Files
maatri_files = {
'with_pkg': '/content/processed_maatri_doctor_visit_report_with_package.xlsx',
'without_pkg': '/content/processed_maatri_doctor_visit_report_without_package.xlsx',
'bill_register': '/content/processed_maatri_print_inpatient_bill_register_report.xlsx',
'visit_output': 'final_processed_maatri_doctor_visit_report.xlsx'
}
# Another Hospital Files (update these paths accordingly)
mssh_files = {
'with_pkg': '/content/processed_doctor_visit_report_with_package.xlsx',
'without_pkg': '/content/processed_doctor_visit_report_without_package.xlsx',
'bill_register': '/content/processed_print_inpatient_bill_register_report.xlsx',
'visit_output': 'final_processed_mssh_doctor_visit_report.xlsx'
}
# Step 1: Combine doctor visit reports for both hospitals
print("\n--- Combining Visit Reports ---")
combine_doctor_visit_reports(
maatri_files['with_pkg'],
maatri_files['without_pkg'],
maatri_files['visit_output']
)
combine_doctor_visit_reports(
mssh_files['with_pkg'],
mssh_files['without_pkg'],
mssh_files['visit_output']
)
# Step 2: Get cross consultations from both hospitals
print("\n--- Extracting Cross Consultations ---")
cross_maatri = get_cross_consultations(
maatri_files['visit_output'],
maatri_files['bill_register'],
doctors,
unit_name='Maatri'
)
print(f"Found {len(cross_maatri)} cross consultations in Maatri")
cross_mssh = get_cross_consultations(
mssh_files['visit_output'],
mssh_files['bill_register'],
doctors,
unit_name='MSSH'
)
print(f"Found {len(cross_mssh)} cross consultations in MSSH")
# Step 3: Combine both hospitals' cross consults
combined_cross = pd.concat([cross_maatri, cross_mssh], ignore_index=True)
# Step 4: Save final merged file
output_file = 'combined_cross_consultations_from_both_hospitals.xlsx'
combined_cross.to_excel(output_file, index=False)
print(f"Final merged report saved at: {output_file}")
print("Each record now includes a 'Unit' column indicating the source hospital.")
if __name__ == "__main__":
main()
# code for handling both surgical and medical management cases
# this one is for MHS Doctors (takes maatri and mssh reports both)
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,
)-> 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]
return sample
def combine_reports(
file_paths: list,
doctor_name: str,
output_path: str
) -> pd.DataFrame:
"""Process multiple files and merge results. Assumes NO DUPLICATES between files."""
dfs = []
for file in file_paths:
try:
df = preprocess_revenue(file, doctor_name)
# Only append non-empty DataFrames
if not df.empty:
dfs.append(df)
else:
print(f"No IPD records found in {file} for {doctor_name}")
except Exception as e:
print(f"Error processing {file}: {e}")
if not dfs:
print(f"Note: No IPD records found for {doctor_name} in any file. Creating empty dataset.")
# 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
# Simply concatenate all DataFrames
combined_df = pd.concat(dfs, ignore_index=True)
# Sort by Admission No. (optional but improves readability)
if 'Admission No.' in combined_df.columns and not combined_df.empty:
combined_df.sort_values(by='Admission No.', inplace=True)
# Export to Excel
combined_df.to_excel(output_path, index=False)
print(f"Combined report saved at: {output_path}")
return combined_df
if __name__ == "__main__":
# Input files
file_paths = [
'/content/processed_print_hospital_revenue_report.php (11).xlsx',
'/content/processed_maatri_print_hospital_revenue_report.php (16).xlsx'
]
doctor_name = 'Dr. Amit Kumar'
output_path = f'processed_medical_and_surgical_cases_with_exclusions.xlsx'
# Combine reports
combined_summary = combine_reports(file_paths, doctor_name, output_path)
# Print first few rows of the combined report
print(combined_summary.head())
# 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, 'mhs_doctors_config.json')
"""
SERVICES = [
"OPD Consultation",
"IPD Cross Consultation",
"OPD Diagnostics & Pathology",
"Daycare Procedure",
"Surgery (Package cases)",
"Surgery (Open cases)",
"Medical Management"
]
[[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]
"""
# SORTED ONE
# Doctor configuration - percentages for services and exclusions
# Backup
'''
DOCTORS = {
"Dr. Akanksha Singh": {
"services": [0.60, 0.60, 0.15, 0.60, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Amit Kumar": {
"services": [0.80, 0.80, 0.10, 0.50, 0.20, 0.20, 0.20],
"exclusions": [
[False, True], # Surgical Management (Package)
[False, True], # Surgical Management (Non-Package)
[False, True] # Medical Management
]
},
"Dr. Avinash Shekhar Jaiswal": {
"services": [0.80, 0.80, 0.10, 0.50, 0.20, 0.20, 0.20],
"exclusions": [
[False, True], # Surgical Management (Package)
[False, True], # Surgical Management (Non-Package)
[False, True] # Medical Management
]
},
"Dr. Bharti Anand": {
"services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Deepti Sinha": {
"services": [0.70, 0.70, 0.10, 0, 0.20, 0.20, 0],
"exclusions": [
[True, True], # Surgical Management (Package)
[True, True], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Farheen Fatma": {
"services": [0.70, 0.70, 0.10, 0, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Ginny": {
"services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Govind Kumar": {
"services": [0.60, 0.60, 0.15, 0.60, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Jyotsana": {
"services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Khalid Husain": {
"services": [0.70, 0.70, 0.20, 0, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Komal Kumari": {
"services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Manvi Singh": {
"services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Raushan Bhatt": {
"services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Raushan Kumar": {
"services": [0.80, 0.80, 0.10, 0.50, 0.20, 0.20, 0.20],
"exclusions": [
[False, True], # Surgical Management (Package)
[False, True], # Surgical Management (Non-Package)
[False, True] # Medical Management
]
},
"Dr. Shiksha Narang": {
"services": [0.70, 0.70, 0.10, 0, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Shreeparna Deb": {
"services": [0.60, 0.60, 0.15, 0.60, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
},
"Dr. Vanshika Rai": {
"services": [0.60, 0.60, 0.15, 0.60, 0, 0, 0],
"exclusions": [
[False, False], # Surgical Management (Package)
[False, False], # Surgical Management (Non-Package)
[False, False] # Medical Management
]
}
}
'''
# FINAL UPDATED CODE handling medical and surgical visibility (without IPD Consultation services)
# and diag_path and daycare services added
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 Cross Consultation",
"OPD Diagnostics & Pathology",
"Daycare Procedure",
"Surgery (Package cases)",
"Surgery (Open cases)",
"Medical Management"
]
# Define management types for exclusions
MANAGEMENT_TYPES = [
"Surgical Management (Package)",
"Surgical Management (Non-Package)",
"Medical Management"
]
# Define exclusion types
EXCLUSION_TYPES = [
"Exclusions - Drugs & Implants",
"Exclusions - Other Doctor Fees"
]
"""
SERVICES = [
"OPD Consultation",
"IPD Cross Consultation",
"OPD Diagnostics & Pathology",
"Daycare Procedure",
"Surgery (Package cases)",
"Surgery (Open cases)",
"Medical Management"
]
[[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]
"""
# 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 / "mhs_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 Cross Consultation": "combined_cross_consultations_from_both_hospitals.xlsx",
"OPD Diagnostics & Pathology": "processed_diag_and_path.xlsx",
"Daycare Procedure": "processed_daycare.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"
}
# 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()
}
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
# Dynamically generate summary_rows based on DOCTOR_CONFIG
summary_rows = []
for service_name, service_data in DOCTOR_CONFIG["services"].items():
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 or
service_name in ["Surgery (Package cases)", "Surgery (Open cases)"]
) and service_name != "Medical Management":
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
show_total_surgeries_line = show_surgery_package or show_surgery_open
# Separate the new services for positioning
new_services_rows = []
for service in ["OPD Diagnostics & Pathology", "Daycare Procedure"]:
if DOCTOR_CONFIG["services"][service]["variable_share"].get(doctor_name, 0.00) != 0.00:
new_services_rows.append({
"service": service,
"file": DOCTOR_CONFIG["services"][service]["file"],
"variable_share": DOCTOR_CONFIG["services"][service]["variable_share"].get(doctor_name)
})
# 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)})
# Remove duplicates from initial summary_rows
services_to_remove = {"Surgery (Package cases)", "Surgery (Open cases)", "Medical Management", "OPD Diagnostics & Pathology", "Daycare Procedure"}
summary_rows = [r for r in summary_rows if r["service"] not in services_to_remove]
# Add new services after OPD/Cross but before surgery sections
summary_rows.extend(new_services_rows)
summary_rows.extend(surgical_rows)
# Add data rows
row_num = 4
for row_data in summary_rows:
summary_sheet[f"B{row_num}"] = row_data["service"]
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}-25"
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}-2025"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
row_num += 1
tds_row = row_num
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}-2025"
summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
# Highlight the net payable row
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
for col_idx in range(2, 4):
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"
summary_sheet.column_dimensions["B"].width = 60
summary_sheet.column_dimensions["D"].width = 25
summary_sheet.column_dimensions["E"].width = 25
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:
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
for col_idx in range(2, 4):
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)
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 = {}
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)
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
if service == "OPD 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 "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()
# REMOVED: IPD Consultation (Non-Package) and IPD Consultation (Package) processing
elif service == "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()
# New services: OPD Diagnostics & Pathology and Daycare Procedure
elif service in ["OPD Diagnostics & 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 == " 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"]
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()
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"]
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()
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"]
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
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"
if variable_share is not None:
if isinstance(variable_share, (int, float)) and variable_share <= 1.0:
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:
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
else:
summary_sheet[f"D{row_num}"] = int(variable_share * 100) if isinstance(variable_share, float) else variable_share
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
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
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"
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 = total_final_share
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"
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
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):
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)
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")
# Skip services that shouldn't have sheets
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
df_to_add_sheet = None
sheet_name = service.replace(" ", "")[:31]
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)
# REMOVED: IPD Consultation sheet creation
elif service == "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)
# New service: Diagnostics & Pathology
elif service == "OPD Diagnostics & Pathology":
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)
# New service: Daycare Procedure
elif service == "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 == " 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"]
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"]
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"]
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)
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)
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)
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
if __name__ == "__main__":
data_dir = "."
#---------------------------------------------------------------------------
doctor_to_process = "Dr. Amit Kumar"
current_month = "Feb"
current_year = "2025"
#---------------------------------------------------------------------------
output_file = f"{doctor_to_process}-{current_month}-{current_year}.xlsx"
report_file, totals = create_combined_report(data_dir, output_file, doctor_to_process)
print(f"Combined report created: {report_file}")
print(f"Total sums: {totals}")
import tempfile
import shutil
def generate_mhs_doctor_report(
doctor_name: str,
mhs_hospital_revenue_report_path: str,
maatri_hospital_revenue_report_path: str,
print_hospital_revenue_report_path: str,
doctor_visit_report_with_package_path: str,
doctor_visit_report_without_package_path: str,
maatri_doctor_visit_report_with_package_path: str,
maatri_doctor_visit_report_without_package_path: str,
print_inpatient_bill_register_report_path: str,
maatri_print_inpatient_bill_register_report_path: str,
current_month: str,
current_year: str
):
"""
End-to-end processing for a single doctor's variable payout report.
"""
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/7] Converting HTML files to Excel...")
html_files_to_convert = {
"mhs_hospital_revenue": mhs_hospital_revenue_report_path,
"maatri_hospital_revenue": maatri_hospital_revenue_report_path,
"print_hospital_revenue": print_hospital_revenue_report_path,
"doctor_visit_with_package": doctor_visit_report_with_package_path,
"doctor_visit_without_package": doctor_visit_report_without_package_path,
"maatri_doctor_visit_with_package": maatri_doctor_visit_report_with_package_path,
"maatri_doctor_visit_without_package": maatri_doctor_visit_report_without_package_path,
"print_inpatient_bill_register": print_inpatient_bill_register_report_path,
"maatri_print_inpatient_bill_register": maatri_print_inpatient_bill_register_report_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/7] Processing OPD Consultations...")
opd_consultations_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["OPD Consultation"]["file"])
results = filter_patient_records(converted_files["mhs_hospital_revenue"], doctor_name)
results.to_excel(opd_consultations_path, index=False)
print(f"β OPD consultations processed and saved.")
else:
print("\n[Step 2/7] Skipping OPD Consultations (0.00% variable share).")
# Step 3: Process Diagnostics & Pathology (if applicable)
if DOCTOR_CONFIG["services"]["OPD Diagnostics & Pathology"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\n[Step 3/7] Processing OPD Diagnostics & Pathology...")
diag_path_output_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["OPD Diagnostics & Pathology"]["file"])
results = filter_diag_path_records(converted_files["mhs_hospital_revenue"], doctor_name)
results.to_excel(diag_path_output_path, index=False)
print(f"β Diagnostics & Pathology processed and saved.")
else:
print("\n[Step 3/7] Skipping Diagnostics & Pathology (0.00% variable share).")
# Step 4: Process Daycare Procedure (if applicable)
if DOCTOR_CONFIG["services"]["Daycare Procedure"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\n[Step 4/7] Processing Daycare Procedure...")
daycare_output_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["Daycare Procedure"]["file"])
results = filter_daycare_records(converted_files["mhs_hospital_revenue"], doctor_name)
results.to_excel(daycare_output_path, index=False)
print(f"β Daycare Procedure processed and saved.")
else:
print("\n[Step 4/7] Skipping Daycare Procedure (0.00% variable share).")
# Step 5: Process IPD Cross Consultation (if applicable)
# Combine doctor visit reports for both hospitals first
print("\n[Step 5/7] Combining and tagging IPD consultations for Cross Consultation...")
maatri_visit_output = os.path.join(tmpdir, 'final_processed_maatri_doctor_visit_report.xlsx')
combine_doctor_visit_reports(
converted_files['maatri_doctor_visit_with_package'],
converted_files['maatri_doctor_visit_without_package'],
maatri_visit_output
)
mssh_visit_output = os.path.join(tmpdir, 'final_processed_mssh_doctor_visit_report.xlsx')
combine_doctor_visit_reports(
converted_files['doctor_visit_with_package'],
converted_files['doctor_visit_without_package'],
mssh_visit_output
)
if DOCTOR_CONFIG["services"]["IPD Cross Consultation"]["variable_share"].get(doctor_name, 0.00) != 0.00:
print("\nProcessing IPD Cross Consultation...")
cross_maatri = get_cross_consultations(
maatri_visit_output,
converted_files['maatri_print_inpatient_bill_register'],
[doctor_name],
unit_name='Maatri'
)
cross_mssh = get_cross_consultations(
mssh_visit_output,
converted_files['print_inpatient_bill_register'],
[doctor_name],
unit_name='MSSH'
)
combined_cross = pd.concat([cross_maatri, cross_mssh], ignore_index=True)
cross_consultation_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["IPD Cross Consultation"]["file"])
combined_cross.to_excel(cross_consultation_path, index=False)
print(f"β IPD Cross Consultation processed and saved.")
else:
print("\nSkipping IPD Cross Consultation (0.00% variable share).")
# Step 6: 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 6/7] Processing Surgical and Medical Management...")
surg_med_output_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["file"])
file_paths_for_combine = [
converted_files['print_hospital_revenue'],
converted_files['maatri_hospital_revenue']
]
combine_reports(file_paths_for_combine, doctor_name, surg_med_output_path)
print(f"β Surgical and Medical Management cases processed and saved.")
else:
print("\n[Step 6/7] Skipping Surgical and Medical Management (all 0.00% variable share).")
# Final Step: Create the combined report
print("\n--- Generating Final Report ---")
final_report_name = f"{doctor_name}-{current_month}-{current_year}.xlsx"
final_report_path = os.path.join(tmpdir, final_report_name)
create_combined_report(tmpdir, final_report_path, doctor_name, current_month, current_year)
permanent_output = os.path.join(os.getcwd(), final_report_name)
shutil.copy(final_report_path, permanent_output)
print(f"\nβββ 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_mhs_doctor_report(
doctor_name= "Dr. Amit Kumar",
mhs_hospital_revenue_report_path= '/content/drive/MyDrive/VarAuto/mhs_print_hospital_revenue_report.php (16).xls',
maatri_hospital_revenue_report_path= '/content/drive/MyDrive/VarAuto/maatri_print_hospital_revenue_report.php (16).xls',
print_hospital_revenue_report_path= '/content/drive/MyDrive/VarAuto/print_hospital_revenue_report.php (11).xls',
doctor_visit_report_with_package_path= '/content/drive/MyDrive/VarAuto/doctor_visit_report_with_package.xls',
doctor_visit_report_without_package_path= '/content/drive/MyDrive/VarAuto/doctor_visit_report_without_package.xls',
maatri_doctor_visit_report_with_package_path= '/content/drive/MyDrive/VarAuto/maatri_doctor_visit_report_with_package.xls',
maatri_doctor_visit_report_without_package_path= '/content/drive/MyDrive/VarAuto/maatri_doctor_visit_report_without_package.xls',
print_inpatient_bill_register_report_path= '/content/drive/MyDrive/VarAuto/print_inpatient_bill_register_report.xls',
maatri_print_inpatient_bill_register_report_path= '/content/drive/MyDrive/VarAuto/maatri_print_inpatient_bill_register_report.xls',
current_month= "Feb",
current_year= "2025"
)
if final_report_path:
print(f"Report successfully generated at: {final_report_path}")
else:
print("Report generation failed.")
# -*- coding: utf-8 -*-
"""MHS_Variable_Payout.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1I5F6Yxj8GpAhw_AEF-u-SijO3rBOa6yi
"""
"""
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):,}")