Angelguava commited on
Commit
39494df
·
verified ·
1 Parent(s): 717b8a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -61
app.py CHANGED
@@ -16,6 +16,7 @@ LATE_TIME = "08:00"
16
  EARLY_LEAVE_TIME = "17:00"
17
  MAX_WORK_HOURS = 12
18
  MIN_WORK_HOURS = 1
 
19
 
20
  GOOGLE_SHEET_URL = "https://docs.google.com/spreadsheets/d/1RGnMJW5Ja0e3rDJrChvrxlExlcqkB1WvIhFU-tRNWmo/edit?usp=sharing"
21
  GOOGLE_WORKSHEET_NAME = "表單回應 1"
@@ -54,6 +55,7 @@ def load_google_sheet_by_url(sheet_url, worksheet_name=None):
54
  def clean_attendance_data(df: pd.DataFrame) -> pd.DataFrame:
55
  df = df.copy()
56
  df.columns = [str(col).strip() for col in df.columns]
 
57
  column_map = {
58
  "員工編號": "emp_id",
59
  "員工姓名": "emp_name",
@@ -61,13 +63,29 @@ def clean_attendance_data(df: pd.DataFrame) -> pd.DataFrame:
61
  "日期": "date",
62
  "上班時間": "check_in",
63
  "下班時間": "check_out",
 
64
  }
65
  df = df.rename(columns={k: v for k, v in column_map.items() if k in df.columns})
 
66
  required_cols = ["emp_id", "emp_name", "date", "check_in", "check_out"]
67
  for col in required_cols:
68
  if col not in df.columns:
69
  raise ValueError(f"缺少必要欄位:{col}")
 
 
 
 
 
 
 
 
70
  df["date"] = pd.to_datetime(df["date"], errors="coerce")
 
 
 
 
 
 
71
  df["check_in"] = pd.to_datetime(
72
  df["date"].dt.strftime("%Y-%m-%d") + " " + df["check_in"].astype(str),
73
  errors="coerce"
@@ -76,29 +94,86 @@ def clean_attendance_data(df: pd.DataFrame) -> pd.DataFrame:
76
  df["date"].dt.strftime("%Y-%m-%d") + " " + df["check_out"].astype(str),
77
  errors="coerce"
78
  )
 
79
  return df
80
 
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  # =========================
83
  # 稽核邏輯
84
  # =========================
85
  def audit_attendance(df: pd.DataFrame) -> pd.DataFrame:
86
  df = df.copy()
 
87
  df["漏打卡"] = df["check_in"].isna() | df["check_out"].isna()
 
88
  df["標準上班時間"] = pd.to_datetime(
89
- df["date"].dt.strftime("%Y-%m-%d") + f" {LATE_TIME}", errors="coerce"
 
90
  )
91
  df["標準下班時間"] = pd.to_datetime(
92
- df["date"].dt.strftime("%Y-%m-%d") + f" {EARLY_LEAVE_TIME}", errors="coerce"
 
93
  )
 
94
  df["遲到"] = (df["check_in"] > df["標準上班時間"]).fillna(False)
95
  df["早退"] = (df["check_out"] < df["標準下班時間"]).fillna(False)
 
96
  df["工時"] = (df["check_out"] - df["check_in"]).dt.total_seconds() / 3600
97
  df["工時過長"] = (df["工時"] > MAX_WORK_HOURS).fillna(False)
98
  df["工時過短"] = (df["工時"] < MIN_WORK_HOURS).fillna(False)
 
 
99
  df["是否異常"] = (
100
- df["漏打卡"] | df["遲到"] | df["早退"] | df["工時過長"] | df["工時過短"]
 
 
 
 
 
101
  )
 
 
 
 
 
 
 
 
 
 
 
102
  return df
103
 
104
 
@@ -112,6 +187,7 @@ def build_employee_summary(df: pd.DataFrame) -> pd.DataFrame:
112
  漏打卡次數=("漏打卡", "sum"),
