medicafe 0.250813.0__tar.gz → 0.250813.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot.py +48 -28
  2. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_Crosswalk_Library.py +6 -6
  3. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_Preprocessor_lib.py +74 -26
  4. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_UI.py +64 -1
  5. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_dataformat_library.py +0 -2
  6. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_smart_import.py +1 -1
  7. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/update_medicafe.py +73 -61
  8. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/api_core.py +0 -1
  9. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Down.py +254 -9
  10. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_main.py +41 -10
  11. {medicafe-0.250813.0/medicafe.egg-info → medicafe-0.250813.2}/PKG-INFO +1 -1
  12. {medicafe-0.250813.0 → medicafe-0.250813.2/medicafe.egg-info}/PKG-INFO +1 -1
  13. {medicafe-0.250813.0 → medicafe-0.250813.2}/setup.py +1 -1
  14. {medicafe-0.250813.0 → medicafe-0.250813.2}/LICENSE +0 -0
  15. {medicafe-0.250813.0 → medicafe-0.250813.2}/MANIFEST.in +0 -0
  16. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot.bat +0 -0
  17. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_Charges.py +0 -0
  18. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_Crosswalk_Utils.py +0 -0
  19. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_Post.py +0 -0
  20. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_Preprocessor.py +0 -0
  21. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/MediBot_docx_decoder.py +0 -0
  22. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/__init__.py +0 -0
  23. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/get_medicafe_version.py +0 -0
  24. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediBot/update_json.py +0 -0
  25. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/MediLink_ConfigLoader.py +0 -0
  26. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/__init__.py +0 -0
  27. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/__main__.py +0 -0
  28. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/api_core_backup.py +0 -0
  29. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/api_factory.py +0 -0
  30. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/api_utils.py +0 -0
  31. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/core_utils.py +0 -0
  32. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/graphql_utils.py +0 -0
  33. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/logging_config.py +0 -0
  34. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/logging_demo.py +0 -0
  35. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/migration_helpers.py +0 -0
  36. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/smart_import.py +0 -0
  37. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediCafe/submission_index.py +0 -0
  38. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/InsuranceTypeService.py +0 -0
  39. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_837p_cob_library.py +0 -0
  40. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_837p_encoder.py +0 -0
  41. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_837p_encoder_library.py +0 -0
  42. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_837p_utilities.py +0 -0
  43. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_API_Generator.py +0 -0
  44. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Azure.py +0 -0
  45. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_ClaimStatus.py +0 -0
  46. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_DataMgmt.py +0 -0
  47. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Decoder.py +0 -0
  48. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Deductible.py +0 -0
  49. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Deductible_Validator.py +0 -0
  50. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Display_Utils.py +0 -0
  51. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Gmail.py +0 -0
  52. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Mailer.py +0 -0
  53. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Parser.py +0 -0
  54. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_PatientProcessor.py +0 -0
  55. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Scan.py +0 -0
  56. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Scheduler.py +0 -0
  57. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_UI.py +0 -0
  58. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_Up.py +0 -0
  59. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_insurance_utils.py +0 -0
  60. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/MediLink_smart_import.py +0 -0
  61. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/Soumit_api.py +0 -0
  62. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/__init__.py +0 -0
  63. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/gmail_http_utils.py +0 -0
  64. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/gmail_oauth_utils.py +0 -0
  65. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/insurance_type_integration_test.py +0 -0
  66. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/openssl.cnf +0 -0
  67. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/test.py +0 -0
  68. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/test_cob_library.py +0 -0
  69. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/test_timing.py +0 -0
  70. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/test_validation.py +0 -0
  71. {medicafe-0.250813.0 → medicafe-0.250813.2}/MediLink/webapp.html +0 -0
  72. {medicafe-0.250813.0 → medicafe-0.250813.2}/README.md +0 -0
  73. {medicafe-0.250813.0 → medicafe-0.250813.2}/medicafe.egg-info/SOURCES.txt +0 -0
  74. {medicafe-0.250813.0 → medicafe-0.250813.2}/medicafe.egg-info/dependency_links.txt +0 -0
  75. {medicafe-0.250813.0 → medicafe-0.250813.2}/medicafe.egg-info/entry_points.txt +0 -0
  76. {medicafe-0.250813.0 → medicafe-0.250813.2}/medicafe.egg-info/not-zip-safe +0 -0
  77. {medicafe-0.250813.0 → medicafe-0.250813.2}/medicafe.egg-info/requires.txt +0 -0
  78. {medicafe-0.250813.0 → medicafe-0.250813.2}/medicafe.egg-info/top_level.txt +0 -0
  79. {medicafe-0.250813.0 → medicafe-0.250813.2}/setup.cfg +0 -0
