Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
| 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 |
-
"""
|
| 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
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 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 |
-
|
| 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 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
sa_amount = sa_row['Amount']
|
| 103 |
-
date_window_start = sa_date - pd.offsets.BDay(3)
|
| 104 |
|
| 105 |
-
|
| 106 |
-
if
|
| 107 |
-
continue
|
| 108 |
-
|
| 109 |
-
branch_candidates = cashbook_by_branch[branch]
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
(
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 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 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 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 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 = """
|