113
  工時過長次數=("工時過長", "sum"),
114
  工時過短次數=("工時過短", "sum"),
 
115
  總異常次數=("是否異常", "sum"),
116
  ).reset_index()
117
  return summary
@@ -122,6 +198,9 @@ def build_department_summary(df: pd.DataFrame) -> pd.DataFrame:
122
  遲到次數=("遲到", "sum"),
123
  早退次數=("早退", "sum"),
124
  漏打卡次數=("漏打卡", "sum"),
 
 
 
125
  總異常次數=("是否異常", "sum"),
126
  ).reset_index().rename(columns={"department": "部門"})
127
  return summary
@@ -133,11 +212,20 @@ def build_department_summary(df: pd.DataFrame) -> pd.DataFrame:
133
  def to_excel_bytes(sheets: dict) -> bytes:
134
  buf = io.BytesIO()
135
  with pd.ExcelWriter(buf, engine="openpyxl") as writer:
136
- for sheet_name, df in sheets.items():
137
- df.to_excel(writer, sheet_name=sheet_name, index=False)
138
  return buf.getvalue()
139
 
140
 
 
 
 
 
 
 
 
 
 
141
  # =========================
142
  # Streamlit UI
143
  # =========================
@@ -146,22 +234,51 @@ st.set_page_config(page_title="打卡稽核系統", layout="wide", page_icon="
146
  # ── 側欄設定 ──
147
  with st.sidebar:
148
  st.header("⚙️ 稽核參數設定")
149
- late_time = st.time_input("遲到判定時間", value=pd.Timestamp(f"2000-01-01 {LATE_TIME}").time())
150
- early_time = st.time_input("早退判定時間", value=pd.Timestamp(f"2000-01-01 {EARLY_LEAVE_TIME}").time())
151
- max_hours = st.number_input("工時過長上限(小時)", min_value=1, max_value=24, value=MAX_WORK_HOURS)
152
- min_hours = st.number_input("工時過短下限(小時)", min_value=0, max_value=12, value=MIN_WORK_HOURS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  st.divider()
154
  st.caption("Google Sheet URL")
155
- sheet_url = st.text_input("試算表連結", value=GOOGLE_SHEET_URL, label_visibility="collapsed")
156
- worksheet_name = st.text_input("工作表名稱", value=GOOGLE_WORKSHEET_NAME)
 
 
 
 
157
 
158
- LATE_TIME = late_time.strftime("%H:%M")
159
- EARLY_LEAVE_TIME = early_time.strftime("%H:%M")
160
- MAX_WORK_HOURS = max_hours
161
- MIN_WORK_HOURS = min_hours
 
162
 
163
  st.title("🕐 Google 打卡稽核系統")
164
- st.caption("連接 Google Sheets,自動偵測遲到 / 早退 / 漏打卡 / 異常工時")
165
 
166
  run_btn = st.button("📥 讀取並開始分析", type="primary", use_container_width=True)
167
 
@@ -177,26 +294,28 @@ if run_btn:
177
  try:
178
  df_clean = clean_attendance_data(df_raw)
179
  df_audit = audit_attendance(df_clean)
180
- emp_summary = build_employee_summary(df_audit)
181
  dept_summary = build_department_summary(df_audit)
182
- abnormal_df = df_audit[df_audit["是否異常"]].copy()
183
  except Exception as e:
184
  st.error(f"❌ 資料處理失敗:{e}")
185
  st.stop()
186
 
187
  # ── KPI 卡片 ──
188
- total = len(df_audit)
189
  abn_cnt = int(df_audit["是否異常"].sum())
190
- late_cnt = int(df_audit["遲到"].sum())
191
- early_cnt = int(df_audit["早退"].sum())
192
- miss_cnt = int(df_audit["漏打卡"].sum())
193
-
194
- c1, c2, c3, c4, c5 = st.columns(5)
195
- c1.metric("📋 總筆數", total)
196
- c2.metric("⚠️ 總異常數", abn_cnt, delta=f"{abn_cnt/total*100:.1f}%", delta_color="inverse")
197
- c3.metric("🕗 遲到", late_cnt)
198
- c4.metric("🏃 早退", early_cnt)
199
- c5.metric("❓ 漏打卡", miss_cnt)
 
 
200
 
201
  st.divider()
202
 
@@ -213,8 +332,11 @@ if run_btn:
213
  st.subheader("各部門異常次數")
214
  if not dept_summary.empty:
215
  fig = px.bar(
216
- dept_summary, x="部門", y="總異常次數",
217
- color="總異常次數", color_continuous_scale="Reds",
 
 
 
218
  text="總異常次數"
219
  )
220
  fig.update_traces(textposition="outside")
@@ -229,12 +351,12 @@ if run_btn:
229
  "漏打卡": miss_cnt,
230
  "工時過長": int(df_audit["工時過長"].sum()),
231
  "工時過短": int(df_audit["工時過短"].sum()),
 
232
  }
233
  fig2 = px.pie(
234
  names=list(anomaly_types.keys()),
235
  values=list(anomaly_types.values()),
236
- hole=0.4,
237
- color_discrete_sequence=px.colors.qualitative.Set2
238
  )
239
  fig2.update_layout(height=350)
240
  st.plotly_chart(fig2, use_container_width=True)
@@ -243,12 +365,14 @@ if run_btn:
243
  work_hours_data = df_audit.dropna(subset=["工時"])
244
  if not work_hours_data.empty:
245
  fig3 = px.histogram(
246
- work_hours_data, x="工時", nbins=20,
247
- labels={"工時": "工時(小時)", "count": "筆數"},
248
- color_discrete_sequence=["#636EFA"]
 
249
  )
250
  fig3.add_vline(x=MIN_WORK_HOURS, line_dash="dash", line_color="orange", annotation_text="最短工時")
251
- fig3.add_vline(x=MAX_WORK_HOURS, line_dash="dash", line_color="red", annotation_text="最長工時")
 
252
  fig3.update_layout(height=300)
253
  st.plotly_chart(fig3, use_container_width=True)
254
 
@@ -256,36 +380,41 @@ if run_btn:
256
  with tab2:
257
  st.subheader(f"⚠️ 異常紀錄(共 {len(abnormal_df)} 筆)")
258
 
259
- # 篩選器
260
  col_f1, col_f2 = st.columns(2)
261
  with col_f1:
262
  anomaly_filter = st.multiselect(
263
  "篩選異常類型",
264
- ["遲到", "早退", "漏打卡", "工時過長", "工時過短"],
265
  default=[]
266
  )
267
  with col_f2:
268
- dept_options = ["全部"] + sorted(df_audit["department"].dropna().unique().tolist())
269
  dept_filter = st.selectbox("篩選部門", dept_options)
270
 
271
  filtered = abnormal_df.copy()
 
272
  if anomaly_filter:
273
- mask = pd.Series([False] * len(filtered), index=filtered.index)
274
  for col in anomaly_filter:
275
  mask = mask | filtered[col]
276
  filtered = filtered[mask]
277
- if dept_filter != "全部":
278
- filtered = filtered[filtered["department"] == dept_filter]
279
 
280
- display_cols = ["emp_id", "emp_name", "department", "date",
281
- "check_in", "check_out", "工時",
282
- "遲到", "早退", "漏打卡", "工時過長", "工時過短"]
 
 
 
 
 
 
283
  display_cols = [c for c in display_cols if c in filtered.columns]
 
284
 
285
  st.dataframe(
286
- filtered[display_cols].style.applymap(
287
  lambda v: "background-color: #ffe0e0;" if v is True else "",
288
- subset=["遲到", "早退", "漏打卡", "工時過長", "工時過短"]
289
  ),
290
  use_container_width=True,
291
  height=400
@@ -294,15 +423,18 @@ if run_btn:
294
  # ── Tab 3:員工統計 ──
295
  with tab3:
296
  st.subheader("👤 員工異常統計")
297
- sort_col = st.selectbox("排序依據", ["總異常次數", "遲到次數", "早退次數", "漏打卡次數"])
298
  emp_sorted = emp_summary.sort_values(sort_col, ascending=False)
299
- st.dataframe(emp_sorted, use_container_width=True, height=400)
300
 
301
  if not emp_sorted.empty:
302
  top10 = emp_sorted.head(10)
303
  fig4 = px.bar(
304
- top10, x="emp_name", y=sort_col,
305
- color=sort_col, color_continuous_scale="Oranges",
 
 
 
306
  title=f"Top 10 員工 — {sort_col}",
307
  text=sort_col
308
  )
@@ -313,14 +445,16 @@ if run_btn:
313
  # ── Tab 4:部門統計 ──
314
  with tab4:
315
  st.subheader("🏢 部門異常統計")
316
- st.dataframe(dept_summary, use_container_width=True)
317
 
318
  if not dept_summary.empty:
319
  melt = dept_summary.melt(id_vars="部門", var_name="類型", value_name="次數")
320
  fig5 = px.bar(
321
  melt[melt["類型"] != "總異常次數"],
322
- x="部門", y="次數", color="類型", barmode="group",
323
- color_discrete_sequence=px.colors.qualitative.Pastel,
 
 
324
  title="部門異常類型明細"
325
  )
326
  fig5.update_layout(height=350)
@@ -329,17 +463,19 @@ if run_btn:
329
  # ── Tab 5:原始資料 ──
330
  with tab5:
331
  st.subheader("🗃️ 原始資料")
332
- st.dataframe(df_raw, use_container_width=True, height=400)
333
 
334
  # ── 匯出按鈕 ──
335
  st.divider()
336
  st.subheader("📤 匯出報表")
 
337
  excel_bytes = to_excel_bytes({
338
- "異常明細": abnormal_df,
339
- "員工統計": emp_summary,
340
- "部門統計": dept_summary,
341
- "完整稽核": df_audit,
342
  })
 
343
  st.download_button(
344
  label="⬇️ 下載 Excel 報表(含四個工作表)",
345
  data=excel_bytes,
@@ -348,4 +484,5 @@ if run_btn:
348
  use_container_width=True,
349
  type="primary"
350
  )
351
- st.success("✅ 分析完成!")
 
 
16
  EARLY_LEAVE_TIME = "17:00"
17
  MAX_WORK_HOURS = 12
18
  MIN_WORK_HOURS = 1
19
+ NORMAL_WORK_HOURS = 8
20
 
21
  GOOGLE_SHEET_URL = "https://docs.google.com/spreadsheets/d/1RGnMJW5Ja0e3rDJrChvrxlExlcqkB1WvIhFU-tRNWmo/edit?usp=sharing"
22
  GOOGLE_WORKSHEET_NAME = "表單回應 1"
 
55
  def clean_attendance_data(df: pd.DataFrame) -> pd.DataFrame:
56
  df = df.copy()
57
  df.columns = [str(col).strip() for col in df.columns]
58
+
59
  column_map = {
60
  "員工編號": "emp_id",
61
  "員工姓名": "emp_name",
 
63
  "日期": "date",
64
  "上班時間": "check_in",
65
  "下班時間": "check_out",
66
+ "備註": "remark"
67
  }
68
  df = df.rename(columns={k: v for k, v in column_map.items() if k in df.columns})
69
+
70
  required_cols = ["emp_id", "emp_name", "date", "check_in", "check_out"]
71
  for col in required_cols:
72
  if col not in df.columns:
73
  raise ValueError(f"缺少必要欄位:{col}")
74
+
75
+ if "department" not in df.columns:
76
+ df["department"] = ""
77
+
78
+ if "remark" not in df.columns:
79
+ df["remark"] = ""
80
+
81
+ # 日期轉換
82
  df["date"] = pd.to_datetime(df["date"], errors="coerce")
83
+
84
+ # 將空字串轉成 NA,避免時間轉換異常
85
+ df["check_in"] = df["check_in"].replace("", pd.NA)
86
+ df["check_out"] = df["check_out"].replace("", pd.NA)
87
+
88
+ # 日期 + 時間 組成完整 datetime
89
  df["check_in"] = pd.to_datetime(
90
  df["date"].dt.strftime("%Y-%m-%d") + " " + df["check_in"].astype(str),
91
  errors="coerce"
 
94
  df["date"].dt.strftime("%Y-%m-%d") + " " + df["check_out"].astype(str),
95
  errors="coerce"
96
  )
97
+
98
  return df
99
 
100
 
101
+ # =========================
102
+ # 備註自動判斷
103
+ # =========================
104
+ def build_remark(row) -> str:
105
+ remarks = []
106
+
107
+ if row["漏打卡"]:
108
+ if pd.isna(row["check_in"]) and pd.isna(row["check_out"]):
109
+ remarks.append("上班、下班皆未打卡")
110
+ elif pd.isna(row["check_in"]):
111
+ remarks.append("上班未打卡")
112
+ elif pd.isna(row["check_out"]):
113
+ remarks.append("下班未打卡")
114
+
115
+ if row["遲到"]:
116
+ remarks.append("遲到")
117
+
118
+ if row["早退"]:
119
+ remarks.append("早退")
120
+
121
+ if row["工時過長"]:
122
+ remarks.append("工時過長")
123
+
124
+ if row["工時過短"]:
125
+ remarks.append("工時過短")
126
+
127
+ if row["工時不足"]:
128
+ remarks.append(f"工時不足{NORMAL_WORK_HOURS}小時")
129
+
130
+ return "、".join(remarks) if remarks else "正常"
131
+
132
+
133
  # =========================
134
  # 稽核邏輯
135
  # =========================
136
  def audit_attendance(df: pd.DataFrame) -> pd.DataFrame:
137
  df = df.copy()
138
+
139
  df["漏打卡"] = df["check_in"].isna() | df["check_out"].isna()
140
+
141
  df["標準上班時間"] = pd.to_datetime(
142
+ df["date"].dt.strftime("%Y-%m-%d") + f" {LATE_TIME}",
143
+ errors="coerce"
144
  )
145
  df["標準下班時間"] = pd.to_datetime(
146
+ df["date"].dt.strftime("%Y-%m-%d") + f" {EARLY_LEAVE_TIME}",
147
+ errors="coerce"
148
  )
149
+
150
  df["遲到"] = (df["check_in"] > df["標準上班時間"]).fillna(False)
151
  df["早退"] = (df["check_out"] < df["標準下班時間"]).fillna(False)
152
+
153
  df["工時"] = (df["check_out"] - df["check_in"]).dt.total_seconds() / 3600
154
  df["工時過長"] = (df["工時"] > MAX_WORK_HOURS).fillna(False)
155
  df["工時過短"] = (df["工時"] < MIN_WORK_HOURS).fillna(False)
156
+ df["工時不足"] = ((df["工時"] >= MIN_WORK_HOURS) & (df["工時"] < NORMAL_WORK_HOURS)).fillna(False)
157
+
158
  df["是否異常"] = (
159
+ df["漏打卡"] |
160
+ df["遲到"] |
161
+ df["早退"] |
162
+ df["工時過長"] |
163
+ df["工時過短"] |
164
+ df["工時不足"]
165
  )
166
+
167
+ # 保留原始備註
168
+ df["原始備註"] = df["remark"].astype(str).fillna("").str.strip()
169
+
170
+ # 系統自動備註
171
+ df["系統備註"] = df.apply(build_remark, axis=1)
172
+
173
+ # 最終備註:人工優先,沒有才帶系統
174
+ df["最終備註"] = df["原始備註"]
175
+ df.loc[df["最終備註"] == "", "最終備註"] = df["系統備註"]
176
+
177
  return df
178
 
179
 
 
187
  漏打卡次數=("漏打卡", "sum"),
188
  工時過長次數=("工時過長", "sum"),
189
  工時過短次數=("工時過短", "sum"),
190
+ 工時不足次數=("工時不足", "sum"),
191
  總異常次數=("是否異常", "sum"),
192
  ).reset_index()
193
  return summary
 
198
  遲到次數=("遲到", "sum"),
199
  早退次數=("早退", "sum"),
200
  漏打卡次數=("漏打卡", "sum"),
201
+ 工時過長次數=("工時過長", "sum"),
202
+ 工時過短次數=("工時過短", "sum"),
203
+ 工時不足次數=("工時不足", "sum"),
204
  總異常次數=("是否異常", "sum"),
205
  ).reset_index().rename(columns={"department": "部門"})