@@ -608,48 +608,68 @@ if __name__ == "__main__":
608
608
  existing_patients, patients_to_process = MediBot_Preprocessor.check_existing_patients(selected_patient_ids, _ac().get_mapat_med_path() if _ac() else '')
609
609
 
610
610
  if existing_patients:
611
- print("\nNOTE: The following patient(s) already EXIST in the system and \n will be excluded from processing:")
612
- # BUG There a "ERROR: 'str' object has no attribute 'strftime'" that shows up after this somewhere.
613
611
  # Collect surgery dates and patient info for existing patients
614
612
  patient_info = []
615
613
  for patient_id, patient_name in existing_patients:
616
614
  try:
617
- surgery_date = next((row.get('Surgery Date') for row in csv_data if row.get(reverse_mapping['Patient ID #2']) == patient_id), None)
618
- if surgery_date is None:
619
- raise ValueError("Surgery Date not found for patient ID: {}".format(patient_id))
620
- patient_info.append((surgery_date, patient_name, patient_id))
615
+ # Find the row for this patient
616
+ patient_row = next((row for row in csv_data if row.get(reverse_mapping['Patient ID #2']) == patient_id), None)
617
+ if patient_row is None:
618
+ raise ValueError("Patient row not found for patient ID: {}".format(patient_id))
619
+
620
+ # Get all surgery dates for this patient
621
+ all_surgery_dates = patient_row.get('_all_surgery_dates', [patient_row.get('Surgery Date')])
622
+ surgery_date_to_diagnosis = patient_row.get('_surgery_date_to_diagnosis', {})
623
+
624
+ # Create entries for each surgery date with its specific diagnosis code
625
+ for surgery_date in all_surgery_dates:
626
+ diagnosis_code = surgery_date_to_diagnosis.get(surgery_date, 'N/A')
627
+ patient_info.append((surgery_date, patient_name, patient_id, diagnosis_code, patient_row))
628
+
621
629
  except Exception as e:
622
- MediLink_ConfigLoader.log("Warning: Error retrieving Surgery Date for patient ID '{}': {}".format(patient_id, e), level="WARNING")
623
- patient_info.append(('Unknown Date', patient_name, patient_id)) # Append with 'Unknown Date' if there's an error
624
-
625
- # Sort by surgery date first and then by patient name
626
- # NOTE: 'surgery_date' may be a string or a datetime depending on upstream data.
627
- # We sort lexicographically which is stable for uniform string inputs. If mixed types
628
- # are encountered, consider normalizing to string first or using a robust key function
629
- # that attempts datetime parsing with a string fallback.
630
- patient_info.sort(key=lambda x: (x[0], x[1]))
631
-
632
- # Print the sorted patient info
633
- for index, (surgery_date, patient_name, patient_id) in enumerate(patient_info):
634
- # Format surgery_date safely whether it's a datetime/date or a string
635
- # This guards the observed "'str' object has no attribute 'strftime'" error on XP.
636
- try:
637
- formatted_date = surgery_date.strftime('%m-%d')
638
- except Exception:
639
- formatted_date = str(surgery_date)
640
- print("{:03d}: {} (ID: {}) {}".format(index + 1, formatted_date, patient_id, patient_name))
630
+ MediLink_ConfigLoader.log("Warning: Error retrieving data for patient ID '{}': {}".format(patient_id, e), level="WARNING")
631
+ patient_info.append(('Unknown Date', patient_name, patient_id, 'N/A', None)) # Append with 'Unknown Date' if there's an error
632
+
633
+ # Display existing patients table using the enhanced display function
634
+ MediBot_UI.display_enhanced_patient_table(
635
+ patient_info,
636
+ "NOTE: The following patient(s) already EXIST in the system but have new dates of service.\n Their diagnosis codes will need to be updated manually by the user to the following list:",
637
+ show_line_numbers=False
638
+ )
641
639
 
642
640
  # Update csv_data to exclude existing patients
643
641
  # TODO: Update this logic to handle patients that exist but need new charges added.
644
642
  csv_data = [row for row in csv_data if row[reverse_mapping['Patient ID #2']] in patients_to_process]
