Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -296,8 +296,19 @@ def refresh_reconciliation_dashboard():
|
|
| 296 |
matches, unmatched_invoices, unapplied_payments = find_exact_matches()
|
| 297 |
summary = get_reconciliation_summary()
|
| 298 |
|
| 299 |
-
# Prepare matches for display
|
| 300 |
matches_df = pd.DataFrame(matches) if matches else pd.DataFrame()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
unmatched_invoices_df = pd.DataFrame(unmatched_invoices) if unmatched_invoices else pd.DataFrame()
|
| 302 |
unapplied_payments_df = pd.DataFrame(unapplied_payments) if unapplied_payments else pd.DataFrame()
|
| 303 |
|
|
@@ -330,12 +341,15 @@ def handle_confirm_match(invoice_record_id: str, payment_record_id: str):
|
|
| 330 |
if not invoice_record_id or not payment_record_id:
|
| 331 |
return "❌ Please select a match to confirm", *refresh_reconciliation_dashboard()[1:]
|
| 332 |
|
|
|
|
|
|
|
| 333 |
result = confirm_match(invoice_record_id, payment_record_id)
|
| 334 |
|
| 335 |
if result['success']:
|
| 336 |
# Synchronize data across all storage
|
| 337 |
_sync_data_after_matching()
|
| 338 |
-
|
|
|
|
| 339 |
else:
|
| 340 |
return f"❌ {result['message']}", *refresh_reconciliation_dashboard()[1:]
|
| 341 |
|
|
@@ -344,12 +358,15 @@ def handle_manual_match(manual_invoice_id: str, manual_payment_id: str):
|
|
| 344 |
if not manual_invoice_id or not manual_payment_id:
|
| 345 |
return "❌ Please select both an unmatched invoice and an unapplied payment", *refresh_reconciliation_dashboard()[1:]
|
| 346 |
|
|
|
|
|
|
|
| 347 |
result = manual_match_invoice_to_payment(manual_invoice_id, manual_payment_id)
|
| 348 |
|
| 349 |
if result['success']:
|
| 350 |
# Synchronize data across all storage
|
| 351 |
_sync_data_after_matching()
|
| 352 |
-
|
|
|
|
| 353 |
else:
|
| 354 |
return f"❌ {result['message']}", *refresh_reconciliation_dashboard()[1:]
|
| 355 |
|
|
@@ -632,7 +649,7 @@ def get_suggested_matches():
|
|
| 632 |
# Document number match (fuzzy)
|
| 633 |
inv_doc = str(invoice.get('document_number', '')).lower().strip()
|
| 634 |
pay_doc = str(payment.get('document_number', '')).lower().strip()
|
| 635 |
-
if inv_doc and pay_doc and inv_doc in pay_doc or pay_doc in inv_doc:
|
| 636 |
match_score += 1
|
| 637 |
|
| 638 |
# Date match (within 7 days)
|
|
@@ -664,6 +681,100 @@ def get_suggested_matches():
|
|
| 664 |
return pd.DataFrame()
|
| 665 |
|
| 666 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 667 |
# ---------------------------------------------------------------------
|
| 668 |
# Main Application with Enhanced Interface
|
| 669 |
# ---------------------------------------------------------------------
|
|
@@ -738,42 +849,51 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AR Reconciliation Portal") as demo
|
|
| 738 |
get_suggestions_btn = gr.Button("💡 Get Suggested Matches", variant="secondary")
|
| 739 |
|
| 740 |
with gr.Row():
|
| 741 |
-
reconciliation_summary = gr.Markdown("### Reconciliation Summary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 742 |
|
| 743 |
with gr.Row():
|
| 744 |
with gr.Column():
|
| 745 |
gr.Markdown("#### ✅ Exact Matches Found")
|
|
|
|
| 746 |
matches_table = gr.Dataframe(
|
| 747 |
label="Auto-Matched Invoices & Payments",
|
| 748 |
interactive=True,
|
| 749 |
-
type="pandas"
|
|
|
|
| 750 |
)
|
| 751 |
|
| 752 |
with gr.Column():
|
| 753 |
gr.Markdown("#### ❌ Unmatched Items - Select for Manual Matching")
|
| 754 |
-
with gr.
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
)
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
|
| 778 |
# Store selected matches
|
| 779 |
selected_invoice_id = gr.State() # For auto matches
|
|
@@ -781,43 +901,6 @@ with gr.Blocks(theme=gr.themes.Soft(), title="AR Reconciliation Portal") as demo
|
|
| 781 |
manual_invoice_id = gr.State() # For manual matches
|
| 782 |
manual_payment_id = gr.State() # For manual matches
|
| 783 |
|
| 784 |
-
# Enhanced selection handlers with display
|
| 785 |
-
def store_auto_selected_match(evt: gr.SelectData, matches_df: pd.DataFrame):
|
| 786 |
-
if evt is None or matches_df is None or matches_df.empty:
|
| 787 |
-
return "", "", "**Selected Invoice:** None", "**Selected Payment:** None"
|
| 788 |
-
selected_row = matches_df.iloc[evt.index]
|
| 789 |
-
invoice_id = selected_row.get('invoice_record_id', '')
|
| 790 |
-
payment_id = selected_row.get('payment_record_id', '')
|
| 791 |
-
invoice_display = f"**Selected Invoice:** {selected_row.get('invoice_document', '')} (${selected_row.get('invoice_amount', 0):.2f})"
|
| 792 |
-
payment_display = f"**Selected Payment:** {selected_row.get('payment_document', '')} (${selected_row.get('payment_amount', 0):.2f})"
|
| 793 |
-
return invoice_id, payment_id, invoice_display, payment_display
|
| 794 |
-
|
| 795 |
-
def store_manual_invoice_selection(evt: gr.SelectData, invoices_df: pd.DataFrame):
|
| 796 |
-
if evt is None or invoices_df is None or invoices_df.empty:
|
| 797 |
-
return "", "**Selected Invoice:** None"
|
| 798 |
-
selected_row = invoices_df.iloc[evt.index]
|
| 799 |
-
record_id = selected_row.get('record_id', '')
|
| 800 |
-
display = f"**Selected Invoice:** {selected_row.get('document_number', '')} (${selected_row.get('total_billed', 0):.2f})"
|
| 801 |
-
return record_id, display
|
| 802 |
-
|
| 803 |
-
def store_manual_payment_selection(evt: gr.SelectData, payments_df: pd.DataFrame):
|
| 804 |
-
if evt is None or payments_df is None or payments_df.empty:
|
| 805 |
-
return "", "**Selected Payment:** None"
|
| 806 |
-
selected_row = payments_df.iloc[evt.index]
|
| 807 |
-
record_id = selected_row.get('record_id', '')
|
| 808 |
-
display = f"**Selected Payment:** {selected_row.get('document_number', '')} (${selected_row.get('payment_amount', 0):.2f})"
|
| 809 |
-
return record_id, display
|
| 810 |
-
|
| 811 |
-
def store_suggested_match_selection(evt: gr.SelectData, suggestions_df: pd.DataFrame):
|
| 812 |
-
if evt is None or suggestions_df is None or suggestions_df.empty:
|
| 813 |
-
return "", "", "**Selected Invoice:** None", "**Selected Payment:** None"
|
| 814 |
-
selected_row = suggestions_df.iloc[evt.index]
|
| 815 |
-
invoice_id = selected_row.get('invoice_record_id', '')
|
| 816 |
-
payment_id = selected_row.get('payment_record_id', '')
|
| 817 |
-
invoice_display = f"**Selected Invoice:** {selected_row.get('invoice_document', '')} (${selected_row.get('invoice_amount', 0):.2f})"
|
| 818 |
-
payment_display = f"**Selected Payment:** {selected_row.get('payment_document', '')} (${selected_row.get('payment_amount', 0):.2f})"
|
| 819 |
-
return invoice_id, payment_id, invoice_display, payment_display
|
| 820 |
-
|
| 821 |
# Event handlers
|
| 822 |
matches_table.select(
|
| 823 |
fn=store_auto_selected_match,
|
|
|
|
| 296 |
matches, unmatched_invoices, unapplied_payments = find_exact_matches()
|
| 297 |
summary = get_reconciliation_summary()
|
| 298 |
|
| 299 |
+
# Prepare matches for display - ensure all required columns are present
|
| 300 |
matches_df = pd.DataFrame(matches) if matches else pd.DataFrame()
|
| 301 |
+
if not matches_df.empty:
|
| 302 |
+
# Add display columns for better user experience
|
| 303 |
+
if 'invoice_document' not in matches_df.columns and 'document_number' in matches_df.columns:
|
| 304 |
+
matches_df['invoice_document'] = matches_df['document_number']
|
| 305 |
+
if 'payment_document' not in matches_df.columns and 'document_number' in matches_df.columns:
|
| 306 |
+
matches_df['payment_document'] = matches_df['document_number']
|
| 307 |
+
if 'invoice_amount' not in matches_df.columns and 'amount' in matches_df.columns:
|
| 308 |
+
matches_df['invoice_amount'] = matches_df['amount']
|
| 309 |
+
if 'payment_amount' not in matches_df.columns and 'amount' in matches_df.columns:
|
| 310 |
+
matches_df['payment_amount'] = matches_df['amount']
|
| 311 |
+
|
| 312 |
unmatched_invoices_df = pd.DataFrame(unmatched_invoices) if unmatched_invoices else pd.DataFrame()
|
| 313 |
unapplied_payments_df = pd.DataFrame(unapplied_payments) if unapplied_payments else pd.DataFrame()
|
| 314 |
|
|
|
|
| 341 |
if not invoice_record_id or not payment_record_id:
|
| 342 |
return "❌ Please select a match to confirm", *refresh_reconciliation_dashboard()[1:]
|
| 343 |
|
| 344 |
+
print(f"Confirming auto match - Invoice: {invoice_record_id}, Payment: {payment_record_id}")
|
| 345 |
+
|
| 346 |
result = confirm_match(invoice_record_id, payment_record_id)
|
| 347 |
|
| 348 |
if result['success']:
|
| 349 |
# Synchronize data across all storage
|
| 350 |
_sync_data_after_matching()
|
| 351 |
+
success_msg = f"✅ {result['message']}\n\n**Data synchronized across all tabs!**"
|
| 352 |
+
return success_msg, *refresh_reconciliation_dashboard()[1:]
|
| 353 |
else:
|
| 354 |
return f"❌ {result['message']}", *refresh_reconciliation_dashboard()[1:]
|
| 355 |
|
|
|
|
| 358 |
if not manual_invoice_id or not manual_payment_id:
|
| 359 |
return "❌ Please select both an unmatched invoice and an unapplied payment", *refresh_reconciliation_dashboard()[1:]
|
| 360 |
|
| 361 |
+
print(f"Manual matching - Invoice: {manual_invoice_id}, Payment: {manual_payment_id}")
|
| 362 |
+
|
| 363 |
result = manual_match_invoice_to_payment(manual_invoice_id, manual_payment_id)
|
| 364 |
|
| 365 |
if result['success']:
|
| 366 |
# Synchronize data across all storage
|
| 367 |
_sync_data_after_matching()
|
| 368 |
+
success_msg = f"✅ {result['message']}\n\n**Data synchronized across all tabs!**"
|
| 369 |
+
return success_msg, *refresh_reconciliation_dashboard()[1:]
|
| 370 |
else:
|
| 371 |
return f"❌ {result['message']}", *refresh_reconciliation_dashboard()[1:]
|
| 372 |
|
|
|
|
| 649 |
# Document number match (fuzzy)
|
| 650 |
inv_doc = str(invoice.get('document_number', '')).lower().strip()
|
| 651 |
pay_doc = str(payment.get('document_number', '')).lower().strip()
|
| 652 |
+
if inv_doc and pay_doc and (inv_doc in pay_doc or pay_doc in inv_doc):
|
| 653 |
match_score += 1
|
| 654 |
|
| 655 |
# Date match (within 7 days)
|
|
|
|
| 681 |
return pd.DataFrame()
|
| 682 |
|
| 683 |
|
| 684 |
+
# ---------------------------------------------------------------------
|
| 685 |
+
# Enhanced Selection Handlers for Reconciliation Dashboard
|
| 686 |
+
# ---------------------------------------------------------------------
|
| 687 |
+
|
| 688 |
+
def store_auto_selected_match(evt: gr.SelectData, matches_df: pd.DataFrame):
|
| 689 |
+
"""Handle selection from auto-matched table with better error handling."""
|
| 690 |
+
if evt is None or matches_df is None or matches_df.empty:
|
| 691 |
+
return "", "", "**Selected Invoice:** None", "**Selected Payment:** None"
|
| 692 |
+
|
| 693 |
+
try:
|
| 694 |
+
selected_row = matches_df.iloc[evt.index]
|
| 695 |
+
invoice_id = selected_row.get('invoice_record_id', '')
|
| 696 |
+
payment_id = selected_row.get('payment_record_id', '')
|
| 697 |
+
|
| 698 |
+
# Get display values with fallbacks
|
| 699 |
+
invoice_doc = selected_row.get('invoice_document', selected_row.get('document_number', 'N/A'))
|
| 700 |
+
payment_doc = selected_row.get('payment_document', selected_row.get('document_number', 'N/A'))
|
| 701 |
+
invoice_amt = selected_row.get('invoice_amount', selected_row.get('amount', 0))
|
| 702 |
+
payment_amt = selected_row.get('payment_amount', selected_row.get('amount', 0))
|
| 703 |
+
|
| 704 |
+
invoice_display = f"**Selected Invoice:** {invoice_doc} (${invoice_amt:.2f})"
|
| 705 |
+
payment_display = f"**Selected Payment:** {payment_doc} (${payment_amt:.2f})"
|
| 706 |
+
|
| 707 |
+
print(f"Auto match selected - Invoice: {invoice_id}, Payment: {payment_id}")
|
| 708 |
+
return invoice_id, payment_id, invoice_display, payment_display
|
| 709 |
+
|
| 710 |
+
except Exception as e:
|
| 711 |
+
print(f"Error in auto selection: {e}")
|
| 712 |
+
return "", "", "**Selected Invoice:** None", "**Selected Payment:** None"
|
| 713 |
+
|
| 714 |
+
def store_manual_invoice_selection(evt: gr.SelectData, invoices_df: pd.DataFrame):
|
| 715 |
+
"""Handle selection from unmatched invoices table."""
|
| 716 |
+
if evt is None or invoices_df is None or invoices_df.empty:
|
| 717 |
+
return "", "**Selected Invoice:** None"
|
| 718 |
+
|
| 719 |
+
try:
|
| 720 |
+
selected_row = invoices_df.iloc[evt.index]
|
| 721 |
+
record_id = selected_row.get('record_id', '')
|
| 722 |
+
document_num = selected_row.get('document_number', 'N/A')
|
| 723 |
+
amount = selected_row.get('total_billed', 0)
|
| 724 |
+
|
| 725 |
+
display = f"**Selected Invoice:** {document_num} (${amount:.2f})"
|
| 726 |
+
print(f"Manual invoice selected: {record_id}")
|
| 727 |
+
return record_id, display
|
| 728 |
+
|
| 729 |
+
except Exception as e:
|
| 730 |
+
print(f"Error in invoice selection: {e}")
|
| 731 |
+
return "", "**Selected Invoice:** None"
|
| 732 |
+
|
| 733 |
+
def store_manual_payment_selection(evt: gr.SelectData, payments_df: pd.DataFrame):
|
| 734 |
+
"""Handle selection from unapplied payments table."""
|
| 735 |
+
if evt is None or payments_df is None or payments_df.empty:
|
| 736 |
+
return "", "**Selected Payment:** None"
|
| 737 |
+
|
| 738 |
+
try:
|
| 739 |
+
selected_row = payments_df.iloc[evt.index]
|
| 740 |
+
record_id = selected_row.get('record_id', '')
|
| 741 |
+
document_num = selected_row.get('document_number', 'N/A')
|
| 742 |
+
amount = selected_row.get('payment_amount', 0)
|
| 743 |
+
|
| 744 |
+
display = f"**Selected Payment:** {document_num} (${amount:.2f})"
|
| 745 |
+
print(f"Manual payment selected: {record_id}")
|
| 746 |
+
return record_id, display
|
| 747 |
+
|
| 748 |
+
except Exception as e:
|
| 749 |
+
print(f"Error in payment selection: {e}")
|
| 750 |
+
return "", "**Selected Payment:** None"
|
| 751 |
+
|
| 752 |
+
def store_suggested_match_selection(evt: gr.SelectData, suggestions_df: pd.DataFrame):
|
| 753 |
+
"""Handle selection from suggested matches table."""
|
| 754 |
+
if evt is None or suggestions_df is None or suggestions_df.empty:
|
| 755 |
+
return "", "", "**Selected Invoice:** None", "**Selected Payment:** None"
|
| 756 |
+
|
| 757 |
+
try:
|
| 758 |
+
selected_row = suggestions_df.iloc[evt.index]
|
| 759 |
+
invoice_id = selected_row.get('invoice_record_id', '')
|
| 760 |
+
payment_id = selected_row.get('payment_record_id', '')
|
| 761 |
+
invoice_doc = selected_row.get('invoice_document', 'N/A')
|
| 762 |
+
payment_doc = selected_row.get('payment_document', 'N/A')
|
| 763 |
+
invoice_amt = selected_row.get('invoice_amount', 0)
|
| 764 |
+
payment_amt = selected_row.get('payment_amount', 0)
|
| 765 |
+
match_score = selected_row.get('match_score', 0)
|
| 766 |
+
|
| 767 |
+
invoice_display = f"**Selected Invoice:** {invoice_doc} (${invoice_amt:.2f})"
|
| 768 |
+
payment_display = f"**Selected Payment:** {payment_doc} (${payment_amt:.2f}) - Score: {match_score}/3"
|
| 769 |
+
|
| 770 |
+
print(f"Suggested match selected - Invoice: {invoice_id}, Payment: {payment_id}")
|
| 771 |
+
return invoice_id, payment_id, invoice_display, payment_display
|
| 772 |
+
|
| 773 |
+
except Exception as e:
|
| 774 |
+
print(f"Error in suggested selection: {e}")
|
| 775 |
+
return "", "", "**Selected Invoice:** None", "**Selected Payment:** None"
|
| 776 |
+
|
| 777 |
+
|
| 778 |
# ---------------------------------------------------------------------
|
| 779 |
# Main Application with Enhanced Interface
|
| 780 |
# ---------------------------------------------------------------------
|
|
|
|
| 849 |
get_suggestions_btn = gr.Button("💡 Get Suggested Matches", variant="secondary")
|
| 850 |
|
| 851 |
with gr.Row():
|
| 852 |
+
reconciliation_summary = gr.Markdown("### Reconciliation Summary - Click Refresh All to load data")
|
| 853 |
+
|
| 854 |
+
# Selection feedback row
|
| 855 |
+
with gr.Row():
|
| 856 |
+
with gr.Column():
|
| 857 |
+
selected_invoice_display = gr.Markdown("**Selected Invoice:** None")
|
| 858 |
+
with gr.Column():
|
| 859 |
+
selected_payment_display = gr.Markdown("**Selected Payment:** None")
|
| 860 |
|
| 861 |
with gr.Row():
|
| 862 |
with gr.Column():
|
| 863 |
gr.Markdown("#### ✅ Exact Matches Found")
|
| 864 |
+
gr.Markdown("**Click on a match below, then click 'Confirm Auto Match'**")
|
| 865 |
matches_table = gr.Dataframe(
|
| 866 |
label="Auto-Matched Invoices & Payments",
|
| 867 |
interactive=True,
|
| 868 |
+
type="pandas",
|
| 869 |
+
wrap=True
|
| 870 |
)
|
| 871 |
|
| 872 |
with gr.Column():
|
| 873 |
gr.Markdown("#### ❌ Unmatched Items - Select for Manual Matching")
|
| 874 |
+
with gr.Tabs():
|
| 875 |
+
with gr.Tab("Unmatched Invoices"):
|
| 876 |
+
gr.Markdown("**Click on an invoice below**")
|
| 877 |
+
unmatched_invoices_table = gr.Dataframe(
|
| 878 |
+
interactive=True,
|
| 879 |
+
type="pandas",
|
| 880 |
+
wrap=True
|
| 881 |
+
)
|
| 882 |
+
with gr.Tab("Unapplied Payments"):
|
| 883 |
+
gr.Markdown("**Click on a payment below**")
|
| 884 |
+
unapplied_payments_table = gr.Dataframe(
|
| 885 |
+
interactive=True,
|
| 886 |
+
type="pandas",
|
| 887 |
+
wrap=True
|
| 888 |
+
)
|
| 889 |
+
with gr.Tab("Suggested Matches"):
|
| 890 |
+
gr.Markdown("**Click on a suggested match below**")
|
| 891 |
+
suggested_matches_table = gr.Dataframe(
|
| 892 |
+
label="Suggested Matches (2 out of 3 fields match)",
|
| 893 |
+
interactive=True,
|
| 894 |
+
type="pandas",
|
| 895 |
+
wrap=True
|
| 896 |
+
)
|
| 897 |
|
| 898 |
# Store selected matches
|
| 899 |
selected_invoice_id = gr.State() # For auto matches
|
|
|
|
| 901 |
manual_invoice_id = gr.State() # For manual matches
|
| 902 |
manual_payment_id = gr.State() # For manual matches
|
| 903 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 904 |
# Event handlers
|
| 905 |
matches_table.select(
|
| 906 |
fn=store_auto_selected_match,
|