Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,59 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
matched_sap = []
|
| 3 |
for _, row in sap_df.iterrows():
|
| 4 |
je = str(row.get('Journal Entry', '')).strip().upper()
|
|
@@ -15,6 +70,101 @@
|
|
| 15 |
|
| 16 |
# Logic B: CSG1 Match (Strictly SU, Solve string starts with SAP Assignment)
|
| 17 |
if je == 'SU':
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
# Check if any of our extracted Solve references start with this exact SAP assignment
|
| 19 |
if any(solve_ref.startswith(assign) for solve_ref in csg_refs if solve_ref):
|
| 20 |
-
matched_sap.append(row)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import uuid
|
| 4 |
+
import os
|
| 5 |
+
import traceback
|
| 6 |
+
|
| 7 |
+
def load_data(file_obj):
|
| 8 |
+
"""Helper to load either CSV or Excel, and automatically strip whitespace from headers."""
|
| 9 |
+
ext = os.path.splitext(file_obj.name)[1].lower()
|
| 10 |
+
if ext in ['.xls', '.xlsx']:
|
| 11 |
+
df = pd.read_excel(file_obj.name)
|
| 12 |
+
else:
|
| 13 |
+
# Some SAP exports lack standard headers or have formatting quirks,
|
| 14 |
+
# but we will assume standard headers as defined in the rules.
|
| 15 |
+
df = pd.read_csv(file_obj.name)
|
| 16 |
+
|
| 17 |
+
# Clean column names (strip trailing/leading spaces and newlines)
|
| 18 |
+
df.columns = [str(c).strip() for c in df.columns]
|
| 19 |
+
return df
|
| 20 |
+
|
| 21 |
+
def process_reconciliation(sa_amount, solve_file, sap_file):
|
| 22 |
+
if not solve_file or not sap_file:
|
| 23 |
+
return "⚠️ Please upload both the Solve Report and the SAP Ledger.", pd.DataFrame()
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
# Load and clean the files
|
| 27 |
+
solve_df = load_data(solve_file)
|
| 28 |
+
sap_df = load_data(sap_file)
|
| 29 |
+
|
| 30 |
+
# 1. Validate Target References from the Solve Report
|
| 31 |
+
if 'Pos ID' not in solve_df.columns or 'Sales Details' not in solve_df.columns:
|
| 32 |
+
detected = ", ".join(solve_df.columns)
|
| 33 |
+
return f"❌ Error: Could not find 'Pos ID' or 'Sales Details'. \nDetected columns in uploaded Solve file: {detected}", pd.DataFrame()
|
| 34 |
+
|
| 35 |
+
csi_mask = solve_df['Pos ID'] == 'CSI1'
|
| 36 |
+
csg_mask = solve_df['Pos ID'] == 'CSG1'
|
| 37 |
+
|
| 38 |
+
# Extraction Logic A: CSI1 (Credit Control) -> Last 6 chars before *PLATFORM
|
| 39 |
+
def extract_csi(text):
|
| 40 |
+
if pd.isna(text): return ""
|
| 41 |
+
part = str(text).split('*PLATFORM')[0]
|
| 42 |
+
return part[-6:]
|
| 43 |
+
|
| 44 |
+
# Extraction Logic B: CSG1 (Goods) -> Everything before *PLATFORM
|
| 45 |
+
def extract_csg(text):
|
| 46 |
+
if pd.isna(text): return ""
|
| 47 |
+
return str(text).split('*PLATFORM')[0]
|
| 48 |
+
|
| 49 |
+
csi_refs = solve_df[csi_mask]['Sales Details'].apply(extract_csi).tolist()
|
| 50 |
+
csg_refs = solve_df[csg_mask]['Sales Details'].apply(extract_csg).tolist()
|
| 51 |
+
|
| 52 |
+
# Remove empty strings
|
| 53 |
+
csi_refs = [r for r in csi_refs if r]
|
| 54 |
+
csg_refs = [r for r in csg_refs if r]
|
| 55 |
+
|
| 56 |
+
# 2. Scan and Match against SAP Ledger
|
| 57 |
matched_sap = []
|
| 58 |
for _, row in sap_df.iterrows():
|
| 59 |
je = str(row.get('Journal Entry', '')).strip().upper()
|
|
|
|
| 70 |
|
| 71 |
# Logic B: CSG1 Match (Strictly SU, Solve string starts with SAP Assignment)
|
| 72 |
if je == 'SU':
|
| 73 |
+
# Safety Net: The SAP assignment must be reasonably long to prevent broad matches
|
| 74 |
+
if len(assign) < 8:
|
| 75 |
+
continue
|
| 76 |
+
|
| 77 |
# Check if any of our extracted Solve references start with this exact SAP assignment
|
| 78 |
if any(solve_ref.startswith(assign) for solve_ref in csg_refs if solve_ref):
|
| 79 |
+
matched_sap.append(row)
|
| 80 |
+
|
| 81 |
+
matched_df = pd.DataFrame(matched_sap)
|
| 82 |
+
|
| 83 |
+
if matched_df.empty:
|
| 84 |
+
return "⚠️ Exception: No matching SAP records found. Check that the SAP file contains the expected Journal Entries and Assignments.", pd.DataFrame()
|
| 85 |
+
|
| 86 |
+
# 3. Validation & Zero-Sum Calculation
|
| 87 |
+
# Ensure 'Value' is numeric before summing (stripping out commas or currency symbols if present)
|
| 88 |
+
if 'Value' in matched_df.columns:
|
| 89 |
+
# Handle potential string formats like "1,200.50 GBP"
|
| 90 |
+
matched_df['Clean_Value'] = matched_df['Value'].astype(str).str.replace(r'[^\d.-]', '', regex=True)
|
| 91 |
+
matched_df['Clean_Value'] = pd.to_numeric(matched_df['Clean_Value'], errors='coerce').fillna(0)
|
| 92 |
+
total_sap = matched_df['Clean_Value'].sum()
|
| 93 |
+
else:
|
| 94 |
+
return "❌ Error: Could not find 'Value' column in SAP file.", pd.DataFrame()
|
| 95 |
+
|
| 96 |
+
balance = total_sap + sa_amount # sa_amount is expected to be negative
|
| 97 |
+
|
| 98 |
+
# Generate unique match ID
|
| 99 |
+
match_id = f"M-{str(uuid.uuid4())[:6].upper()}"
|
| 100 |
+
|
| 101 |
+
# 4. Generate Output Data format
|
| 102 |
+
output_rows = []
|
| 103 |
+
|
| 104 |
+
# Add the SA Bank Statement Line
|
| 105 |
+
output_rows.append({
|
| 106 |
+
'Match Number': match_id,
|
| 107 |
+
'Journal Entry': 'SA',
|
| 108 |
+
'Value': sa_amount,
|
| 109 |
+
'Date': 'T+1 Settlement Date',
|
| 110 |
+
'Assignment': '',
|
| 111 |
+
'Item Text': '7964 Website Settlement'
|
| 112 |
+
})
|
| 113 |
+
|
| 114 |
+
# Add the matched SAP lines
|
| 115 |
+
for _, row in matched_df.iterrows():
|
| 116 |
+
output_rows.append({
|
| 117 |
+
'Match Number': match_id,
|
| 118 |
+
'Journal Entry': row.get('Journal Entry', ''),
|
| 119 |
+
'Value': row.get('Value', 0.0),
|
| 120 |
+
'Date': row.get('Date', ''),
|
| 121 |
+
'Assignment': row.get('Assignment', ''),
|
| 122 |
+
'Item Text': row.get('Item Text', '')
|
| 123 |
+
})
|
| 124 |
+
|
| 125 |
+
out_df = pd.DataFrame(output_rows)
|
| 126 |
+
|
| 127 |
+
# Determine Final Status
|
| 128 |
+
if abs(balance) < 0.01: # Using 0.01 to account for minor floating point variations
|
| 129 |
+
status = f"✅ SUCCESS: Perfectly Balanced (Zero-Sum).\nTotal SAP matched: {total_sap:.2f}\nStatement: {sa_amount:.2f}"
|
| 130 |
+
else:
|
| 131 |
+
status = f"❌ EXCEPTION: Imbalance detected! \nSAP Sum: {total_sap:.2f} \nStatement: {sa_amount:.2f} \nDifference: {round(balance, 2)} \n\n*Review the output table below for missing or partial matches.*"
|
| 132 |
+
|
| 133 |
+
return status, out_df
|
| 134 |
+
|
| 135 |
+
except Exception as e:
|
| 136 |
+
# Improved error logging to catch exactly what failed
|
| 137 |
+
trace = traceback.format_exc()
|
| 138 |
+
return f"Error processing files: {str(e)}\n\nDetails:\n{trace}", pd.DataFrame()
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# ---------------- GRADIO UI SETUP ---------------- #
|
| 142 |
+
|
| 143 |
+
with gr.Blocks(theme=gr.themes.Default()) as demo:
|
| 144 |
+
gr.Markdown("# 🤖 Auto-Reconciliation Tool: Branch 7964")
|
| 145 |
+
gr.Markdown("Upload your daily reports to match website settlements against the SAP cashbook.")
|
| 146 |
+
|
| 147 |
+
with gr.Row():
|
| 148 |
+
with gr.Column():
|
| 149 |
+
sa_val = gr.Number(label="Bank Statement 'SA' Amount (Enter as a Negative Number)", value=-0.00)
|
| 150 |
+
solve_csv = gr.File(label="Upload: Solve Centurion Report (CSV/XLSX)")
|
| 151 |
+
sap_csv = gr.File(label="Upload: SAP Cashbook Ledger (CSV/XLSX)")
|
| 152 |
+
|
| 153 |
+
run_btn = gr.Button("Run Reconciliation", variant="primary")
|
| 154 |
+
|
| 155 |
+
with gr.Column():
|
| 156 |
+
status_output = gr.Textbox(label="Reconciliation Status", lines=6)
|
| 157 |
+
|
| 158 |
+
gr.Markdown("### Match Output Table")
|
| 159 |
+
table_output = gr.Dataframe(
|
| 160 |
+
headers=['Match Number', 'Journal Entry', 'Value', 'Date', 'Assignment', 'Item Text'],
|
| 161 |
+
interactive=False
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
run_btn.click(
|
| 165 |
+
fn=process_reconciliation,
|
| 166 |
+
inputs=[sa_val, solve_csv, sap_csv],
|
| 167 |
+
outputs=[status_output, table_output]
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
if __name
|