645
- else:
646
- print("\nSelected patient(s) are NEW patients and will be processed.")
643
+
644
+ # Show NEW patients that will be processed (if any)
645
+ if patients_to_process:
646
+ # Collect surgery dates and patient info for NEW patients
647
+ new_patient_info = []
648
+ for row in csv_data:
649
+ patient_id = row.get(reverse_mapping['Patient ID #2'])
650
+ patient_name = row.get(reverse_mapping['Patient Name'])
651
+
652
+ # Get all surgery dates for this patient
653
+ all_surgery_dates = row.get('_all_surgery_dates', [row.get('Surgery Date')])
654
+ surgery_date_to_diagnosis = row.get('_surgery_date_to_diagnosis', {})
655
+
656
+ # Create entries for each surgery date with its specific diagnosis code
657
+ for surgery_date in all_surgery_dates:
658
+ diagnosis_code = surgery_date_to_diagnosis.get(surgery_date, 'N/A')
659
+ new_patient_info.append((surgery_date, patient_name, patient_id, diagnosis_code, row))
660
+
661
+ # Display new patients table using the enhanced display function
662
+ MediBot_UI.display_enhanced_patient_table(
663
+ new_patient_info,
664
+ "NOTE: The following NEW patient(s) will be automatically entered into Medisoft:",
665
+ show_line_numbers=True
666
+ )
647
667
 
648
668
  # Check if there are patients left to process
649
669
  if len(patients_to_process) == 0:
650
670
  proceed = input("\nAll patients have been processed. Continue anyway?: ").lower().strip() in ['yes', 'y']
651
671
  else:
652
- proceed = input("\nDo you want to proceed with the {} remaining patient(s)? (yes/no): ".format(len(patients_to_process))).lower().strip() in ['yes', 'y']
672
+ proceed = input("\nDo you want to proceed with entering {} new patient(s) into Medisoft? (yes/no): ".format(len(patients_to_process))).lower().strip() in ['yes', 'y']
653
673
 
654
674
  # TODO: Here is where we need to add the step where we move to MediBot_Charges.
655
675
  # The return is an enriched dataset to be picked up by MediBot which means we need to return:
@@ -4,17 +4,13 @@ Core crosswalk library for MediBot
4
4
  Handles crosswalk operations and API interactions.
