import gradio as gr import pandas as pd import uuid import os import traceback import re def load_data(file_obj, is_sap=False): """Helper to dynamically find true headers and bypass metadata junk at the top of CSVs.""" if file_obj is None: return pd.DataFrame() ext = os.path.splitext(file_obj.name)[1].lower() try: if ext in ['.xls', '.xlsx']: df = pd.read_excel(file_obj.name, header=None) else: df = pd.read_csv(file_obj.name, header=None, low_memory=False) except Exception as e: print(f"Error reading {file_obj.name}: {e}") return pd.DataFrame() header_idx = 0 for i in range(min(20, len(df))): row_strs = [str(x).upper() for x in df.iloc[i].values] if is_sap: if any('JOURNAL ENTRY' in x or 'ASSIGNMENT' in x or 'COMPANY CODE' in x for x in row_strs): header_idx = i break else: if any('SALES DETAILS' in x or 'POS ID' in x or 'TRANS AMOUNT' in x for x in row_strs): header_idx = i break df.columns = [str(c).strip() for c in df.iloc[header_idx].values] df = df.iloc[header_idx+1:].reset_index(drop=True) cols = [] counts = {} for col in df.columns: col_str = str(col) if col_str in counts: counts[col_str] += 1 cols.append(f"{col_str}_{counts[col_str]}") else: counts[col_str] = 0 cols.append(col_str) df.columns = cols if is_sap: mapping = {} for c in df.columns: c_upper = str(c).upper() if 'JOURNAL ENTRY TYPE' in c_upper or c_upper == 'JOURNAL ENTRY TYPE': mapping[c] = 'Journal Entry Type' elif c_upper == 'JOURNAL ENTRY' or (c_upper.startswith('JOURNAL') and 'TYPE' not in c_upper and 'DATE' not in c_upper): mapping[c] = 'Journal Entry Doc' elif 'TEXT' in c_upper or 'DESCR' in c_upper: mapping[c] = 'Item Text' elif 'DATE' in c_upper: mapping[c] = 'Date' elif 'VALUE' in c_upper or 'AMOUNT' in c_upper or 'BAL' in c_upper: mapping[c] = 'Value' elif 'ASSIGN' in c_upper or 'ALLOC' in c_upper or 'REF' in c_upper: mapping[c] = 'Assignment' if 'Journal Entry Type' not in mapping.values() or 'Date' not in mapping.values(): if len(df.columns) >= 8: mapping[df.columns[3]] = 'Journal Entry Type' mapping[df.columns[4]] = 'Item Text' mapping[df.columns[5]] = 'Date' mapping[df.columns[6]] = 'Value' mapping[df.columns[7]] = 'Assignment' df = df.rename(columns=mapping) return df def clean_numeric_value(val): if pd.isna(val): return 0.0 cleaned = re.sub(r'[^\d.-]', '', str(val)) try: return float(cleaned) if cleaned else 0.0 except: return 0.0 def process_reconciliation(sa_amount, solve_file, sap_file, exclude_amex): if not solve_file or not sap_file: return "⚠️ Please upload both the Solve Report and the SAP Ledger.", pd.DataFrame(), None, None try: solve_df = load_data(solve_file, is_sap=False) sap_df = load_data(sap_file, is_sap=True) required_solve = ['Pos ID', 'Transaction Date', 'Trans Amount(HUC)', 'Transaction Number'] if not all(c in solve_df.columns for c in required_solve): return f"❌ ERROR: Solve file missing expected columns (Make sure 'Transaction Number' is present).", pd.DataFrame(), None, None required_sap = ['Journal Entry Type', 'Date', 'Value'] if not all(c in sap_df.columns for c in required_sap): return f"❌ ERROR: SAP ledger mapping failed.", pd.DataFrame(), None, None solve_df['Parsed_Date'] = pd.to_datetime(solve_df['Transaction Date'], errors='coerce') solve_targets = [] for idx, row in solve_df.iterrows(): card_type = str(row.get('Card Type', '')).strip().upper() if exclude_amex and 'AMEX' in card_type: continue pos_id = str(row.get('Pos ID', '')).strip() amount = clean_numeric_value(row.get('Trans Amount(HUC)', 0)) solve_date = row.get('Parsed_Date') trans_num_raw = str(row.get('Transaction Number', '')).strip() if not trans_num_raw or trans_num_raw.upper() == 'NAN': continue customer_no = trans_num_raw.split('-')[0].upper() if pd.isna(solve_date): continue solve_targets.append({ 'index': idx, 'type': pos_id, 'customer_no': customer_no, 'date': solve_date, 'amount': abs(amount), 'matched': False }) sap_df = sap_df[sap_df['Journal Entry Type'].isin(['SU', 'DZ'])].copy() sap_df['Parsed_Date'] = pd.to_datetime(sap_df['Date'], errors='coerce', dayfirst=True) sap_df['Abs_Value_Calc'] = sap_df['Value'].apply(clean_numeric_value).abs().round(2) sap_assign = sap_df['Assignment'].astype(str).str.replace(r'\.0$', '', regex=True).fillna('') sap_text = sap_df['Item Text'].astype(str).str.replace(r'\.0$', '', regex=True).fillna('') sap_df['Search_Text'] = (sap_assign + " " + sap_text).str.upper() # --- OPTIMIZED FOR SPEED --- # Convert SAP df to a dictionary list to avoid heavy Pandas lookup overhead inside the loop sap_records = [] for idx, row in sap_df.iterrows(): sap_records.append({ 'index': idx, 'Abs_Value_Calc': row['Abs_Value_Calc'], 'Search_Text': row['Search_Text'], 'Parsed_Date': row['Parsed_Date'], 'row_obj': row }) matched_sap = [] used_sap_indices = set() # LIGHTNING-FAST PYTHON ITERATION ENGINE for target in solve_targets: target_amt = target['amount'] customer_ref = target['customer_no'] target_date = target['date'] for rec in sap_records: sap_idx = rec['index'] if sap_idx in used_sap_indices: continue # Pure string evaluation is drastically faster than .str.contains() inside loops if customer_ref not in rec['Search_Text']: continue # Date logic check if pd.notna(rec['Parsed_Date']) and pd.notna(target_date): days_diff = abs((rec['Parsed_Date'] - target_date).days) if days_diff > 7: continue # Tight 1-to-1 variance tolerance comparison if abs(rec['Abs_Value_Calc'] - target_amt) <= 0.02: target['matched'] = True used_sap_indices.add(sap_idx) row_copy = rec['row_obj'].copy() row_copy['Clean_Value_Calc'] = target_amt matched_sap.append(row_copy) break # UNMATCHED SOLVE LINES EXPORT & SUMMARY GENERATION unmatched_indices = [t['index'] for t in solve_targets if not t['matched']] match_id = f"M-{str(uuid.uuid4())[:6].upper()}" unmatched_targets = [t for t in solve_targets if not t['matched']] if unmatched_targets: unmatched_details = f"\n\n⚠️ UNRECONCILED SOLVE LINES DETECTED (Total: {len(unmatched_targets)}):\n" for t in unmatched_targets: date_str = str(t['date']).split(' ')[0] if pd.notna(t['date']) else 'N/A' unmatched_details += f"• [Row Reference Approx: {t['index'] + 2}] | Type: {t['type']} | Ref Token: {t['customer_no']} | Date: {date_str} | Amt: {t['amount']:,.2f}\n" else: unmatched_details = "\n\n✨ All eligible processed Solve lines matched successfully!" unmatched_filename = f"unmatched_solve_{match_id}.csv" if unmatched_indices: unmatched_df = solve_df.loc[unmatched_indices].copy() unmatched_df = unmatched_df.drop(columns=['Parsed_Date'], errors='ignore') unmatched_df.to_csv(unmatched_filename, index=False) else: unmatched_df = pd.DataFrame(columns=solve_df.drop(columns=['Parsed_Date'], errors='ignore').columns) unmatched_df.to_csv(unmatched_filename, index=False) if not matched_sap: return f"⚠️ EXCEPTION: No matching records located inside the workday window.{unmatched_details}", pd.DataFrame(), None, unmatched_filename matched_df = pd.DataFrame(matched_sap) total_sap = matched_df['Clean_Value_Calc'].sum() balance = total_sap + sa_amount matched_count = sum(1 for t in solve_targets if t['matched']) total_targets = len(solve_targets) output_rows = [{ 'Match Number': match_id, 'Journal Entry Type': 'SA', 'Journal Entry Number': 'Bulk Bank Settlement', 'Value': f"{sa_amount:,.2f}", 'Date': 'Settlement Date', 'Assignment': '', 'Item Text': '4199 Solve Centurion Settlement Bulk' }] for _, row in matched_df.iterrows(): doc_raw = str(row.get('Journal Entry Doc', '')) doc_num = doc_raw.split('.')[0] output_rows.append({ 'Match Number': match_id, 'Journal Entry Type': row.get('Journal Entry Type', ''), 'Journal Entry Number': doc_num, 'Value': f"{row.get('Clean_Value_Calc', 0.0):,.2f}", 'Date': str(row.get('Date', '')).split(' ')[0], 'Assignment': row.get('Assignment', '') if str(row.get('Assignment', '')) != 'nan' else '', 'Item Text': row.get('Item Text', '') if str(row.get('Item Text', '')) != 'nan' else '' }) out_df = pd.DataFrame(output_rows) export_filename = f"reconciliation_4199_match_{match_id}.csv" out_df.to_csv(export_filename, index=False) if abs(balance) < 0.05: status = f"✅ SUCCESS: Perfectly Balanced (Zero-Sum).\n• Total SAP lines matched: {total_sap:,.2f}\n• Statement line: {sa_amount:,.2f}\n• Solve Lines Matched: {matched_count} of {total_targets}\n• Unmatched Solve Lines: {len(unmatched_indices)}\n\n👉 Click the boxes below to download your spreadsheets.{unmatched_details}" else: status = f"❌ EXCEPTION: Imbalance detected!\n• SAP Matched Total: {total_sap:,.2f} \n• Statement Line: {sa_amount:,.2f} \n• Difference: {round(balance, 2):,.2f}\n• Solve Lines Matched: {matched_count} of {total_targets}\n• Unmatched Solve Lines: {len(unmatched_indices)}{unmatched_details}" return status, out_df, export_filename, unmatched_filename except Exception as e: trace = traceback.format_exc() return f"Error processing files: {str(e)}\n\nDetails:\n{trace}", pd.DataFrame(), None, None # ---------------- GRADIO UI ENVIRONMENT ---------------- # custom_theme = gr.themes.Default( primary_hue="amber", neutral_hue="slate" ).set( body_background_fill="#F8FAFC", block_background_fill="#FFFFFF", block_border_color="#002060", block_title_text_color="#002060", button_primary_background_fill="#002060", button_primary_text_color="#FFFFFF", button_primary_background_fill_hover="#001845", button_primary_border_color="#FFD700", input_background_fill="#FFFFFF", input_border_color="#002060" ) custom_css = """ h1 { color: #002060 !important; font-weight: bold !important; border-bottom: 4px solid #FFD700; padding-bottom: 12px; } .status-box textarea { border: 2px solid #002060 !important; background-color: #FFFDF2 !important; font-weight: bold; color: #002060 !important; } .download-box { border: 2px dashed #FFD700 !important; background-color: #FAFAF0 !important; } .run-btn { border: 2px solid #FFD700 !important; box-shadow: 0px 4px 6px rgba(0, 32, 96, 0.1); } """ with gr.Blocks(theme=custom_theme, css=custom_css) as demo: gr.Markdown("# 🤖 Auto-Reconciliation Tool: 4199 Solve Centurion") gr.Markdown("High-speed transaction processing engine to clear ledger entries against Solve Centurion.") with gr.Row(): with gr.Column(): sa_val = gr.Number(label="Bank Statement 'SA' Amount (Enter as a Negative Number)", value=-0.00) solve_csv = gr.File(label="Upload: Solve Centurion Report (CSV/XLSX)") sap_csv = gr.File(label="Upload: SAP Cashbook Ledger (CSV/XLSX)") exclude_amex = gr.Checkbox(label="Exclude AMEX Transactions (Settles Separately)", value=True) with gr.Row(): run_btn = gr.Button("Run Reconciliation", variant="primary", elem_classes="run-btn") clear_btn = gr.ClearButton(value="🔄 Refresh / Clear All", elem_classes="run-btn") with gr.Column(): status_output = gr.Textbox(label="Reconciliation Status", lines=10, elem_classes="status-box") download_output = gr.File(label="📥 Download Matched Results (CSV)", elem_classes="download-box") unmatched_download = gr.File(label="⚠️ Download Unmatched Solve Lines (CSV)", elem_classes="download-box") gr.Markdown("### Match Output Table") table_output = gr.Dataframe(interactive=False) clear_btn.add([sa_val, solve_csv, sap_csv, exclude_amex, status_output, download_output, unmatched_download, table_output]) run_btn.click( fn=process_reconciliation, inputs=[sa_val, solve_csv, sap_csv, exclude_amex], outputs=[status_output, table_output, download_output, unmatched_download] ) if __name__ == "__main__": username_gate = os.getenv("RECON_USER", "admin") password_gate = os.getenv("RECON_PASS", "SecretPassword4199") demo.launch(auth=(username_gate, password_gate))