Spaces:
Runtime error

File size: 6,467 Bytes
858f00c
10ba0b5
d70a27d
10ba0b5
858f00c
10ba0b5
858f00c
10ba0b5
 
038573a
d70a27d
10ba0b5
 
 
 
858f00c
10ba0b5
 
 
 
 
 
 
858f00c
10ba0b5
 
 
 
 
 
 
 
 
 
 
c823597
10ba0b5
 
 
 
858f00c
10ba0b5
70d1169
10ba0b5
 
 
c823597
10ba0b5
858f00c
10ba0b5
c823597
 
10ba0b5
858f00c
c823597
10ba0b5
 
 
 
 
 
 
 
 
 
858f00c
10ba0b5
d70a27d
 
 
 
10ba0b5
d70a27d
 
 
 
 
 
10ba0b5
 
 
d70a27d
10ba0b5
d70a27d
10ba0b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import streamlit as st
import pandas as pd
import requests
import matplotlib.pyplot as plt
from datetime import datetime
import altair as alt

# --- App Configuration ---
st.set_page_config(page_title="πŸ’Έ Expense Tracker", layout="wide")
st.title("πŸ’Έ Personal Expense Tracker")
API_URL = st.secrets['API_URL']
SHEET_URL = st.secrets['SHEET_URL']
PWD = st.secrets['PWD']
USER_CREDENTIALS = {"admin": PWD}  # Set your username and password here


# --- Session State Setup ---
if "authenticated" not in st.session_state:
    st.session_state.authenticated = False
if "last_amount_selected" not in st.session_state:
    st.session_state.last_amount_selected = 0.0
if "expense_date" not in st.session_state:
    st.session_state.expense_date = datetime.today()

# --- Login UI ---
def login():
    st.title("πŸ” Login to Expense Tracker")
    username = st.text_input("Username")
    password = st.text_input("Password", type="password")
    if st.button("Login"):
        if username in USER_CREDENTIALS and USER_CREDENTIALS[username] == password:
            st.session_state.authenticated = True
            st.rerun()
        else:
            st.error("❌ Invalid credentials")

# --- Stop if Not Authenticated ---
if not st.session_state.authenticated:
    login()
    st.stop()

# --- Main UI ---

st.caption("Track your spending smartly, securely, and stylishly.")

# --- Expense Entry Form ---
with st.form("expense_form"):
    st.subheader("βž• Add New Expense")

    col1, col2 = st.columns([2, 1])
    with col1:
        category = st.selectbox("Category", ["Food", "Transport", "Utilities", "Shopping", "Entertainment", "Other"])
        notes = st.text_input("Notes (optional)", placeholder="E.g. Cafe, Uber ride...")

    with col2:
        date = st.date_input("Date", value=st.session_state.expense_date)
        amount = st.number_input("Amount (β‚Ή)", min_value=0, step=50, value=int(st.session_state.last_amount_selected), format="%d")


        st.markdown("#### πŸ’‘ Quick Add")
        q1, q2, q3, q4 = st.columns(4)
        if q1.form_submit_button("β‚Ή100"): st.session_state.last_amount_selected = 100.0; st.rerun()
        if q2.form_submit_button("β‚Ή200"): st.session_state.last_amount_selected = 200.0; st.rerun()
        if q3.form_submit_button("β‚Ή500"): st.session_state.last_amount_selected = 500.0; st.rerun()
        if q4.form_submit_button("β‚Ή1000"): st.session_state.last_amount_selected = 1000.0; st.rerun()

    submitted = st.form_submit_button("πŸ“€ Submit Expense")
    if submitted:
        payload = {
            "date": str(date),
            "category": category,
            "amount": str(amount),
            "notes": notes
        }
        with st.spinner("Logging your expense..."):
            try:
                res = requests.post(API_URL, data=payload)
                if res.status_code == 200 and "Success" in res.text:
                    st.success("βœ… Expense logged successfully!")
                    st.session_state.last_amount_selected = 0.0
                    st.session_state.expense_date = datetime.today()
                else:
                    st.error("❌ Failed to log expense.")
            except Exception as e:
                st.error(f"⚠️ Error: {e}")