206
  return summary
 
212
  def to_excel_bytes(sheets: dict) -> bytes:
213
  buf = io.BytesIO()
214
  with pd.ExcelWriter(buf, engine="openpyxl") as writer:
215
+ for sheet_name, df_sheet in sheets.items():
216
+ df_sheet.to_excel(writer, sheet_name=sheet_name, index=False)
217
  return buf.getvalue()
218
 
219
 
220
+ # =========================
221
+ # 通用:index 從 1 開始
222
+ # =========================
223
+ def reset_display_index(df: pd.DataFrame) -> pd.DataFrame:
224
+ df = df.copy()
225
+ df.index = range(1, len(df) + 1)
226
+ return df
227
+
228
+
229
  # =========================
230
  # Streamlit UI
231
  # =========================
 
234
  # ── 側欄設定 ──
235
  with st.sidebar:
236
  st.header("⚙️ 稽核參數設定")
237
+
238
+ late_time = st.time_input(
239
+ "遲到判定時間",
240
+ value=pd.Timestamp(f"2000-01-01 {LATE_TIME}").time()
241
+ )
242
+ early_time = st.time_input(
243
+ "早退判定時間",
244
+ value=pd.Timestamp(f"2000-01-01 {EARLY_LEAVE_TIME}").time()
245
+ )
246
+ max_hours = st.number_input(
247
+ "工時過長上限(小時)",
248
+ min_value=1,
249
+ max_value=24,
250
+ value=MAX_WORK_HOURS
251
+ )
252
+ min_hours = st.number_input(
253
+ "工時過短下限(小時)",
254
+ min_value=0,
255
+ max_value=12,
256
+ value=MIN_WORK_HOURS
257
+ )
258
+ normal_hours = st.number_input(
259
+ "標準工時(小時,低於此值視為工時不足)",
260
+ min_value=1,
261
+ max_value=24,
262
+ value=NORMAL_WORK_HOURS
263
+ )
264
+
265
  st.divider()