5
5
  """
6
6
 
7
- import os
8
7
  import sys
9
- import csv
10
- import json
11
- import re
12
- from datetime import datetime
13
8
 
14
9
  # Use core utilities for standardized imports
15
10
  from MediCafe.core_utils import (
16
11
  import_medibot_module,
17
- get_config_loader_with_fallback
12
+ get_config_loader_with_fallback,
13
+ smart_import
18
14
  )
19
15
 
20
16
  # Initialize configuration loader with fallback
@@ -45,6 +41,10 @@ else:
45
41
  update_crosswalk_with_new_payer_id = None
46
42
  load_and_parse_z_data = None
47
43
 
44
+ # Import API functions using centralized import pattern
45
+ MediLink_API_v3 = smart_import(['MediCafe.api_core', 'MediCafe.api_core_backup'])
46
+ fetch_payer_name_from_api = getattr(MediLink_API_v3, 'fetch_payer_name_from_api', None) if MediLink_API_v3 else None
47
+
48
48
  # Module-level cache to prevent redundant API calls
49
49
  _api_cache = {}
50
50
 
@@ -262,7 +262,7 @@ def add_columns(csv_data, column_headers):
262
262
 
263
263
  # Extracting the list to a variable for future refactoring:
264
264
  def filter_rows(csv_data):
265
- # TODO: This should be handled in the crosswalk.
265
+ # TODO: This should be written in the crosswalk and not hardcoded here.
266
266
  excluded_insurance = {'AETNA', 'AETNA MEDICARE', 'HUMANA MED HMO'}
267
267
  csv_data[:] = [row for row in csv_data if row.get('Patient ID') and row.get('Primary Insurance') not in excluded_insurance]
268
268
 
@@ -515,17 +515,40 @@ def convert_surgery_date(csv_data):
515
515
  def sort_and_deduplicate(csv_data):
516
516
  # Create a dictionary to hold unique patients based on Patient ID
517
517
  unique_patients = {}
518
+ # Create a dictionary to store multiple surgery dates per patient
519
+ patient_surgery_dates = {}
518
520
 
519
521
  # Iterate through the CSV data and populate the unique_patients dictionary
520
522
  for row in csv_data:
521
523
  patient_id = row.get('Patient ID')
524
+ surgery_date = row.get('Surgery Date')
525
+
522
526
  if patient_id not in unique_patients:
523
527
  unique_patients[patient_id] = row
528
+ patient_surgery_dates[patient_id] = [surgery_date]
524
529
  else:
525
530
  # If the patient ID already exists, compare surgery dates
526
531
  existing_row = unique_patients[patient_id]
527
- if row['Surgery Date'] < existing_row['Surgery Date']:
532
+ existing_date = existing_row['Surgery Date']
533
+
534
+ # Keep the most current demographic data (later surgery date takes precedence)
535
+ if surgery_date > existing_date:
536
+ # Store the old row's surgery date before replacing
537
+ old_date = existing_row['Surgery Date']
538
+ patient_surgery_dates[patient_id].append(old_date)
539
+ # Replace with newer row (better demographics)
528
540
  unique_patients[patient_id] = row
541
+ # Update the surgery dates list to reflect the new primary date
542
+ patient_surgery_dates[patient_id] = [surgery_date] + [d for d in patient_surgery_dates[patient_id] if d != surgery_date]
543
+ else:
544
+ # Add this surgery date to the list for this patient
545
+ if surgery_date not in patient_surgery_dates[patient_id]:
546
+ patient_surgery_dates[patient_id].append(surgery_date)
547
+
548
+ # Store the surgery dates information in the first row of each patient for later access
549
+ for patient_id, row in unique_patients.items():
550
+ row['_all_surgery_dates'] = sorted(patient_surgery_dates[patient_id])
551
+ row['_primary_surgery_date'] = row['Surgery Date'] # Keep track of which date has the demographics
529
552
 
530
553
  # Convert the unique_patients dictionary back to a list and sort it
531
554
  csv_data[:] = sorted(unique_patients.values(), key=lambda x: (x['Surgery Date'], x.get('Patient Last', '').strip())) # TODO Does this need to be sorted twice? once before and once after?
@@ -1096,7 +1119,7 @@ def update_diagnosis_codes(csv_data):
1096
1119
  updated_count = 0
1097
1120
 
1098
1121
  # PERFORMANCE OPTIMIZATION: Single pass through CSV data with pre-processed lookups
1099
- # Update the "Default Diagnosis #1" column in the CSV data
1122
+ # Update the "Default Diagnosis #1" column in the CSV data and store diagnosis codes for all surgery dates
1100
1123
  for row_num, row in enumerate(csv_data, start=1):
1101
1124
  patient_id = row.get('Patient ID', '').strip()
1102
1125
  # Use pre-processed patient ID lookup for efficiency
@@ -1104,31 +1127,56 @@ def update_diagnosis_codes(csv_data):
1104
1127
  continue # Skip rows that do not match any patient ID
1105
1128
 
1106
1129
  MediLink_ConfigLoader.log("Processing row number {}.".format(row_num), level="DEBUG")
1107
- # Use pre-converted surgery date string for efficient lookup
1108
- surgery_date_str = surgery_date_strings.get(patient_id, '')
1109
-
1110
- MediLink_ConfigLoader.log("Patient ID: {}, Surgery Date: {}".format(patient_id, surgery_date_str), level="DEBUG")
1111
-
1130
+
1131
+ # Get all surgery dates for this patient
1132
+ all_surgery_dates = row.get('_all_surgery_dates', [row.get('Surgery Date')])
1133
+
1134
+ # Create a mapping of surgery dates to diagnosis codes for this patient
1135
+ surgery_date_to_diagnosis = {}
1136
+
1112
1137
  if patient_id in all_patient_data:
1113
- if surgery_date_str in all_patient_data[patient_id]:
1114
- diagnosis_code, left_or_right_eye, femto_yes_or_no = all_patient_data[patient_id][surgery_date_str]
1115
- MediLink_ConfigLoader.log("Found diagnosis data for Patient ID: {}, Surgery Date: {}".format(patient_id, surgery_date_str), level="DEBUG")
1116
-
1117
- # Convert diagnosis code to Medisoft shorthand format.
1118
- medisoft_shorthand = diagnosis_to_medisoft.get(diagnosis_code, None)
1119
- if medisoft_shorthand is None and diagnosis_code:
1120
- # Use fallback logic for missing mapping
1121
- defaulted_code = diagnosis_code.lstrip('H').lstrip('T8').replace('.', '')[-5:]
1122
- medisoft_shorthand = defaulted_code
1123
- MediLink_ConfigLoader.log("Missing diagnosis mapping for '{}', using fallback code '{}'".format(
1124
- diagnosis_code, medisoft_shorthand), level="WARNING")
1125
- MediLink_ConfigLoader.log("Converted diagnosis code to Medisoft shorthand: {}".format(medisoft_shorthand), level="DEBUG")
1138
+ # Process each surgery date for this patient
1139
+ for surgery_date in all_surgery_dates:
1140
+ # Convert surgery date to string format for lookup
1141
+ try:
1142
+ if hasattr(surgery_date, 'strftime'):
1143
+ surgery_date_str = surgery_date.strftime('%m-%d-%Y')
1144
+ else:
1145
+ surgery_date_str = str(surgery_date)
1146
+ except Exception:
1147
+ surgery_date_str = str(surgery_date)
1126
1148
 
1127
- row['Default Diagnosis #1'] = medisoft_shorthand
1128
- updated_count += 1
1129
- MediLink_ConfigLoader.log("Updated row number {} with new diagnosis code.".format(row_num), level="INFO")
1130
- else:
1131
- MediLink_ConfigLoader.log("No matching surgery date found for Patient ID: {} in row {}.".format(patient_id, row_num), level="INFO")
1149
+ MediLink_ConfigLoader.log("Patient ID: {}, Surgery Date: {}".format(patient_id, surgery_date_str), level="DEBUG")
1150
+
1151
+ if surgery_date_str in all_patient_data[patient_id]:
1152
+ diagnosis_code, left_or_right_eye, femto_yes_or_no = all_patient_data[patient_id][surgery_date_str]
1153
+ MediLink_ConfigLoader.log("Found diagnosis data for Patient ID: {}, Surgery Date: {}".format(patient_id, surgery_date_str), level="DEBUG")
1154
+
1155
+ # Convert diagnosis code to Medisoft shorthand format.
1156
+ medisoft_shorthand = diagnosis_to_medisoft.get(diagnosis_code, None)
1157
+ if medisoft_shorthand is None and diagnosis_code:
1158
+ # Use fallback logic for missing mapping
1159
+ defaulted_code = diagnosis_code.lstrip('H').lstrip('T8').replace('.', '')[-5:]
1160
+ medisoft_shorthand = defaulted_code
1161
+ MediLink_ConfigLoader.log("Missing diagnosis mapping for '{}', using fallback code '{}'".format(
1162
+ diagnosis_code, medisoft_shorthand), level="WARNING")
1163
+ MediLink_ConfigLoader.log("Converted diagnosis code to Medisoft shorthand: {}".format(medisoft_shorthand), level="DEBUG")
1164
+
1165
+ surgery_date_to_diagnosis[surgery_date] = medisoft_shorthand
1166
+ else:
1167
+ MediLink_ConfigLoader.log("No matching surgery date found for Patient ID: {} on date {}.".format(patient_id, surgery_date_str), level="INFO")
1168
+ surgery_date_to_diagnosis[surgery_date] = 'N/A'
1169
+
1170
+ # Store the diagnosis mapping for all surgery dates
1171
+ row['_surgery_date_to_diagnosis'] = surgery_date_to_diagnosis
1172
+
1173
+ # Set the primary diagnosis code (for the main surgery date)
1174
+ primary_surgery_date = row.get('Surgery Date')
1175
+ primary_diagnosis = surgery_date_to_diagnosis.get(primary_surgery_date, 'N/A')
1176
+ row['Default Diagnosis #1'] = primary_diagnosis
1177
+
1178
+ updated_count += 1
1179
+ MediLink_ConfigLoader.log("Updated row number {} with diagnosis codes for {} surgery dates.".format(row_num, len(all_surgery_dates)), level="INFO")
1132
1180
  else:
1133
1181
  MediLink_ConfigLoader.log("Patient ID: {} not found in DOCX data for row {}.".format(patient_id, row_num), level="INFO")
1134
1182
 
@@ -1,5 +1,5 @@
1
1
  #MediBot_UI.py
2
- import ctypes, time, re, os, sys
2
+ import ctypes, time, re
3
3
  from ctypes import wintypes
4
4
  from sys import exit
5
5
 
@@ -27,6 +27,69 @@ except ImportError:
27
27
  from MediCafe.core_utils import create_config_cache
28
28
  _get_config, (_config_cache, _crosswalk_cache) = create_config_cache()
29
29
 
30
+ def display_enhanced_patient_table(patient_info, title, show_line_numbers=True):
31
+ """
32
+ Display an enhanced patient table with multiple surgery dates and diagnosis codes.
33
+
34
+ Args:
35
+ patient_info: List of tuples (surgery_date, patient_name, patient_id, diagnosis_code, patient_row)
36
+ title: Title for the table section
37
+ show_line_numbers: Whether to show line numbers (True for new patients, False for existing)
38
+ """
39
+ if not patient_info:
40
+ return
41
+
42
+ print(title)
43
+ print()
44
+
45
+ # Sort by surgery date first and then by patient name
46
+ patient_info.sort(key=lambda x: (x[0], x[1]))
47
+
48
+ # Calculate column widths for proper alignment
49
+ max_patient_id_len = max(len(str(pid)) for _, _, pid, _, _ in patient_info)
50
+ max_patient_name_len = max(len(pname) for _, pname, _, _, _ in patient_info)
51
+ max_diagnosis_len = max(len(dcode) for _, _, _, dcode, _ in patient_info)
52
+
53
+ # Ensure minimum widths for readability
54
+ max_patient_id_len = max(max_patient_id_len, 5) # 5-digit ID max
55
+ max_patient_name_len = max(max_patient_name_len, 12) # "Patient Name" header
56
+ max_diagnosis_len = max(max_diagnosis_len, 10) # "Diagnosis" header
57
+
58
+ # Print the sorted patient info with multiple surgery dates
59
+ current_patient = None
60
+ line_number = 1
61
+
62
+ for surgery_date, patient_name, patient_id, diagnosis_code, patient_row in patient_info:
63
+ # Format surgery_date safely whether it's a datetime/date or a string
64
+ try:
65
+ formatted_date = surgery_date.strftime('%m-%d')
66
+ except Exception:
67
+ formatted_date = str(surgery_date)
68
+
69
+ # Transform diagnosis code display: show "-Not Found-" instead of "N/A"
70
+ display_diagnosis = "-Not Found-" if diagnosis_code == "N/A" else diagnosis_code
71
+
72
+ # Check if this is the same patient as the previous line
73
+ if current_patient == patient_id:
74
+ # Secondary surgery date - indent and show dashes for patient info
75
+ # Use exact character count matching for dashes
76
+ patient_id_dashes = '-' * len(str(patient_id))
77
+ patient_name_dashes = '-' * len(patient_name)
78
+
79
+ secondary_format = " {:<6} | {:<" + str(max_patient_id_len) + "} | {:<" + str(max_patient_name_len) + "} | {:<" + str(max_diagnosis_len) + "}"
80
+ print(secondary_format.format(formatted_date, patient_id_dashes, patient_name_dashes, display_diagnosis))
81
+ else:
82
+ # New patient - show full patient info
83
+ current_patient = patient_id
84
+ if show_line_numbers:
85
+ primary_format = "{:03d}: {:<6} | {:<" + str(max_patient_id_len) + "} | {:<" + str(max_patient_name_len) + "} | {:<" + str(max_diagnosis_len) + "}"
86
+ print(primary_format.format(line_number, formatted_date, str(patient_id), patient_name, display_diagnosis))
87
+ line_number += 1
88
+ else:
89
+ # For existing patients, don't show line numbers
90
+ primary_format = " {:<6} | {:<" + str(max_patient_id_len) + "} | {:<" + str(max_patient_name_len) + "} | {:<" + str(max_diagnosis_len) + "}"
91
+ print(primary_format.format(formatted_date, str(patient_id), patient_name, display_diagnosis))
92
+
30
93
  # Function to check if a specific key is pressed
31
94
  def _get_vk_codes():
32
95
  """Get VK codes from config."""
@@ -6,8 +6,6 @@ Contains functions for formatting various data types and handling CSV operations
6
6
 
7
7
  import os
8
8
  import sys
9
- import csv
10
- import json
11
9
  import re
12
10
  from datetime import datetime
13
11
 
@@ -7,7 +7,7 @@ new centralized smart import system, eliminating sys.path manipulation
7
7
  and circular import risks.
8
8
  """
