medicafe 0.250812.5__tar.gz → 0.250813.0__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.250812.5 → medicafe-0.250813.0}/MediBot/MediBot.bat +9 -10
  2. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_Crosswalk_Library.py +2 -0
  3. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_Crosswalk_Utils.py +6 -4
  4. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_Preprocessor_lib.py +5 -0
  5. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/update_medicafe.py +36 -13
  6. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/api_core.py +39 -12
  7. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/submission_index.py +44 -0
  8. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_837p_cob_library.py +8 -1
  9. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_837p_encoder.py +6 -0
  10. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_837p_encoder_library.py +38 -0
  11. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_DataMgmt.py +74 -43
  12. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Decoder.py +38 -9
  13. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Down.py +104 -12
  14. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Parser.py +80 -1
  15. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_UI.py +2 -0
  16. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_main.py +69 -0
  17. {medicafe-0.250812.5/medicafe.egg-info → medicafe-0.250813.0}/PKG-INFO +1 -1
  18. {medicafe-0.250812.5 → medicafe-0.250813.0/medicafe.egg-info}/PKG-INFO +1 -1
  19. {medicafe-0.250812.5 → medicafe-0.250813.0}/setup.py +1 -1
  20. {medicafe-0.250812.5 → medicafe-0.250813.0}/LICENSE +0 -0
  21. {medicafe-0.250812.5 → medicafe-0.250813.0}/MANIFEST.in +0 -0
  22. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot.py +0 -0
  23. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_Charges.py +0 -0
  24. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_Post.py +0 -0
  25. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_Preprocessor.py +0 -0
  26. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_UI.py +0 -0
  27. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_dataformat_library.py +0 -0
  28. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_docx_decoder.py +0 -0
  29. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/MediBot_smart_import.py +0 -0
  30. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/__init__.py +0 -0
  31. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/get_medicafe_version.py +0 -0
  32. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediBot/update_json.py +0 -0
  33. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/MediLink_ConfigLoader.py +0 -0
  34. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/__init__.py +0 -0
  35. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/__main__.py +0 -0
  36. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/api_core_backup.py +0 -0
  37. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/api_factory.py +0 -0
  38. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/api_utils.py +0 -0
  39. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/core_utils.py +0 -0
  40. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/graphql_utils.py +0 -0
  41. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/logging_config.py +0 -0
  42. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/logging_demo.py +0 -0
  43. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/migration_helpers.py +0 -0
  44. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediCafe/smart_import.py +0 -0
  45. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/InsuranceTypeService.py +0 -0
  46. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_837p_utilities.py +0 -0
  47. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_API_Generator.py +0 -0
  48. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Azure.py +0 -0
  49. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_ClaimStatus.py +0 -0
  50. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Deductible.py +0 -0
  51. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Deductible_Validator.py +0 -0
  52. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Display_Utils.py +0 -0
  53. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Gmail.py +0 -0
  54. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Mailer.py +0 -0
  55. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_PatientProcessor.py +0 -0
  56. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Scan.py +0 -0
  57. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Scheduler.py +0 -0
  58. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_Up.py +0 -0
  59. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_insurance_utils.py +0 -0
  60. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/MediLink_smart_import.py +0 -0
  61. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/Soumit_api.py +0 -0
  62. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/__init__.py +0 -0
  63. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/gmail_http_utils.py +0 -0
  64. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/gmail_oauth_utils.py +0 -0
  65. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/insurance_type_integration_test.py +0 -0
  66. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/openssl.cnf +0 -0
  67. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/test.py +0 -0
  68. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/test_cob_library.py +0 -0
  69. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/test_timing.py +0 -0
  70. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/test_validation.py +0 -0
  71. {medicafe-0.250812.5 → medicafe-0.250813.0}/MediLink/webapp.html +0 -0
  72. {medicafe-0.250812.5 → medicafe-0.250813.0}/README.md +0 -0
  73. {medicafe-0.250812.5 → medicafe-0.250813.0}/medicafe.egg-info/SOURCES.txt +0 -0
  74. {medicafe-0.250812.5 → medicafe-0.250813.0}/medicafe.egg-info/dependency_links.txt +0 -0
  75. {medicafe-0.250812.5 → medicafe-0.250813.0}/medicafe.egg-info/entry_points.txt +0 -0
  76. {medicafe-0.250812.5 → medicafe-0.250813.0}/medicafe.egg-info/not-zip-safe +0 -0
  77. {medicafe-0.250812.5 → medicafe-0.250813.0}/medicafe.egg-info/requires.txt +0 -0
  78. {medicafe-0.250812.5 → medicafe-0.250813.0}/medicafe.egg-info/top_level.txt +0 -0
  79. {medicafe-0.250812.5 → medicafe-0.250813.0}/setup.cfg +0 -0
@@ -405,8 +405,6 @@ echo 6. Run MediBot
405
405
  echo.
406
406
  echo 7. Troubleshooting
407
407
  echo.
408
- echo 9. Toggle Performance Logging (session)
409
- echo.
410
408
  echo 8. Exit
411
409
  echo.