266
  st.caption("Google Sheet URL")
267
+ sheet_url = st.text_input(
268
+ "試算表連結",
269
+ value=GOOGLE_SHEET_URL,
270
+ label_visibility="collapsed"
271
+ )
272
+ worksheet_name = st.text_input("工作表名稱", value=GOOGLE_WORKSHEET_NAME)
273
 
274
+ LATE_TIME = late_time.strftime("%H:%M")
275
+ EARLY_LEAVE_TIME = early_time.strftime("%H:%M")
276
+ MAX_WORK_HOURS = max_hours
277
+ MIN_WORK_HOURS = min_hours
278
+ NORMAL_WORK_HOURS = normal_hours
279
 
280
  st.title("🕐 Google 打卡稽核系統")
281
+ st.caption("連接 Google Sheets,自動偵測遲到 / 早退 / 漏打卡 / 異常工時 / 工時不足 / 自動備註")
282
 
283
  run_btn = st.button("📥 讀取並開始分析", type="primary", use_container_width=True)
284
 
 
294
  try:
295
  df_clean = clean_attendance_data(df_raw)
296
  df_audit = audit_attendance(df_clean)
297
+ emp_summary = build_employee_summary(df_audit)
298
  dept_summary = build_department_summary(df_audit)
299
+ abnormal_df = df_audit[df_audit["是否異常"]].copy()
300
  except Exception as e:
