import gradio as gr import pandas as pd import uuid import os import traceback import re def smart_parse_date(val): """Format-aware date parser that prevents YYYY-MM-DD from being flipped into MM-DD-YYYY.""" if pd.isna(val): return pd.NaT s = str(val).strip() if not s or s.upper() in ['NAT', 'NAN']: return pd.NaT # 1. ISO Format (YYYY-MM-DD or YYYY/MM/DD) if re.match(r'^\d{4}[-/]\d{1,2}[-/]\d{1,2}', s): return pd.to_datetime(s, errors='coerce') # 2. European Format (DD.MM.YYYY, DD/MM/YYYY, or DD-MM-YYYY) if re.match(r'^\d{1,2}[./-]\d{1,2}[./-]\d{4}', s): return pd.to_datetime(s, dayfirst=True, errors='coerce') return pd.to_datetime(s, errors='coerce') def extract_core_key(ref): """Extracts core identifier for CPS (CPS + 8 digits) and CPSM (CPSM + 6 digits) references.""" if not ref or pd.isna(ref): return "" s = str(ref).strip().upper() # 1. CPSM pattern: CPSM followed by 6 digits (e.g., CPSM442106 or CPSM442144) cpsm_match = re.search(r'CPSM\d{6}', s) if cpsm_match: return cpsm_match.group(0) # 2. CPS / CPS3 pattern: CPS followed by 8 digits (e.g., CPS36637238 or CPS36637263) cps_match = re.search(r'CPS\d{8}', s) if cps_match: return cps_match.group(0) return s def is_ref_match(target_ref, sap_assign, sap_item_text=""): """Flexible matcher between Solve references and SAP Assignment/Item Text.""" t_ref = str(target_ref).strip().upper() s_assign = str(sap_assign).strip().upper() if pd.notna(sap_assign) else "" s_text = str(sap_item_text).strip().upper() if pd.notna(sap_item_text) else "" if not t_ref: return False # Direct equality or containment (Handles CSI1 items like KH7601, HG5762, FG3142, 077994) if s_assign and (t_ref == s_assign or t_ref in s_assign or s_assign in t_ref): return True if s_text and (t_ref in s_text or s_text in t_ref): return True # Core Key Extraction Matching for CPS and CPSM core_target = extract_core_key(t_ref) core_assign = extract_core_key(s_assign) core_text = extract_core_key(s_text) if core_target and len(core_target) >= 6: if core_assign and core_target == core_assign: return True if core_text and core_target == core_text: return True if s_assign and core_target in s_assign: return True if s_text and core_target in s_text: return True return False def load_data(file_obj, is_sap=False): """Helper to load CSV/Excel and dynamically auto-detect column layouts using content analysis.""" ext = os.path.splitext(file_obj.name)[1].lower() if ext in ['.xls', '.xlsx']: df = pd.read_excel(file_obj.name) else: df = pd.read_csv(file_obj.name, header='infer') df = df.reset_index(drop=True) df.columns = [str(c).strip() for c in df.columns] if len(df) > 0: first_row_strings = [str(x).upper() for x in df.iloc[0].values] has_headers = any(any(kw == cell or kw in cell for kw in ['COMPANY CODE', 'JOURNAL ENTRY', 'ASSIGNMENT', 'POSTING DATE', 'JOURNAL ENTRY TYPE']) for cell in first_row_strings) if has_headers: df.columns = [str(c).strip() for c in df.iloc[0]] df = df[1:].reset_index(drop=True) # Header De-duplication Engine 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 # Unique Keyword Mapping mapping = {} if is_sap: 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 is_within_one_workday(date1, date2): """Calculates if two dates are within a 1-workday tolerance using Pandas business days.""" if pd.isna(date1) or pd.isna(date2): return False try: start, end = min(date1, date2), max(date1, date2) bdays = pd.bdate_range(start=start.date(), end=end.date()) return len(bdays) <= 2 except: return False def clean_numeric_value(val): """Extracts a clean float number from messy accounting string formats.""" if pd.isna(val): return 0.0 s_val = str(val).strip() if not s_val: return 0.0 is_negative = '-' in s_val or ('(' in s_val and ')' in s_val) cleaned = re.sub(r'[^\d.]', '', s_val) try: res = float(cleaned) if cleaned else 0.0 return -res if is_negative else res except: return 0.0 def process_reconciliation(sa_amount, solve_file, sap_file): if not solve_file or not sap_file: return "⚠️ Please upload both the Solve Report and the SAP Ledger.", pd.DataFrame(), None try: solve_df = load_data(solve_file, is_sap=False) sap_df = load_data(sap_file, is_sap=True) required_solve = ['Pos ID', 'Sales Details', 'Transaction Date', 'Trans Amount(HUC)'] if not all(col in solve_df.columns for col in required_solve): detected = ", ".join(solve_df.columns) return f"❌ Error: Solve file missing columns. Expected: {required_solve}. \nDetected: {detected}", pd.DataFrame(), None required_sap = ['Journal Entry Type', 'Date', 'Value'] if not all(col in sap_df.columns for col in required_sap): detected = ", ".join(sap_df.columns) return f"❌ Error: SAP ledger mapping failed. Check column names. \nDetected columns: {detected}", pd.DataFrame(), None # Format-aware date parsing applied to Solve file solve_df['Parsed_Date'] = solve_df['Transaction Date'].apply(smart_parse_date) solve_targets = [] for idx, row in solve_df.iterrows(): pos_id = str(row.get('Pos ID', '')).strip() details = str(row.get('Sales Details', '')).strip() solve_date = row.get('Parsed_Date') amount = clean_numeric_value(row.get('Trans Amount(HUC)', 0)) if pd.isna(solve_date) or not details or '*PLATFORM' not in details: continue ref = details.split('*PLATFORM')[0].strip() if pos_id == 'CSI1' and len(ref) > 6: ref = ref[-6:] if ref and ref.upper() != 'NAN': solve_targets.append({ 'index': idx, 'type': pos_id, 'ref': ref, 'date': solve_date, 'amount': abs(amount), 'matched': False }) # Pre-filtering vectorized optimization matrices sap_df = sap_df[sap_df['Journal Entry Type'].isin(['SU', 'DZ'])].copy() # Format-aware date parsing applied to SAP ledger sap_df['Parsed_Date'] = sap_df['Date'].apply(smart_parse_date) sap_df['Abs_Value_Calc'] = sap_df['Value'].apply(clean_numeric_value).abs().round(2) # Match SAP Ledger lines against available Solve targets matched_sap = [] used_sap_indices = set() for target in solve_targets: target_amt = target['amount'] amt_candidates = sap_df[ (sap_df['Abs_Value_Calc'] >= target_amt - 0.02) & (sap_df['Abs_Value_Calc'] <= target_amt + 0.02) & (~sap_df.index.isin(used_sap_indices)) ] for idx, row in amt_candidates.iterrows(): je = str(row['Journal Entry Type']).strip().upper() assign = str(row['Assignment']).strip() if pd.notna(row['Assignment']) else '' item_text = str(row['Item Text']).strip() if pd.notna(row['Item Text']) else '' sap_date = row['Parsed_Date'] if not is_within_one_workday(sap_date, target['date']): continue is_match = False if je in ['SU', 'DZ']: if is_ref_match(target['ref'], assign, item_text): is_match = True if is_match: target['matched'] = True used_sap_indices.add(idx) row_copy = row.copy() row_copy['Clean_Value_Calc'] = target_amt matched_sap.append(row_copy) break 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"• [Excel Row Approx: {t['index'] + 2}] | Type: {t['type']} | Ref: {t['ref']} | Date: {date_str} | Amt: {t['amount']:,.2f}\n" else: unmatched_details = "\n\n✨ All eligible processed Solve lines matched successfully!" if not matched_sap: return f"⚠️ Exception: No matching records located inside the workday window.{unmatched_details}", pd.DataFrame(), None 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) match_id = f"M-{str(uuid.uuid4())[:6].upper()}" 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': '7964 Website Settlement Bulk' }] for _, row in matched_df.iterrows(): doc_num = str(row.get('Journal Entry Doc', '')).split('.')[0] if pd.notna(row.get('Journal Entry Doc')) else '' 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_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\n👉 Click the box below to download your spreadsheet.{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}{unmatched_details}" return status, out_df, export_filename except Exception as e: trace = traceback.format_exc() return f"Error processing files: {str(e)}\n\nDetails:\n{trace}", pd.DataFrame(), 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: Branch 7964") gr.Markdown("High-speed transaction processing engine to clear ledger entries while bypassing unreversed duplicates.") 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)") run_btn = gr.Button("Run Reconciliation", variant="primary", 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") gr.Markdown("### Match Output Table") table_output = gr.Dataframe(interactive=False) run_btn.click( fn=process_reconciliation, inputs=[sa_val, solve_csv, sap_csv], outputs=[status_output, table_output, download_output] ) if __name__ == "__main__": username_gate = os.getenv("RECON_USER", "admin") password_gate = os.getenv("RECON_PASS", "SecretPassword7964") demo.launch(auth=(username_gate, password_gate))