-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
334 lines (273 loc) · 12.7 KB
/
app.py
File metadata and controls
334 lines (273 loc) · 12.7 KB
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import pandas as pd
import streamlit as st
import altair as alt
st.set_page_config(page_title="Branch Performance Dashboard", layout="wide")
st.title("📊 Company Overview")
# --- Blinking star function ---
def blinking_star():
blinking_css = """
<style>
@keyframes blink {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 1; }
}
.blink {
animation: blink 1s infinite;
font-size: 24px;
color: gold;
font-weight: bold;
}
</style>
"""
st.markdown(blinking_css, unsafe_allow_html=True)
return '<span class="blink">⭐✨</span>'
# --- Performance Status Display (with Star) ---
def performance_status_display(ratio):
if ratio >= 3:
return blinking_star() # Blinking star for PW
elif ratio > 1:
return "⭐" # Single star for NPW with ratio > 1
else:
return "" # No star for NPW with ratio <= 1
# --- Sidebar: File Uploads ---
st.sidebar.header("📤 Upload CSV Files")
uploaded_employees = st.sidebar.file_uploader("Upload Employees CSV", type="csv")
uploaded_branches = st.sidebar.file_uploader("Upload Branches CSV", type="csv")
uploaded_transactions = st.sidebar.file_uploader("Upload Transactions CSV", type="csv")
# --- Function to Load and Process Data ---
def load_data(emp_file, branch_file, trans_file):
employees = pd.read_csv(emp_file)
branches = pd.read_csv(branch_file)
transactions = pd.read_csv(trans_file)
# Merge datasets
emp_branch = pd.merge(employees, branches, on='BranchID', how='left')
df = pd.merge(transactions, emp_branch, on='EmployeeID', how='left')
# Parse dates
df['Date'] = pd.to_datetime(df['Date'])
df['Year'] = df['Date'].dt.year
df['Month'] = df['Date'].dt.month
# Pivot table by transaction type
pivot_df = df.pivot_table(
index=['EmployeeID', 'EmployeeName', 'BranchName', 'Year', 'Month', 'Date'],
columns='Type',
values='Amount',
aggfunc='sum',
fill_value=0
).reset_index()
# Flatten columns
pivot_df.columns = ['_'.join(col).strip() if isinstance(col, tuple) else col for col in pivot_df.columns.values]
# Clean and compute Net Income
pivot_df['BranchName'] = pivot_df['BranchName'].astype(str)
for col in ['Revenue', 'Expense', 'Salary']:
if col not in pivot_df.columns:
pivot_df[col] = 0
else:
pivot_df[col] = pd.to_numeric(pivot_df[col], errors='coerce').fillna(0)
pivot_df['Net Income'] = pivot_df['Revenue'] - pivot_df['Expense'] - pivot_df['Salary']
return pivot_df
# --- Chart: Financials by Branch ---
def financials_by_branch_chart(df):
summary = df.groupby("BranchName")[["Revenue", "Expense", "Salary"]].sum().reset_index()
summary["Total Expenses"] = summary["Expense"] + summary["Salary"]
summary["Net Income"] = summary["Revenue"] - summary["Total Expenses"]
summary["Net Income Category"] = summary["Net Income"].apply(lambda x: "Net Income (Good)" if x > 0 else "Net Income (Review)")
bar_df = summary.melt(
id_vars=["BranchName", "Net Income Category"],
value_vars=["Revenue", "Total Expenses", "Net Income"],
var_name="Metric",
value_name="Amount"
)
bar_df["Display Label"] = bar_df.apply(lambda row: (
"Net Income (Good)" if row["Metric"] == "Net Income" and row["Net Income Category"] == "Net Income (Good)"
else "Net Income (Review)" if row["Metric"] == "Net Income"
else row["Metric"]
), axis=1)
color_scale = alt.Scale(domain=[
"Net Income (Good)", "Net Income (Review)", "Total Expenses", "Revenue"
], range=["#2ecc71", "#f1c40f", "#e74c3c", "#9b59b6"])
chart = alt.Chart(bar_df).mark_bar().encode(
x=alt.X("BranchName:N", title="Branch", axis=alt.Axis(labelAngle=-30)),
y=alt.Y("Amount:Q", title="Amount ($)", stack=None),
color=alt.Color("Display Label:N", scale=color_scale, title="Metric"),
tooltip=["BranchName", "Metric", "Amount"],
xOffset='Display Label:N'
).properties(
width=600,
height=400,
title="📊 Financials by Branch"
)
return chart
# --- Chart: 12-Month Company Performance ---
def monthly_company_performance_chart(df):
df['Month_Year'] = df['Date'].dt.to_period('M').astype(str)
monthly = df.groupby("Month_Year").agg({
"Revenue": "sum",
"Expense": "sum",
"Salary": "sum"
}).reset_index()
monthly["Gross Sales"] = monthly["Revenue"]
monthly["Total Expenses"] = monthly["Expense"] + monthly["Salary"]
monthly["Net Sales"] = monthly["Revenue"] - monthly["Total Expenses"]
bar_df = monthly.melt(
id_vars=["Month_Year", "Net Sales"],
value_vars=["Gross Sales", "Total Expenses"],
var_name="Metric",
value_name="Amount"
)
bar_color_scale = alt.Scale(
domain=["Gross Sales", "Total Expenses"],
range=["#9b59b6", "#e74c3c"]
)
bar_chart = alt.Chart(bar_df).mark_bar().encode(
x=alt.X("Month_Year:N", title="Month", axis=alt.Axis(labelAngle=-45)),
y=alt.Y("Amount:Q", title="Amount ($)", stack=None),
color=alt.Color("Metric:N", scale=bar_color_scale, title=""),
xOffset="Metric:N",
tooltip=["Month_Year", "Metric", "Amount"]
)
line_chart = alt.Chart(monthly).mark_line(point=alt.OverlayMarkDef(color="#2ecc71", filled=True)).encode(
x=alt.X("Month_Year:N"),
y=alt.Y("Net Sales:Q"),
color=alt.value("#2ecc71"),
tooltip=["Month_Year", "Net Sales"]
)
chart = alt.layer(bar_chart, line_chart).properties(
width=700,
height=400,
title="📅 12-Month Company Performance"
)
return chart
# --- Chart: 12-Month Branch Performance (filtered) ---
def monthly_performance_for_branch_chart(df, branch_name):
df['Month_Year'] = df['Date'].dt.to_period('M').astype(str)
monthly = df.groupby("Month_Year").agg({
"Revenue": "sum",
"Expense": "sum",
"Salary": "sum"
}).reset_index()
monthly["Gross Sales"] = monthly["Revenue"]
monthly["Total Expenses"] = monthly["Expense"] + monthly["Salary"]
monthly["Net Sales"] = monthly["Revenue"] - monthly["Total Expenses"]
bar_df = monthly.melt(
id_vars=["Month_Year", "Net Sales"],
value_vars=["Gross Sales", "Total Expenses"],
var_name="Metric",
value_name="Amount"
)
bar_color_scale = alt.Scale(
domain=["Gross Sales", "Total Expenses"],
range=["#9b59b6", "#e74c3c"]
)
bar_chart = alt.Chart(bar_df).mark_bar().encode(
x=alt.X("Month_Year:N", title="Month", axis=alt.Axis(labelAngle=-45)),
y=alt.Y("Amount:Q", title="Amount ($)", stack=None),
color=alt.Color("Metric:N", scale=bar_color_scale, title=""),
xOffset="Metric:N",
tooltip=["Month_Year", "Metric", "Amount"]
)
line_chart = alt.Chart(monthly).mark_line(point=alt.OverlayMarkDef(color="#2ecc71", filled=True)).encode(
x=alt.X("Month_Year:N"),
y=alt.Y("Net Sales:Q"),
color=alt.value("#2ecc71"),
tooltip=["Month_Year", "Net Sales"]
)
chart = alt.layer(bar_chart, line_chart).properties(
width=700,
height=400,
title=f"📅 12-Month Performance: {branch_name}"
)
return chart
# --- Main App Logic ---
if uploaded_employees and uploaded_branches and uploaded_transactions:
df = load_data(uploaded_employees, uploaded_branches, uploaded_transactions)
branches = sorted(df['BranchName'].dropna().unique())
overview_options = ["📊 Company Overview"] + [f"📍 {branch}" for branch in branches]
st.sidebar.header("📋 Select Overview")
selected_overview = st.sidebar.radio("Choose Overview", overview_options)
if selected_overview == "📊 Company Overview":
# Company-wide metrics
total_sales = df['Revenue'].sum()
total_expenses = df['Expense'].sum() + df['Salary'].sum()
net_income = total_sales - total_expenses
avg_customer_rating = 4.69
total_branches = df['BranchName'].nunique()
total_employees = df['EmployeeID'].nunique()
performance_ratio = total_sales / total_expenses if total_expenses > 0 else float('inf')
performance_status = "PW" if performance_ratio >= 3 else "NPW"
perf_status_display = blinking_star() if performance_status == "PW" else ("⭐" if performance_ratio > 1 else "")
# Display company overview
col1, col2, col3, col4 = st.columns(4)
col1.metric("Total Sales", f"${total_sales:,.0f}")
col2.metric("Total Expenses", f"${total_expenses:,.0f}")
col3.metric("Net Income", f"${net_income:,.0f}")
col4.metric("Avg. Customer Rating", f"{avg_customer_rating}")
col5, col6, col7, col8 = st.columns(4)
col5.metric("Total Branches", f"{total_branches}")
col6.metric("Performance Ratio", f"{performance_ratio:.2f}x")
col7.markdown(f"**Performance Status:** {perf_status_display}", unsafe_allow_html=True)
col8.metric("Total Employees", total_employees)
st.markdown("### 📈 Visualizations")
# Financials by branch bar chart
st.altair_chart(financials_by_branch_chart(df), use_container_width=True)
# 12-Month Company Performance chart
st.altair_chart(monthly_company_performance_chart(df), use_container_width=True)
else:
# Branch overview
selected_branch = selected_overview.replace("📍 ", "")
branch_df = df[df['BranchName'] == selected_branch]
total_sales = branch_df['Revenue'].sum()
total_expenses = branch_df['Expense'].sum() + branch_df['Salary'].sum()
net_income = total_sales - total_expenses
avg_customer_rating = 4.69 # Placeholder for branch rating if available
total_employees = branch_df['EmployeeID'].nunique()
performance_ratio = total_sales / total_expenses if total_expenses > 0 else float('inf')
performance_status = "PW" if performance_ratio >= 3 else "NPW"
perf_status_display = blinking_star() if performance_status == "PW" else ("⭐" if performance_ratio > 1 else "")
# Aggregate individual employee performance
agg_cols = ['EmployeeID', 'EmployeeName']
agg_df = branch_df.groupby(agg_cols).agg({
'Revenue': 'sum',
'Expense': 'sum',
'Salary': 'sum'
}).reset_index()
agg_df['Net Income'] = agg_df['Revenue'] - agg_df['Expense'] - agg_df['Salary']
agg_df['Performance Ratio'] = agg_df.apply(
lambda row: row['Revenue'] / (row['Expense'] + row['Salary']) if (row['Expense'] + row['Salary']) > 0 else float('inf'),
axis=1
)
# Employees needing review (performance ratio below 3)
needs_review_df = agg_df[agg_df['Performance Ratio'] < 3][['EmployeeID', 'EmployeeName']]
# Prepare display string for needs review employees
if not needs_review_df.empty:
needs_review_str = "\n".join(
f"- {row.EmployeeID}: {row.EmployeeName}" for row in needs_review_df.itertuples()
)
else:
needs_review_str = "None 🎉"
# Display branch overview metrics
st.header(f"📍 Branch Overview: {selected_branch}")
col1, col2, col3, col4 = st.columns(4)
col1.metric("Total Sales", f"${total_sales:,.0f}")
col2.metric("Total Expenses", f"${total_expenses:,.0f}")
col3.metric("Net Income", f"${net_income:,.0f}")
col4.metric("Avg. Customer Rating", f"{avg_customer_rating}")
col5, col6, col7, col8 = st.columns(4)
col5.metric("Total Employees", f"{total_employees}")
col6.metric("Performance Ratio", f"{performance_ratio:.2f}x")
col7.markdown(f"**Performance Status:** {perf_status_display}", unsafe_allow_html=True)
col8.markdown(f"**Needs Review:**\n{needs_review_str}")
st.markdown("### 📈 Visualizations")
st.altair_chart(monthly_performance_for_branch_chart(branch_df, selected_branch), use_container_width=True)
# Individual Employee Performance Table
st.markdown("### 🧑💼 Individual Performance")
# Format currency for display
for col in ['Revenue', 'Expense', 'Salary', 'Net Income']:
agg_df[col] = agg_df[col].apply(lambda x: f"${x:,.0f}")
# Format status as rounded 'X' times or infinity
agg_df['Status'] = agg_df['Performance Ratio'].apply(lambda x: f"{x:.1f}x" if x != float('inf') else "∞")
# Drop raw Performance Ratio for cleaner display
agg_df = agg_df.drop(columns=['Performance Ratio'])
st.dataframe(agg_df.sort_values(by='Net Income', ascending=False))
else:
st.warning("Please upload all three CSV files in the sidebar to proceed.")