python Copy code
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
from datetime import datetime, timedelta
import io
# Page config
st.set_page_config(
page_title="Cash Application Quality Monitor",
page_icon="💰",
layout="wide",
initial_sidebar_state="expanded"
)
st.title("💰 Cash Application Quality Monitor")
st.markdown("Track **match rates** and **exceptions** for AR cash application efficiency. Upload your data to get started!")
# Sidebar for data upload and filters
st.sidebar.header("📊 Data & Filters")
uploaded_file = st.sidebar.file_uploader("Upload CSV file", type="csv", help="Expected columns: payment_id, payment_date, payment_amount, invoice_id, match_type, exception_reason")
# Date range filter
col1, col2 = st.sidebar.columns(2)
start_date = col1.date_input("Start Date", value=datetime.now().date() - timedelta(days=30))
end_date = col2.date_input("End Date", value=datetime.now().date())
if uploaded_file is not None:
@st.cache_data
def load_data(file):
df = pd.read_csv(file)
df['payment_date'] = pd.to_datetime(df['payment_date'])
df['payment_amount'] = pd.to_numeric(df['payment_amount'], errors='coerce')
return df
df = load_data(uploaded_file)
# Filter data
df_filtered = df[(df['payment_date'] >= pd.to_datetime(start_date)) &
(df['payment_date'] <= pd.to_datetime(end_date))].copy()
if df_filtered.empty:
st.warning("No data in the selected date range.")
else:
# Key Metrics Calculation
total_payments = len(df_filtered)
auto_matched = len(df_filtered[df_filtered['match_type'] == 'Auto'])
manual_matched = len(df_filtered[df_filtered['match_type'] == 'Manual'])
exceptions = len(df_filtered[df_filtered['match_type'] == 'Exception'])
match_rate = (auto_matched / total_payments * 100) if total_payments > 0 else 0
touchless_rate = match_rate # Alias for auto-match
# KPIs Row
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Payments", f"{total_payments:,}", delta=None)
with col2:
st.metric("Auto-Match Rate", f"{match_rate:.1f}%", delta=None)
with col3:
st.metric("Exceptions", f"{exceptions:,}", delta=None)
with col4:
st.metric("Manual Touches", f"{manual_matched:,}", delta=None)
# Charts Row 1: Match Rate Trend & Breakdown
col1, col2 = st.columns(2)
with col1:
st.subheader("📈 Match Rate Trend")
if 'payment_date' in df_filtered.columns:
daily_data = df_filtered.groupby(df_filtered['payment_date'].dt.date).agg({
'payment_id': 'count',
'match_type': lambda x: (x == 'Auto').sum()
}).rename(columns={'payment_id': 'total', 'match_type': 'auto'})
daily_data['match_rate'] = daily_data['auto'] / daily_data['total'] * 100
daily_data = daily_data.reset_index()
daily_data['payment_date'] = pd.to_datetime(daily_data['payment_date'])
fig_trend = px.line(daily_data, x='payment_date', y='match_rate',
title="Daily Auto-Match Rate (%)",
markers=True)
fig_trend.update_yaxis(range=[0, 100])
st.plotly_chart(fig_trend, use_container_width=True)
with col2:
st.subheader("📊 Payment Breakdown")
breakdown = df_filtered['match_type'].value_counts()
fig_pie = px.pie(values=breakdown.values, names=breakdown.index,
title="Payments by Match Type")
st.plotly_chart(fig_pie, use_container_width=True)
# Exceptions Table
st.subheader("🚨 Exceptions Details")
exceptions_df = df_filtered[df_filtered['match_type'] == 'Exception'].copy()
if 'exception_reason' in exceptions_df.columns:
exceptions_df = exceptions_df.sort_values(['payment_date', 'payment_amount'], ascending=[False, False])
st.dataframe(exceptions_df[['payment_id', 'payment_date', 'payment_amount', 'invoice_id', 'exception_reason']],
use_container_width=True)
else:
st.info("Add 'exception_reason' column for richer exception details.")
# Exception Reasons Breakdown (if available)
if 'exception_reason' in df_filtered.columns and not exceptions_df.empty:
st.subheader("🔍 Top Exception Reasons")
reason_counts = exceptions_df['exception_reason'].value_counts().head(10)
fig_bar = px.bar(x=reason_counts.values, y=reason_counts.index,
orientation='h', title="Top 10 Exception Reasons")
st.plotly_chart(fig_bar, use_container_width=True)
# Amount Analysis
st.subheader("💵 Amount Insights")
col1, col2 = st.columns(2)
with col1:
auto_avg = df_filtered[df_filtered['match_type'] == 'Auto']['payment_amount'].mean()
exc_avg = exceptions_df['payment_amount'].mean() if not exceptions_df.empty else 0
st.metric("Avg Auto-Match Amount", f"${auto_avg:,.2f}")
st.metric("Avg Exception Amount", f"${exc_avg:,.2f}")
with col2:
total_auto_amount = df_filtered[df_filtered['match_type'] == 'Auto']['payment_amount'].sum()
total_exc_amount = exceptions_df['payment_amount'].sum()
st.metric("Total Auto-Matched $", f"${total_auto_amount:,.2f}")
st.metric("Total Exception $", f"${total_exc_amount:,.2f}")
# Download processed data
csv_buffer = io.StringIO()
df_filtered.to_csv(csv_buffer, index=False)
st.sidebar.download_button("Download Filtered Data", csv_buffer.getvalue(), "filtered_cash_app_data.csv")
else:
# Sample Data Generator for Demo
if st.sidebar.button("Generate Sample Data"):
np.random.seed(42)
n = 1000
dates = pd.date_range(start='2024-01-01', end='2024-10-01', freq='D')
sample_df = pd.DataFrame({
'payment_id': [f'PAY_{i:06d}' for i in range(n)],
'payment_date': np.random.choice(dates, n),
'payment_amount': np.random.uniform(100, 5000, n).round(2),
'invoice_id': [f'INV_{i:06d}' if np.random.rand() > 0.2 else None for i in range(n)],
'match_type': np.random.choice(['Auto', 'Manual', 'Exception'], n, p=[0.75, 0.15, 0.10]),
'exception_reason': np.random.choice(['Short Pay', 'Over Pay', 'No Matching Invoice', 'Duplicate', None], n)
})
sample_df.loc[sample_df['match_type'] != 'Exception', 'exception_reason'] = None
csv_buffer = io.StringIO()
sample_df.to_csv(csv_buffer, index=False)
st.sidebar.download_button("Download Sample Data", csv_buffer.getvalue(), "sample_cash_app_data.csv")
st.success("Sample data generated! Download and upload it to see the monitor in action.")
st.markdown("**Expected CSV Columns:**")
st.code("""
payment_id,payment_date,payment_amount,invoice_id,match_type,exception_reason
PAY_000001,2024-01-15,1500.00,INV_000001,Auto,
PAY_000002,2024-01-16,1200.50,,Exception,Short Pay
PAY_000003,2024-01-17,2500.00,INV_000003,Manual,
""")
# Footer
st.markdown("---")
st.markdown("Built with ❤️ by Sherlock | Trailblazer Labs | Deploy with `streamlit run this_script.py`")
This monitor flags quality issues like low match rates (<80% target?) or spiking exceptions. Customize thresholds or integrate with your ERP (e.g., via API) for production! 🔍