9
9
 
10
- import os, subprocess, tempfile, traceback, re, time, sys
10
+ import os, sys
11
11
 
12
12
  # Add workspace directory to Python path for MediCafe imports
13
13
  current_dir = os.path.dirname(os.path.abspath(__file__))
@@ -292,7 +292,7 @@ def compare_versions(version1, version2):
292
292
 
293
293
  def upgrade_package(package, retries=4, delay=2, target_version=None): # Updated retries to 4
294
294
  """
295
- Attempts to upgrade the package multiple times with delays in between.
295
+ Attempts to upgrade the package multiple times with escalating techniques.
296
296
  """
297
297
  if not check_internet_connection():
298
298
  print_status("No internet connection detected. Please check your internet connection and try again.", "ERROR")
@@ -302,82 +302,94 @@ def upgrade_package(package, retries=4, delay=2, target_version=None): # Update
302
302
  if target_version:
303
303
  print("Pinned target version: {}".format(target_version))
304
304
 
305
- for attempt in range(1, retries + 1):
306
- print("Attempt {}/{} to upgrade {}...".format(attempt, retries, package))
305
+ def get_installed_version_fresh(package):
306
+ """Get installed version using a fresh subprocess to avoid pkg_resources cache issues."""
307
+ try:
308
+ process = subprocess.Popen(
309
+ [sys.executable, '-m', 'pip', 'show', package],
310
+ stdout=subprocess.PIPE,
311
+ stderr=subprocess.PIPE
312
+ )
313
+ stdout, stderr = process.communicate()
314
+ if process.returncode == 0:
315
+ for line in stdout.decode().splitlines():
316
+ if line.startswith("Version:"):
317
+ return line.split(":", 1)[1].strip()
318
+ return None
319
+ except Exception as e:
320
+ print("Warning: Could not get fresh version: {}".format(e))
321
+ return None
322
+
323
+ def try_upgrade_with_strategy(attempt, strategy_name, cmd_args):
324
+ """Try upgrade with specific strategy and return success status."""
325
+ print("Attempt {}/{}: Using {} strategy...".format(attempt, retries, strategy_name))
307
326
 