301
  st.error(f"❌ 資料處理失敗:{e}")
302
  st.stop()
303
 
304
  # ── KPI 卡片 ──
305
+ total = len(df_audit)
306
  abn_cnt = int(df_audit["是否異常"].sum())
307
+ late_cnt = int(df_audit["遲到"].sum())
308
+ early_cnt = int(df_audit["早退"].sum())
309
+ miss_cnt = int(df_audit["漏打卡"].sum())
310
+ short_cnt = int(df_audit["工時不足"].sum())
311
+
312
+ c1, c2, c3, c4, c5, c6 = st.columns(6)
313
+ c1.metric("📋 總筆數", total)
314
+ c2.metric("⚠️ 總異常數", abn_cnt, delta=f"{abn_cnt/total*100:.1f}%" if total > 0 else "0%", delta_color="inverse")
315
+ c3.metric("🕗 遲到", late_cnt)
316
+ c4.metric("🏃 早退", early_cnt)
317
+ c5.metric("❓ 漏打卡", miss_cnt)
318
+ c6.metric("⏱️ 工時不足", short_cnt)
319
 
320
  st.divider()
321
 
 
332
  st.subheader("各部門異常次數")
333
  if not dept_summary.empty:
334
  fig = px.bar(
335
+ dept_summary,
336
+ x="部門",
337
+ y="總異常次數",
338
+ color="總異常次數",
339
+ color_continuous_scale="Reds",
340
  text="總異常次數"
341
  )
