Dwinward commited on
Commit
1b6203c
·
verified ·
1 Parent(s): 7a5a2b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -134
app.py CHANGED
@@ -6,7 +6,7 @@ import tempfile
6
  import os
7
 
8
  def clean_amount(val):
9
- """Robustly converts SAP amount strings into clean floats using fast string mechanics."""
10
  if pd.isna(val):
11
  return 0.0
12
  if isinstance(val, (int, float)):
@@ -24,7 +24,7 @@ def clean_amount(val):
24
  return 0.0
25
 
26
  def extract_branch(text):
27
- """Optimized regex extraction for branch codes."""
28
  if pd.isna(text):
29
  return None
30
  text_str = str(text).strip()
@@ -49,151 +49,175 @@ def extract_branch(text):
49
  return None
50
 
51
  def process_reconciliation(file_main, file_mapping):
52
- """High-speed reconciliation engine separating matched and unmatched items using indexed dictionaries."""
53
- # 1. Load Data
54
- main_df = pd.read_csv(file_main.name)
55
- mapping_df = pd.read_csv(file_mapping.name)
56
-
57
- # 2. Field Normalization
58
- main_df['Amount'] = main_df['Amount (GBP)'].apply(clean_amount)
59
- main_df['Journal Entry Date'] = pd.to_datetime(main_df['Journal Entry Date'], format='%d.%m.%Y', errors='coerce')
60
-
61
- mapping_df['Assignment_clean'] = mapping_df['Assignment'].astype(str).str.strip()
62
- mapping_df['Branch_clean'] = mapping_df['Branch number'].astype(str).str.split('.').str[0].str.zfill(4)
63
- till_map = dict(zip(mapping_df['Assignment_clean'], mapping_df['Branch_clean']))
64
-
65
- # 3. High-Speed Vectorized Branch Extraction Loop (Bypasses slow iterrows)
66
- assignments_clean = main_df['Assignment_clean'].values
67
- item_texts = main_df['Item Text'].values
68
- assignments_raw = main_df['Assignment'].values
69
-
70
- extracted_branches = []
71
- for i in range(len(main_df)):
72
- asg_c = assignments_clean[i]
73
- if asg_c in till_map:
74
- extracted_branches.append(till_map[asg_c])
75
- else:
76
- branch = extract_branch(item_texts[i]) or extract_branch(assignments_raw[i])
77
- extracted_branches.append(branch)
78
 
79
- main_df['Extracted_Branch'] = extracted_branches
80
-
81
- # 4. Separate Data Segments
82
- statements = main_df[main_df['Journal Entry Type'] == 'SA'].copy()
83
- cashbook = main_df[main_df['Journal Entry Type'].astype(str).str.upper().isin(['SU', 'DZ'])].copy()
84
-
85
- # CRITICAL OPTIMIZATION: Index the cashbook by branch up front
86
- # This transforms lookups from an O(N) full-scan to an O(1) dictionary split
87
- cashbook_by_branch = {str(b): grp for b, grp in cashbook.groupby('Extracted_Branch')}
88
-
89
- matched_records = []
90
- match_counter = 1
91
-
92
- used_statement_indices = set()
93
- used_cashbook_indices = set()
94
 
95
- # 5. One-to-Many Optimized Balance Engine
96
- for idx, sa_row in statements.iterrows():
97
- branch = sa_row['Extracted_Branch']
98
- if not branch or sa_row['Amount'] >= 0:
99
- continue
100
-
101
- sa_date = sa_row['Journal Entry Date']
102
- sa_amount = sa_row['Amount']
103
- date_window_start = sa_date - pd.offsets.BDay(3)
104
 
105
- # Fast dictionary lookup instead of filtering the entire dataframe
106
- if branch not in cashbook_by_branch:
107
- continue
108
-
109
- branch_candidates = cashbook_by_branch[branch]
110
 