412
410
  set /p choice=Enter your choice:
@@ -420,7 +418,6 @@ if "!choice!"=="4" goto united_claims_status
420
418
  if "!choice!"=="3" goto medilink_flow
421
419
  if "!choice!"=="2" goto download_emails
422
420
  if "!choice!"=="1" goto check_updates
423
- if "!choice!"=="9" goto toggle_perf_logging
424
421
  if "!choice!"=="0" goto end_script
425
422
 
426
423
  echo Invalid choice. Please try again.
@@ -572,7 +569,7 @@ if not exist "%_UPD_RUNNER%" (
572
569
  echo.
573
570
  echo Launching updater and closing this window...
574
571
  start "MediCafe Update" "%_UPD_RUNNER%"
575
- exit /b 0
572
+ exit 0
576
573
 
577
574
  :: Download Carol's Emails
578
575
  :download_emails
@@ -636,7 +633,7 @@ if /I "%MEDICAFE_PERFORMANCE_LOGGING%"=="1" (
636
633
  echo.
637
634
  echo Note: This affects current session only. To persist, set in config.json.
638
635
  pause
639
- goto main_menu
636
+ goto troubleshooting_menu
640
637
 
641
638
  :: United Claims Status
642
639
  :united_claims_status
@@ -715,14 +712,16 @@ echo Troubleshooting Options:
715
712
  echo.
716
713
  echo 1. Open Latest Log File
717
714
  echo 2. Clear Python Cache
718
- echo 3. Forced MediCafe version rollback - no dependencies
719
- echo 4. Back to Main Menu
715
+ echo 3. Toggle Performance Logging ^(session^)
716
+ echo 4. Forced MediCafe version rollback
717
+ echo 5. Back to Main Menu
720
718
  echo.
721
719
  set /p tchoice=Enter your choice:
722
720
  if "%tchoice%"=="1" goto open_latest_log
723
721
  if "%tchoice%"=="2" goto clear_cache_menu
724
- if "%tchoice%"=="3" goto forced_version_rollback
725
- if "%tchoice%"=="4" goto main_menu
722
+ if "%tchoice%"=="3" goto toggle_perf_logging
723
+ if "%tchoice%"=="4" goto forced_version_rollback
724
+ if "%tchoice%"=="5" goto main_menu
726
725
  echo Invalid choice. Please try again.
727
726
  pause
728
727
  goto troubleshooting_menu
@@ -743,7 +742,7 @@ goto troubleshooting_menu
743
742
  :: End Script
744
743
  :end_script
745
744
  echo Exiting MediBot
746
- exit /b 0
745
+ exit 0
747
746
 
748
747
  :: Full Debug Mode moved to external script full_debug_suite.bat
749
748
 
@@ -376,6 +376,8 @@ def crosswalk_update(client, config, crosswalk): # Upstream of this is only Medi
376
376
  'medisoft_medicare_id': [] # PERFORMANCE FIX: Use list instead of set to avoid conversions
377
377
  }
378
378
  MediLink_ConfigLoader.log("Initialized payer ID {} in crosswalk with endpoint '{}'.".format(payer_id, selected_endpoint), config, level="DEBUG")
379
+ # TODO (MEDICARE ENDPOINTS): If payer_id is Medicare (e.g., in config['MediLink_Config']['cob_settings']['medicare_payer_ids']),
380
+ # set endpoint to 'MEDICARE_PRIMARY' and optionally store 'crossover_endpoint' for later automation.
379
381
 
380
382
  # Add the insurance ID to the payer ID entry (PERFORMANCE FIX: Use list operations)
381
383
  insurance_id_str = str(insurance_id) # Ensure ID is string
@@ -370,10 +370,12 @@ def save_crosswalk(client, config, crosswalk, skip_api_operations=False, api_cac
370
370
  crosswalk['payer_id'][payer_id]['endpoint'] = select_endpoint(config) # Use the helper function to set the endpoint
371
371
  MediLink_ConfigLoader.log("Initialized 'endpoint' for payer ID {}.".format(payer_id), config, level="DEBUG")
372
372
 
373
- # Initialize medisoft_id and medisoft_medicare_id as empty lists if they do not exist
374
- crosswalk['payer_id'][payer_id].setdefault('medisoft_id', [])
375
- crosswalk['payer_id'][payer_id].setdefault('medisoft_medicare_id', []) # does this work in 3.4.4?
376
- MediLink_ConfigLoader.log("Ensured 'medisoft_id' and 'medisoft_medicare_id' for payer ID {} are initialized.".format(payer_id), config, level="DEBUG")
373
+ # Initialize medisoft_id and medisoft_medicare_id as empty lists if they do not exist
374
+ crosswalk['payer_id'][payer_id].setdefault('medisoft_id', [])
375
+ crosswalk['payer_id'][payer_id].setdefault('medisoft_medicare_id', []) # does this work in 3.4.4?
376
+ MediLink_ConfigLoader.log("Ensured 'medisoft_id' and 'medisoft_medicare_id' for payer ID {} are initialized.".format(payer_id), config, level="DEBUG")
377
+ # TODO (CROSSWALK VALIDATION): Enforce distinctness between 'medisoft_id' and 'medisoft_medicare_id' and support optional
378
+ # 'crossover_endpoint' per payer. Use config['MediLink_Config']['cob_settings']['medicare_payer_ids'] to detect Medicare payers.
377
379
 
378
380
  # Convert sets to sorted lists for JSON serialization
379
381
  for payer_id, details in crosswalk.get('payer_id', {}).items():
@@ -816,6 +816,11 @@ def update_insurance_ids(csv_data, config, crosswalk):
816
816
 
817
817
  # Assign the resolved insurance ID to the row
818
818
  row['Ins1 Insurance ID'] = insurance_id
819
+ # TODO (SECONDARY QUEUE): When building a secondary-claims queue after Medicare crossover,
820
+ # set claim_type='secondary' and attach prior payer fields here from the Medicare primary outcome:
821
+ # - row['prior_payer_name'] = 'MEDICARE'
822
+ # - row['prior_payer_id'] = best Medicare ID from config/crosswalk
823
+ # - optionally row['primary_paid_amount'], row['cas_adjustments'] extracted from 835
819
824
  processed_count += 1
820
825
  # LOGGING STRATEGY: Remove success logging - DEBUG is typically silent anyway
821
826
  # if processed_count <= 10 or processed_count % 100 == 0: # Log first 10 and every 100th
@@ -1,5 +1,5 @@
1
1
  #update_medicafe.py
2
- import subprocess, sys, time, platform, os, shutil
2
+ import subprocess, sys, time, platform, os, shutil, random
3
3
 
4
4
  # Safe import for pkg_resources with fallback
5
5
  try:
@@ -162,6 +162,8 @@ def get_latest_version(package, retries=3, delay=1):
162
162
  time.sleep(delay)
163
163
  return None
164
164
 
165
+
166
+
165
167
  def check_internet_connection():
166
168
  try:
167
169
  requests.get("http://www.google.com", timeout=5)
@@ -288,7 +290,7 @@ def compare_versions(version1, version2):
288
290
  v2_parts = list(map(int, version2.split(".")))
289
291
  return (v1_parts > v2_parts) - (v1_parts < v2_parts)
290
292
 
291
- def upgrade_package(package, retries=3, delay=2): # Updated retries to 3
293
+ def upgrade_package(package, retries=4, delay=2, target_version=None): # Updated retries to 4
292
294
  """
293
295
  Attempts to upgrade the package multiple times with delays in between.
294
296
  """
@@ -296,23 +298,33 @@ def upgrade_package(package, retries=3, delay=2): # Updated retries to 3
296
298
  print_status("No internet connection detected. Please check your internet connection and try again.", "ERROR")
297
299
  print_final_result(False, "No internet connection available")
298
300
 
301
+ # Light verbosity: show pinned target once
302
+ if target_version:
303
+ print("Pinned target version: {}".format(target_version))
304
+
299
305
  for attempt in range(1, retries + 1):
300
- print("Attempt {} to upgrade {}...".format(attempt, package))
306
+ print("Attempt {}/{} to upgrade {}...".format(attempt, retries, package))
301
307
 
302
308
  # Use a more compatible approach for Python 3.4
303
309
  # Try with --no-deps first to avoid dependency resolution issues
310
+ pkg_spec = package
311
+ if target_version:
312
+ pkg_spec = "{}=={}".format(package, target_version)
313
+
304
314
  cmd = [
305
315
  sys.executable, '-m', 'pip', 'install', '--upgrade',
306
- '--no-deps', '--no-cache-dir', '--disable-pip-version-check', '-q', package
316
+ '--no-deps', '--no-cache-dir', '--disable-pip-version-check', '-q', pkg_spec
307
317
  ]
308
318
 
319
+ print("Using pip upgrade with --no-deps and --no-cache-dir")
309
320
  process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
310
321
  stdout, stderr = process.communicate()
311
322
 
312
323
  if process.returncode == 0:
313
324
  print(stdout.decode().strip())
314
325
  new_version = get_installed_version(package) # Get new version after upgrade
315
- if compare_versions(new_version, get_latest_version(package)) >= 0: # Compare versions
326
+ expected_version = target_version or get_latest_version(package)
327
+ if expected_version and compare_versions(new_version, expected_version) >= 0: # Compare versions
316
328
  if attempt == 1:
317
329
  print_status("Upgrade succeeded!", "SUCCESS")
318
330
  else:
@@ -320,20 +332,27 @@ def upgrade_package(package, retries=3, delay=2): # Updated retries to 3
320
332
  time.sleep(delay)
321
333
  return True
322
334
  else:
323
- print_status("Upgrade failed. Current version remains: {}".format(new_version), "WARNING")
335
+ print_status("Upgrade incomplete. Current version: {} Expected at least: {}".format(new_version, expected_version), "WARNING")
324
336
  if attempt < retries:
325
337
  print("Retrying in {} seconds...".format(delay))
326
- time.sleep(delay)
338
+ try:
339
+ time.sleep(delay + (random.random() * 0.5))
340
+ except Exception:
341
+ time.sleep(delay)
327
342
  else:
328
343
  print(stderr.decode().strip())
329
344
  print_status("Attempt {}: Upgrade failed with --no-deps.".format(attempt), "WARNING")
330
345
 
331
346
  # If --no-deps failed, try with --force-reinstall to bypass dependency issues
332
347
  if attempt < retries:
333
- print("Retrying with --force-reinstall...")
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
+
334
353
  cmd = [
335
354
  sys.executable, '-m', 'pip', 'install', '--upgrade',
336
- '--force-reinstall', '--no-cache-dir', '--disable-pip-version-check', '-q', package
355
+ '--force-reinstall', '--no-cache-dir', '--disable-pip-version-check', '-q', pkg_spec
337
356
  ]
338
357
 
339
358
  process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
@@ -342,19 +361,23 @@ def upgrade_package(package, retries=3, delay=2): # Updated retries to 3
342
361
  if process.returncode == 0:
343
362
  print(stdout.decode().strip())
344
363
  new_version = get_installed_version(package)
345
- if compare_versions(new_version, get_latest_version(package)) >= 0:
364
+ expected_version = target_version or get_latest_version(package)
365
+ if expected_version and compare_versions(new_version, expected_version) >= 0:
346
366
  print_status("Attempt {}: Upgrade succeeded with --force-reinstall!".format(attempt), "SUCCESS")
347
367
  time.sleep(delay)
348
368
  return True
349
369
  else:
350
- print_status("Upgrade failed. Current version remains: {}".format(new_version), "WARNING")
370
+ print_status("Upgrade incomplete. Current version: {} Expected at least: {}".format(new_version, expected_version), "WARNING")
351
371
  else:
352
372
  print(stderr.decode().strip())
353
373
  print_status("Attempt {}: Upgrade failed with --force-reinstall.".format(attempt), "WARNING")
354
374
 
355
375
  if attempt < retries:
356
376
  print("Retrying in {} seconds...".format(delay))
357
- time.sleep(delay)
377
+ try:
378
+ time.sleep(delay + (random.random() * 0.5))
379
+ except Exception:
380
+ time.sleep(delay)
358
381
 
359
382
  print_status("All upgrade attempts failed.", "ERROR")
360
383
  return False
@@ -566,7 +589,7 @@ def main():
566
589
  print("Current version: {}".format(current_version))
567
590
  print("Target version: {}".format(latest_version))
568
591
 
569
- if upgrade_package(package):
592
+ if upgrade_package(package, target_version=latest_version):
570
593
  # STEP 8: Verify upgrade
571
594
  debug_step(8, "Upgrade Verification")
572
595
  new_version = get_installed_version(package)
@@ -983,18 +983,18 @@ def is_test_mode(client, body, endpoint_type):
983
983
  def submit_uhc_claim(client, x12_request_data):
984
984
  """
985
985
  Submits a UHC claim and retrieves the claim acknowledgement details.
986
-
986
+
987
987
  This function first submits the claim using the provided x12 837p data. If the client is in Test Mode,
988
988
  it returns a simulated response. If Test Mode is not enabled, it submits the claim and then retrieves
989
989
  the claim acknowledgement details using the transaction ID from the initial response.
990
-
990
+
991
991
  NOTE: This function uses endpoints that may not be available in the new swagger version:
992
992
  - /Claims/api/claim-submission/v1 (claim submission)
993
993
  - /Claims/api/claim-details/v1 (claim acknowledgement)
994
994
 
995
995
  If these endpoints are deprecated in the new swagger, this function will need to be updated
996
996
  to use the new available endpoints.
997
-
997
+
998
998
  :param client: An instance of APIClient
999
999
  :param x12_request_data: The x12 837p data as a string
1000
1000
  :return: The final response containing the claim acknowledgement details or a dummy response if in Test Mode
@@ -1014,24 +1014,24 @@ def submit_uhc_claim(client, x12_request_data):
1014
1014
  endpoints = medi.get('endpoints', {})
1015
1015
  claim_submission_url = endpoints.get(endpoint_name, {}).get('additional_endpoints', {}).get('claim_submission', '')
1016
1016
  claim_details_url = endpoints.get(endpoint_name, {}).get('additional_endpoints', {}).get('claim_details', '')
1017
-
1017
+
1018
1018
  MediLink_ConfigLoader.log("Claim Submission URL: {}".format(claim_submission_url), level="INFO")
1019
1019
  MediLink_ConfigLoader.log("Claim Details URL: {}".format(claim_details_url), level="INFO")
1020
-
1020
+
1021
1021
  # Headers for the request
1022
1022
  headers = {'Content-Type': 'application/json'}
1023
-
1023
+
1024
1024
  # Request body for claim submission
1025
1025
  claim_body = {'x12RequestData': x12_request_data}
1026
-
1026
+
1027
1027
  MediLink_ConfigLoader.log("Claim Body Keys: {}".format(list(claim_body.keys())), level="INFO")
1028
1028
  MediLink_ConfigLoader.log("Headers: {}".format(json.dumps(headers, indent=2)), level="INFO")
1029
-
1029
+
1030
1030
  # Check if Test Mode is enabled and return simulated response if so
1031
1031
  test_mode_response = is_test_mode(client, claim_body, 'claim_submission')
1032
1032
  if test_mode_response:
1033
1033
  return test_mode_response
1034
-
1034
+
1035
1035
  # Make the API call to submit the claim
1036
1036
  try:
1037
1037
  MediLink_ConfigLoader.log("Making claim submission API call...", level="INFO")
@@ -1047,16 +1047,43 @@ def submit_uhc_claim(client, x12_request_data):
1047
1047
 
1048
1048
  # Prepare the request body for the claim acknowledgement retrieval
1049
1049
  acknowledgement_body = {'transactionId': transaction_id}
1050
-
1050
+
1051
1051
  # Check if Test Mode is enabled and return simulated response if so
1052
1052
  test_mode_response = is_test_mode(client, acknowledgement_body, 'claim_details')
1053
1053
  if test_mode_response:
1054
1054
  return test_mode_response
1055
-
1055
+
1056
1056
  # Make the API call to retrieve the claim acknowledgement details
1057
1057
  acknowledgement_response = client.make_api_call(endpoint_name, 'POST', claim_details_url, data=acknowledgement_body, headers=headers)
1058
+
1059
+ # Persist as unified ack event (best-effort)
1060
+ try:
1061
+ from MediCafe.submission_index import append_ack_event, ensure_submission_index
1062
+ cfg, _ = MediLink_ConfigLoader.load_configuration()
1063
+ receipts_root = extract_medilink_config(cfg).get('local_claims_path', None)
1064
+ if receipts_root:
1065
+ ensure_submission_index(receipts_root)
1066
+ status_text = ''
1067
+ try:
1068
+ # Attempt to pull a readable status from the response
1069
+ status_text = acknowledgement_response.get('status') or acknowledgement_response.get('message') or ''
1070
+ except Exception:
1071
+ status_text = ''
1072
+ append_ack_event(
1073
+ receipts_root,
1074
+ '', # claim_key unknown here
1075
+ status_text,
1076
+ 'API-277',
1077
+ 'uhcapi',
1078
+ {'transactionId': transaction_id},
1079
+ 'api_ack',
1080
+ int(time.time())
1081
+ )
1082
+ except Exception:
1083
+ pass
1084
+
1058
1085
  return acknowledgement_response
1059
-
1086
+
1060
1087
  except Exception as e:
1061
1088
  print("Error during claim processing: {}".format(e))
1062
1089
  raise
@@ -22,6 +22,9 @@ META_FILENAME = 'submission_index_meta.json'
22
22
  INDEX_FILENAME = 'submission_index.jsonl'
23
23
  LOCK_FILENAME = 'submission_index.lock'
24
24
 
25
+ # New: ack field keys for richer timeline entries
26
+ ACK_FIELDS = ['ack_type', 'ack_timestamp', 'control_ids', 'source', 'file_name']
27
+
25
28
 
26
29
  def build_initial_index(receipts_root, lookback_days=200):
27
30
  """
@@ -123,6 +126,47 @@ def compute_claim_key(patient_id, payer_id, primary_insurance, date_of_service,
123
126
  ])
124
127
 
125
128
 
129
+ def append_ack_event(receipts_root, claim_key, status_text, ack_type, file_name, control_ids, source, ack_timestamp=None):
130
+ """
131
+ Append a lightweight ack/timeline event to the index. XP/Py3.4/ASCII-safe.
132
+ - claim_key may be empty if unknown. Caller should pass when available.
133
+ - control_ids is a dict with optional ISA/GS/ST/TRN or transactionId.
134
+ """
135
+ try:
136
+ _ensure_files_exist(receipts_root)
137
+ event = {
138
+ 'claim_key': claim_key or '',
139
+ 'patient_id': '',
140
+ 'payer_id': '',
141
+ 'primary_insurance': '',
142
+ 'dos': '',
143
+ 'endpoint': source or 'download_ack',
144
+ 'submitted_at': '',
145
+ 'receipt_file': file_name or '',
146
+ 'status': status_text or '',
147
+ 'notes': 'ack event',
148
+ }
149
+ # Attach ack fields with basic validation
150
+ try:
151
+ event['ack_type'] = ack_type or ''
152
+ event['ack_timestamp'] = ack_timestamp or int(time.time())
153
+ event['control_ids'] = control_ids or {}
154
+ event['source'] = source or ''
155
+ event['file_name'] = file_name or ''
156
+ except Exception:
157
+ pass
158
+ path = _index_path(receipts_root)
159
+ line = json.dumps(event)
160
+ f = open(path, 'a')
161
+ try:
162
+ f.write(line)
163
+ f.write("\n")
164
+ finally:
165
+ f.close()
166
+ except Exception:
167
+ pass
168
+
169
+
126
170
  # ------------------------- ASCII-safe meta/lock helpers -----------------------
127
171
 
128
172
  def _meta_path(root_dir):
@@ -101,6 +101,10 @@ def create_2320_other_subscriber_segments(patient_data, config, crosswalk):
101
101
  is_secondary = patient_data.get('claim_type', 'primary') == 'secondary'
102
102
 
103
103
  if is_secondary:
104
+ # TODO (DATA CONTRACT): If 835-derived fields are present on patient_data, prefer them:
105
+ # - total_paid -> AMT*D
106
+ # - cas_adjustments -> CAS
107
+ # Otherwise accept 'primary_paid_amount' and 'cas_adjustments' provided by upstream workflow.
104
108
  # SBR segment for secondary payer
105
109
  responsibility_code = "S" # Secondary
106
110
  insurance_type = determine_medicare_payer_type(patient_data, config)
@@ -111,7 +115,9 @@ def create_2320_other_subscriber_segments(patient_data, config, crosswalk):
111
115
  segments.append(sbr_segment)
112
116
 
113
117
  # AMT*D segment for total amount paid by primary
114
- total_paid = patient_data.get('primary_paid_amount', '0.00')
118
+ # TODO (STRICT MODE): When config['MediLink_Config']['cob_settings']['validation_level'] >= 2,
119
+ # require presence of a numeric total (from 'total_paid' or 'primary_paid_amount').
120
+ total_paid = patient_data.get('total_paid', patient_data.get('primary_paid_amount', '0.00'))
115
121
  amt_segment = "AMT*D*{}~".format(total_paid)
116
122
  segments.append(amt_segment)
117
123
 
@@ -152,6 +158,7 @@ def create_2330B_prior_payer_segments(patient_data, config, crosswalk):
152
158
  segments = []
153
159
 
154
160
  # Get prior payer information
161
+ # TODO (CONFIG): Resolve Medicare payer ID from config['MediLink_Config']['cob_settings']['medicare_payer_ids'] if prior_payer_id not provided.
155
162
  prior_payer_name = patient_data.get('prior_payer_name', 'MEDICARE')
156
163
  prior_payer_id = patient_data.get('prior_payer_id', '00850')
157
164
 
@@ -613,6 +613,12 @@ def process_claim(config, endpoint, patient_data_list, crosswalk, client, suffix
613
613
  document_segments = []
614
614
 
615
615
  for patient_data in patient_data_list:
616
+ # TODO (SECONDARY PREP): Upstream should mark secondary claims and provide Medicare prior payer info when applicable.
617
+ # Expected minimal keys for Medicare-secondary:
618
+ # - claim_type='secondary'
619
+ # - prior_payer_name='MEDICARE'
620
+ # - prior_payer_id from config cob_settings.medicare_payer_ids (default '00850')
621
+ # - optional: primary_paid_amount, cas_adjustments
616
622
  # Validate each patient's data before processing
617
623
  is_valid, validation_errors = validate_claim_data(patient_data, medi)
618
624
  if is_valid:
@@ -980,6 +980,43 @@ def create_clm_and_related_segments(parsed_data, config, crosswalk):
980
980
  # - create_2330B_prior_payer_segments() for Medicare prior payer
981
981
  # - create_2430_service_line_cob_segments() for service-level adjudication
982
982
  # - create_2330C_other_subscriber_name_segments() when patient != subscriber
983
+ #
984
+ # Minimal, safe integration (guarded by feature flag):
985
+ if COB is not None:
986
+ cob_enabled = False
987
+ try:
988
+ # Read feature flag from configuration (expects medi['cob_settings']['enabled'])
989
+ from MediCafe.core_utils import extract_medilink_config
990
+ medi_cfg = extract_medilink_config(config)
991
+ cob_enabled = bool(medi_cfg.get('cob_settings', {}).get('enabled', False))
992
+ except Exception:
993
+ cob_enabled = False
994
+
995
+ # Only add COB loops when explicitly enabled and claim is secondary
996
+ # TODO (COB VALIDATION): When COB is enabled and claim is secondary, validate required fields:
997
+ # - prior_payer_id/prior_payer_name present
998
+ # - primary_paid_amount present when sending AMT*D (or skip AMT if not available)
999
+ # - cas_adjustments schema if provided (list of {group, reason, amount})
1000
+ # If critical fields are missing, log and proceed with best-effort unless config enforces strict mode.
1001
+ if cob_enabled and validated_data.get('claim_type') == 'secondary':
1002
+ try:
1003
+ # 2320 - Other Subscriber Information (OI, AMT, CAS, etc.)
1004
+ segments.extend(COB.create_2320_other_subscriber_segments(validated_data, config, crosswalk))
1005
+ except Exception as _e1:
1006
+ try:
1007
+ MediLink_ConfigLoader.log("COB 2320 insertion failed: {}".format(str(_e1)), config, level="WARNING")
1008
+ except Exception:
1009
+ pass
1010
+
1011
+ try:
1012
+ # 2330B - Prior Payer (Medicare prior payer info, e.g., 00850)
1013
+ segments.extend(COB.create_2330B_prior_payer_segments(validated_data, config, crosswalk))
1014
+ except Exception as _e2:
1015
+ try:
1016
+ MediLink_ConfigLoader.log("COB 2330B insertion failed: {}".format(str(_e2)), config, level="WARNING")
1017
+ except Exception:
1018
+ pass
1019
+
983
1020
  # TODO (COB ENHANCEMENT): Optional attachment references (PWK) for non-electronic EOB handling
984
1021
  # See MediLink_837p_cob_library.create_pwk_attachment_segment() for implementation
985
1022
  # Example: PWK*EB*FX*123456~ for attachment control number
@@ -1002,6 +1039,7 @@ def create_clm_and_related_segments(parsed_data, config, crosswalk):
1002
1039
  segments.append("DTP*472*D8*{}~".format(convert_date_format(validated_data['DATE'])))
1003
1040
 
1004
1041
  # Is there REF - Line Item Control Number missing here? Private insurance doesn't need it, but Medicare does?
1042
+ # TODO (MEDICARE REF): Add conditional REF*6R (line item control number) when payer is Medicare or when crosswalk/config requires it.
1005
1043
  # segments.append("REF*6R*1~") # REF01, Reference Identification Qualifier; REF02, Line Item Control Number.
1006
1044
  # 6R - Provider Control Number (Number assigned by information provider company for tracking and billing purposes)
1007
1045
  # 1 - Reference information as defined for a particular Transaction Set or as specified by the Reference Identification Qualifier
@@ -330,7 +330,12 @@ def operate_winscp(operation_type, files, endpoint_config, local_storage_path, c
330
330
  local_storage_path = validate_local_storage_path(local_storage_path, config)
331
331
 
332
332
  remote_directory = get_remote_directory(endpoint_config, operation_type)
333
- command = build_command(winscp_path, winscp_log_path, endpoint_config, remote_directory, operation_type, files, local_storage_path)
333
+ if operation_type == "download":
334
+ # Prefer explicit ack-focused mask if not provided by endpoint
335
+ filemask = endpoint_config.get('filemask') or ['era', '277', '277ibr', '277ebr', '999']
336
+ else:
337
+ filemask = None
338
+ command = build_command(winscp_path, winscp_log_path, endpoint_config, remote_directory, operation_type, files, local_storage_path, newer_than=None, filemask=filemask)
334
339
 
335
340
  if config.get("TestMode", True):
336
341
  MediLink_ConfigLoader.log("Test mode is enabled. Simulating operation.")
@@ -470,6 +475,48 @@ def get_remote_directory(endpoint_config, operation_type):
470
475
  MediLink_ConfigLoader.log("Critical Error: Endpoint config is missing key: {}".format(e))
471
476
  raise RuntimeError("Configuration error: Missing required remote directory in endpoint configuration.")
472
477
 
478
+ def normalize_filemask(filemask):
479
+ """
480
+ Normalize various filemask inputs into WinSCP-compatible string.
481
+ Supports list of extensions, comma-separated string, or dict with 'extensions' and other filters.
482
+ Falls back to '*' when input is invalid.
483
+ """
484
+ try:
485
+ if not filemask:
486
+ return '*'
487
+ if isinstance(filemask, list):
488
+ parts = []
489
+ for ext in filemask:
490
+ s = str(ext).strip().lstrip('*.').lstrip('.')
491
+ if s:
492
+ parts.append('*.{}'.format(s))
493
+ return '|'.join(parts) if parts else '*'
494
+ if isinstance(filemask, dict):
495
+ exts = filemask.get('extensions', [])
496
+ other = []
497
+ for k, v in filemask.items():
498
+ if k == 'extensions':
499
+ continue
500
+ other.append(str(v))
501
+ ext_part = normalize_filemask(exts)
502
+ other_part = ';'.join(other)
503
+ if ext_part and other_part:
504
+ return '{};{}'.format(ext_part, other_part)
505
+ return ext_part or other_part or '*'
506
+ if isinstance(filemask, str):
507
+ # Support comma-separated or pipe-separated lists of extensions
508
+ raw = filemask.replace(' ', '')
509
+ if any(sep in raw for sep in [',', '|']):
510
+ tokens = raw.replace('|', ',').split(',')
511
+ return normalize_filemask([t for t in tokens if t])
512
+ # If looks like an extension, prefix
513
+ s = raw.lstrip('*.').lstrip('.')
514
+ if s and all(ch.isalnum() for ch in s):
515
+ return '*.{}'.format(s)
516
+ return raw or '*'
517
+ except Exception:
518
+ return '*'
519
+
473
520
  def build_command(winscp_path, winscp_log_path, endpoint_config, remote_directory, operation_type, files, local_storage_path, newer_than=None, filemask=None):
474
521
  # Log the operation type
475
522
  MediLink_ConfigLoader.log("[Build Command] Building WinSCP command for operation type: {}".format(operation_type))
@@ -581,14 +628,7 @@ def build_command(winscp_path, winscp_log_path, endpoint_config, remote_director
581
628
  # 5. Add validation for WinSCP-compatible patterns
582
629
  # 6. Add logging for debugging filemask translations
583
630
  # 7. XP QUIRK: Prefer simple masks (e.g., *.csv|*.txt) and avoid complex AND/OR until verified on XP.
584
- if isinstance(filemask, list):
585
- filemask_str = '|'.join(['*.' + ext for ext in filemask])
586
- elif isinstance(filemask, dict):
587
- filemask_str = '|'.join(['*.' + ext for ext in filemask.keys()])
588
- elif isinstance(filemask, str):
589
- filemask_str = filemask # Assume it's already in the correct format
590
- else:
591
- filemask_str = '*' # Default to all files if filemask is None or unsupported type
631
+ filemask_str = normalize_filemask(filemask)
592
632
  else:
593
633
  filemask_str = '*' # Default to all files if filemask is None
594
634
 
@@ -659,38 +699,25 @@ def execute_winscp_command(command, operation_type, files, local_storage_path):
659
699
  MediLink_ConfigLoader.log("WinSCP {} operation completed successfully.".format(operation_type))
660
700
 
661
701
  if operation_type == 'download':
662
- downloaded_files = list_downloaded_files(local_storage_path)
663
- # TODO (HIGH PRIORITY - WinSCP Path Configuration Issue):
664
- # PROBLEM: WinSCP is not downloading files to the expected local_storage_path directory.
665
- # The list_downloaded_files() function is checking the wrong location.
666
- #
667
- # XP/WinSCP SUGGESTION:
668
- # - Add config override 'winscp_download_path' to explicitly set WinSCP's target directory.
669
- # - If set, prefer list_downloaded_files(config['MediLink_Config']['winscp_download_path']).
670
- # - Otherwise, parse the WinSCP log to detect the actual path and fall back to local_storage_path.
671
- #
672
- # INVESTIGATION STEPS:
673
- # 1. Check WinSCP logs to determine actual download destination:
674
- # - Look in config['MediLink_Config']['local_claims_path'] + "winscp_download.log"
675
- # - Parse log entries for "file downloaded to:" or similar patterns
676
- # 2. Compare actual WinSCP download path vs configured local_storage_path
677
- # 3. Check if WinSCP uses different path conventions (forward/backward slashes)
678
- #
679
- # IMPLEMENTATION OPTIONS:
680
- # Option A: Fix WinSCP command to use correct target directory
681
- # - Update the lcd_command generation in execute_winscp_command()
682
- # - Ensure local_storage_path is properly escaped for WinSCP
683
- # Option B: Update list_downloaded_files() to check actual WinSCP location
684
- # - Add function get_actual_winscp_download_path() that parses logs
685
- # - Call list_downloaded_files(get_actual_winscp_download_path())
686
- # Option C: Add configuration parameter for WinSCP-specific download path
687
- # - Add 'winscp_download_path' to config
688
- # - Default to local_storage_path if not specified
689
- #
690
- # RECOMMENDED: Option A (fix root cause) + Option C (explicit config)
691
- # FILES TO MODIFY: This file (execute_winscp_command, list_downloaded_files functions)
692
- # TESTING: Verify downloads work correctly after fix with various file types
693
- MediLink_ConfigLoader.log("Files currently located in local_storage_path: {}".format(downloaded_files), level="DEBUG")
702
+ # Prefer configured override if present
703
+ winscp_download_path = None
704
+ try:
705
+ from MediCafe.core_utils import extract_medilink_config
706
+ config, _ = MediLink_ConfigLoader.load_configuration()
707
+ medi = extract_medilink_config(config)
708
+ winscp_download_path = medi.get('winscp_download_path')
709
+ except Exception:
710
+ winscp_download_path = None
711
+
712
+ target_dir = winscp_download_path or local_storage_path
713
+ downloaded_files = list_downloaded_files(target_dir)
714
+ MediLink_ConfigLoader.log("Files currently located in target directory ({}): {}".format(target_dir, downloaded_files), level="DEBUG")
715
+
716
+ if not downloaded_files and winscp_download_path and winscp_download_path != local_storage_path:
717
+ # Fallback to original path if override empty
718
+ fallback_files = list_downloaded_files(local_storage_path)
719
+ MediLink_ConfigLoader.log("Fallback to local_storage_path yielded: {}".format(fallback_files), level="DEBUG")
720
+ downloaded_files = fallback_files
694
721
 
695
722
  if not downloaded_files:
696
723
  MediLink_ConfigLoader.log("No files were downloaded or an error occurred during the listing process.", level="WARNING")
@@ -727,8 +754,12 @@ def list_downloaded_files(local_storage_path):
727
754
  except Exception as e:
728
755
  MediLink_ConfigLoader.log("Error occurred while listing files in {}: {}".format(local_storage_path, e), level="ERROR")
729
756
 
730
- # Ensure that the function always returns a list
731
- return downloaded_files
757
+ # Normalize to basenames so downstream move logic in MediLink_Down works cross-platform
758
+ try:
759
+ basenames = [os.path.basename(p) for p in downloaded_files]
760
+ return basenames
761
+ except Exception:
762
+ return downloaded_files
732
763
 
733
764
  def detect_new_files(directory_path, file_extension='.DAT'):
734
765
  """