342
  fig.update_traces(textposition="outside")
 
351
  "漏打卡": miss_cnt,
352
  "工時過長": int(df_audit["工時過長"].sum()),
353
  "工時過短": int(df_audit["工時過短"].sum()),
354
+ "工時不足": short_cnt,
355
  }
356
  fig2 = px.pie(
357
  names=list(anomaly_types.keys()),
358
  values=list(anomaly_types.values()),
359
+ hole=0.4
 
360
  )
361
  fig2.update_layout(height=350)
362
  st.plotly_chart(fig2, use_container_width=True)
 
365
  work_hours_data = df_audit.dropna(subset=["工時"])
366
  if not work_hours_data.empty:
367
  fig3 = px.histogram(
368
+ work_hours_data,
369
+ x="工時",
370
+ nbins=20,
371
+ labels={"工時": "工時(小時)", "count": "筆數"}
372
  )
373
  fig3.add_vline(x=MIN_WORK_HOURS, line_dash="dash", line_color="orange", annotation_text="最短工時")
374
+ fig3.add_vline(x=NORMAL_WORK_HOURS, line_dash="dash", line_color="blue", annotation_text=f"標準工時({NORMAL_WORK_HOURS}h)")
375
+ fig3.add_vline(x=MAX_WORK_HOURS, line_dash="dash", line_color="red", annotation_text="最長工時")
376
  fig3.update_layout(height=300)