111
- # Filter down the pre-isolated branch subset by date window criteria
112
- candidates = branch_candidates[
113
- (branch_candidates['Journal Entry Date'] >= date_window_start) &
114
- (branch_candidates['Journal Entry Date'] <= sa_date) &
115
- (~branch_candidates.index.isin(used_cashbook_indices))
116
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- if candidates.empty:
119
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
- # Analyze daily transactional groupings for balance execution
122
- for date_group, group_df in candidates.groupby('Journal Entry Date'):
123
- if round(group_df['Amount'].sum(), 2) == round(abs(sa_amount), 2):
124
- match_id = f"SAP_MATCH_{str(match_counter).zfill(5)}"
125
 
126
- # Format & Save Statement Line
127
- sa_row_dict = sa_row.to_dict()
128
- sa_row_dict['SAP_Match_ID'] = match_id
129
- sa_row_dict['Extracted_Branch'] = int(branch) if branch.isdigit() else branch
130
- sa_row_dict['Extracted_Date'] = sa_date.strftime('%d/%m/%Y') if pd.notna(sa_date) else ''
131
- sa_row_dict['Match_Pass'] = 'Pass'
132
- matched_records.append(sa_row_dict)
133
- used_statement_indices.add(idx)
 
134
 
135
- # Format & Save Cashbook Records
136
- for c_idx, c_row in group_df.iterrows():
137
- c_row_dict = c_row.to_dict()
138
- c_row_dict['SAP_Match_ID'] = match_id
139
- c_row_dict['Extracted_Branch'] = int(branch) if branch.isdigit() else branch
140
- c_row_dict['Extracted_Date'] = c_row['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(c_row['Journal Entry Date']) else ''
141
- c_row_dict['Match_Pass'] = 'Pass'
142
- matched_records.append(c_row_dict)
143
- used_cashbook_indices.add(c_idx)
 
 
 
 
144
 
145
- match_counter += 1
146
- break
 
 
 
 
 
 
 
 
 
 
147
 
148
- # 6. Gather Unmatched Residual Items
149
- unmatched_statements = statements[~statements.index.isin(used_statement_indices)]
150
- unmatched_cashbook = cashbook[~cashbook.index.isin(used_cashbook_indices)]
151
-
152
- unmatched_records = []
153
- for idx, row in unmatched_statements.iterrows():
154
- r_dict = row.to_dict()
155
- r_dict['SAP_Match_ID'] = ''
156
- r_dict['Match_Pass'] = 'Unreconciled'
157
- r_dict['Extracted_Date'] = row['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(row['Journal Entry Date']) else ''
158
- unmatched_records.append(r_dict)
159
 
160
- for idx, row in unmatched_cashbook.iterrows():
161
- r_dict = row.to_dict()
162
- r_dict['SAP_Match_ID'] = ''
163
- r_dict['Match_Pass'] = 'Unreconciled'
164
- r_dict['Extracted_Date'] = row['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(row['Journal Entry Date']) else ''
165
- unmatched_records.append(r_dict)
 
 
 
 
 
 
 
 
166
 
167
- # 7. Standard Output Formatting
168
- target_columns = [
169
- 'SAP_Match_ID', 'Company Code', 'G/L Account', 'Journal Entry',
170
- 'Journal Entry Type', 'Item Text', 'Journal Entry Date',
171
- 'Amount (GBP)', 'Assignment', 'Profit Center', 'Amount',
172
- 'Extracted_Branch', 'Extracted_Date', 'Match_Pass', 'Trade Date'
173
- ]
174
-
175
- def finalize_dataframe(records_list):
176
- if not records_list:
177
- return pd.DataFrame(columns=target_columns)
178
- res_df = pd.DataFrame(records_list)
179
- if 'Journal Entry Date' in res_df.columns and pd.api.types.is_datetime64_any_dtype(res_df['Journal Entry Date']):
180
- res_df['Journal Entry Date'] = res_df['Journal Entry Date'].dt.strftime('%d/%m/%Y')
181
- for col in target_columns:
182
- if col not in res_df.columns:
183
- res_df[col] = ''
184
- return res_df[target_columns].copy()
185
 
186
- final_matched_df = finalize_dataframe(matched_records)
187
- final_unmatched_df = finalize_dataframe(unmatched_records)
188
-
189
- # 8. Save Files
190
- temp_matched = tempfile.NamedTemporaryFile(delete=False, suffix='_matched.csv')
191
- final_matched_df.to_csv(temp_matched.name, index=False)
192
-
193
- temp_unmatched = tempfile.NamedTemporaryFile(delete=False, suffix='_unreconciled.csv')
194
- final_unmatched_df.to_csv(temp_unmatched.name, index=False)
195
-
196
- return temp_matched.name, temp_unmatched.name
 
 
 
 
 
 
197
 
198
  # --- Interface Styling Configuration ---
199
  custom_css = """
 
6
  import os
7
 
8
  def clean_amount(val):
9
+ """Robustly converts SAP amount strings into clean floats."""
10
  if pd.isna(val):
11
  return 0.0
12
  if isinstance(val, (int, float)):
 
24
  return 0.0
25
 
26
  def extract_branch(text):
27
+ """Extracts a 3 or 4 digit branch code from text and normalizes it to 4 digits."""
28
  if pd.isna(text):
29
  return None
30
  text_str = str(text).strip()
 
49
  return None
50
 
51
  def process_reconciliation(file_main, file_mapping):
52
+ """High-speed reconciliation engine with safety nets and verbose error handling."""
53
+ try:
54
+ # 1. Load Data
55
+ if file_main is None or file_mapping is None:
56
+ raise ValueError("Missing file upload. Please provide both the Main Ledger and Sheet 1 Mapping.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ main_df = pd.read_csv(file_main.name)
59
+ mapping_df = pd.read_csv(file_mapping.name)
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
+ # 2. Resiliency Step: Clean Column Names (Removes hidden spaces & makes matching foolproof)
62
+ main_df.columns = main_df.columns.str.strip()
63
+ mapping_df.columns = mapping_df.columns.str.strip()
64
+
65
+ # Validate Critical Columns Exist
66
+ required_main = ['Journal Entry Type', 'Amount (GBP)', 'Journal Entry Date', 'Assignment', 'Item Text']
67
+ required_map = ['Assignment', 'Branch number']
 
 
68
 
69
+ missing_main = [col for col in required_main if col not in main_df.columns]
70
+ missing_map = [col for col in required_map if col not in mapping_df.columns]
 
 
 
71
 
72
+ if missing_main:
73
+ raise KeyError(f"The Main Ledger is missing required columns: {missing_main}")
74
+ if missing_map:
75
+ raise KeyError(f"The Mapping Sheet is missing required columns: {missing_map}")
76
+
77
+ # 3. Field Normalization
78
+ main_df['Amount'] = main_df['Amount (GBP)'].apply(clean_amount)
79
+ main_df['Journal Entry Date'] = pd.to_datetime(main_df['Journal Entry Date'], format='%d.%m.%Y', errors='coerce')
80
+
81
+ main_df['Assignment_clean'] = main_df['Assignment'].astype(str).str.strip()
82
+ mapping_df['Assignment_clean'] = mapping_df['Assignment'].astype(str).str.strip()
83
+ mapping_df['Branch_clean'] = mapping_df['Branch number'].astype(str).str.split('.').str[0].str.zfill(4)
84
+
85
+ till_map = dict(zip(mapping_df['Assignment_clean'], mapping_df['Branch_clean']))
86
+
87
+ # 4. Vectorized Branch Extraction Execution
88
+ assignments_clean = main_df['Assignment_clean'].values
89
+ item_texts = main_df['Item Text'].values
90
+ assignments_raw = main_df['Assignment'].values
91
+
92
+ extracted_branches = []
93
+ for i in range(len(main_df)):
94
+ asg_c = assignments_clean[i]
95
+ if asg_c in till_map:
96
+ extracted_branches.append(till_map[asg_c])
97
+ else:
98
+ branch = extract_branch(item_texts[i]) or extract_branch(assignments_raw[i])
99
+ extracted_branches.append(branch)
100
+
101
+ main_df['Extracted_Branch'] = extracted_branches
102
 
103
+ # 5. Separate Data Segments
104
+ statements = main_df[main_df['Journal Entry Type'] == 'SA'].copy()
105
+ cashbook = main_df[main_df['Journal Entry Type'].astype(str).str.upper().isin(['SU', 'DZ'])].copy()
106
+
107
+ # Index the cashbook by branch up front for maximum lookup speeds
108
+ cashbook_by_branch = {str(b): grp for b, grp in cashbook.groupby('Extracted_Branch')}
109
+
110
+ matched_records = []
111
+ match_counter = 1
112
+
113
+ used_statement_indices = set()
114
+ used_cashbook_indices = set()
115
+
116
+ # 6. One-to-Many Optimized Balance Engine
117
+ for idx, sa_row in statements.iterrows():
118
+ branch = sa_row['Extracted_Branch']
119
+ if not branch or sa_row['Amount'] >= 0:
120
+ continue
121
+
122
+ sa_date = sa_row['Journal Entry Date']
123
+ sa_amount = sa_row['Amount']
124
+ date_window_start = sa_date - pd.offsets.BDay(3)
125
 
126
+ if branch not in cashbook_by_branch:
127
+ continue
 
 
128
 
129
+ branch_candidates = cashbook_by_branch[branch]
130
+ candidates = branch_candidates[
131
+ (branch_candidates['Journal Entry Date'] >= date_window_start) &
132
+ (branch_candidates['Journal Entry Date'] <= sa_date) &
133
+ (~branch_candidates.index.isin(used_cashbook_indices))
134
+ ]
135
+
136
+ if candidates.empty:
137
+ continue
138
 
139
+ # Check individual day groups
140
+ for date_group, group_df in candidates.groupby('Journal Entry Date'):
141
+ if round(group_df['Amount'].sum(), 2) == round(abs(sa_amount), 2):
142
+ match_id = f"SAP_MATCH_{str(match_counter).zfill(5)}"
143
+
144
+ # Store statement row
145
+ sa_row_dict = sa_row.to_dict()
146
+ sa_row_dict['SAP_Match_ID'] = match_id
147
+ sa_row_dict['Extracted_Branch'] = int(branch) if branch.isdigit() else branch
148
+ sa_row_dict['Extracted_Date'] = sa_date.strftime('%d/%m/%Y') if pd.notna(sa_date) else ''
149
+ sa_row_dict['Match_Pass'] = 'Pass'
150
+ matched_records.append(sa_row_dict)
151
+ used_statement_indices.add(idx)
152
 
153
+ # Store matching cashbook lines
154
+ for c_idx, c_row in group_df.iterrows():
155
+ c_row_dict = c_row.to_dict()
156
+ c_row_dict['SAP_Match_ID'] = match_id
157
+ c_row_dict['Extracted_Branch'] = int(branch) if branch.isdigit() else branch
158
+ c_row_dict['Extracted_Date'] = c_row['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(c_row['Journal Entry Date']) else ''
159
+ c_row_dict['Match_Pass'] = 'Pass'
160
+ matched_records.append(c_row_dict)
161
+ used_cashbook_indices.add(c_idx)
162
+
163
+ match_counter += 1
164
+ break
165
 
166
+ # 7. Collect Exceptions
167
+ unmatched_statements = statements[~statements.index.isin(used_statement_indices)]
168
+ unmatched_cashbook = cashbook[~cashbook.index.isin(used_cashbook_indices)]
 
 
 
 
 
 
 
 
169
 
170
+ unmatched_records = []
171
+ for idx, row in unmatched_statements.iterrows():
172
+ r_dict = row.to_dict()
173
+ r_dict['SAP_Match_ID'] = ''
174
+ r_dict['Match_Pass'] = 'Unreconciled'
175
+ r_dict['Extracted_Date'] = row['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(row['Journal Entry Date']) else ''
176
+ unmatched_records.append(r_dict)
177
+
178
+ for idx, row in unmatched_cashbook.iterrows():
179
+ r_dict = row.to_dict()
180
+ r_dict['SAP_Match_ID'] = ''
181
+ r_dict['Match_Pass'] = 'Unreconciled'
182
+ r_dict['Extracted_Date'] = row['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(row['Journal Entry Date']) else ''
183
+ unmatched_records.append(r_dict)
184
 
185
+ # 8. Framing Final Output Structure
186
+ target_columns = [
187
+ 'SAP_Match_ID', 'Company Code', 'G/L Account', 'Journal Entry',
188
+ 'Journal Entry Type', 'Item Text', 'Journal Entry Date',
189
+ 'Amount (GBP)', 'Assignment', 'Profit Center', 'Amount',
190
+ 'Extracted_Branch', 'Extracted_Date', 'Match_Pass', 'Trade Date'
191
+ ]
192
+
193
+ def finalize_dataframe(records_list):
194
+ if not records_list:
195
+ return pd.DataFrame(columns=target_columns)
196
+ res_df = pd.DataFrame(records_list)
197
+ if 'Journal Entry Date' in res_df.columns and pd.api.types.is_datetime64_any_dtype(res_df['Journal Entry Date']):
198
+ res_df['Journal Entry Date'] = res_df['Journal Entry Date'].dt.strftime('%d/%m/%Y')
199
+ for col in target_columns:
200
+ if col not in res_df.columns:
201
+ res_df[col] = ''
202
+ return res_df[target_columns].copy()
203
 
204
+ final_matched_df = finalize_dataframe(matched_records)
205
+ final_unmatched_df = finalize_dataframe(unmatched_records)
206
+
207
+ # 9. Cross-Platform Safe File Exporters (Closes files right away to prevent OS locking bugs)
208
+ fd_m, path_m = tempfile.mkstemp(suffix='_matched.csv')
209
+ os.close(fd_m)
210
+ final_matched_df.to_csv(path_m, index=False)
211
+
212
+ fd_u, path_u = tempfile.mkstemp(suffix='_unreconciled.csv')
213
+ os.close(fd_u)
214
+ final_unmatched_df.to_csv(path_u, index=False)
215
+
216
+ return path_m, path_u
217
+
218
+ except Exception as error:
219
+ # Intercepts background bugs and explicitly outputs them inside the web interface
220
+ raise gr.Error(f"Engine Alert: {str(error)}")
221
 
222
  # --- Interface Styling Configuration ---
223
  custom_css = """