# --- Analytics Section ---
st.subheader("πŸ“Š Expense Analytics")
try:
    df = pd.read_csv(SHEET_URL)
    df.columns = [c.strip() for c in df.columns]
    df["Date"] = pd.to_datetime(df["Date"], errors="coerce")
    df = df.dropna(subset=["Date", "Amount"])
    df["Amount"] = pd.to_numeric(df["Amount"], errors="coerce")
    df["Month"] = df["Date"].dt.to_period("M").astype(str)

    # Layout: Metrics
    col1, col2 = st.columns(2)
    with col1:
        st.metric("Total Spent", f"β‚Ή{df['Amount'].sum():,.2f}")
    with col2:
        st.metric("Entries", len(df))

    # Monthly Expense Trend
    st.subheader("πŸ“† Monthly Expense Trend")
    monthly_data = df.groupby("Month")["Amount"].sum().reset_index()
    line = alt.Chart(monthly_data).mark_line(point=alt.OverlayMarkDef(size=50, filled=True, color="#FF6B6B")).encode(
        x=alt.X("Month:O", title="Month", sort=None),  # Preserve Month order
        y=alt.Y("Amount:Q", title="Total Amount (β‚Ή)", axis=alt.Axis(grid=True)),
        tooltip=[alt.Tooltip("Month:O"), alt.Tooltip("Amount:Q", format=".2f")]
    )
    text = line.mark_text(align="center", baseline="middle", dy=-15, fontSize=12, fontWeight="bold").encode(
        text=alt.Text("Amount:Q", format=".2f")
    )
    monthly_chart = (line + text).properties(width=700, height=300, title="Monthly Expense Trend").configure_line(
        color="#4ECDC4", strokeWidth=3
    ).configure_axis(labelFontSize=12, titleFontSize=14)
    st.altair_chart(monthly_chart, use_container_width=True)

    # Daily Spending Pattern
    st.subheader("πŸ• Spend by Category")
    cat_sum = df.groupby("Category")["Amount"].sum()
    explode = [0.05] * len(cat_sum)
    colors = plt.cm.Paired(range(len(cat_sum)))

    fig, ax = plt.subplots(figsize=(25, 5))
    labels = [f"{cat}\nβ‚Ή{amt:,.0f}" for cat, amt in cat_sum.items()]
    ax.pie(
        cat_sum.values,
        labels=labels,
        autopct='%1.0f%%',
        startangle=90,
        counterclock=False,
        explode=explode,
        wedgeprops={'edgecolor': 'white', 'linewidth': 1},
        colors=colors,
        textprops={'fontsize': 12}
    )
    ax.axis("equal")
    fig.suptitle("Spend by Category", fontsize=16)
    st.pyplot(fig)



    # All Expense Entries
    st.subheader("πŸ“‹ All Expense Entries")
    st.dataframe(df.sort_values("Date", ascending=False), use_container_width=True)

    # Optional: Add filter for interactivity
    st.sidebar.header("Filter Data")
    date_range = st.sidebar.date_input("Select Date Range", [df["Date"].min(), df["Date"].max()])
    categories = st.sidebar.multiselect("Select Categories", options=df["Category"].unique(), default=df["Category"].unique())
    filtered_df = df[(df["Date"].dt.date >= date_range[0]) & (df["Date"].dt.date <= date_range[1]) & (df["Category"].isin(categories))]
    if not filtered_df.empty:
        st.subheader("πŸ“Š Filtered Metrics")
        col1, col2 = st.columns(2)
        with col1:
            st.metric("Filtered Total Spent", f"β‚Ή{filtered_df['Amount'].sum():,.2f}")
        with col2:
            st.metric("Filtered Entries", len(filtered_df))

except Exception as e:
    st.error("⚠️ Analytics not available.")
    st.text(f"Reason: {e}")