377
  st.plotly_chart(fig3, use_container_width=True)
378
 
 
380
  with tab2:
381
  st.subheader(f"⚠️ 異常紀錄(共 {len(abnormal_df)} 筆)")
382
 
 
383
  col_f1, col_f2 = st.columns(2)
384
  with col_f1:
385
  anomaly_filter = st.multiselect(
386
  "篩選異常類型",
387
+ ["遲到", "早退", "漏打卡", "工時過長", "工時過短", "工時不足"],
388
  default=[]
389
  )
390
  with col_f2:
391
+ dept_options = ["全部"] + sorted(df_audit["department"].dropna().astype(str).unique().tolist())
392
  dept_filter = st.selectbox("篩選部門", dept_options)
393
 
394
  filtered = abnormal_df.copy()
395
+
396
  if anomaly_filter:
397
+ mask = pd.Series(False, index=filtered.index)
398
  for col in anomaly_filter:
399
  mask = mask | filtered[col]
400
  filtered = filtered[mask]
 
 
401
 
402
+ if dept_filter != "全部":
403
+ filtered = filtered[filtered["department"].astype(str) == dept_filter]
404
+
405
+ display_cols = [
406
+ "emp_id", "emp_name", "department", "date",
407
+ "check_in", "check_out", "工時",
408
+ "遲到", "早退", "漏打卡", "工時過長", "工時過短", "工時不足",
409
+ "系統備註", "最終備註"
410
+ ]
411
  display_cols = [c for c in display_cols if c in filtered.columns]
