medicafe 0.240415.1__py3-none-any.whl → 0.240517.0__py3-none-any.whl
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.
Potentially problematic release.
This version of medicafe might be problematic. Click here for more details.
- MediBot/MediBot.bat +198 -0
- MediBot/MediBot.py +346 -0
- MediBot/MediBot_Charges.py +28 -0
- MediBot/MediBot_Crosswalk_Library.py +280 -0
- MediBot/MediBot_Preprocessor.py +247 -0
- MediBot/MediBot_Preprocessor_lib.py +357 -0
- MediBot/MediBot_UI.py +240 -0
- MediBot/MediBot_dataformat_library.py +198 -0
- MediBot/MediBot_docx_decoder.py +80 -0
- MediBot/MediPost.py +5 -0
- MediBot/PDF_to_CSV_Cleaner.py +211 -0
- MediBot/__init__.py +0 -0
- MediBot/update_json.py +43 -0
- MediBot/update_medicafe.py +57 -0
- MediLink/MediLink.py +381 -0
- MediLink/MediLink_277_decoder.py +92 -0
- MediLink/MediLink_837p_encoder.py +502 -0
- MediLink/MediLink_837p_encoder_library.py +890 -0
- MediLink/MediLink_API_v2.py +174 -0
- MediLink/MediLink_APIs.py +137 -0
- MediLink/MediLink_ConfigLoader.py +81 -0
- MediLink/MediLink_DataMgmt.py +258 -0
- MediLink/MediLink_Down.py +128 -0
- MediLink/MediLink_ERA_decoder.py +192 -0
- MediLink/MediLink_Gmail.py +100 -0
- MediLink/MediLink_Mailer.py +7 -0
- MediLink/MediLink_Scheduler.py +173 -0
- MediLink/MediLink_StatusCheck.py +4 -0
- MediLink/MediLink_UI.py +118 -0
- MediLink/MediLink_Up.py +383 -0
- MediLink/MediLink_batch.bat +7 -0
- MediLink/Soumit_api.py +22 -0
- MediLink/__init__.py +0 -0
- MediLink/test.py +74 -0
- medicafe-0.240517.0.dist-info/METADATA +53 -0
- medicafe-0.240517.0.dist-info/RECORD +39 -0
- {medicafe-0.240415.1.dist-info → medicafe-0.240517.0.dist-info}/WHEEL +1 -1
- medicafe-0.240517.0.dist-info/top_level.txt +2 -0
- medicafe-0.240415.1.dist-info/METADATA +0 -17
- medicafe-0.240415.1.dist-info/RECORD +0 -5
- medicafe-0.240415.1.dist-info/top_level.txt +0 -1
- {medicafe-0.240415.1.dist-info → medicafe-0.240517.0.dist-info}/LICENSE +0 -0
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import MediLink_ConfigLoader
|
|
6
|
+
from MediLink_DataMgmt import parse_fixed_width_data, read_fixed_width_data
|
|
7
|
+
import MediLink_837p_encoder_library
|
|
8
|
+
#from tqdm import tqdm
|
|
9
|
+
|
|
10
|
+
"""
|
|
11
|
+
Single File Processing Flow:
|
|
12
|
+
|
|
13
|
+
This flow is triggered when the -d (directory) flag is not set. It handles the conversion of a single file specified by the -p flag.
|
|
14
|
+
It directly processes the single file specified, without the need to iterate over a directory.
|
|
15
|
+
The conversion initializes and processes this single file, appending the necessary EDI segments, and directly writes the output once processing is complete.
|
|
16
|
+
|
|
17
|
+
Batch Directory Processing Flow:
|
|
18
|
+
|
|
19
|
+
Activated when the -d flag is set, indicating that the -p flag points to a directory rather than a single file.
|
|
20
|
+
Iterates over all files in the specified directory, processing only those that end with the ".DAT" extension.
|
|
21
|
+
Each file is processed in sequence, with each undergoing a full cycle of reading, processing, and output file generation as in the single file flow.
|
|
22
|
+
|
|
23
|
+
Development Task List:
|
|
24
|
+
|
|
25
|
+
- [ ] 1. File Path Management: Enhance the handling of input paths to efficiently manage both individual files and directories, accommodating a range of file processing scenarios.
|
|
26
|
+
- [ ] 2. User Interface Improvement: Advance the CLI for intuitive user interaction, offering clear options for file processing and real-time progress updates.
|
|
27
|
+
- [ ] 3. Validation and Logging: Strengthen validation processes for input data, incorporating thorough checks against business rules and enhanced detailed logging for improved traceability and troubleshooting.
|
|
28
|
+
- [ ] 4. Batch Processing and Output Handling: Enhance output file management to support efficient batch operations, including systematic naming and organization for output files.
|
|
29
|
+
- [ ] 5. Comprehensive Documentation: Maintain up-to-date and detailed documentation within the codebase, ensuring all functions and complex logic are clearly explained.
|
|
30
|
+
- [ ] 6. De-persisting Intermediate Files.
|
|
31
|
+
- [ ] 7. Determination of Relationship to Patient for insurance holder. Can Compare Insured Name & closeness of DOB (usually spouse [2], child [3]).
|
|
32
|
+
- [ ] 8. Consolidation of certain functions needs to happen here.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def format_single_claim(patient_data, config, endpoint, transaction_set_control_number):
|
|
36
|
+
"""
|
|
37
|
+
Formats a single claim into 837P segments based on the provided patient data and endpoint.
|
|
38
|
+
|
|
39
|
+
Parameters:
|
|
40
|
+
- patient_data: Dictionary containing detailed patient data.
|
|
41
|
+
- config: Configuration settings loaded from a JSON file.
|
|
42
|
+
- endpoint: The endpoint key representing the specific endpoint.
|
|
43
|
+
- transaction_set_control_number: Starting transaction set control number for 837P segments.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
- String representation of the formatted 837P claim.
|
|
47
|
+
"""
|
|
48
|
+
# Pre-resolve and enrich with Payer Name and ID for special case handling like Florida Blue.
|
|
49
|
+
patient_data = MediLink_837p_encoder_library.payer_id_to_payer_name(patient_data, config, endpoint)
|
|
50
|
+
|
|
51
|
+
segments = []
|
|
52
|
+
|
|
53
|
+
# Initialize with standard segments for all claims
|
|
54
|
+
segments.append(MediLink_837p_encoder_library.create_st_segment(transaction_set_control_number))
|
|
55
|
+
segments.append(MediLink_837p_encoder_library.create_bht_segment(patient_data))
|
|
56
|
+
|
|
57
|
+
# Submitter Name Segment and PER Contact Information (1000A Loop)
|
|
58
|
+
segments.extend(MediLink_837p_encoder_library.create_1000A_submitter_name_segment(patient_data, config, endpoint))
|
|
59
|
+
|
|
60
|
+
# Receiver Name Segment (1000B Loop)
|
|
61
|
+
segments.extend([MediLink_837p_encoder_library.create_1000B_receiver_name_segment(config, endpoint)])
|
|
62
|
+
|
|
63
|
+
# Billing Provider Segments (2010AA Loop)
|
|
64
|
+
segments.extend([MediLink_837p_encoder_library.create_hl_billing_provider_segment()])
|
|
65
|
+
segments.extend(MediLink_837p_encoder_library.create_nm1_billing_provider_segment(config, endpoint))
|
|
66
|
+
|
|
67
|
+
# Pay-To Address Segment (2010AB Loop) if the Pay-To Address differs from the Billing Provider's address
|
|
68
|
+
#segments.extend(MediLink_837p_encoder_library.create_nm1_payto_address_segments(config))
|
|
69
|
+
|
|
70
|
+
# PRV Provider Taxonomy Segment
|
|
71
|
+
#segments.extend([MediLink_837p_encoder_library.create_billing_prv_segment(config, endpoint)])
|
|
72
|
+
|
|
73
|
+
# Subscriber information, possibly including endpoint-specific logic
|
|
74
|
+
segments.extend(MediLink_837p_encoder_library.create_hl_subscriber_segment())
|
|
75
|
+
segments.append(MediLink_837p_encoder_library.create_sbr_segment(config, patient_data, endpoint))
|
|
76
|
+
segments.append(MediLink_837p_encoder_library.create_nm1_subscriber_segment(config, patient_data, endpoint))
|
|
77
|
+
segments.extend(MediLink_837p_encoder_library.create_subscriber_address_segments(patient_data))
|
|
78
|
+
segments.append(MediLink_837p_encoder_library.create_dmg_segment(patient_data))
|
|
79
|
+
|
|
80
|
+
# Payer information (2010BB loop)
|
|
81
|
+
# TODO This function now includes detailed outputs and potential user interactions with the new implementation.
|
|
82
|
+
# The new implementation introduces user inputs directly in the flow, which could disrupt automated batch processes.
|
|
83
|
+
# Ensure that there are mechanisms or workflows in place to handle such interruptions appropriately.
|
|
84
|
+
segments.extend([MediLink_837p_encoder_library.create_2010BB_payer_information_segment(patient_data)])
|
|
85
|
+
#segments.extend(MediLink_837p_encoder_library.create_payer_address_segments(config)) OMITTED
|
|
86
|
+
|
|
87
|
+
# Rendering Provider (2310B Loop)
|
|
88
|
+
segments.extend(MediLink_837p_encoder_library.create_nm1_rendering_provider_segment(config))
|
|
89
|
+
|
|
90
|
+
# Claim information 2300, 2310C Service Facility and 2400 loop segments
|
|
91
|
+
segments.extend(MediLink_837p_encoder_library.create_clm_and_related_segments(patient_data, config))
|
|
92
|
+
|
|
93
|
+
# Placeholder for the SE segment to be updated with actual segment count later
|
|
94
|
+
segments.append("SE**{transaction_set_control_number:04d}~")
|
|
95
|
+
|
|
96
|
+
# Update SE segment with the actual segment count and generate the final formatted 837P string
|
|
97
|
+
formatted_837p = MediLink_837p_encoder_library.generate_segment_counts('\n'.join(filter(None, segments)), transaction_set_control_number)
|
|
98
|
+
|
|
99
|
+
# Optionally, print or log the formatted 837P for debugging or verification
|
|
100
|
+
# TODO (Low UI/usability) Add chart number to this.
|
|
101
|
+
MediLink_ConfigLoader.log("Formatted 837P for endpoint {}.".format(endpoint), config, level="INFO")
|
|
102
|
+
|
|
103
|
+
return formatted_837p
|
|
104
|
+
|
|
105
|
+
def write_output_file(document_segments, output_directory, endpoint_key, input_file_path, config):
|
|
106
|
+
"""
|
|
107
|
+
Writes formatted 837P document segments to an output file with a dynamically generated name.
|
|
108
|
+
|
|
109
|
+
Development Roadmap:
|
|
110
|
+
- Ensure input `document_segments` is a non-empty list to avoid creating empty files.
|
|
111
|
+
- Verify `output_directory` exists and is writable before proceeding. Create the directory if it does not exist.
|
|
112
|
+
- Consider parameterizing the file naming convention or providing options for customization to accommodate different organizational needs.
|
|
113
|
+
- Implement error handling to gracefully manage file writing failures, potentially returning a status or error message alongside the file path.
|
|
114
|
+
- Incorporate logging directly within the function, accepting an optional `config` or `logger` parameter to facilitate tracking of the file writing process and outcomes.
|
|
115
|
+
- Update the return value to include both the path to the output file and any relevant status information (e.g., success flag, error message) to enhance downstream error handling and user feedback.
|
|
116
|
+
|
|
117
|
+
Parameters:
|
|
118
|
+
- document_segments: List of strings, where each string is a segment of the 837P document to be written.
|
|
119
|
+
- output_directory: String specifying the directory where the output file will be saved.
|
|
120
|
+
- endpoint_key: String specifying the endpoint for which the claim is processed, used in naming the output file.
|
|
121
|
+
- input_file_path: String specifying the path to the input file being processed, used in naming the output file.
|
|
122
|
+
|
|
123
|
+
Returns:
|
|
124
|
+
- String specifying the path to the successfully created output file. Consider returning a tuple (path, status) for enhanced error handling.
|
|
125
|
+
"""
|
|
126
|
+
# Check if document segments are empty
|
|
127
|
+
if not document_segments:
|
|
128
|
+
MediLink_ConfigLoader.log("Error: Empty document segments provided. No output file created.", config, level="ERROR")
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
# Check if the output directory exists and is writable
|
|
132
|
+
if not os.path.exists(output_directory):
|
|
133
|
+
try:
|
|
134
|
+
os.makedirs(output_directory)
|
|
135
|
+
except OSError as e:
|
|
136
|
+
MediLink_ConfigLoader.log("Error: Failed to create output directory. {}".format(e), config, level="ERROR")
|
|
137
|
+
return None
|
|
138
|
+
elif not os.access(output_directory, os.W_OK):
|
|
139
|
+
MediLink_ConfigLoader.log("Error: Output directory is not writable.", config, level="ERROR")
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
# Generate new output file path
|
|
143
|
+
base_name = os.path.splitext(os.path.basename(input_file_path))[0]
|
|
144
|
+
timestamp = datetime.now().strftime("%m%d%H%M")
|
|
145
|
+
new_output_file_name = "{}_{}_{}.txt".format(base_name, endpoint_key.lower(), timestamp)
|
|
146
|
+
new_output_file_path = os.path.join(output_directory, new_output_file_name)
|
|
147
|
+
|
|
148
|
+
# Write formatted 837P document to the output file
|
|
149
|
+
try:
|
|
150
|
+
with open(new_output_file_path, 'w') as output_file:
|
|
151
|
+
output_file.write('\n'.join(document_segments))
|
|
152
|
+
MediLink_ConfigLoader.log("Successfully converted and saved to {}".format(new_output_file_path), config, level="INFO")
|
|
153
|
+
return new_output_file_path
|
|
154
|
+
except Exception as e:
|
|
155
|
+
MediLink_ConfigLoader.log("Error: Failed to write output file. {}".format(e), config, level="ERROR")
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
def process_file(file_path, config, endpoint_key, transaction_set_control_number):
|
|
159
|
+
"""
|
|
160
|
+
Process the claim data from a file into the 837P format.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
file_path (str): The path to the file containing the claim data.
|
|
164
|
+
config (dict): Configuration settings loaded from a JSON file.
|
|
165
|
+
endpoint_key (str): The key representing the endpoint for which the claim is being processed.
|
|
166
|
+
transaction_set_control_number (int): The starting transaction set control number for 837P segments.
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
tuple: A tuple containing the formatted claim segments and the next transaction set control number.
|
|
170
|
+
"""
|
|
171
|
+
valid_claims, validation_errors = read_and_validate_claims(file_path, config)
|
|
172
|
+
|
|
173
|
+
# Handle validation errors
|
|
174
|
+
if validation_errors:
|
|
175
|
+
if not MediLink_837p_encoder_library.handle_validation_errors(transaction_set_control_number, validation_errors, config):
|
|
176
|
+
return None, transaction_set_control_number # Halt processing if the user chooses
|
|
177
|
+
|
|
178
|
+
# Process each valid claim
|
|
179
|
+
formatted_claims, transaction_set_control_number = format_claims(valid_claims, config, endpoint_key, transaction_set_control_number)
|
|
180
|
+
|
|
181
|
+
formatted_claims_str = '\n'.join(formatted_claims) # Join formatted claims into a single string
|
|
182
|
+
return formatted_claims_str, transaction_set_control_number
|
|
183
|
+
|
|
184
|
+
def read_and_validate_claims(file_path, config):
|
|
185
|
+
"""
|
|
186
|
+
Read and validate claim data from a file.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
file_path (str): The path to the file containing the claim data.
|
|
190
|
+
config (dict): Configuration settings loaded from a JSON file.
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
tuple: A tuple containing a list of valid parsed data and a list of validation errors.
|
|
194
|
+
"""
|
|
195
|
+
valid_claims = [] # List to store valid parsed data
|
|
196
|
+
validation_errors = [] # List to store validation errors
|
|
197
|
+
|
|
198
|
+
# Iterate over data in the file
|
|
199
|
+
for personal_info, insurance_info, service_info in read_fixed_width_data(file_path):
|
|
200
|
+
# Parse data into a usable format
|
|
201
|
+
parsed_data = parse_fixed_width_data(personal_info, insurance_info, service_info, config.get('MediLink_Config', config))
|
|
202
|
+
# Validate the parsed data
|
|
203
|
+
is_valid, errors = validate_claim_data(parsed_data, config)
|
|
204
|
+
if is_valid:
|
|
205
|
+
valid_claims.append(parsed_data) # Add valid data to the list
|
|
206
|
+
else:
|
|
207
|
+
validation_errors.append(errors) # Add validation errors to the list
|
|
208
|
+
# Log validation failure
|
|
209
|
+
MediLink_ConfigLoader.log("Validation failed for claim data in file: {}. Errors: {}".format(file_path, errors), config, level="ERROR")
|
|
210
|
+
|
|
211
|
+
return valid_claims, validation_errors
|
|
212
|
+
|
|
213
|
+
def format_claims(parsed_data_list, config, endpoint, starting_transaction_set_control_number):
|
|
214
|
+
"""
|
|
215
|
+
Formats a list of parsed claim data into 837P segments.
|
|
216
|
+
|
|
217
|
+
Parameters:
|
|
218
|
+
- parsed_data_list: List of dictionaries containing parsed claim data.
|
|
219
|
+
- config: Configuration settings loaded from a JSON file.
|
|
220
|
+
- endpoint: The endpoint key representing the specific endpoint.
|
|
221
|
+
- starting_transaction_set_control_number: Starting transaction set control number for 837P segments.
|
|
222
|
+
|
|
223
|
+
Returns:
|
|
224
|
+
- A list of formatted 837P claims and the next transaction set control number.
|
|
225
|
+
"""
|
|
226
|
+
formatted_claims = []
|
|
227
|
+
transaction_set_control_number = starting_transaction_set_control_number
|
|
228
|
+
|
|
229
|
+
for parsed_data in parsed_data_list:
|
|
230
|
+
formatted_claim = format_single_claim(parsed_data, config, endpoint, transaction_set_control_number)
|
|
231
|
+
formatted_claims.append(formatted_claim)
|
|
232
|
+
transaction_set_control_number += 1 # Increment for each successfully processed claim
|
|
233
|
+
|
|
234
|
+
return formatted_claims, transaction_set_control_number
|
|
235
|
+
|
|
236
|
+
# Validation Function checks the completeness and correctness of each claim's data
|
|
237
|
+
def validate_claim_data(parsed_data, config, required_fields=[]):
|
|
238
|
+
"""
|
|
239
|
+
Used by both paths.
|
|
240
|
+
|
|
241
|
+
Validates the completeness and correctness of each claim's data based on configurable requirements.
|
|
242
|
+
|
|
243
|
+
Parameters:
|
|
244
|
+
- parsed_data: Dictionary containing claim data to validate.
|
|
245
|
+
- config: Configuration settings loaded from a JSON file.
|
|
246
|
+
- required_fields: Optional list of tuples indicating required fields and their respective regex patterns for validation.
|
|
247
|
+
|
|
248
|
+
Returns:
|
|
249
|
+
- (bool, list): Tuple containing a boolean indicating whether the data is valid and a list of error messages if any.
|
|
250
|
+
|
|
251
|
+
# TODO This required fields thing needs to be redone.
|
|
252
|
+
|
|
253
|
+
if required_fields is None:
|
|
254
|
+
required_fields = [
|
|
255
|
+
('CHART', None),
|
|
256
|
+
('billing_provider_npi', r'^\d{10}$'),
|
|
257
|
+
('IPOLICY', None),
|
|
258
|
+
('CODEA', None),
|
|
259
|
+
('DATE', r'^\d{8}$'),
|
|
260
|
+
('AMOUNT', None),
|
|
261
|
+
('TOS', None),
|
|
262
|
+
('DIAG', None)
|
|
263
|
+
]
|
|
264
|
+
"""
|
|
265
|
+
errors = []
|
|
266
|
+
MediLink_ConfigLoader.log("Starting claim vata validation...")
|
|
267
|
+
if not required_fields:
|
|
268
|
+
# If no required fields are specified, assume validation is true
|
|
269
|
+
return True, []
|
|
270
|
+
|
|
271
|
+
expected_keys = {field[0] for field in required_fields} # Set of expected field keys
|
|
272
|
+
received_keys = set(parsed_data.keys()) # Set of keys present in the parsed data
|
|
273
|
+
|
|
274
|
+
# Check if there is any intersection between expected keys and received keys
|
|
275
|
+
if not expected_keys & received_keys:
|
|
276
|
+
# Log the preview of expected and received keys
|
|
277
|
+
preview_msg = "Validation skipped: No matching fields found between expected and received data."
|
|
278
|
+
error_msg = "{}\nExpected keys: {}\nReceived keys: {}".format(preview_msg, expected_keys, received_keys)
|
|
279
|
+
MediLink_ConfigLoader.log(error_msg, config, level="WARNING")
|
|
280
|
+
print(error_msg) # Optionally print to console for immediate feedback
|
|
281
|
+
return True, [preview_msg] # Return true to say that it's valid data anyway.
|
|
282
|
+
|
|
283
|
+
# Check for missing or empty fields and validate patterns
|
|
284
|
+
for field, pattern in required_fields:
|
|
285
|
+
value = parsed_data.get(field)
|
|
286
|
+
if not value:
|
|
287
|
+
errors.append("Missing or empty field: {}".format(field))
|
|
288
|
+
elif pattern and not re.match(pattern, value):
|
|
289
|
+
errors.append("Invalid format in field {}: {}".format(field, value))
|
|
290
|
+
|
|
291
|
+
# Validate date fields if required and ensure they are in the correct format
|
|
292
|
+
date_field = 'DATE'
|
|
293
|
+
date_value = parsed_data.get(date_field)
|
|
294
|
+
if date_value:
|
|
295
|
+
try:
|
|
296
|
+
datetime.strptime(date_value, "%Y%m%d")
|
|
297
|
+
except ValueError:
|
|
298
|
+
errors.append("Invalid date format: {}".format(date_value))
|
|
299
|
+
|
|
300
|
+
# Log validation errors and return
|
|
301
|
+
if errors:
|
|
302
|
+
for error in errors:
|
|
303
|
+
MediLink_ConfigLoader.log(error, config, level="ERROR")
|
|
304
|
+
return False, errors
|
|
305
|
+
|
|
306
|
+
return True, []
|
|
307
|
+
|
|
308
|
+
def process_and_write_file(file_path, config, endpoint, starting_tscn=1):
|
|
309
|
+
"""
|
|
310
|
+
Process a single file, create complete 837P document with headers and trailers, and write to output file.
|
|
311
|
+
|
|
312
|
+
Parameters:
|
|
313
|
+
- file_path: Path to the .DAT file to be processed.
|
|
314
|
+
- config: Configuration settings.
|
|
315
|
+
- endpoint: Endpoint key.
|
|
316
|
+
- starting_tscn: Starting Transaction Set Control Number.
|
|
317
|
+
"""
|
|
318
|
+
print("Processing: {}".format(file_path))
|
|
319
|
+
MediLink_ConfigLoader.log("Processing: {}".format(file_path))
|
|
320
|
+
formatted_data, transaction_set_control_number = process_file(file_path, config, endpoint, starting_tscn)
|
|
321
|
+
isa_header, gs_header, ge_trailer, iea_trailer = MediLink_837p_encoder_library.create_interchange_elements(config, endpoint, transaction_set_control_number - 1)
|
|
322
|
+
|
|
323
|
+
# Combine everything into a single document
|
|
324
|
+
complete_document = "{}\n{}\n{}\n{}\n{}".format(
|
|
325
|
+
isa_header,
|
|
326
|
+
gs_header,
|
|
327
|
+
formatted_data,
|
|
328
|
+
ge_trailer,
|
|
329
|
+
iea_trailer
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
# Write to output file
|
|
333
|
+
output_file_path = write_output_file([complete_document], config.get('outputFilePath', ''), endpoint, file_path, config)
|
|
334
|
+
print("File processed. Output saved to: {}".format(output_file_path))
|
|
335
|
+
|
|
336
|
+
def main():
|
|
337
|
+
"""
|
|
338
|
+
Converts fixed-width files to 837P format for health claim submissions.
|
|
339
|
+
|
|
340
|
+
Usage:
|
|
341
|
+
------
|
|
342
|
+
1. Convert a single file:
|
|
343
|
+
python MediLink_837p_encoder.py -e [endpoint] -p [file_path]
|
|
344
|
+
|
|
345
|
+
2. Convert all files in a directory:
|
|
346
|
+
python MediLink_837p_encoder.py -e [endpoint] -p [directory_path] -d
|
|
347
|
+
|
|
348
|
+
Arguments:
|
|
349
|
+
----------
|
|
350
|
+
- "-e": Specify endpoint ("AVAILITY", "OPTUMEDI", "PNT_DATA").
|
|
351
|
+
- "-p": Path to file/directory for processing.
|
|
352
|
+
- "-d": Flag for directory processing.
|
|
353
|
+
|
|
354
|
+
Note: Ensure correct config file path.
|
|
355
|
+
"""
|
|
356
|
+
parser = argparse.ArgumentParser(
|
|
357
|
+
description="Converts fixed-width files to the 837P format for health claim submissions. Supports processing individual files or all files within a directory.",
|
|
358
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter
|
|
359
|
+
)
|
|
360
|
+
parser.add_argument(
|
|
361
|
+
"-e", "--endpoint",
|
|
362
|
+
required=True,
|
|
363
|
+
choices=["AVAILITY", "OPTUMEDI", "PNT_DATA"],
|
|
364
|
+
help="Specify the endpoint for which the conversion is intended."
|
|
365
|
+
)
|
|
366
|
+
parser.add_argument(
|
|
367
|
+
"-p", "--path",
|
|
368
|
+
required=True,
|
|
369
|
+
help="Path to the input fixed-width file or directory to process. If a directory is provided, all .DAT files within will be processed."
|
|
370
|
+
)
|
|
371
|
+
parser.add_argument(
|
|
372
|
+
"-d", "--is-directory",
|
|
373
|
+
action='store_true',
|
|
374
|
+
help="Flag indicating the path provided is a directory. If set, all .DAT files within the directory will be processed."
|
|
375
|
+
)
|
|
376
|
+
args = parser.parse_args()
|
|
377
|
+
|
|
378
|
+
print("Starting the conversion process for {}. Processing {} at '{}'.".format(args.endpoint, 'directory' if args.is_directory else 'file', args.path))
|
|
379
|
+
|
|
380
|
+
config, _ = MediLink_ConfigLoader.load_configuration()
|
|
381
|
+
config = config.get('MediLink_Config', config)
|
|
382
|
+
|
|
383
|
+
process_files(args.path, config, args.endpoint, args.is_directory)
|
|
384
|
+
print("Conversion complete.")
|
|
385
|
+
|
|
386
|
+
def process_files(path, config, endpoint, is_directory):
|
|
387
|
+
"""
|
|
388
|
+
Processes either a single file or all files within a directory.
|
|
389
|
+
|
|
390
|
+
Parameters:
|
|
391
|
+
- path: Path to the input fixed-width file or directory to process.
|
|
392
|
+
- config: Configuration settings loaded from a JSON file.
|
|
393
|
+
- endpoint: The endpoint for which the conversion is intended.
|
|
394
|
+
- is_directory: Boolean flag indicating if the path is a directory.
|
|
395
|
+
|
|
396
|
+
Returns:
|
|
397
|
+
- None
|
|
398
|
+
"""
|
|
399
|
+
if is_directory:
|
|
400
|
+
MediLink_ConfigLoader.log("Processing all .DAT files in: {}".format(path))
|
|
401
|
+
for file_name in os.listdir(path):
|
|
402
|
+
if file_name.endswith(".DAT"):
|
|
403
|
+
file_path = os.path.join(path, file_name)
|
|
404
|
+
process_and_write_file(file_path, config, endpoint)
|
|
405
|
+
else:
|
|
406
|
+
MediLink_ConfigLoader.log("Processing the single file: {}".format(path))
|
|
407
|
+
process_and_write_file(path, config, endpoint)
|
|
408
|
+
|
|
409
|
+
if __name__ == "__main__":
|
|
410
|
+
main()
|
|
411
|
+
|
|
412
|
+
# The functions below are the ones that are used as non-main library by outside scripts.
|
|
413
|
+
#######################################################################################
|
|
414
|
+
|
|
415
|
+
def convert_files_for_submission(detailed_patient_data, config):
|
|
416
|
+
"""
|
|
417
|
+
Processes detailed patient data for submission based on their confirmed endpoints,
|
|
418
|
+
generating a separate 837P file for each endpoint.
|
|
419
|
+
|
|
420
|
+
Parameters:
|
|
421
|
+
- detailed_patient_data: A list containing detailed patient data with endpoint information.
|
|
422
|
+
- config: Configuration settings loaded from a JSON file.
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
- A list of paths to the converted files ready for submission.
|
|
426
|
+
"""
|
|
427
|
+
|
|
428
|
+
# Initialize a dictionary to hold patient data segregated by confirmed endpoints
|
|
429
|
+
data_by_endpoint = {}
|
|
430
|
+
|
|
431
|
+
# Populate the dictionary with patient data
|
|
432
|
+
for data in detailed_patient_data:
|
|
433
|
+
endpoint = data['confirmed_endpoint']
|
|
434
|
+
if endpoint not in data_by_endpoint:
|
|
435
|
+
data_by_endpoint[endpoint] = []
|
|
436
|
+
data_by_endpoint[endpoint].append(data)
|
|
437
|
+
|
|
438
|
+
# List to store paths of converted files for each endpoint
|
|
439
|
+
converted_files_paths = []
|
|
440
|
+
|
|
441
|
+
# Determine the total number of unique endpoints for progress bar
|
|
442
|
+
# total_endpoints = len(data_by_endpoint)
|
|
443
|
+
|
|
444
|
+
# Iterate over each endpoint and process its corresponding patient data
|
|
445
|
+
for endpoint, patient_data_list in data_by_endpoint.items():
|
|
446
|
+
# tqdm(data_by_endpoint.items(), desc="Creating 837p(s)", total=total_endpoints, ascii=True)
|
|
447
|
+
# Each endpoint might have multiple patients' data to be processed into a single 837P file
|
|
448
|
+
if patient_data_list:
|
|
449
|
+
converted_path = process_claim(config['MediLink_Config'], endpoint, patient_data_list)
|
|
450
|
+
if converted_path:
|
|
451
|
+
converted_files_paths.append(converted_path)
|
|
452
|
+
|
|
453
|
+
return converted_files_paths
|
|
454
|
+
|
|
455
|
+
def process_claim(config, endpoint, patient_data_list):
|
|
456
|
+
"""
|
|
457
|
+
Processes patient data for a specified endpoint, converting it into the 837P format.
|
|
458
|
+
Generates a separate 837P file for each endpoint based on detailed patient data.
|
|
459
|
+
|
|
460
|
+
Parameters:
|
|
461
|
+
- config: Configuration settings loaded from a JSON file.
|
|
462
|
+
- endpoint_key: The key representing the endpoint for which the data is being processed.
|
|
463
|
+
- patient_data_list: A list of dictionaries, each containing detailed patient data.
|
|
464
|
+
|
|
465
|
+
Returns:
|
|
466
|
+
- Path to the converted file, or None if an error occurs.
|
|
467
|
+
|
|
468
|
+
TODO (LOW) Why are there duplicated interchange flows? Because the arg if we're doing a .dat directory or not.
|
|
469
|
+
Although, that shouldn't be making duplicates of these interchange headers. That's still confusing and could end up making
|
|
470
|
+
duplicate interchange headers because processing .dat in batch might be fast enough to be a problem.
|
|
471
|
+
"""
|
|
472
|
+
output_directory = MediLink_837p_encoder_library.get_output_directory(config)
|
|
473
|
+
if not output_directory:
|
|
474
|
+
return None
|
|
475
|
+
|
|
476
|
+
# Initialize the transaction set control number and document segments
|
|
477
|
+
transaction_set_control_number = 1
|
|
478
|
+
document_segments = []
|
|
479
|
+
|
|
480
|
+
# Process each patient's data in the list
|
|
481
|
+
for patient_data in patient_data_list:
|
|
482
|
+
# Validate each patient's data
|
|
483
|
+
is_valid, validation_errors = validate_claim_data(patient_data, config)
|
|
484
|
+
if is_valid:
|
|
485
|
+
# Format the claim if data is valid
|
|
486
|
+
formatted_claim = format_single_claim(patient_data, config, endpoint, transaction_set_control_number)
|
|
487
|
+
document_segments.append(formatted_claim)
|
|
488
|
+
transaction_set_control_number += 1
|
|
489
|
+
else:
|
|
490
|
+
if MediLink_837p_encoder_library.handle_validation_errors(transaction_set_control_number, validation_errors, config):
|
|
491
|
+
continue # Skip the current patient
|
|
492
|
+
|
|
493
|
+
# Create interchange elements with the final transaction set control number
|
|
494
|
+
isa_header, gs_header, ge_trailer, iea_trailer = MediLink_837p_encoder_library.create_interchange_elements(config, endpoint, transaction_set_control_number - 1)
|
|
495
|
+
|
|
496
|
+
# Insert headers at the beginning and append trailers at the end of document segments
|
|
497
|
+
document_segments.insert(0, gs_header)
|
|
498
|
+
document_segments.insert(0, isa_header)
|
|
499
|
+
document_segments.extend([ge_trailer, iea_trailer])
|
|
500
|
+
|
|
501
|
+
# Write the complete 837P document to an output file and return its path
|
|
502
|
+
return write_output_file(document_segments, output_directory, endpoint, patient_data_list[0]['file_path'], config)
|