import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
# --- Page Configuration ---
st.set_page_config(page_title="Restricted Funds Compliance", layout="wide", initial_sidebar_state="expanded")
# --- Mock Data Generation (Replace with SQL/Excel connection) ---
@st.cache_data
def generate_data():
# Create dummy grants
grants = [
{"ID": "G-1001", "Name": "Education Outreach", "Start": "2023-01-01", "End": "2023-12-31", "Total_Budget": 100000, "Spent": 85000, "Category": "Program"},
{"ID": "G-1002", "Name": "COVID Relief Fund", "Start": "2023-03-01", "End": "2024-02-28", "Total_Budget": 500000, "Spent": 120000, "Category": "Emergency"},
{"ID": "G-1003", "Name": "Tech Innovation Grant", "Start": "2022-06-01", "End": "2023-05-31", "Total_Budget": 25000, "Spent": 24900, "Category": "R&D"},
{"ID": "G-1004", "Name": "Community Garden", "Start": "2023-01-01", "End": "2023-06-30", "Total_Budget": 15000, "Spent": 16000, "Category": "Capital"}, # Overspent
{"ID": "G-1005", "Name": "Staff Training Initiative", "Start": "2023-05-01", "End": "2024-04-30", "Total_Budget": 80000, "Spent": 10000, "Category": "Operations"},
]
# Create detailed transactions
transactions = []
for g in grants:
for i in range(10):
amount = np.random.randint(500, 5000)
date = pd.to_datetime(g["Start"]) + timedelta(days=np.random.randint(0, 180))
# Randomly assign compliance flags
is_allowable = np.random.choice([True, False], p=[0.9, 0.1])
category = np.random.choice(["Personnel", "Travel", "Equipment", "Admin"])
transactions.append({
"Date": date,
"Grant_ID": g["ID"],
"Grant_Name": g["Name"],
"Amount": amount if is_allowable else amount + 5000, # Inflated if non-compliant
"Category": category,
"Vendor": f"Vendor {i}",
"Is_Compliant": is_allowable,
"Notes": "OK" if is_allowable else "Requires Review - Unallowable Cost"
})
return pd.DataFrame(grants), pd.DataFrame(transactions)
df_grants, df_trans = generate_data()
# --- Sidebar ---
st.sidebar.title("🗂️ Filters")
selected_grants = st.sidebar.multiselect(
"Select Grant Funds",
options=df_grants['Name'].unique(),
default=df_grants['Name'].unique()
)
# Filter Data
df_grants_filtered = df_grants[df_grants['Name'].isin(selected_grants)]
df_trans_filtered = df_trans[df_trans['Grant_Name'].isin(selected_grants)]
# --- Dashboard Header ---
st.title("📊 Restricted Funds Compliance Dashboard")
st.markdown(f"**Last Updated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# --- KPI Row ---
kpi1, kpi2, kpi3, kpi4 = st.columns(4)
# Calculation Logic
total_budget = df_grants_filtered['Total_Budget'].sum()
total_spent = df_grants_filtered['Spent'].sum()
pct_spent = (total_spent / total_budget) * 100 if total_budget > 0 else 0
non_compliant_count = df_trans_filtered[df_trans_filtered['Is_Compliant'] == False].shape[0]
with kpi1:
st.metric(label="Total Restricted Budget", value=f"${total_budget:,.0f}")
with kpi2:
st.metric(label="Total Disbursed", value=f"${total_spent:,.0f}", delta=f"{pct_spent:.1f}% of total")
with kpi3:
st.metric(label="Avg. Burn Rate", value=f"{pct_spent:.1f}%", delta="Time vs Spend")
with kpi4:
st.metric(label="Compliance Flags", value=f"⚠️ {non_compliant_count}", delta=None)
st.markdown("---")
# --- Visualization Row 1: Grant Status ---
st.subheader("Fund Status & Burn Rate")
# Prepare data for chart
df_grants_filtered['Remaining'] = df_grants_filtered['Total_Budget'] - df_grants_filtered['Spent']
df_grants_filtered['Status'] = df_grants_filtered.apply(
lambda x: 'Overspent' if x['Remaining'] < 0 else ('On Track' if x['Spent']/x['Total_Budget'] < 0.9 else 'Near Limit'),
axis=1
)
fig_bar = go.Figure(data=[
go.Bar(name='Spent', x=df_grants_filtered['Name'], y=df_grants_filtered['Spent'], marker_color='#EF553B'),
go.Bar(name='Remaining', x=df_grants_filtered['Name'], y=df_grants_filtered['Remaining'], marker_color='#00CC96')
])
fig_bar.update_layout(barmode='stack', title_text='Budget Utilization by Grant', height=400)
st.plotly_chart(fig_bar, use_container_width=True)
# --- Visualization Row 2: Risk & Timeline ---
c1, c2 = st.columns([1, 1])
with c1:
st.subheader("Compliance Status by Category")
# Count compliant vs non-compliant transactions
comp_counts = df_trans_filtered['Is_Compliant'].value_counts().reset_index()
comp_counts.columns = ['Status', 'Count']
comp_counts['Status'] = comp_counts['Status'].map({True: 'Compliant', False: 'Non-Compliant'})
fig_pie = px.pie(comp_counts, values='Count', names='Status', title='Transaction Compliance Rate',
color='Status', color_discrete_map={'Compliant':'#2E86AB', 'Non-Compliant':'#A23B72'})
st.plotly_chart(fig_pie, use_container_width=True)
with c2:
st.subheader("Expiring Funds (Next 90 Days)")
today = datetime.now()
df_grants_filtered['End'] = pd.to_datetime(df_grants_filtered['End'])
expiring = df_grants_filtered[df_grants_filtered['End'] <= today + timedelta(days=90)]
if not expiring.empty:
fig_timeline = px.timeline(expiring, x_start="Start", x_end="End", y="Name", color="Status")
fig_timeline.update_yaxes(autorange="reversed")
st.plotly_chart(fig_timeline, use_container_width=True)
else:
st.info("No funds expiring in the next 90 days.")
# --- Detail Section: Transaction Ledger ---
st.subheader("🚨 Flagged Transactions (Non-Compliant)")
st.warning("The following transactions require immediate review by the Finance Committee.")
# Show only non-compliant items
non_compliant_df = df_trans_filtered[df_trans_filtered['Is_Compliant'] == False]
if non_compliant_df.empty:
st.success("No non-compliant transactions found based on current data.")
else:
st.dataframe(
non_compliant_df[['Date', 'Grant_Name', 'Amount', 'Vendor', 'Notes']],
column_config={
"Amount": st.column_config.NumberColumn(format="$%.2f"),
"Date": st.column_config.DateColumn("Date"),
},
use_container_width=True,
hide_index=True
)
# --- Raw Data Expander ---
with st.expander("View All Grant Details"):
st.dataframe(df_grants_filtered)