412
+ flag_cols = [c for c in ["遲到", "早退", "漏打卡", "工時過長", "工時過短", "工時不足"] if c in filtered.columns]
413
 
414
  st.dataframe(
415
+ reset_display_index(filtered[display_cols]).style.applymap(
416
  lambda v: "background-color: #ffe0e0;" if v is True else "",
417
+ subset=flag_cols
418
  ),
419
  use_container_width=True,
420
  height=400
 
423
  # ── Tab 3:員工統計 ──
424
  with tab3:
425
  st.subheader("👤 員工異常統計")
426
+ sort_col = st.selectbox("排序依據", ["總異常次數", "遲到次數", "早退次數", "漏打卡次數", "工時不足次數"])
427
  emp_sorted = emp_summary.sort_values(sort_col, ascending=False)
428
+ st.dataframe(reset_display_index(emp_sorted), use_container_width=True, height=400)
429
 
430
  if not emp_sorted.empty:
431
  top10 = emp_sorted.head(10)
432
  fig4 = px.bar(
433
+ top10,
434
+ x="emp_name",
435
+ y=sort_col,
436
+ color=sort_col,
437
+ color_continuous_scale="Oranges",
438
  title=f"Top 10 員工 — {sort_col}",
439
  text=sort_col
440
  )
 
445
  # ── Tab 4:部門統計 ──
446
  with tab4:
447
  st.subheader("🏢 部門異常統計")
448
+ st.dataframe(reset_display_index(dept_summary), use_container_width=True)
449
 
450
  if not dept_summary.empty:
451
  melt = dept_summary.melt(id_vars="部門", var_name="類型", value_name="次數")
452
  fig5 = px.bar(
453
  melt[melt["類型"] != "總異常次數"],
454
+ x="部門",
455
+ y="次數",
456
+ color="類型",
457
+ barmode="group",
458
  title="部門異常類型明細"
459
  )
460
  fig5.update_layout(height=350)
 
463
  # ── Tab 5:原始資料 ──
464
  with tab5:
465
  st.subheader("🗃️ 原始資料")
466
+ st.dataframe(reset_display_index(df_raw), use_container_width=True, height=400)
467
 
468
  # ── 匯出按鈕 ──
469
  st.divider()
470
  st.subheader("📤 匯出報表")
471
+
472
  excel_bytes = to_excel_bytes({
473
+ "異常明細": abnormal_df,
474
+ "員工統計": emp_summary,
475
+ "部門統計": dept_summary,
476
+ "完整稽核": df_audit,
477
  })
478
+
479
  st.download_button(
480
  label="⬇️ 下載 Excel 報表(含四個工作表)",
481
  data=excel_bytes,
 
484
  use_container_width=True,
485
  type="primary"
486
  )
487
+
488
+ st.success("✅ 分析完成!")