Function bodies 34 total
_check_password function · python · L17-L31 (15 LOC)dashboard.py
def _check_password():
if st.session_state.get("authenticated"):
return True
st.image("kp_logo.png", width=180)
st.markdown("## KP Staffing Activity Dashboard")
st.markdown("Please enter the password to continue.")
pw = st.text_input("Password", type="password", key="_login_pw")
if st.button("Login"):
correct = st.secrets.get("APP_PASSWORD", "kpstaffing2025")
if pw == correct:
st.session_state["authenticated"] = True
st.rerun()
else:
st.error("Incorrect password.")
return Falsesafe_int function · python · L213-L217 (5 LOC)dashboard.py
def safe_int(val):
try:
return int(val)
except (ValueError, TypeError):
return 0find_row function · python · L220-L226 (7 LOC)dashboard.py
def find_row(df, keyword, col=0):
"""Return index of first row where col contains keyword (case-insensitive)."""
for i in range(len(df)):
cell = str(df.iloc[i, col]) if pd.notna(df.iloc[i, col]) else ""
if keyword.lower() in cell.lower():
return i
return Nonefilter_data_by_dates function · python · L658-L691 (34 LOC)dashboard.py
def filter_data_by_dates(data, start_date, end_date):
"""Return a copy of data filtered to the given date window."""
import copy
d = copy.copy(data)
# Filter headcount rows to weeks ending within window
hc = data["headcount"].copy()
if not hc.empty and "Week Ending" in hc.columns:
hc = hc[(hc["Week Ending"] >= pd.Timestamp(start_date)) &
(hc["Week Ending"] <= pd.Timestamp(end_date))]
d["headcount"] = hc
# Filter terms by End Date
terms = data["terms"].copy()
if not terms.empty and "End Date" in terms.columns:
terms = terms[(terms["End Date"] >= pd.Timestamp(start_date)) &
(terms["End Date"] <= pd.Timestamp(end_date))]
d["terms"] = terms
# Filter hires by Start Date
hires = data["hires"].copy()
if not hires.empty and "Start Date" in hires.columns:
hires = hires[(hires["Start Date"] >= pd.Timestamp(start_date)) &
(hires["Start Date"] <= pd.Timestafilter_data_by_reps function · python · L694-L706 (13 LOC)dashboard.py
def filter_data_by_reps(data, allowed_reps):
"""Return a copy of data filtered to only include records for the given staffing reps."""
import copy
d = copy.copy(data)
allowed = set(allowed_reps)
for key in ("hires", "terms", "converted"):
df = data[key].copy()
if not df.empty and "Staffing Rep" in df.columns:
df = df[df["Staffing Rep"].isin(allowed)].reset_index(drop=True)
d[key] = df
return dcollect_staffing_reps function · python · L709-L718 (10 LOC)dashboard.py
def collect_staffing_reps(data):
"""Return a sorted list of unique staffing reps across hires, terms, and converted."""
reps = set()
for key in ("hires", "terms", "converted"):
df = data.get(key, pd.DataFrame())
if not df.empty and "Staffing Rep" in df.columns:
reps.update(df["Staffing Rep"].dropna().astype(str).str.strip().tolist())
reps.discard("")
reps.discard("Staffing Rep")
return sorted(reps)compute_metrics function · python · L721-L850 (130 LOC)dashboard.py
def compute_metrics(data):
terms = data["terms"]
hires = data["hires"]
hc = data["headcount"]
empty = pd.DataFrame()
involuntary = terms[terms["Type"] == "Involuntary"] if not terms.empty else empty
voluntary = terms[terms["Type"] == "Voluntary"] if not terms.empty else empty
layoffs = terms[terms["Type"] == "Layoff"] if not terms.empty else empty
inval_count = int(involuntary["Count"].sum()) if not involuntary.empty else 0
vol_count = int(voluntary["Count"].sum()) if not voluntary.empty else 0
layoff_count = int(layoffs["Count"].sum()) if not layoffs.empty else 0
# --- Starting headcount calculation ---
# Take the first week's on-site headcount, then subtract any new placements
# whose start date falls on or before that first week-end date.
# This isolates the employees who were already on site before the period began.
starting_headcount = None
first_week_end = None
new_hires_wk1 Repobility's GitHub App fixes findings like these · https://github.com/apps/repobility-bot
make_fig_headcount function · python · L853-L921 (69 LOC)dashboard.py
def make_fig_headcount(headcount_df, include_hours=True):
hc = headcount_df.copy()
hc["Week"] = hc["Week Ending"].dt.strftime("%b %d")
has_hours = include_hours and "Hours" in hc.columns and float(hc["Hours"].sum()) > 0
max_hc = float(hc["Headcount"].max()) if not hc.empty else 10.0
fig = go.Figure()
# Headcount trace (left y-axis)
fig.add_trace(go.Scatter(
x=hc["Week"], y=hc["Headcount"],
name="Headcount",
mode="lines+markers",
line=dict(color="#940000", width=3),
marker=dict(size=10, color="#940000"),
fill="tozeroy", fillcolor="rgba(148,0,0,0.07)",
yaxis="y1",
))
num_pts = len(hc)
for idx, (_, row) in enumerate(hc.iterrows()):
xs = 20 if idx == 0 else (-20 if idx == num_pts - 1 else 0)
fig.add_annotation(
x=row["Week"], y=float(row["Headcount"]),
text=str(int(row["Headcount"])),
showarrow=False, yshift=14, xshift=xs,
font=dimake_fig_donut function · python · L924-L942 (19 LOC)dashboard.py
def make_fig_donut(m):
df = pd.DataFrame({
"Type": ["Involuntary", "Voluntary", "Layoff / Assignment Complete"],
"Count": [m["inval_count"], m["vol_count"], m["layoff_count"]]
})
df = df[df["Count"] > 0]
fig = px.pie(df, names="Type", values="Count",
color_discrete_sequence=["#940000", "#2C3E50", "#B2B5B8"],
hole=0.55)
fig.update_layout(
plot_bgcolor="#ffffff", paper_bgcolor="#ffffff",
font=dict(color="#131313", size=12),
margin=dict(l=10, r=10, t=10, b=10),
legend=dict(orientation="h", yanchor="bottom", y=-0.25,
font=dict(color="#131313", size=12)),
height=260,
)
fig.update_traces(textinfo="percent+value")
return figmake_fig_reasons function · python · L952-L1014 (63 LOC)dashboard.py
def make_fig_reasons(df, color_seq, df_past=None):
if df.empty:
return go.Figure()
filtered = df[df["End Reason"].str.strip() != ""]
if filtered.empty:
return go.Figure()
curr = filtered.groupby("End Reason")["Count"].sum().reset_index(name="Current")
if df_past is not None and not df_past.empty:
past_f = df_past[df_past["End Reason"].str.strip() != ""]
past = past_f.groupby("End Reason")["Count"].sum().reset_index(name="Prior")
merged = curr.merge(past, on="End Reason", how="outer").fillna(0)
merged = merged.sort_values("Current", ascending=True)
_cm = merged["Current"].max()
_pm = merged["Prior"].max()
max_count = int(max(_cm if pd.notna(_cm) else 0, _pm if pd.notna(_pm) else 0))
if max_count == 0:
return go.Figure()
tick_step = max(1, round(max_count / 10))
num_reasons = len(merged)
fig = go.Figure()
fig.add_trace(go.Bar(
y=mermake_fig_jobs_fill function · python · L1017-L1041 (25 LOC)dashboard.py
def make_fig_jobs_fill(jobs_df):
df = jobs_df.copy()
df["Fill %"] = (df["Fill Rate"] * 100).round(1)
df["Short Title"] = df["Job Title"].str[:35]
df = df.sort_values("Fill %")
fig = go.Figure()
fig.add_trace(go.Bar(
x=df["Short Title"], y=df["# Openings"],
name="Openings", marker_color="rgba(124,134,247,0.35)",
))
fig.add_trace(go.Bar(
x=df["Short Title"], y=df["Placements"],
name="Placed", marker_color="#940000",
))
fig.update_layout(
barmode="overlay",
plot_bgcolor="#ffffff", paper_bgcolor="#ffffff",
font=dict(color="#131313", size=12),
margin=dict(l=10, r=10, t=10, b=80),
xaxis=dict(**DARK_AXIS, tickangle=-35, tickfont=dict(size=10)),
yaxis=dict(**DARK_AXIS, title="Count"),
legend=dict(orientation="h", yanchor="bottom", y=1.02),
height=320,
)
return figmake_fig_jobs_fillrate function · python · L1044-L1066 (23 LOC)dashboard.py
def make_fig_jobs_fillrate(jobs_df):
df = jobs_df.copy()
df["Fill %"] = (df["Fill Rate"] * 100).round(1)
df["Short Title"] = df["Job Title"].str[:35]
df = df.sort_values("Fill %")
fig = px.bar(
df, x="Short Title", y="Fill %",
color="Fill %",
color_continuous_scale=["#f77c8a", "#B2B5B8", "#B2B5B8"],
range_color=[0, 100],
text="Fill %",
)
fig.update_traces(texttemplate="%{text:.0f}%", textposition="outside")
fig.update_layout(
plot_bgcolor="#ffffff", paper_bgcolor="#ffffff",
font=dict(color="#131313", size=12),
margin=dict(l=10, r=10, t=10, b=80),
xaxis=dict(**DARK_AXIS, tickangle=-35, tickfont=dict(size=10)),
yaxis=dict(**DARK_AXIS, title="Fill %", range=[0, 120]),
coloraxis_showscale=False,
height=300,
)
return figmake_fig_jobs_days function · python · L1069-L1089 (21 LOC)dashboard.py
def make_fig_jobs_days(jobs_df):
df = jobs_df.copy()
df["Short Title"] = df["Job Title"].str[:35]
df = df.sort_values("Days Opened", ascending=True)
fig = px.bar(
df, x="Days Opened", y="Short Title", orientation="h",
color="Days Opened",
color_continuous_scale=["#B2B5B8", "#B2B5B8", "#f77c8a"],
text="Days Opened",
)
fig.update_traces(textposition="outside")
fig.update_layout(
plot_bgcolor="#ffffff", paper_bgcolor="#ffffff",
font=dict(color="#131313", size=12),
margin=dict(l=10, r=10, t=10, b=10),
xaxis=dict(**DARK_AXIS, title="Days Open"),
yaxis=dict(**DARK_AXIS),
coloraxis_showscale=False,
height=320,
)
return figmake_fig_hires function · python · L1092-L1112 (21 LOC)dashboard.py
def make_fig_hires(hires_df):
if hires_df.empty:
return go.Figure()
df = hires_df.copy()
df["Week"] = df["Start Date"].dt.to_period("W").dt.start_time
weekly = df.groupby("Week")["Name"].nunique().reset_index(name="New Hires")
weekly["Week Label"] = weekly["Week"].dt.strftime("%b %d")
_mv = weekly["New Hires"].max()
max_val = int(_mv) if pd.notna(_mv) and _mv > 0 else 1
fig = px.bar(weekly, x="Week Label", y="New Hires",
color_discrete_sequence=["#7D1F32"], text="New Hires")
fig.update_traces(textposition="outside")
fig.update_layout(
plot_bgcolor="#ffffff", paper_bgcolor="#ffffff",
font=dict(color="#131313", size=12),
margin=dict(l=10, r=10, t=30, b=10),
xaxis=dict(**DARK_AXIS, title=""),
yaxis=dict(**DARK_AXIS, title=dict(text="# Hires", font=dict(color="#131313")), range=[0, max_val * 1.2]),
height=300,
)
return fig_grouped_bar_chart function · python · L1115-L1167 (53 LOC)dashboard.py
def _grouped_bar_chart(curr_df, past_df, category_col, value_col, main_color, past_color="rgba(180,180,180,0.6)"):
"""Reusable grouped horizontal bar chart with optional prior period overlay."""
curr = curr_df.groupby(category_col)[value_col].sum().reset_index(name="Current")
if past_df is not None and not past_df.empty and category_col in past_df.columns:
past = past_df.groupby(category_col)[value_col].sum().reset_index(name="Prior")
merged = curr.merge(past, on=category_col, how="outer").fillna(0)
merged = merged.sort_values("Current", ascending=True)
max_val = int(max(merged["Current"].max(), merged["Prior"].max()))
tick_step = max(1, round(max_val / 10))
num_cats = len(merged)
fig = go.Figure()
fig.add_trace(go.Bar(
y=merged[category_col], x=merged["Prior"],
name="Prior Period", orientation="h",
marker_color=past_color,
text=merged["Prior"].apply(lambda v: intSame scanner, your repo: https://repobility.com — Repobility
make_fig_retention_tiers function · python · L1170-L1233 (64 LOC)dashboard.py
def make_fig_retention_tiers(metrics, metrics_past=None, active_days=None):
"""Bar chart showing 7/30/60-day retention percentages."""
tiers = metrics["retention_tiers"]
total = metrics["total_new_starts"]
if total == 0:
return go.Figure()
all_days = [7, 30, 60]
all_labels = ["7-Day", "30-Day", "60-Day"]
all_colors = ["#7b0000", "#940000", "#c0392b"]
if active_days is None:
active_days = all_days
days_keys = [d for d in all_days if d in active_days]
labels = [l for d, l in zip(all_days, all_labels) if d in active_days]
colors = [c for d, c in zip(all_days, all_colors) if d in active_days]
# Filter out tiers with no data (pct=None)
valid = [(d, l, c) for d, l, c in zip(days_keys, labels, colors) if tiers[d]["pct"] is not None]
if not valid:
return go.Figure()
days_keys, labels, colors = zip(*valid)
pcts = [tiers[d]["pct"] for d in days_keys]
retained = [tiers[d]["retained"] for make_fig_early_terms_by_reason function · python · L1236-L1258 (23 LOC)dashboard.py
def make_fig_early_terms_by_reason(early_terms_df, title_suffix=""):
"""Horizontal bar chart of early terminations by end reason."""
if early_terms_df.empty:
return go.Figure()
grouped = early_terms_df.groupby("End Reason")["Count"].sum().reset_index(name="Count")
grouped = grouped.sort_values("Count", ascending=True)
max_val = int(grouped["Count"].max()) if not grouped.empty else 1
fig = go.Figure(go.Bar(
y=grouped["End Reason"], x=grouped["Count"],
orientation="h", marker_color="#c62828",
text=grouped["Count"], textposition="outside",
))
fig.update_layout(
plot_bgcolor="#ffffff", paper_bgcolor="#ffffff",
font=dict(color="#131313", size=12),
margin=dict(l=10, r=10, t=10, b=10),
xaxis=dict(**DARK_AXIS, range=[0, max_val * 1.3], dtick=max(1, round(max_val / 10))),
yaxis=dict(**DARK_AXIS),
showlegend=False,
height=max(220, len(grouped) * 40),
)
return figmake_fig_rep_hires function · python · L1261-L1272 (12 LOC)dashboard.py
def make_fig_rep_hires(hires_df, hires_past=None):
if hires_df.empty or "Staffing Rep" not in hires_df.columns:
return go.Figure()
df = hires_df[hires_df["Staffing Rep"].str.strip() != "Unknown"].copy()
if df.empty:
df = hires_df.copy()
df["_n"] = 1
past_df = None
if hires_past is not None and not hires_past.empty and "Staffing Rep" in hires_past.columns:
past_df = hires_past[hires_past["Staffing Rep"].str.strip() != "Unknown"].copy()
past_df["_n"] = 1
return _grouped_bar_chart(df, past_df, "Staffing Rep", "_n", "#940000")make_fig_job_title_hires function · python · L1275-L1286 (12 LOC)dashboard.py
def make_fig_job_title_hires(hires_df, hires_past=None):
if hires_df.empty or "Job Title" not in hires_df.columns:
return go.Figure()
df = hires_df[hires_df["Job Title"].str.strip() != "Unknown"].copy()
if df.empty:
df = hires_df.copy()
df["_n"] = 1
past_df = None
if hires_past is not None and not hires_past.empty and "Job Title" in hires_past.columns:
past_df = hires_past[hires_past["Job Title"].str.strip() != "Unknown"].copy()
past_df["_n"] = 1
return _grouped_bar_chart(df, past_df, "Job Title", "_n", "#7D1F32")strip_html function · python · L1289-L1292 (4 LOC)dashboard.py
def strip_html(val):
import re, html
if pd.isna(val): return ""
return html.unescape(re.sub(r"<[^>]+>", " ", str(val))).strip()format_terms_display function · python · L1294-L1305 (12 LOC)dashboard.py
def format_terms_display(df):
if df.empty:
return df
d = df.copy()
cols = ["Name", "End Reason", "Comments", "Start Date", "End Date"]
cols = [c for c in cols if c in d.columns]
for col in ["Start Date", "End Date"]:
if col in d.columns:
d[col] = pd.to_datetime(d[col], errors="coerce").dt.strftime("%b %d, %Y").fillna("")
if "Comments" in d.columns:
d["Comments"] = d["Comments"].apply(strip_html)
return d[cols]_pdf_layout function · python · L1314-L1323 (10 LOC)dashboard.py
def _pdf_layout(extra=None):
base = dict(
plot_bgcolor=PDF_BG, paper_bgcolor=PDF_BG,
font=dict(color=PDF_FONT, family="Helvetica, Arial, sans-serif", size=11),
margin=dict(l=160, r=30, t=20, b=50),
height=300,
)
if extra:
base.update(extra)
return basemake_pdf_fig_headcount function · python · L1325-L1393 (69 LOC)dashboard.py
def make_pdf_fig_headcount(hc_df):
hc = hc_df.copy()
hc["Week"] = hc["Week Ending"].dt.strftime("%b %d")
max_hc = float(hc["Headcount"].max()) if not hc.empty else 1.0
min_hc = float(hc["Headcount"].min()) if not hc.empty else 0.0
has_hours = "Hours" in hc.columns and float(hc["Hours"].sum()) > 0
fig = go.Figure()
fig.add_trace(go.Scatter(
x=hc["Week"], y=hc["Headcount"],
name="Headcount",
mode="lines+markers",
line=dict(color=PDF_ACCENT, width=2.5),
marker=dict(size=8, color=PDF_ACCENT),
fillcolor="rgba(148,0,0,0.08)",
yaxis="y1",
))
num_pts = len(hc)
for idx, (_, row) in enumerate(hc.iterrows()):
# Push edge labels inward so they don't get clipped
xs = 20 if idx == 0 else (-20 if idx == num_pts - 1 else 0)
fig.add_annotation(
x=row["Week"], y=float(row["Headcount"]),
text=str(int(row["Headcount"])),
showarrow=False, yshift=14, xsOpen data scored by Repobility · https://repobility.com
make_pdf_fig_donut function · python · L1395-L1413 (19 LOC)dashboard.py
def make_pdf_fig_donut(m):
types = ["Involuntary", "Voluntary", "Layoff / Assignment Complete"]
counts = [m["inval_count"], m["vol_count"], m["layoff_count"]]
clrs = ["#940000", "#7D1F32", "#B2B5B8"]
fig = px.pie(
pd.DataFrame({"Type": types, "Count": counts}),
names="Type", values="Count",
color_discrete_sequence=clrs, hole=0.5,
)
fig.update_traces(textinfo="percent+value", textfont_size=13)
fig.update_layout(
plot_bgcolor=PDF_BG, paper_bgcolor=PDF_BG,
font=dict(color=PDF_FONT, family="Helvetica, Arial, sans-serif", size=11),
margin=dict(l=10, r=10, t=10, b=80),
height=380,
legend=dict(orientation="h", yanchor="bottom", y=-0.2,
xanchor="center", x=0.5, font=dict(size=11)),
)
return figmake_pdf_fig_reasons function · python · L1415-L1437 (23 LOC)dashboard.py
def make_pdf_fig_reasons(df, bar_color):
if df.empty:
return go.Figure()
grouped = df.groupby("End Reason")["Count"].sum().reset_index().sort_values("Count")
# Wrap long labels
grouped["Label"] = grouped["End Reason"].str.replace("/", "/<br>")
fig = go.Figure(go.Bar(
x=grouped["Count"], y=grouped["Label"],
orientation="h",
marker_color=bar_color,
text=grouped["Count"], textposition="outside",
textfont=dict(size=11),
))
max_count = grouped["Count"].max() if not grouped.empty else 1
fig.update_layout(**_pdf_layout({
"margin": dict(l=200, r=60, t=20, b=40),
"xaxis": dict(gridcolor=PDF_GRID, linecolor="#cccccc", showline=True,
range=[0, max_count * 1.25], dtick=1),
"yaxis": dict(gridcolor=PDF_GRID, linecolor="#cccccc", showline=True,
tickfont=dict(size=10)),
"showlegend": False,
}))
return figmake_pdf_fig_hires function · python · L1439-L1459 (21 LOC)dashboard.py
def make_pdf_fig_hires(hires_df):
if hires_df.empty:
return go.Figure()
df = hires_df.copy()
df["Week"] = df["Start Date"].dt.to_period("W").dt.start_time
weekly = df.groupby("Week")["Name"].nunique().reset_index(name="New Hires")
weekly["Label"] = weekly["Week"].dt.strftime("%b %d")
fig = go.Figure(go.Bar(
x=weekly["Label"], y=weekly["New Hires"],
marker_color=PDF_ACCENT2,
text=weekly["New Hires"], textposition="outside",
textfont=dict(size=11),
))
max_val = weekly["New Hires"].max() if not weekly.empty else 1
fig.update_layout(**_pdf_layout({
"margin": dict(l=50, r=30, t=20, b=50),
"xaxis": dict(gridcolor=PDF_GRID, linecolor="#cccccc", showline=True),
"yaxis": dict(gridcolor=PDF_GRID, linecolor="#cccccc", showline=True,
title="Hires", range=[0, max_val * 1.2]),
}))
return figgenerate_excel function · python · L1462-L1755 (294 LOC)dashboard.py
def generate_excel(data, metrics, data_past=None, metrics_past=None):
import io
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side, numbers
from openpyxl.utils import get_column_letter
# ── Color palette matching PDF ────────────────────────────────────────────
C_RED = "940000"
C_MAROON = "7D1F32"
C_LIGHT = "fdf0f0"
C_STRIPE = "faf7f7"
C_GRID = "e8d8d8"
C_WHITE = "FFFFFF"
C_GREY = "888888"
C_GREEN = "2e7d32"
C_DKRED = "c62828"
def fill(hex_color):
return PatternFill("solid", fgColor=hex_color)
def border(color=C_GRID, top=False, bottom=False, left=False, right=False):
s = Side(style="thin", color=color)
n = None
return Border(top=s if top else n, bottom=s if bottom else n,
left=s if left else n, right=s if right else n)
def thick_top(color=C_RED):
return Border(top=Side(style="medium", color=co_write_raw_sheet function · python · L1758-L1792 (35 LOC)dashboard.py
def _write_raw_sheet(ws, df, title, C_RED, C_LIGHT, C_STRIPE, C_GRID):
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
def fill(h): return PatternFill("solid", fgColor=h)
def all_border():
s = Side(style="thin", color=C_GRID)
return Border(top=s, bottom=s, left=s, right=s)
cols = list(df.columns)
# Header row
ws.cell(1, 1, title).font = Font(bold=True, size=12, color="FFFFFF")
ws.cell(1, 1).fill = fill(C_RED)
ws.merge_cells(f"A1:{get_column_letter(len(cols))}1")
ws.row_dimensions[1].height = 20
# Column headers
for ci, col in enumerate(cols, 1):
c = ws.cell(2, ci, col)
c.font = Font(bold=True, size=9)
c.fill = fill("e8edf2")
c.border = all_border()
c.alignment = Alignment(horizontal="center")
ws.column_dimensions[get_column_letter(ci)].width = max(12, len(str(col)) + 2)
ws.row_dimensions[2].height = 14
_date_bounds function · python · L2426-L2440 (15 LOC)dashboard.py
def _date_bounds(parsed_data):
"""Return (min_date, max_date) across all data in the parsed report."""
all_dates = []
hc = parsed_data.get("headcount", pd.DataFrame())
if not hc.empty and "Week Ending" in hc.columns:
all_dates += hc["Week Ending"].dropna().dt.date.tolist()
terms = parsed_data.get("terms", pd.DataFrame())
if not terms.empty and "End Date" in terms.columns:
all_dates += terms["End Date"].dropna().dt.date.tolist()
hires = parsed_data.get("hires", pd.DataFrame())
if not hires.empty and "Start Date" in hires.columns:
all_dates += hires["Start Date"].dropna().dt.date.tolist()
if not all_dates:
return None, None
return min(all_dates), max(all_dates)_delta_html function · python · L2566-L2584 (19 LOC)dashboard.py
def _delta_html(diff, good="down", is_pct=False):
"""Return a styled delta badge. Colors flip based on 'good' direction.
good='up' → increase=green, decrease=red (headcount, starts, hours)
good='down' → increase=red, decrease=green (terms, turnover)
good='neutral' → always neutral color
"""
suffix = "pp" if is_pct else ""
if abs(diff) < (0.05 if is_pct else 0.5):
return '<div class="delta-neutral">→ No change vs prior</div>'
arrow = "↑" if diff > 0 else "↓"
sign = "+" if diff > 0 else ""
val = f"{sign}{diff:.1f}{suffix}" if is_pct else f"{sign}{int(diff)}"
if good == "neutral":
css = "delta-neutral"
elif good == "up":
css = "delta-good" if diff > 0 else "delta-bad"
else: # good == "down"
css = "delta-bad" if diff > 0 else "delta-good"
return f'<div class="{css}">{arrow} <strong>{val}</strong> vs prior</div>'simple_card function · python · L2586-L2596 (11 LOC)dashboard.py
def simple_card(col, val, label, sub, delta_html=""):
with col:
parts = [
'<div class="metric-card">',
f'<div class="metric-value">{val}</div>',
f'<div class="metric-label">{label}</div>',
]
if delta_html:
parts.append(delta_html)
parts += [f'<div class="metric-sub">{sub}</div>', '</div>']
st.markdown("".join(parts), unsafe_allow_html=True)About: code-quality intelligence by Repobility · https://repobility.com
pct_card function · python · L2598-L2614 (17 LOC)dashboard.py
def pct_card(col, val, label, sub, pct, delta_count_html="", delta_pct_html=""):
with col:
parts = [
'<div class="metric-card">',
f'<div class="metric-value">{val}</div>',
f'<div class="metric-label">{label}</div>',
]
if delta_count_html:
parts.append(delta_count_html)
parts += [
'<div class="metric-divider"></div>',
f'<div class="metric-pct">{pct}</div>',
]
if delta_pct_html:
parts.append(delta_pct_html)
parts += [f'<div class="metric-sub">{sub}</div>', '</div>']
st.markdown("".join(parts), unsafe_allow_html=True)_render_card function · python · L2662-L2666 (5 LOC)dashboard.py
def _render_card(col, cd):
if cd[0] == "simple":
simple_card(col, cd[1], cd[2], cd[3], delta_html=cd[4])
else:
pct_card(col, cd[1], cd[2], cd[3], cd[4], delta_count_html=cd[5], delta_pct_html=cd[6])_render_row function · python · L2668-L2674 (7 LOC)dashboard.py
def _render_row(cards):
if not cards:
return
cols = st.columns(len(cards))
for i, cd in enumerate(cards):
_render_card(cols[i], cd)
st.markdown("<div style='height:10px'></div>", unsafe_allow_html=True)