# -*- 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.")