308
- # Use a more compatible approach for Python 3.4
309
- # Try with --no-deps first to avoid dependency resolution issues
310
327
  pkg_spec = package
311
328
  if target_version:
312
329
  pkg_spec = "{}=={}".format(package, target_version)
313
330
 
314
- cmd = [
315
- sys.executable, '-m', 'pip', 'install', '--upgrade',
316
- '--no-deps', '--no-cache-dir', '--disable-pip-version-check', '-q', pkg_spec
317
- ]
331
+ cmd = [sys.executable, '-m', 'pip', 'install'] + cmd_args + [pkg_spec]
318
332
 
319
- print("Using pip upgrade with --no-deps and --no-cache-dir")
320
333
  process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
321
334
  stdout, stderr = process.communicate()
322
335
 
323
336
  if process.returncode == 0:
324
337
  print(stdout.decode().strip())
325
- new_version = get_installed_version(package) # Get new version after upgrade
338
+ # Add delay to allow file system to settle
339
+ time.sleep(1)
340
+ new_version = get_installed_version_fresh(package)
326
341
  expected_version = target_version or get_latest_version(package)
327
- if expected_version and compare_versions(new_version, expected_version) >= 0: # Compare versions
328
- if attempt == 1:
329
- print_status("Upgrade succeeded!", "SUCCESS")
330
- else:
331
- print_status("Attempt {}: Upgrade succeeded!".format(attempt), "SUCCESS")
332
- time.sleep(delay)
342
+
343
+ if expected_version and new_version and compare_versions(new_version, expected_version) >= 0:
344
+ print_status("Attempt {}: Upgrade succeeded with {}!".format(attempt, strategy_name), "SUCCESS")
333
345
  return True
