import pandas as pd import numpy as np import gradio as gr import re import tempfile import os import itertools from collections import defaultdict def clean_amount_fixed(val): """Advanced decimal parser that strips out hidden layout spaces after minus signs.""" if pd.isna(val): return 0.0 if isinstance(val, (int, float)): return float(val) val_str = str(val).replace(',', '').replace('GBP', '').strip() # Strip out all internal blank spaces to ensure clean float conversion val_str = re.sub(r'\s+', '', val_str) if val_str.endswith('-'): val_str = '-' + val_str[:-1] try: return float(val_str) except ValueError: return 0.0 def normalize_branch_string(val): """Converts mixed floats/strings into clean 4-digit text keys.""" if pd.isna(val): return None val_str = str(val).split('.')[0].strip() if val_str == "" or val_str.lower() == "nan" or val_str.lower() == "none": return None return val_str.zfill(4) def extract_branch_from_assignment(asg_text, valid_set): """Scans alpha-numeric cashbook assignments to find squashed branch identifiers.""" if pd.isna(asg_text): return None asg_str = str(asg_text).strip() # Check for a 4-digit sequence matching a valid merchant branch matches = re.findall(r'\d{4}', asg_str) for m in matches: if m in valid_set: return m # Fallback to check for padding on a 3-digit sequence matches_3 = re.findall(r'\b\d{3}\b|\d{3}', asg_str) for m in matches_3: padded = m.zfill(4) if padded in valid_set: return padded return None def extract_branch_advanced(text, assignment, assignment_clean, till_map, mid_map, valid_set, existing_branch): """Advanced multi-tier extractor that normalizes columns and isolates embedded branch numbers.""" norm_existing = normalize_branch_string(existing_branch) if norm_existing and norm_existing != '0000': return norm_existing text_str = str(text).strip() if pd.notna(text) else "" asg_clean_str = str(assignment_clean).strip() if pd.notna(assignment_clean) else "" asg_str = str(assignment).strip() if pd.notna(assignment) else "" if asg_clean_str in till_map: return till_map[asg_clean_str] # Extract branch from January 'Payment for Order TILL' string formats inside Item Text match_till_order = re.search(r'TILL\s*(\d+)', text_str.upper()) if match_till_order: raw_digits = match_till_order.group(1) reconstructed_key = f"TILL{raw_digits}" if reconstructed_key in till_map: return till_map[reconstructed_key] if raw_digits in till_map: return till_map[raw_digits] if "BARCLAYCARD" in text_str.upper(): mid_match = re.search(r'STL0(\d{7})', text_str) if mid_match: mid_number = mid_match.group(1) if mid_number in mid_map: return mid_map[mid_number] # Direct alpha-numeric field scan fallback asg_br = extract_branch_from_assignment(assignment, valid_set) if asg_br: return asg_br if "TBPTB" in text_str: parts = text_str.split('*') if len(parts) > 2: return normalize_branch_string(parts[2]) match_sa = re.search(r'-000(\d{3,4})', text_str) if match_sa: return normalize_branch_string(match_sa.group(1)) # Ticket pattern lookup inside Item Text match_ticket = re.search(r'(\d{3,4})[AaBbKk]\d+', text_str) if match_ticket: return normalize_branch_string(match_ticket.group(1)) # [ADDED LOGIC] Ticket pattern lookup inside Assignment field for mixed layouts match_ticket_asg = re.search(r'(\d{3,4})[AaBbKk]\d+', asg_str) if match_ticket_asg: return normalize_branch_string(match_ticket_asg.group(1)) match_generic = re.search(r'\b(\d{3,4})\b', text_str) if match_generic: return normalize_branch_string(match_generic.group(1)) return None def process_reconciliation(file_main, file_mapping, file_mid, start_match_id): """High-speed multi-pass reconciliation engine featuring space correction and assignment extractors.""" try: if file_main is None or file_mapping is None: raise ValueError("Missing file upload. Please provide both the Ledger and TILL mapping files.") main_df = pd.read_csv(file_main.name) mapping_df = pd.read_csv(file_mapping.name) main_df.columns = main_df.columns.str.strip() mapping_df.columns = mapping_df.columns.str.strip() main_df['Amount'] = main_df['Amount (GBP)'].apply(clean_amount_fixed) main_df['Journal Entry Date'] = pd.to_datetime(main_df['Journal Entry Date'], dayfirst=True, errors='coerce') main_df['Assignment_clean'] = main_df['Assignment'].astype(str).str.strip() mapping_df['Assignment_clean'] = mapping_df['Assignment'].astype(str).str.strip() mapping_df['Branch_clean'] = mapping_df['Branch number'].astype(str).apply(normalize_branch_string) till_map = dict(zip(mapping_df['Assignment_clean'], mapping_df['Branch_clean'])) mid_map = {} valid_bps_branches = set() if file_mid is not None: try: mid_df = pd.read_csv(file_mid.name, skiprows=4) mid_df.columns = mid_df.columns.str.strip() mid_col = "Outlet Number" if "Outlet Number" in mid_df.columns else None br_col = "Customer Reference No" if "Customer Reference No" in mid_df.columns else None if mid_col and br_col: for _, row in mid_df.dropna(subset=[mid_col, br_col]).iterrows(): m_id = str(row[mid_col]).split('.')[0].strip() b_id = str(row[br_col]).split('.')[0].strip() norm_b = normalize_branch_string(b_id) mid_map[m_id] = norm_b if norm_b: valid_bps_branches.add(norm_b) except Exception as e: print(f"BPS Header Shift Handled: {str(e)}") # Core advanced extraction loop extracted_branches = [] for idx, row in main_df.iterrows(): br_res = extract_branch_advanced( row['Item Text'], row['Assignment'], row['Assignment_clean'], till_map, mid_map, valid_bps_branches, row.get('Extracted_Branch', None) ) extracted_branches.append(br_res) main_df['Extracted_Branch'] = extracted_branches matched_records = [] match_counter = int(start_match_id) used_global_indices = set() # ------------------------------------------------------------------------- # PASS 1: STRICT SEQUENTIAL DZ DOCUMENT PAIR NETTING # ------------------------------------------------------------------------- dz_all = main_df[main_df['Journal Entry Type'] == 'DZ'].copy() dz_all['orig_index'] = dz_all.index dz_all['JE_numeric'] = pd.to_numeric(dz_all['Journal Entry'], errors='coerce') dz_all = dz_all.dropna(subset=['JE_numeric']).sort_values(by='JE_numeric') dz_list = dz_all.to_dict('records') i = 0 while i < len(dz_list) - 1: row1 = dz_list[i] row2 = dz_list[i+1] if (row2['JE_numeric'] == row1['JE_numeric'] + 1) and (round(row1['Amount'] + row2['Amount'], 2) == 0.0): match_id = f"SAP_MATCH_{str(match_counter).zfill(5)}" for r in [row1, row2]: r['SAP_Match_ID'] = match_id r['Extracted_Date'] = r['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(r['Journal Entry Date']) else '' r['Match_Pass'] = 'Pass (DZ Sequential Pair)' matched_records.append(r) used_global_indices.add(r['orig_index']) match_counter += 1 i += 2 else: i += 1 # ------------------------------------------------------------------------- # PASS 1B: High-Speed Sequential DZ CARD Netting Pass # ------------------------------------------------------------------------- dz_cards = main_df[ (main_df['Journal Entry Type'] == 'DZ') & (main_df['Assignment_clean'].str.upper() == 'CARD') & (~main_df.index.isin(used_global_indices)) ].copy() dz_cards['orig_index'] = dz_cards.index dz_cards = dz_cards.sort_values(by=['Extracted_Branch', 'Journal Entry Date', 'Journal Entry']) dz_card_list = dz_cards.to_dict('records') i = 0 while i < len(dz_card_list) - 1: row1 = dz_card_list[i] row2 = dz_card_list[i+1] if (row1['Extracted_Branch'] == row2['Extracted_Branch']) and (round(row1['Amount'] + row2['Amount'], 2) == 0.0): match_id = f"SAP_MATCH_{str(match_counter).zfill(5)}" for r in [row1, row2]: r['SAP_Match_ID'] = match_id r['Extracted_Date'] = r['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(r['Journal Entry Date']) else '' r['Match_Pass'] = 'Pass (Card Net)' matched_records.append(r) used_global_indices.add(r['orig_index']) match_counter += 1 i += 2 else: i += 1 statements = main_df[(main_df['Journal Entry Type'] == 'SA') & (~main_df.index.isin(used_global_indices))].copy() cashbook = main_df[(main_df['Journal Entry Type'].astype(str).str.upper().isin(['SU', 'DZ'])) & (~main_df.index.isin(used_global_indices))].copy() cashbook['orig_index'] = cashbook.index used_statement_indices = set() used_cashbook_indices = set() cb_daily_map = defaultdict(list) cb_branch_window_pool = defaultdict(list) # [ADDED LOGIC] Allocation map tracking TILL orders without hardcoded branches till_unbranched_daily_map = defaultdict(list) for cb_row in cashbook.to_dict('records'): br = str(cb_row['Extracted_Branch']) dt = cb_row['Journal Entry Date'] if br and br != 'None' and pd.notna(dt): cb_daily_map[(br, dt)].append(cb_row) cb_branch_window_pool[br].append(cb_row) elif pd.notna(dt): # Classify unbranched TILL transactions by date text_str = str(cb_row['Item Text']).upper() if 'TILL' in text_str or 'PAYMENT FOR ORDER' in text_str: till_unbranched_daily_map[dt].append(cb_row) # ------------------------------------------------------------------------- # PASS 2: STRATIFIED SEARCH - DAILY BUNDLES PREFERRED FIRST, THEN OUT-OF-SYNC COMBOS # ------------------------------------------------------------------------- for idx, sa_row in statements.iterrows(): branch = str(sa_row['Extracted_Branch']) if not branch or branch == 'None' or pd.isna(sa_row['Journal Entry Date']): continue sa_date = sa_row['Journal Entry Date'] target_cb_sum = round(-sa_row['Amount'], 2) sa_text = str(sa_row['Item Text']).upper() is_barclaycard = "BARCLAYCARD" in sa_text # Enforce lookback bounds days_span = 6 if is_barclaycard else 4 lookback_start = sa_date - pd.offsets.BDay(days_span) lookahead_end = sa_date + pd.offsets.BDay(3) matched_subset = None match_type = '' curr_date = sa_date # Phase A: Scan standalone day-by-day calculations sequentially while curr_date >= lookback_start: day_key = (branch, curr_date) day_rows = [] if day_key in cb_daily_map: day_rows.extend([r for r in cb_daily_map[day_key] if r['orig_index'] not in used_cashbook_indices]) # Pull unbranched daily TILL lines posted on this specific day till_rows = [] if curr_date in till_unbranched_daily_map: till_rows.extend([r for r in till_unbranched_daily_map[curr_date] if r['orig_index'] not in used_cashbook_indices]) if day_rows: day_sum = round(sum(r['Amount'] for r in day_rows), 2) if day_sum == target_cb_sum: matched_subset = day_rows match_type = 'Pass (Daily Agg)' break elif day_sum == round(2 * target_cb_sum, 2): freq_map = defaultdict(list) for r in day_rows: freq_map[round(r['Amount'], 2)].append(r) if all(len(v) % 2 == 0 for v in freq_map.values()): halved_subset = [] for amt, r_list in freq_map.items(): halved_subset.extend(r_list[:len(r_list) // 2]) matched_subset = halved_subset match_type = 'Pass (Duplicate Day Split)' break elif len(day_rows) <= 15: matched_combo = None for r_len in range(2, 4): for combo in itertools.combinations(day_rows, r_len): if round(sum(x['Amount'] for x in combo), 2) == target_cb_sum: matched_combo = list(combo) break if matched_combo: break if matched_combo: matched_subset = matched_combo match_type = 'Pass (Bounded Combo)' break # [ADDED LOGIC] Evaluate mixed bundles combining explicitly branched entries + unbranched TILL components combined_pool = day_rows + till_rows if combined_pool: combined_sum = round(sum(r['Amount'] for r in combined_pool), 2) if combined_sum == target_cb_sum: matched_subset = combined_pool match_type = 'Pass (Daily Agg with TILL Orders)' break # Target combinatorial gaps to loop in trailing till order variances gap = round(target_cb_sum - sum(r['Amount'] for r in day_rows), 2) if till_rows and gap != target_cb_sum: matched_combo = None for r_len in range(1, min(6, len(till_rows) + 1)): for till_combo in itertools.combinations(till_rows, r_len): if round(sum(x['Amount'] for x in till_combo), 2) == gap: matched_combo = day_rows + list(till_combo) break if matched_combo: break if matched_combo: matched_subset = matched_combo match_type = 'Pass (Bounded Combo with TILL Orders)' break curr_date -= pd.Timedelta(days=1) # Phase B: Bidirectional Bounded Combination Fallback Loop if not matched_subset: all_branch_rows = cb_branch_window_pool.get(branch, []) window_rows = [ r for r in all_branch_rows if lookback_start <= r['Journal Entry Date'] <= lookahead_end and r['orig_index'] not in used_cashbook_indices ] # Gather untagged cashbook TILL receipts within the lookback boundaries window_till_rows = [] curr_w_date = lookback_start while curr_w_date <= lookahead_end: if curr_w_date in till_unbranched_daily_map: window_till_rows.extend([ r for r in till_unbranched_daily_map[curr_w_date] if r['orig_index'] not in used_cashbook_indices ]) curr_w_date += pd.Timedelta(days=1) combined_window_pool = window_rows + window_till_rows if combined_window_pool: total_window_sum = round(sum(r['Amount'] for r in combined_window_pool), 2) if total_window_sum == target_cb_sum: matched_subset = combined_window_pool match_type = 'Pass (Many-to-One Window Pool)' else: positive_pool = [r for r in combined_window_pool if r['Amount'] > 0] sorted_pool = sorted(positive_pool, key=lambda x: x['Amount'], reverse=True)[:16] matched_combo = None for r_len in range(2, 5): for combo in itertools.combinations(sorted_pool, r_len): if round(sum(x['Amount'] for x in combo), 2) == target_cb_sum: matched_combo = list(combo) break if matched_combo: break if matched_combo: matched_subset = matched_combo match_type = 'Pass (Cross-Day Out-of-Sync Combo)' # Placed outside to record ALL pass types seamlessly if matched_subset: match_id = f"SAP_MATCH_{str(match_counter).zfill(5)}" sa_dict = sa_row.to_dict() sa_dict['SAP_Match_ID'] = match_id sa_dict['Extracted_Date'] = sa_date.strftime('%d/%m/%Y') sa_dict['Match_Pass'] = match_type matched_records.append(sa_dict) used_statement_indices.add(idx) for r in matched_subset: cb_dict = r.copy() cb_dict['SAP_Match_ID'] = match_id cb_dict['Extracted_Date'] = r['Journal Entry Date'].strftime('%d/%m/%Y') cb_dict['Match_Pass'] = match_type matched_records.append(cb_dict) used_cashbook_indices.add(r['orig_index']) match_counter += 1 # Exception Compilation unmatched_statements = statements[~statements.index.isin(used_statement_indices)] unmatched_cashbook = cashbook[~cashbook.index.isin(used_cashbook_indices)] unmatched_records = [] for r in unmatched_statements.to_dict('records'): r['SAP_Match_ID'] = '' r['Match_Pass'] = 'Unreconciled' r['Extracted_Date'] = r['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(r['Journal Entry Date']) else '' unmatched_records.append(r) for r in unmatched_cashbook.to_dict('records'): r['SAP_Match_ID'] = '' r['Match_Pass'] = 'Unreconciled' r['Extracted_Date'] = r['Journal Entry Date'].strftime('%d/%m/%Y') if pd.notna(r['Journal Entry Date']) else '' unmatched_records.append(r) target_columns = [ 'SAP_Match_ID', 'Company Code', 'G/L Account', 'Journal Entry', 'Journal Entry Type', 'Item Text', 'Journal Entry Date', 'Amount (GBP)', 'Assignment', 'Profit Center', 'Amount', 'Extracted_Branch', 'Extracted_Date', 'Match_Pass', 'Trade Date' ] def finalize_dataframe(records_list): if not records_list: return pd.DataFrame(columns=target_columns) res_df = pd.DataFrame(records_list) if 'Journal Entry Date' in res_df.columns and pd.api.types.is_datetime64_any_dtype(res_df['Journal Entry Date']): res_df['Journal Entry Date'] = res_df['Journal Entry Date'].dt.strftime('%d/%m/%Y') for col in target_columns: if col not in res_df.columns: res_df[col] = '' return res_df[target_columns].copy() final_matched_df = finalize_dataframe(matched_records) final_unmatched_df = finalize_dataframe(unmatched_records) fd_m, path_m = tempfile.mkstemp(suffix='_matched.csv') os.close(fd_m) final_matched_df.to_csv(path_m, index=False) fd_u, path_u = tempfile.mkstemp(suffix='_unreconciled.csv') os.close(fd_u) final_unmatched_df.to_csv(path_u, index=False) return path_m, path_u except Exception as error: raise gr.Error(f"Engine Alert: {str(error)}") # --- Interface Styling Configuration --- custom_css = """.header-banner { background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); padding: 2.5rem; border-radius: 12px; text-align: center; margin-bottom: 2rem; border: 1px solid #334155; } .header-banner h1 { color: #f8fafc !important; font-size: 2.25rem !important; font-weight: 700 !important; margin-bottom: 0.5rem !important; } .header-banner p { color: #94a3b8 !important; font-size: 1.1rem !important; } .action-btn { background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%) !important; color: white !important; font-weight: 600 !important; border-radius: 8px !important; padding: 0.75rem 1.5rem !important; transition: all 0.2s ease !important; } .action-btn:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2); }""" app_theme = gr.themes.Soft( primary_hue="blue", secondary_hue="slate", neutral_hue="slate", font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui"] ).set( block_background_fill="*neutral_50", block_border_width="1px", block_label_text_weight="600" ) with gr.Blocks() as demo: gr.HTML("""
""") with gr.Row(): with gr.Column(scale=1): with gr.Group(): gr.Markdown("### 📥 Input Ledger Data") file_main = gr.File(label="SAP Main Ledger / Unreconciled File (CSV)", file_types=[".csv"]) file_map = gr.File(label="TILL Reference Mapping (Sheet 1 - CSV)", file_types=[".csv"]) file_mid = gr.File(label="Barclaycard Merchant ID Mapping Sheet (CSV)", file_types=[".csv"]) start_id_input = gr.Number(value=51077, label="Starting Match ID Number", precision=0, info="The ID number to start counting from for this run.") process_btn = gr.Button("Execute Match Engine", variant="primary", elem_classes="action-btn") with gr.Column(scale=1): with gr.Group(): gr.Markdown("### 📤 Output Delivery") output_matched = gr.File(label="Verified Perfect-Match Output Document") output_unmatched = gr.File(label="Unreconciled / Unmatched Items Exception List") process_btn.click( fn=process_reconciliation, inputs=[file_main, file_map, file_mid, start_id_input], outputs=[output_matched, output_unmatched] ) HF_USER = os.environ.get("APP_USERNAME", "cityplumbing") HF_PASS = os.environ.get("APP_PASSWORD", "cashandbanking") demo.launch(auth=(HF_USER, HF_PASS), theme=app_theme, css=custom_css)