334
346
  else:
335
- print_status("Upgrade incomplete. Current version: {} Expected at least: {}".format(new_version, expected_version), "WARNING")
336
- if attempt < retries:
337
- print("Retrying in {} seconds...".format(delay))
338
- try:
339
- time.sleep(delay + (random.random() * 0.5))
340
- except Exception:
341
- time.sleep(delay)
347
+ print_status("Upgrade incomplete. Current version: {} Expected at least: {}".format(
348
+ new_version or "unknown", expected_version), "WARNING")
349
+ return False
342
350
  else:
343
351
  print(stderr.decode().strip())
344
- print_status("Attempt {}: Upgrade failed with --no-deps.".format(attempt), "WARNING")
345
-
346
- # If --no-deps failed, try with --force-reinstall to bypass dependency issues
347
- if attempt < retries:
348
- print("Fallback this attempt: retrying with --force-reinstall...")
349
- pkg_spec = package
350
- if target_version:
351
- pkg_spec = "{}=={}".format(package, target_version)
352
-
353
- cmd = [
354
- sys.executable, '-m', 'pip', 'install', '--upgrade',
355
- '--force-reinstall', '--no-cache-dir', '--disable-pip-version-check', '-q', pkg_spec
356
- ]
357
-
358
- process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
359
- stdout, stderr = process.communicate()
360
-
361
- if process.returncode == 0:
362
- print(stdout.decode().strip())
363
- new_version = get_installed_version(package)
364
- expected_version = target_version or get_latest_version(package)
365
- if expected_version and compare_versions(new_version, expected_version) >= 0:
366
- print_status("Attempt {}: Upgrade succeeded with --force-reinstall!".format(attempt), "SUCCESS")
367
- time.sleep(delay)
368
- return True
369
- else:
370
- print_status("Upgrade incomplete. Current version: {} Expected at least: {}".format(new_version, expected_version), "WARNING")
371
- else:
372
- print(stderr.decode().strip())
373
- print_status("Attempt {}: Upgrade failed with --force-reinstall.".format(attempt), "WARNING")
374
-
375
- if attempt < retries:
376
- print("Retrying in {} seconds...".format(delay))
377
- try:
378
- time.sleep(delay + (random.random() * 0.5))
379
- except Exception:
380
- time.sleep(delay)
352
+ print_status("Attempt {}: Upgrade failed with {}.".format(attempt, strategy_name), "WARNING")
353
+ return False
354
+
355
+ # Define escalation strategies for each attempt
356
+ strategies = {
357
+ 1: [
358
+ ("Gentle Upgrade", ['--upgrade', '--no-deps', '--no-cache-dir', '--disable-pip-version-check', '-q']),
359
+ ("Force Reinstall", ['--upgrade', '--force-reinstall', '--no-cache-dir', '--disable-pip-version-check', '-q'])
360
+ ],
361
+ 2: [
362
+ ("Clean Install", ['--upgrade', '--force-reinstall', '--no-cache-dir', '--disable-pip-version-check', '--ignore-installed', '-q']),
363
+ ("User Install", ['--upgrade', '--user', '--no-cache-dir', '--disable-pip-version-check', '-q'])
364
+ ],
365
+ 3: [
366
+ ("Aggressive Clean", ['--upgrade', '--force-reinstall', '--no-cache-dir', '--disable-pip-version-check', '--ignore-installed', '--no-deps', '-q']),
367
+ ("Pre-download", ['--upgrade', '--force-reinstall', '--no-cache-dir', '--disable-pip-version-check', '--pre', '-q'])
368
+ ],
369
+ 4: [
370
+ ("Nuclear Option", ['--upgrade', '--force-reinstall', '--no-cache-dir', '--disable-pip-version-check', '--ignore-installed', '--no-deps', '--pre', '-q']),
371
+ ("Last Resort", ['--upgrade', '--force-reinstall', '--no-cache-dir', '--disable-pip-version-check', '--ignore-installed', '--no-deps', '--pre', '--user', '-q'])
372
+ ]
373
+ }
374
+
375
+ for attempt in range(1, retries + 1):
376
+ print("Attempt {}/{} to upgrade {}...".format(attempt, retries, package))
377
+
378
+ # Try each strategy for this attempt
379
+ for strategy_name, cmd_args in strategies[attempt]:
380
+ if try_upgrade_with_strategy(attempt, strategy_name, cmd_args):
381
+ time.sleep(delay)
382
+ return True
383
+
384
+ # If we get here, all strategies for this attempt failed
385
+ if attempt < retries:
386
+ # Escalating delays: 2s, 3s, 5s
387
+ current_delay = delay + (attempt - 1)
388
+ print("All strategies failed for attempt {}. Retrying in {} seconds...".format(attempt, current_delay))
389
+ try:
390
+ time.sleep(current_delay + (random.random() * 1.0))
391
+ except Exception:
392
+ time.sleep(current_delay)
381
393
 
382
394
  print_status("All upgrade attempts failed.", "ERROR")
383
395
  return False
@@ -7,7 +7,6 @@ COMPATIBILITY: Python 3.4.4 and Windows XP compatible
7
7
  """
8
8
 
9
9
  import time, json, os, traceback, sys, requests
10
- from datetime import datetime, timedelta
11
10
 
12
11
  # Import centralized logging configuration
13
12
  try: