Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -84,6 +84,7 @@ def load_orders():
|
|
| 84 |
loaded_data = df.to_dict('records')
|
| 85 |
|
| 86 |
for o in loaded_data:
|
|
|
|
| 87 |
o["單價"] = int(float(o.get("單價", 0) or 0))
|
| 88 |
o["成本"] = int(float(o.get("成本", 0) or 0))
|
| 89 |
o["數量"] = int(float(o.get("數量", 0) or 0))
|
|
@@ -99,8 +100,11 @@ def load_orders():
|
|
| 99 |
print("⚠️ 備份檔是空的 (EmptyDataError),無法還原。")
|
| 100 |
except Exception as e:
|
| 101 |
print(f"❌ 從 CSV 還原失敗: {e}")
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
return loaded_data
|
| 106 |
|
|
@@ -115,7 +119,6 @@ orders_db = load_orders()
|
|
| 115 |
|
| 116 |
def load_menu():
|
| 117 |
loaded_menu = []
|
| 118 |
-
# 支援讀取舊版的 Dictionary 格式,並自動轉換成可容許重複品項的 List 格式
|
| 119 |
if os.path.exists(MENU_FILE):
|
| 120 |
try:
|
| 121 |
with open(MENU_FILE, "r", encoding="utf-8") as f:
|
|
@@ -252,7 +255,6 @@ def get_frontend_menu_items(user_level="全部"):
|
|
| 252 |
cat = cat.strip() if cat.strip() else "未分類"
|
| 253 |
if cat not in category_order:
|
| 254 |
category_order.append(cat)
|
| 255 |
-
# 提取名稱並附上原本的字典資料
|
| 256 |
items_by_cat.setdefault(cat, []).append((details.get("name", "未命名"), details))
|
| 257 |
|
| 258 |
flat_list = []
|
|
@@ -298,25 +300,20 @@ def get_menu_df(cat_filter="全部分類", lvl_filter="全部等級", item_filte
|
|
| 298 |
v.get("note", "")
|
| 299 |
])
|
| 300 |
|
| 301 |
-
#
|
| 302 |
-
max_seq = max([v.get("seq", 0) for v in MENU]) if MENU else 0
|
| 303 |
-
for i in range(20):
|
| 304 |
-
data.append([max_seq + i + 1, False, "全部", "未分類", "", "", 0, 0, ""])
|
| 305 |
-
|
| 306 |
df = pd.DataFrame(data, columns=["流水號", "啟用", "適用等級", "分類", "品項", "規格", "價格", "成本", "備註"])
|
| 307 |
-
|
|
|
|
| 308 |
return df
|
| 309 |
|
| 310 |
def get_members_df():
|
| 311 |
data = []
|
| 312 |
for acc, info in MEMBERS.items():
|
| 313 |
data.append([acc, info.get("password", ""), info.get("level", "1"), info.get("name", ""), info.get("location", "")])
|
| 314 |
-
|
| 315 |
-
for _ in range(5):
|
| 316 |
-
data.append(["", "", "1", "", ""])
|
| 317 |
|
| 318 |
df = pd.DataFrame(data, columns=["會員登入帳號", "密碼", "會員等級", "顧客姓名", "送貨地點"])
|
| 319 |
-
|
|
|
|
| 320 |
return df
|
| 321 |
|
| 322 |
def save_menu_to_file():
|
|
@@ -342,59 +339,42 @@ def save_members_to_file():
|
|
| 342 |
except Exception as e:
|
| 343 |
print(f"儲存會員失敗: {e}")
|
| 344 |
|
| 345 |
-
|
|
|
|
| 346 |
global MENU
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
except: price = 0
|
| 369 |
-
|
| 370 |
-
try: cost = int(float(row[7])) if pd.notna(row[7]) else 0
|
| 371 |
-
except: cost = 0
|
| 372 |
-
|
| 373 |
-
note = str(row[8]).strip() if pd.notna(row[8]) else ""
|
| 374 |
-
|
| 375 |
-
if item:
|
| 376 |
-
new_menu.append({
|
| 377 |
-
"name": item, "price": price, "cost": cost,
|
| 378 |
-
"enable": enable, "level": target_lvl, "seq": seq,
|
| 379 |
-
"category": cat, "spec": spec, "note": note
|
| 380 |
})
|
|
|
|
|
|
|
| 381 |
|
| 382 |
-
if not
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
# 如果是局部更新 (有開啟過濾),透過 seq 作為主鍵進行更新或新增,避免影響被隱藏的資料
|
| 391 |
-
menu_dict = {m.get("seq", 999): m for m in MENU}
|
| 392 |
-
for vr in new_menu:
|
| 393 |
-
menu_dict[vr["seq"]] = vr
|
| 394 |
-
MENU.clear()
|
| 395 |
-
MENU.extend(list(menu_dict.values()))
|
| 396 |
-
|
| 397 |
-
# 自動重新排列流水號 (依據當前設定的順序,重新編排為 1~N)
|
| 398 |
sorted_menu = sorted(MENU, key=lambda x: x.get("seq", 999))
|
| 399 |
for i, item_dict in enumerate(sorted_menu):
|
| 400 |
item_dict["seq"] = i + 1
|
|
@@ -402,52 +382,55 @@ def _internal_update_menu(df, cat_f="全部分類", lvl_f="全部等級", item_f
|
|
| 402 |
MENU.clear()
|
| 403 |
MENU.extend(sorted_menu)
|
| 404 |
save_menu_to_file()
|
| 405 |
-
return True
|
| 406 |
-
|
| 407 |
-
def _internal_update_members(df):
|
| 408 |
-
global MEMBERS
|
| 409 |
-
if df is None: return
|
| 410 |
-
new_members = {}
|
| 411 |
-
for row in df.values.tolist():
|
| 412 |
-
acc = str(row[0]).strip() if pd.notna(row[0]) else ""
|
| 413 |
-
pwd = str(row[1]).strip() if pd.notna(row[1]) else ""
|
| 414 |
-
lvl = str(row[2]).strip() if pd.notna(row[2]) else "1"
|
| 415 |
-
name = str(row[3]).strip() if pd.notna(row[3]) else ""
|
| 416 |
-
loc = str(row[4]).strip() if pd.notna(row[4]) else ""
|
| 417 |
-
|
| 418 |
-
if acc:
|
| 419 |
-
new_members[acc] = {"password": pwd, "level": lvl, "name": name, "location": loc}
|
| 420 |
-
|
| 421 |
-
MEMBERS.clear()
|
| 422 |
-
MEMBERS.update(new_members)
|
| 423 |
-
save_members_to_file()
|
| 424 |
-
|
| 425 |
-
def update_menu(df, cat_f, lvl_f, item_f):
|
| 426 |
-
success = _internal_update_menu(df, cat_f, lvl_f, item_f)
|
| 427 |
-
if not success:
|
| 428 |
-
return gr.update(value="❌ 錯誤:菜單不能為空!"), gr.update(), gr.update(), gr.skip(), gr.update(), gr.update(), gr.update()
|
| 429 |
|
| 430 |
new_trigger = datetime.now(TAIPEI_TZ).timestamp()
|
| 431 |
|
| 432 |
-
# 儲存後同步更新下拉選單的選項 (因為可能新增了新分類或品項)
|
| 433 |
cats = get_menu_cat_choices()
|
| 434 |
lvls = get_menu_lvl_choices()
|
| 435 |
items = get_menu_item_choices()
|
| 436 |
-
|
| 437 |
if cat_f not in cats: cat_f = "全部分類"
|
| 438 |
if lvl_f not in lvls: lvl_f = "全部等級"
|
| 439 |
if item_f not in items: item_f = "所有品項"
|
| 440 |
-
|
|
|
|
| 441 |
return (
|
| 442 |
-
gr.update(value=
|
| 443 |
-
get_menu_df(cat_f, lvl_f, item_f),
|
| 444 |
-
gr.update(value=""),
|
| 445 |
-
new_trigger,
|
| 446 |
gr.update(choices=cats, value=cat_f),
|
| 447 |
gr.update(choices=lvls, value=lvl_f),
|
| 448 |
-
gr.update(choices=items, value=item_f)
|
|
|
|
| 449 |
)
|
| 450 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
def refresh_menu_filters(cat_f, lvl_f, item_f):
|
| 452 |
cats = get_menu_cat_choices()
|
| 453 |
lvls = get_menu_lvl_choices()
|
|
@@ -473,7 +456,6 @@ def delete_menu_item(target_str, cat_f, lvl_f, item_f):
|
|
| 473 |
if not target_str:
|
| 474 |
return gr.update(value="❌ 錯誤:請點擊表格選擇或輸入要刪除的品項!"), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
| 475 |
|
| 476 |
-
# 解析名稱與規格
|
| 477 |
parts = target_str.split(" | ")
|
| 478 |
target_name = parts[0].strip()
|
| 479 |
target_spec = parts[1].strip() if len(parts) > 1 else ""
|
|
@@ -482,7 +464,6 @@ def delete_menu_item(target_str, cat_f, lvl_f, item_f):
|
|
| 482 |
new_menu = []
|
| 483 |
deleted = False
|
| 484 |
|
| 485 |
-
# 尋找並刪除匹配的品項 (只刪除第一筆符合的,避免誤刪全部同名同規格項目)
|
| 486 |
for m in MENU:
|
| 487 |
if not deleted and m.get("name") == target_name and m.get("spec", "") == target_spec:
|
| 488 |
deleted = True
|
|
@@ -492,7 +473,6 @@ def delete_menu_item(target_str, cat_f, lvl_f, item_f):
|
|
| 492 |
if len(new_menu) == original_len:
|
| 493 |
return gr.update(value=f"❌ 找不到對應的品項:{target_str}"), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
| 494 |
|
| 495 |
-
# 刪除後自動重排流水號
|
| 496 |
for i, m in enumerate(new_menu):
|
| 497 |
m["seq"] = i + 1
|
| 498 |
|
|
@@ -501,12 +481,9 @@ def delete_menu_item(target_str, cat_f, lvl_f, item_f):
|
|
| 501 |
save_menu_to_file()
|
| 502 |
|
| 503 |
new_trigger = datetime.now(TAIPEI_TZ).timestamp()
|
| 504 |
-
|
| 505 |
-
# 同步更新下拉選單
|
| 506 |
cats = get_menu_cat_choices()
|
| 507 |
lvls = get_menu_lvl_choices()
|
| 508 |
items = get_menu_item_choices()
|
| 509 |
-
|
| 510 |
if cat_f not in cats: cat_f = "全部分類"
|
| 511 |
if lvl_f not in lvls: lvl_f = "全部等級"
|
| 512 |
if item_f not in items: item_f = "所有品項"
|
|
@@ -514,26 +491,13 @@ def delete_menu_item(target_str, cat_f, lvl_f, item_f):
|
|
| 514 |
return (
|
| 515 |
gr.update(value=f"✅ 成功刪除品項:{target_str},且流水號已自動重排!({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})"),
|
| 516 |
get_menu_df(cat_f, lvl_f, item_f),
|
| 517 |
-
gr.update(value=""),
|
| 518 |
new_trigger,
|
| 519 |
gr.update(choices=cats, value=cat_f),
|
| 520 |
gr.update(choices=lvls, value=lvl_f),
|
| 521 |
gr.update(choices=items, value=item_f)
|
| 522 |
)
|
| 523 |
|
| 524 |
-
def update_members_list(df):
|
| 525 |
-
_internal_update_members(df)
|
| 526 |
-
return gr.update(value=f"✅ 會員資料已成功更新!({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})"), get_members_df()
|
| 527 |
-
|
| 528 |
-
def change_password(old_pwd, new_pwd):
|
| 529 |
-
if not new_pwd.strip():
|
| 530 |
-
return gr.update(value="❌ 新密碼不能為空白!")
|
| 531 |
-
if old_pwd != ADMIN_PASSWORD:
|
| 532 |
-
return gr.update(value="❌ 舊密碼輸入錯誤,請重新確認!")
|
| 533 |
-
|
| 534 |
-
save_pwd_to_file(new_pwd.strip())
|
| 535 |
-
return gr.update(value=f"✅ 密碼修改成功!下次登入請使用新密碼。({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})")
|
| 536 |
-
|
| 537 |
# ----------------------------
|
| 538 |
# 🤖 LINE Bot 邏輯
|
| 539 |
# ----------------------------
|
|
@@ -559,7 +523,6 @@ def handle_message(event):
|
|
| 559 |
item_name = parts[1]
|
| 560 |
quantity = int(parts[2])
|
| 561 |
|
| 562 |
-
# 從 List 中尋找第一個匹配名稱且啟用的品項
|
| 563 |
matched_item = None
|
| 564 |
for menu_item in MENU:
|
| 565 |
if menu_item.get("name") == item_name and menu_item.get("enable", True):
|
|
@@ -581,6 +544,7 @@ def handle_message(event):
|
|
| 581 |
|
| 582 |
orders_db.append({
|
| 583 |
"訂單編號": order_id,
|
|
|
|
| 584 |
"時間": timestamp,
|
| 585 |
"預定交期": "盡快 (LINE)",
|
| 586 |
"取貨方式": "自取",
|
|
@@ -599,7 +563,6 @@ def handle_message(event):
|
|
| 599 |
|
| 600 |
reply_text = f"✅ 訂單成立!\n您訂購了 {item_name} x {quantity}。\n總金額為 {total} 元,請稍候為您準備!"
|
| 601 |
else:
|
| 602 |
-
# 產出過濾重複名稱的清單供用戶參考
|
| 603 |
active_item_names = list(dict.fromkeys([v.get("name") for v in MENU if v.get("enable", True)]))
|
| 604 |
reply_text = f"❌ 找不到商品『{item_name}』,或該商品目前未提供!\n目前供應:{', '.join(active_item_names)}"
|
| 605 |
except Exception:
|
|
@@ -666,10 +629,11 @@ def get_orders_data(filter_name="所有顧客", filter_time="所有時間", filt
|
|
| 666 |
filtered_db = [o for o in filtered_db if o.get("預定交期") == filter_delivery]
|
| 667 |
|
| 668 |
if not filtered_db:
|
| 669 |
-
return [[""] *
|
| 670 |
|
| 671 |
return [[
|
| 672 |
o.get("訂單編號", ""),
|
|
|
|
| 673 |
o.get("時間", "") or o.get("訂單時間", ""),
|
| 674 |
o.get("預定交期", ""),
|
| 675 |
o.get("取貨方式", "自取"),
|
|
@@ -746,6 +710,7 @@ def restore_from_backup():
|
|
| 746 |
loaded_data = df.to_dict('records')
|
| 747 |
|
| 748 |
for o in loaded_data:
|
|
|
|
| 749 |
o["單價"] = int(float(o.get("單價", 0) or 0))
|
| 750 |
o["成本"] = int(float(o.get("成本", 0) or 0))
|
| 751 |
o["數量"] = int(float(o.get("數量", 0) or 0))
|
|
@@ -816,7 +781,6 @@ def restore_from_backup():
|
|
| 816 |
except Exception as e:
|
| 817 |
msg += f"\n❌ 會員資料還原失敗:{e}"
|
| 818 |
|
| 819 |
-
# 復原後重設選單選項
|
| 820 |
cats = get_menu_cat_choices()
|
| 821 |
lvls = get_menu_lvl_choices()
|
| 822 |
items = get_menu_item_choices()
|
|
@@ -831,6 +795,49 @@ def restore_from_backup():
|
|
| 831 |
gr.update(choices=items, value="所有品項")
|
| 832 |
)
|
| 833 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 834 |
def add_order(current_user, c_name, p_method, d_location, d_month, d_day, d_time, nts, *qty_args):
|
| 835 |
try:
|
| 836 |
user_level = "全部"
|
|
@@ -852,17 +859,12 @@ def add_order(current_user, c_name, p_method, d_location, d_month, d_day, d_time
|
|
| 852 |
|
| 853 |
reset_qtys = [gr.update(value="0") for _ in range(len(flat_list))]
|
| 854 |
|
| 855 |
-
if not c_name:
|
| 856 |
-
return [gr.update(value="❌ 錯誤:請輸入顧客姓名")] + reset_qtys
|
| 857 |
-
|
| 858 |
timestamp = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M:%S")
|
| 859 |
total_order_price = 0
|
| 860 |
items_desc = []
|
| 861 |
-
has_ordered_items = False
|
| 862 |
|
| 863 |
for i, qty in enumerate(quantities):
|
| 864 |
if qty > 0:
|
| 865 |
-
has_ordered_items = True
|
| 866 |
item_name, details = flat_list[i]
|
| 867 |
price = details["price"]
|
| 868 |
cost = details.get("cost", 0)
|
|
@@ -878,6 +880,7 @@ def add_order(current_user, c_name, p_method, d_location, d_month, d_day, d_time
|
|
| 878 |
|
| 879 |
orders_db.append({
|
| 880 |
"訂單編號": order_id,
|
|
|
|
| 881 |
"時間": timestamp,
|
| 882 |
"預定交期": delivery_date,
|
| 883 |
"取貨方式": p_method,
|
|
@@ -891,29 +894,39 @@ def add_order(current_user, c_name, p_method, d_location, d_month, d_day, d_time
|
|
| 891 |
"總成本": total_cost,
|
| 892 |
"備註": final_note
|
| 893 |
})
|
| 894 |
-
|
| 895 |
desc = f"{item_name}{item_note}x{qty}"
|
| 896 |
items_desc.append(desc)
|
| 897 |
|
| 898 |
-
if not has_ordered_items:
|
| 899 |
-
return [gr.update(value="❌ 錯誤:請至少選擇一項商品的數量")] + reset_qtys
|
| 900 |
-
|
| 901 |
save_orders()
|
| 902 |
-
msg = f"
|
| 903 |
|
| 904 |
-
return [gr.update(value=msg)] + reset_qtys
|
| 905 |
|
| 906 |
except Exception as e:
|
| 907 |
err_msg = f"❌ 系統異常:{str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 908 |
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
|
|
|
|
|
|
| 915 |
|
| 916 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 917 |
|
| 918 |
def delete_single_order(order_id, current_filter, current_time_filter, current_item_filter, current_delivery_filter):
|
| 919 |
if order_id == "__CANCEL__":
|
|
@@ -931,9 +944,8 @@ def delete_single_order(order_id, current_filter, current_time_filter, current_i
|
|
| 931 |
return gr.update(value=f"❌ 找不到訂單編號:{order_id}"), gr.update(), gr.update(), gr.update()
|
| 932 |
|
| 933 |
save_orders()
|
| 934 |
-
|
| 935 |
return (
|
| 936 |
-
gr.update(value=f"✅ 成功刪除訂單:{order_id}"),
|
| 937 |
gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 938 |
gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 939 |
gr.update(value="")
|
|
@@ -1023,26 +1035,18 @@ def run_git_cmd(command):
|
|
| 1023 |
return True, f"✅ 成功: {command}\n> {result.stdout.strip()}"
|
| 1024 |
return False, f"❌ 失敗: {command}\n> {result.stderr.strip()}"
|
| 1025 |
|
| 1026 |
-
def backup_and_push_to_github(
|
| 1027 |
log_messages = ["🚀 開始備份...\n" + "-"*40]
|
| 1028 |
-
|
| 1029 |
-
# 強制先儲存目前的 UI 編輯狀態 (避免按了備份卻沒按存檔的資料流失)
|
| 1030 |
-
try:
|
| 1031 |
-
if menu_df_in is not None:
|
| 1032 |
-
_internal_update_menu(menu_df_in, cat_f, lvl_f, item_f)
|
| 1033 |
-
if members_df_in is not None:
|
| 1034 |
-
_internal_update_members(members_df_in)
|
| 1035 |
-
log_messages.append("💾 已自動擷取目前畫面上的最新菜單與會員設定。")
|
| 1036 |
-
except Exception as e:
|
| 1037 |
-
log_messages.append(f"⚠️ 自動同步前端資料時發生錯誤:{e}")
|
| 1038 |
|
| 1039 |
if not orders_db:
|
| 1040 |
-
df = pd.DataFrame(columns=["訂單編號", "訂單時間", "預定交期", "取貨方式", "送貨地點", "顧客姓名", "商品", "單價", "成本", "數量", "總價", "總成本", "備註"])
|
| 1041 |
else:
|
| 1042 |
export_data = []
|
| 1043 |
for o in orders_db:
|
| 1044 |
export_data.append({
|
| 1045 |
"訂單編號": o.get("訂單編號", ""),
|
|
|
|
| 1046 |
"訂單時間": o.get("時間", "") or o.get("訂單時間", ""),
|
| 1047 |
"預定交期": o.get("預定交期", ""),
|
| 1048 |
"取貨方式": o.get("取貨方式", "自取"),
|
|
@@ -1114,18 +1118,35 @@ def autofill_delete_target(evt: gr.SelectData, df_data):
|
|
| 1114 |
except:
|
| 1115 |
return ""
|
| 1116 |
|
| 1117 |
-
def
|
| 1118 |
try:
|
| 1119 |
row_idx = evt.index[0]
|
| 1120 |
-
|
| 1121 |
-
|
| 1122 |
-
|
| 1123 |
-
|
| 1124 |
-
|
| 1125 |
-
|
| 1126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1127 |
except:
|
| 1128 |
-
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1129 |
|
| 1130 |
# ----------------------------
|
| 1131 |
# 🖥️ 網頁介面 (UI) 與 終極防護注射
|
|
@@ -1178,95 +1199,57 @@ custom_css = """
|
|
| 1178 |
.login-box { max-width: 400px; margin: 0 auto !important; padding: 20px; border: 1px solid #e5e7eb; border-radius: 10px; background: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
|
| 1179 |
"""
|
| 1180 |
|
| 1181 |
-
# 改用高頻 JS 注入 (完全脫離 Gradio 樣式封裝,直接修改原生 DOM 結構)
|
| 1182 |
kill_badge_js = """
|
| 1183 |
function() {
|
| 1184 |
-
// 網址整理
|
| 1185 |
if (window.location.search.includes("openExternalBrowser")) {
|
| 1186 |
const newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
| 1187 |
window.history.replaceState({path: newUrl}, "", newUrl);
|
| 1188 |
}
|
| 1189 |
-
|
| 1190 |
const nukeHF = () => {
|
| 1191 |
-
// 1. 強制移除已知標籤
|
| 1192 |
['huggingface-space-header', 'huggingface-workspace-badge', 'huggingface-space-badge'].forEach(tag => {
|
| 1193 |
document.querySelectorAll(tag).forEach(el => el.remove());
|
| 1194 |
});
|
| 1195 |
-
|
| 1196 |
-
// 2. 掃描 body 子元素,移除包含 HF 元素的外部容器 (徹底解決登入帳號、按鈕殘留)
|
| 1197 |
if (document.body) {
|
| 1198 |
Array.from(document.body.children).forEach(el => {
|
| 1199 |
if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || el.tagName === 'LINK') return;
|
| 1200 |
-
|
| 1201 |
-
// 安全檢查:絕對不可以刪除 Gradio 主容器
|
| 1202 |
if (el.classList.contains('gradio-container-wrap') || el.querySelector('.gradio-container') || el.id === 'custom-css-injector') return;
|
| 1203 |
-
|
| 1204 |
-
// 如果該容器內部帶有 HF 的網域、登入按鈕、或是 Duplicate 文字,直接殲滅
|
| 1205 |
const html = el.innerHTML || '';
|
| 1206 |
if (html.includes('huggingface.co') || html.includes('Sign in') || html.includes('Duplicate Space') || html.includes('Log in')) {
|
| 1207 |
el.style.setProperty('display', 'none', 'important');
|
| 1208 |
el.remove();
|
| 1209 |
}
|
| 1210 |
});
|
| 1211 |
-
|
| 1212 |
-
// 重置 HF Header 造成的版面往下推擠
|
| 1213 |
document.body.style.setProperty('padding-top', '0px', 'important');
|
| 1214 |
document.body.style.setProperty('margin-top', '0px', 'important');
|
| 1215 |
}
|
| 1216 |
-
|
| 1217 |
-
// 3. 清理 Gradio 內建的右上角「Use via API / Share」以及底部 Footer
|
| 1218 |
document.querySelectorAll('.gradio-container-header, footer').forEach(el => el.remove());
|
| 1219 |
-
|
| 1220 |
if (document.documentElement) {
|
| 1221 |
document.documentElement.style.setProperty('padding-top', '0px', 'important');
|
| 1222 |
}
|
| 1223 |
};
|
| 1224 |
-
|
| 1225 |
-
// 注入終極隱藏 CSS,以防 DOM 還沒被刪除前閃爍
|
| 1226 |
const style = document.createElement('style');
|
| 1227 |
style.innerHTML = `
|
| 1228 |
-
huggingface-space-header,
|
| 1229 |
-
|
| 1230 |
-
huggingface-space-badge {
|
| 1231 |
-
display: none !important;
|
| 1232 |
-
visibility: hidden !important;
|
| 1233 |
-
opacity: 0 !important;
|
| 1234 |
-
position: absolute !important;
|
| 1235 |
-
z-index: -99999 !important;
|
| 1236 |
-
width: 0px !important;
|
| 1237 |
-
height: 0px !important;
|
| 1238 |
-
pointer-events: none !important;
|
| 1239 |
}
|
| 1240 |
.gradio-container-header, footer { display: none !important; }
|
| 1241 |
`;
|
| 1242 |
document.head.appendChild(style);
|
| 1243 |
-
|
| 1244 |
-
// 建立微秒級巡邏器
|
| 1245 |
setInterval(nukeHF, 50);
|
| 1246 |
-
|
| 1247 |
-
// 綁定全域 DOM 變動監視器
|
| 1248 |
new MutationObserver(nukeHF).observe(document.documentElement, { childList: true, subtree: true });
|
| 1249 |
-
|
| 1250 |
nukeHF();
|
| 1251 |
return [];
|
| 1252 |
}
|
| 1253 |
"""
|
| 1254 |
|
| 1255 |
-
# 取消原本會噴 UserWarning 的 css 與 head 參數
|
| 1256 |
with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo_ui:
|
| 1257 |
-
|
| 1258 |
-
# 手動將自訂 CSS 注入
|
| 1259 |
gr.HTML(f"<style>{custom_css}</style>", elem_id="custom-css-injector")
|
| 1260 |
|
| 1261 |
-
# --- 全域狀態 ---
|
| 1262 |
menu_trigger = gr.State(value=0)
|
| 1263 |
current_user_state = gr.State(value="")
|
| 1264 |
|
| 1265 |
gr.Markdown("<h1 style='text-align: center;'>🛒 簡易訂單管理系統 (LINE 整合版)</h1>")
|
| 1266 |
|
| 1267 |
-
# ==========================
|
| 1268 |
-
# 登入介面 (Login View)
|
| 1269 |
-
# ==========================
|
| 1270 |
with gr.Column(visible=True, elem_classes="login-box") as login_container:
|
| 1271 |
gr.Markdown("<h2 style='text-align: center;'>🔐 會員登入</h2>")
|
| 1272 |
login_acc = gr.Textbox(label="會員帳號", placeholder="請輸入帳號")
|
|
@@ -1274,9 +1257,6 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo
|
|
| 1274 |
login_btn = gr.Button("登入系統", variant="primary", size="lg")
|
| 1275 |
login_msg = gr.Markdown(value="")
|
| 1276 |
|
| 1277 |
-
# ==========================
|
| 1278 |
-
# 主系統介面 (Main View) - 靜態分頁結構,內容動態渲染
|
| 1279 |
-
# ==========================
|
| 1280 |
with gr.Column(visible=False) as main_container:
|
| 1281 |
with gr.Row(elem_classes="menu-row"):
|
| 1282 |
user_greeting = gr.Markdown(value="")
|
|
@@ -1284,11 +1264,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo
|
|
| 1284 |
logout_btn = gr.Button("🚪 登出系統", size="sm", min_width=100, scale=0)
|
| 1285 |
|
| 1286 |
with gr.Tabs() as main_tabs:
|
| 1287 |
-
|
| 1288 |
-
# --- 📝 現場/網頁新增訂單 (所有登入者可見) ---
|
| 1289 |
with gr.TabItem("📝 現場/網頁新增訂單"):
|
| 1290 |
-
|
| 1291 |
-
# 只有商品選單區塊包在 render 裡,這樣更新菜單才不會破壞外層分頁!
|
| 1292 |
@gr.render(inputs=[current_user_state, menu_trigger])
|
| 1293 |
def render_order_form(current_user, m_trigger):
|
| 1294 |
if not current_user:
|
|
@@ -1342,8 +1318,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo
|
|
| 1342 |
|
| 1343 |
quantity_components = []
|
| 1344 |
pic_dir = os.path.join(BASE_DIR, "pic")
|
| 1345 |
-
if not os.path.exists(pic_dir):
|
| 1346 |
-
os.makedirs(pic_dir, exist_ok=True)
|
| 1347 |
|
| 1348 |
category_order, items_by_cat, flat_list = get_frontend_menu_items(user_level)
|
| 1349 |
|
|
@@ -1371,47 +1346,25 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo
|
|
| 1371 |
for ext in ['.jpg', '.jpeg', '.png', '.JPG', '.PNG']:
|
| 1372 |
temp_path = os.path.join(pic_dir, f"{item_name}{ext}")
|
| 1373 |
if os.path.exists(temp_path):
|
| 1374 |
-
found_img_path = temp_path
|
| 1375 |
-
break
|
| 1376 |
|
| 1377 |
if found_img_path:
|
| 1378 |
try:
|
| 1379 |
with open(found_img_path, "rb") as img_file:
|
| 1380 |
encoded_string = base64.b64encode(img_file.read()).decode('utf-8')
|
| 1381 |
mime_type = "image/png" if found_img_path.lower().endswith(".png") else "image/jpeg"
|
| 1382 |
-
|
| 1383 |
-
img_html = f"""
|
| 1384 |
-
<div style="width: 60px; height: 60px; border-radius: 8px; overflow: hidden; margin: 0 auto; pointer-events: none; background: white;">
|
| 1385 |
-
<img src="data:{mime_type};base64,{encoded_string}" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;">
|
| 1386 |
-
</div>
|
| 1387 |
-
"""
|
| 1388 |
gr.HTML(value=img_html)
|
| 1389 |
-
except
|
| 1390 |
first_char = item_name[0] if item_name else "品"
|
| 1391 |
-
|
| 1392 |
-
<div style="width: 60px; height: 60px; background-color: #e2e8f0; color: #475569; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-size: 24px; font-weight: bold; margin: 0 auto; pointer-events: none;">
|
| 1393 |
-
{first_char}
|
| 1394 |
-
</div>
|
| 1395 |
-
"""
|
| 1396 |
-
gr.HTML(value=placeholder_html)
|
| 1397 |
else:
|
| 1398 |
first_char = item_name[0] if item_name else "品"
|
| 1399 |
-
|
| 1400 |
-
<div style="width: 60px; height: 60px; background-color: #e2e8f0; color: #475569; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-size: 24px; font-weight: bold; margin: 0 auto; pointer-events: none;">
|
| 1401 |
-
{first_char}
|
| 1402 |
-
</div>
|
| 1403 |
-
"""
|
| 1404 |
-
gr.HTML(value=placeholder_html)
|
| 1405 |
|
| 1406 |
with gr.Column(scale=1, min_width=150, elem_classes="center-col"):
|
| 1407 |
spec_html = f"<span style='font-size: 0.85em; color: #ef4444; padding: 2px 6px; background: #fee2e2; border-radius: 4px;'>{spec}</span>" if spec else ""
|
| 1408 |
-
info_html = f""
|
| 1409 |
-
<div style='display: flex; width: 100%; align-items: center; text-align: center; margin: auto 0;'>
|
| 1410 |
-
<div style='flex: 1; font-weight: bold; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>{item_name}</div>
|
| 1411 |
-
<div style='flex: 1;'>{spec_html}</div>
|
| 1412 |
-
<div style='flex: 1; color: gray; font-size: 0.9em; white-space: nowrap;'>NT$ {price}</div>
|
| 1413 |
-
</div>
|
| 1414 |
-
"""
|
| 1415 |
gr.HTML(info_html)
|
| 1416 |
|
| 1417 |
with gr.Column(scale=0, min_width=140, elem_classes="center-col"):
|
|
@@ -1420,27 +1373,23 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo
|
|
| 1420 |
qty_box = gr.Textbox(value="0", show_label=False, interactive=True, elem_classes="qty-input", container=False, min_width=45)
|
| 1421 |
plus_btn = gr.Button("➕", elem_classes="action-btn", variant="secondary", min_width=36)
|
| 1422 |
|
| 1423 |
-
minus_btn.click(
|
| 1424 |
-
|
| 1425 |
-
js="(v) => { let n = parseInt(v || 0); return Math.max(0, n - 1).toString(); }"
|
| 1426 |
-
)
|
| 1427 |
-
plus_btn.click(
|
| 1428 |
-
fn=None, inputs=[qty_box], outputs=[qty_box],
|
| 1429 |
-
js="(v) => { let n = parseInt(v || 0); return (n + 1).toString(); }"
|
| 1430 |
-
)
|
| 1431 |
-
|
| 1432 |
quantity_components.append(qty_box)
|
| 1433 |
|
| 1434 |
notes = gr.Textbox(label="備註", placeholder="例如:少冰微糖...")
|
| 1435 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1436 |
status_msg = gr.Textbox(label="系統狀態", interactive=False)
|
| 1437 |
|
| 1438 |
inputs_list = [current_user_state, customer_name, pickup_method, delivery_location, delivery_month, delivery_day, delivery_time, notes] + quantity_components
|
| 1439 |
-
outputs_list = [status_msg] + quantity_components
|
| 1440 |
|
| 1441 |
-
|
|
|
|
| 1442 |
|
| 1443 |
-
# --- 📊 系統管理與總覽 (靜態放置,動態隱藏) ---
|
| 1444 |
with gr.TabItem("📊 系統管理與總覽", visible=False, id="admin_tab") as admin_tab:
|
| 1445 |
with gr.Accordion("☁️ 雲端備份與還原 (點擊展開/收合)", open=True):
|
| 1446 |
with gr.Row():
|
|
@@ -1458,57 +1407,88 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo
|
|
| 1458 |
delivery_filter = gr.Dropdown(choices=["所有交期"], value="所有交期", label="🕒 篩選預定交期", interactive=True)
|
| 1459 |
refresh_btn = gr.Button("🔄 抓取最新訂單", variant="secondary")
|
| 1460 |
|
| 1461 |
-
orders_table = gr.Dataframe(value=get_orders_data(), headers=["訂單編號", "訂單時間", "預定交期", "取貨方式", "送貨地點", "顧客姓名", "商品", "單價", "成本", "數量", "總價", "總成本", "備註"], interactive=False)
|
| 1462 |
|
| 1463 |
gr.Markdown("---")
|
| 1464 |
-
gr.Markdown("###
|
| 1465 |
with gr.Row(elem_classes="menu-row"):
|
| 1466 |
with gr.Column(scale=2):
|
| 1467 |
-
delete_target = gr.Textbox(label="
|
| 1468 |
with gr.Column(scale=1):
|
| 1469 |
-
|
| 1470 |
with gr.Column(scale=1):
|
| 1471 |
-
|
|
|
|
|
|
|
| 1472 |
|
| 1473 |
-
admin_status_msg = gr.Textbox(label="
|
|
|
|
| 1474 |
|
| 1475 |
with gr.TabItem("📝 菜單管理"):
|
| 1476 |
-
gr.Markdown("
|
| 1477 |
|
| 1478 |
with gr.Row():
|
| 1479 |
menu_cat_filter = gr.Dropdown(choices=get_menu_cat_choices(), value="全部分類", label="🔍 篩選分類", interactive=True)
|
| 1480 |
menu_lvl_filter = gr.Dropdown(choices=get_menu_lvl_choices(), value="全部等級", label="🏅 篩選等級", interactive=True)
|
| 1481 |
menu_item_filter = gr.Dropdown(choices=get_menu_item_choices(), value="所有品項", label="🍔 篩選品項", interactive=True)
|
| 1482 |
-
menu_refresh_btn = gr.Button("🔄 刷新
|
| 1483 |
|
| 1484 |
menu_table = gr.Dataframe(
|
| 1485 |
value=get_menu_df(),
|
| 1486 |
headers=["流水號", "啟用", "適用等級", "分類", "品項", "規格", "價格", "成本", "備註"],
|
| 1487 |
datatype=["number", "bool", "str", "str", "str", "str", "number", "number", "str"],
|
| 1488 |
-
interactive=
|
| 1489 |
column_widths=["6%", "6%", "8%", "12%", "20%", "15%", "8%", "8%", "17%"]
|
| 1490 |
)
|
| 1491 |
-
save_menu_btn = gr.Button("💾 儲存菜單並更新", variant="primary")
|
| 1492 |
|
| 1493 |
gr.Markdown("---")
|
| 1494 |
-
gr.Markdown("###
|
| 1495 |
-
with gr.
|
| 1496 |
-
with gr.
|
| 1497 |
-
|
| 1498 |
-
|
| 1499 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1500 |
|
| 1501 |
with gr.TabItem("👥 會員資料管理"):
|
| 1502 |
-
gr.Markdown("
|
| 1503 |
|
| 1504 |
members_table = gr.Dataframe(
|
| 1505 |
value=get_members_df(),
|
| 1506 |
headers=["會員登入帳號", "密碼", "會員等級", "顧客姓名", "送貨地點"],
|
| 1507 |
datatype=["str", "str", "str", "str", "str"],
|
| 1508 |
-
interactive=
|
| 1509 |
column_widths=["20%", "20%", "10%", "25%", "25%"]
|
| 1510 |
)
|
| 1511 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1512 |
members_status = gr.Markdown()
|
| 1513 |
|
| 1514 |
with gr.TabItem("🔑 安全性設定"):
|
|
@@ -1522,129 +1502,74 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo
|
|
| 1522 |
update_pwd_btn = gr.Button("💾 確認更新密碼", variant="primary")
|
| 1523 |
pwd_update_status = gr.Markdown()
|
| 1524 |
|
| 1525 |
-
# --- Admin
|
| 1526 |
-
|
| 1527 |
-
|
| 1528 |
-
|
| 1529 |
-
|
| 1530 |
-
|
| 1531 |
-
|
| 1532 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter], outputs=[orders_table, revenue_display]
|
| 1533 |
-
)
|
| 1534 |
-
item_filter.change(
|
| 1535 |
-
fn=lambda c, t, i, d: (gr.update(value=get_orders_data(c, t, i, d)), gr.update(value=get_revenue(c, t, i, d))),
|
| 1536 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter], outputs=[orders_table, revenue_display]
|
| 1537 |
-
)
|
| 1538 |
-
delivery_filter.change(
|
| 1539 |
-
fn=lambda c, t, i, d: (gr.update(value=get_orders_data(c, t, i, d)), gr.update(value=get_revenue(c, t, i, d))),
|
| 1540 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter], outputs=[orders_table, revenue_display]
|
| 1541 |
-
)
|
| 1542 |
|
| 1543 |
-
refresh_btn.click(
|
| 1544 |
-
fn=refresh_data,
|
| 1545 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter],
|
| 1546 |
-
outputs=[orders_table, revenue_display, customer_filter, time_filter, item_filter, delivery_filter]
|
| 1547 |
-
)
|
| 1548 |
|
| 1549 |
-
#
|
| 1550 |
-
orders_table.select(
|
| 1551 |
-
|
| 1552 |
-
)
|
| 1553 |
|
| 1554 |
delete_single_btn.click(
|
| 1555 |
-
fn=delete_single_order,
|
| 1556 |
-
|
| 1557 |
-
outputs=[admin_status_msg, orders_table, revenue_display, delete_target],
|
| 1558 |
-
js="(target, c_filter, t_filter, i_filter, d_filter) => { if (!target) { return [target, c_filter, t_filter, i_filter, d_filter]; } return confirm('⚠️ 確認要刪除訂單編號 [' + target + '] 嗎?此動作無法復原!') ? [target, c_filter, t_filter, i_filter, d_filter] : ['__CANCEL__', c_filter, t_filter, i_filter, d_filter]; }"
|
| 1559 |
)
|
| 1560 |
-
|
| 1561 |
clear_btn.click(
|
| 1562 |
-
fn=clear_orders,
|
| 1563 |
-
|
| 1564 |
-
outputs=[admin_status_msg, orders_table, revenue_display, customer_filter, time_filter, item_filter, delivery_filter],
|
| 1565 |
-
js="(filter) => { return confirm('🚨 極度危險:確定要清空【所有】訂單資料嗎?此動作無法復原!') ? [filter] : ['__CANCEL__']; }"
|
| 1566 |
)
|
| 1567 |
|
| 1568 |
-
#
|
| 1569 |
-
menu_cat_filter
|
| 1570 |
-
fn=get_menu_df, inputs=[menu_cat_filter, menu_lvl_filter, menu_item_filter], outputs=[menu_table]
|
| 1571 |
-
)
|
| 1572 |
-
menu_lvl_filter.change(
|
| 1573 |
-
fn=get_menu_df, inputs=[menu_cat_filter, menu_lvl_filter, menu_item_filter], outputs=[menu_table]
|
| 1574 |
-
)
|
| 1575 |
-
menu_item_filter.change(
|
| 1576 |
-
fn=get_menu_df, inputs=[menu_cat_filter, menu_lvl_filter, menu_item_filter], outputs=[menu_table]
|
| 1577 |
-
)
|
| 1578 |
|
| 1579 |
-
|
| 1580 |
-
|
| 1581 |
-
|
| 1582 |
-
outputs=[menu_table, menu_cat_filter, menu_lvl_filter, menu_item_filter]
|
| 1583 |
-
)
|
| 1584 |
|
| 1585 |
-
|
| 1586 |
-
|
| 1587 |
-
|
|
|
|
| 1588 |
)
|
| 1589 |
|
| 1590 |
menu_delete_btn.click(
|
| 1591 |
fn=delete_menu_item,
|
| 1592 |
-
inputs=[
|
| 1593 |
-
outputs=[global_sys_msg, menu_table,
|
| 1594 |
-
js="(
|
| 1595 |
-
)
|
| 1596 |
-
|
| 1597 |
-
# 備份按鈕,傳入目前的表單資料
|
| 1598 |
-
github_btn.click(
|
| 1599 |
-
fn=backup_and_push_to_github,
|
| 1600 |
-
inputs=[menu_table, menu_cat_filter, menu_lvl_filter, menu_item_filter, members_table],
|
| 1601 |
-
outputs=[github_log_output]
|
| 1602 |
-
)
|
| 1603 |
-
|
| 1604 |
-
save_menu_btn.click(
|
| 1605 |
-
fn=update_menu,
|
| 1606 |
-
inputs=[menu_table, menu_cat_filter, menu_lvl_filter, menu_item_filter],
|
| 1607 |
-
outputs=[global_sys_msg, menu_table, menu_delete_target, menu_trigger, menu_cat_filter, menu_lvl_filter, menu_item_filter]
|
| 1608 |
-
)
|
| 1609 |
-
|
| 1610 |
-
restore_btn.click(
|
| 1611 |
-
fn=restore_from_backup,
|
| 1612 |
-
inputs=[],
|
| 1613 |
-
outputs=[global_sys_msg, menu_table, members_table, menu_trigger, menu_cat_filter, menu_lvl_filter, menu_item_filter]
|
| 1614 |
)
|
| 1615 |
|
| 1616 |
-
|
| 1617 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1618 |
)
|
| 1619 |
|
| 1620 |
-
|
| 1621 |
-
|
| 1622 |
-
)
|
|
|
|
| 1623 |
|
| 1624 |
-
#
|
| 1625 |
-
login_btn.click(
|
| 1626 |
-
|
| 1627 |
-
|
| 1628 |
-
outputs=[login_container, main_container, admin_tab, login_msg, current_user_state, user_greeting, global_sys_msg]
|
| 1629 |
-
)
|
| 1630 |
-
login_pwd.submit(
|
| 1631 |
-
fn=do_login,
|
| 1632 |
-
inputs=[login_acc, login_pwd],
|
| 1633 |
-
outputs=[login_container, main_container, admin_tab, login_msg, current_user_state, user_greeting, global_sys_msg]
|
| 1634 |
-
)
|
| 1635 |
-
|
| 1636 |
-
logout_btn.click(
|
| 1637 |
-
fn=logout,
|
| 1638 |
-
inputs=[],
|
| 1639 |
-
outputs=[login_container, main_container, admin_tab, login_acc, login_pwd, login_msg, current_user_state, user_greeting, global_sys_msg]
|
| 1640 |
-
)
|
| 1641 |
|
| 1642 |
-
# 執行啟動時自動掛載暴力防護 JS (取代無效的 head 參數)
|
| 1643 |
demo_ui.load(fn=None, js=kill_badge_js)
|
| 1644 |
|
| 1645 |
-
# ----------------------------
|
| 1646 |
-
# 🚀 啟動伺服器
|
| 1647 |
-
# ----------------------------
|
| 1648 |
app = gr.mount_gradio_app(custom_api, demo_ui.queue(), path="/")
|
| 1649 |
|
| 1650 |
if __name__ == "__main__":
|
|
|
|
| 84 |
loaded_data = df.to_dict('records')
|
| 85 |
|
| 86 |
for o in loaded_data:
|
| 87 |
+
o["狀態"] = str(o.get("狀態", "處理中"))
|
| 88 |
o["單價"] = int(float(o.get("單價", 0) or 0))
|
| 89 |
o["成本"] = int(float(o.get("成本", 0) or 0))
|
| 90 |
o["數量"] = int(float(o.get("數量", 0) or 0))
|
|
|
|
| 100 |
print("⚠️ 備份檔是空的 (EmptyDataError),無法還原。")
|
| 101 |
except Exception as e:
|
| 102 |
print(f"❌ 從 CSV 還原失敗: {e}")
|
| 103 |
+
|
| 104 |
+
# 確保所有歷史訂單都有狀態欄位
|
| 105 |
+
for o in loaded_data:
|
| 106 |
+
if "狀態" not in o:
|
| 107 |
+
o["狀態"] = "處理中"
|
| 108 |
|
| 109 |
return loaded_data
|
| 110 |
|
|
|
|
| 119 |
|
| 120 |
def load_menu():
|
| 121 |
loaded_menu = []
|
|
|
|
| 122 |
if os.path.exists(MENU_FILE):
|
| 123 |
try:
|
| 124 |
with open(MENU_FILE, "r", encoding="utf-8") as f:
|
|
|
|
| 255 |
cat = cat.strip() if cat.strip() else "未分類"
|
| 256 |
if cat not in category_order:
|
| 257 |
category_order.append(cat)
|
|
|
|
| 258 |
items_by_cat.setdefault(cat, []).append((details.get("name", "未命名"), details))
|
| 259 |
|
| 260 |
flat_list = []
|
|
|
|
| 300 |
v.get("note", "")
|
| 301 |
])
|
| 302 |
|
| 303 |
+
# UI/UX 優化:移除多餘空白行,改為表單新增
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
df = pd.DataFrame(data, columns=["流水號", "啟用", "適用等級", "分類", "品項", "規格", "價格", "成本", "備註"])
|
| 305 |
+
if not df.empty:
|
| 306 |
+
df["品項"] = df["品項"].astype(str)
|
| 307 |
return df
|
| 308 |
|
| 309 |
def get_members_df():
|
| 310 |
data = []
|
| 311 |
for acc, info in MEMBERS.items():
|
| 312 |
data.append([acc, info.get("password", ""), info.get("level", "1"), info.get("name", ""), info.get("location", "")])
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
df = pd.DataFrame(data, columns=["會員登入帳號", "密碼", "會員等級", "顧客姓名", "送貨地點"])
|
| 315 |
+
if not df.empty:
|
| 316 |
+
df["顧客姓名"] = df["顧客姓名"].astype(str)
|
| 317 |
return df
|
| 318 |
|
| 319 |
def save_menu_to_file():
|
|
|
|
| 339 |
except Exception as e:
|
| 340 |
print(f"儲存會員失敗: {e}")
|
| 341 |
|
| 342 |
+
# 單一品項表單儲存機制
|
| 343 |
+
def save_single_menu_item(seq, enable, lvl, cat, name, spec, price, cost, note, cat_f, lvl_f, item_f):
|
| 344 |
global MENU
|
| 345 |
+
name = str(name).strip() if name else ""
|
| 346 |
+
if not name:
|
| 347 |
+
return gr.update(value="❌ 錯誤:品項名稱不可為空!"), gr.update(), gr.update(), gr.update(), gr.update()
|
| 348 |
+
|
| 349 |
+
spec = str(spec).strip() if spec else ""
|
| 350 |
+
cat = str(cat).strip() if cat else "未分類"
|
| 351 |
+
lvl = str(lvl).strip() if lvl else "全部"
|
| 352 |
+
note = str(note).strip() if note else ""
|
| 353 |
+
try: seq = int(seq)
|
| 354 |
+
except: seq = 999
|
| 355 |
+
try: price = int(price)
|
| 356 |
+
except: price = 0
|
| 357 |
+
try: cost = int(cost)
|
| 358 |
+
except: cost = 0
|
| 359 |
+
|
| 360 |
+
found = False
|
| 361 |
+
for m in MENU:
|
| 362 |
+
if m.get("name") == name and m.get("spec", "") == spec:
|
| 363 |
+
m.update({
|
| 364 |
+
"seq": seq, "enable": enable, "level": lvl,
|
| 365 |
+
"category": cat, "price": price, "cost": cost, "note": note
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
})
|
| 367 |
+
found = True
|
| 368 |
+
break
|
| 369 |
|
| 370 |
+
if not found:
|
| 371 |
+
MENU.append({
|
| 372 |
+
"name": name, "price": price, "cost": cost,
|
| 373 |
+
"enable": enable, "level": lvl, "seq": seq,
|
| 374 |
+
"category": cat, "spec": spec, "note": note
|
| 375 |
+
})
|
| 376 |
+
|
| 377 |
+
# 自動重排流水號
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
sorted_menu = sorted(MENU, key=lambda x: x.get("seq", 999))
|
| 379 |
for i, item_dict in enumerate(sorted_menu):
|
| 380 |
item_dict["seq"] = i + 1
|
|
|
|
| 382 |
MENU.clear()
|
| 383 |
MENU.extend(sorted_menu)
|
| 384 |
save_menu_to_file()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
|
| 386 |
new_trigger = datetime.now(TAIPEI_TZ).timestamp()
|
| 387 |
|
|
|
|
| 388 |
cats = get_menu_cat_choices()
|
| 389 |
lvls = get_menu_lvl_choices()
|
| 390 |
items = get_menu_item_choices()
|
|
|
|
| 391 |
if cat_f not in cats: cat_f = "全部分類"
|
| 392 |
if lvl_f not in lvls: lvl_f = "全部等級"
|
| 393 |
if item_f not in items: item_f = "所有品項"
|
| 394 |
+
|
| 395 |
+
msg = f"✅ 品項 {name} ({spec}) 已儲存成功!({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})"
|
| 396 |
return (
|
| 397 |
+
gr.update(value=msg),
|
| 398 |
+
get_menu_df(cat_f, lvl_f, item_f),
|
|
|
|
|
|
|
| 399 |
gr.update(choices=cats, value=cat_f),
|
| 400 |
gr.update(choices=lvls, value=lvl_f),
|
| 401 |
+
gr.update(choices=items, value=item_f),
|
| 402 |
+
new_trigger
|
| 403 |
)
|
| 404 |
|
| 405 |
+
def save_single_member(acc, pwd, lvl, name, loc):
|
| 406 |
+
global MEMBERS
|
| 407 |
+
acc = str(acc).strip() if acc else ""
|
| 408 |
+
if not acc:
|
| 409 |
+
return gr.update(value="❌ 錯誤:會員登入帳號不可為空!"), gr.update()
|
| 410 |
+
|
| 411 |
+
MEMBERS[acc] = {
|
| 412 |
+
"password": str(pwd).strip() if pwd else "",
|
| 413 |
+
"level": str(lvl).strip() if lvl else "1",
|
| 414 |
+
"name": str(name).strip() if name else "",
|
| 415 |
+
"location": str(loc).strip() if loc else ""
|
| 416 |
+
}
|
| 417 |
+
save_members_to_file()
|
| 418 |
+
|
| 419 |
+
msg = f"✅ 會員 {acc} 已儲存成功!({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})"
|
| 420 |
+
return gr.update(value=msg), get_members_df()
|
| 421 |
+
|
| 422 |
+
def delete_single_member(acc):
|
| 423 |
+
global MEMBERS
|
| 424 |
+
acc = str(acc).strip() if acc else ""
|
| 425 |
+
if not acc:
|
| 426 |
+
return gr.update(value="❌ 錯誤:請先選擇要刪除的會員帳號!"), gr.update()
|
| 427 |
+
|
| 428 |
+
if acc in MEMBERS:
|
| 429 |
+
del MEMBERS[acc]
|
| 430 |
+
save_members_to_file()
|
| 431 |
+
return gr.update(value=f"🗑️ 會員 {acc} 已刪除!"), get_members_df()
|
| 432 |
+
return gr.update(value=f"❌ 找不到會員 {acc}"), gr.update()
|
| 433 |
+
|
| 434 |
def refresh_menu_filters(cat_f, lvl_f, item_f):
|
| 435 |
cats = get_menu_cat_choices()
|
| 436 |
lvls = get_menu_lvl_choices()
|
|
|
|
| 456 |
if not target_str:
|
| 457 |
return gr.update(value="❌ 錯誤:請點擊表格選擇或輸入要刪除的品項!"), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
| 458 |
|
|
|
|
| 459 |
parts = target_str.split(" | ")
|
| 460 |
target_name = parts[0].strip()
|
| 461 |
target_spec = parts[1].strip() if len(parts) > 1 else ""
|
|
|
|
| 464 |
new_menu = []
|
| 465 |
deleted = False
|
| 466 |
|
|
|
|
| 467 |
for m in MENU:
|
| 468 |
if not deleted and m.get("name") == target_name and m.get("spec", "") == target_spec:
|
| 469 |
deleted = True
|
|
|
|
| 473 |
if len(new_menu) == original_len:
|
| 474 |
return gr.update(value=f"❌ 找不到對應的品項:{target_str}"), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
| 475 |
|
|
|
|
| 476 |
for i, m in enumerate(new_menu):
|
| 477 |
m["seq"] = i + 1
|
| 478 |
|
|
|
|
| 481 |
save_menu_to_file()
|
| 482 |
|
| 483 |
new_trigger = datetime.now(TAIPEI_TZ).timestamp()
|
|
|
|
|
|
|
| 484 |
cats = get_menu_cat_choices()
|
| 485 |
lvls = get_menu_lvl_choices()
|
| 486 |
items = get_menu_item_choices()
|
|
|
|
| 487 |
if cat_f not in cats: cat_f = "全部分類"
|
| 488 |
if lvl_f not in lvls: lvl_f = "全部等級"
|
| 489 |
if item_f not in items: item_f = "所有品項"
|
|
|
|
| 491 |
return (
|
| 492 |
gr.update(value=f"✅ 成功刪除品項:{target_str},且流水號已自動重排!({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})"),
|
| 493 |
get_menu_df(cat_f, lvl_f, item_f),
|
| 494 |
+
gr.update(value=""),
|
| 495 |
new_trigger,
|
| 496 |
gr.update(choices=cats, value=cat_f),
|
| 497 |
gr.update(choices=lvls, value=lvl_f),
|
| 498 |
gr.update(choices=items, value=item_f)
|
| 499 |
)
|
| 500 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 501 |
# ----------------------------
|
| 502 |
# 🤖 LINE Bot 邏輯
|
| 503 |
# ----------------------------
|
|
|
|
| 523 |
item_name = parts[1]
|
| 524 |
quantity = int(parts[2])
|
| 525 |
|
|
|
|
| 526 |
matched_item = None
|
| 527 |
for menu_item in MENU:
|
| 528 |
if menu_item.get("name") == item_name and menu_item.get("enable", True):
|
|
|
|
| 544 |
|
| 545 |
orders_db.append({
|
| 546 |
"訂單編號": order_id,
|
| 547 |
+
"狀態": "處理中",
|
| 548 |
"時間": timestamp,
|
| 549 |
"預定交期": "盡快 (LINE)",
|
| 550 |
"取貨方式": "自取",
|
|
|
|
| 563 |
|
| 564 |
reply_text = f"✅ 訂單成立!\n您訂購了 {item_name} x {quantity}。\n總金額為 {total} 元,請稍候為您準備!"
|
| 565 |
else:
|
|
|
|
| 566 |
active_item_names = list(dict.fromkeys([v.get("name") for v in MENU if v.get("enable", True)]))
|
| 567 |
reply_text = f"❌ 找不到商品『{item_name}』,或該商品目前未提供!\n目前供應:{', '.join(active_item_names)}"
|
| 568 |
except Exception:
|
|
|
|
| 629 |
filtered_db = [o for o in filtered_db if o.get("預定交期") == filter_delivery]
|
| 630 |
|
| 631 |
if not filtered_db:
|
| 632 |
+
return [[""] * 14]
|
| 633 |
|
| 634 |
return [[
|
| 635 |
o.get("訂單編號", ""),
|
| 636 |
+
o.get("狀態", "處理中"),
|
| 637 |
o.get("時間", "") or o.get("訂單時間", ""),
|
| 638 |
o.get("預定交期", ""),
|
| 639 |
o.get("取貨方式", "自取"),
|
|
|
|
| 710 |
loaded_data = df.to_dict('records')
|
| 711 |
|
| 712 |
for o in loaded_data:
|
| 713 |
+
o["狀態"] = str(o.get("狀態", "處理中"))
|
| 714 |
o["單價"] = int(float(o.get("單價", 0) or 0))
|
| 715 |
o["成本"] = int(float(o.get("成本", 0) or 0))
|
| 716 |
o["數量"] = int(float(o.get("數量", 0) or 0))
|
|
|
|
| 781 |
except Exception as e:
|
| 782 |
msg += f"\n❌ 會員資料還原失敗:{e}"
|
| 783 |
|
|
|
|
| 784 |
cats = get_menu_cat_choices()
|
| 785 |
lvls = get_menu_lvl_choices()
|
| 786 |
items = get_menu_item_choices()
|
|
|
|
| 795 |
gr.update(choices=items, value="所有品項")
|
| 796 |
)
|
| 797 |
|
| 798 |
+
# 購物車確認與明細結算函數
|
| 799 |
+
def calc_cart_summary(current_user, c_name, p_method, d_location, d_month, d_day, d_time, nts, *qty_args):
|
| 800 |
+
user_level = "全部"
|
| 801 |
+
if current_user == "admin": user_level = "admin"
|
| 802 |
+
elif current_user in MEMBERS: user_level = MEMBERS[current_user].get("level", "1")
|
| 803 |
+
|
| 804 |
+
_, _, flat_list = get_frontend_menu_items(user_level)
|
| 805 |
+
c_name = str(c_name).strip() if c_name else ""
|
| 806 |
+
|
| 807 |
+
quantities = []
|
| 808 |
+
for q in qty_args:
|
| 809 |
+
try: quantities.append(int(q))
|
| 810 |
+
except: quantities.append(0)
|
| 811 |
+
|
| 812 |
+
if sum(quantities) == 0:
|
| 813 |
+
return "❌ **購物車是空的,請先在上方選擇商品數量!**", gr.update(visible=False)
|
| 814 |
+
|
| 815 |
+
if not c_name:
|
| 816 |
+
return "❌ **請先輸入上方的「顧客姓名」才能結帳!**", gr.update(visible=False)
|
| 817 |
+
|
| 818 |
+
total_order_price = 0
|
| 819 |
+
items_desc = []
|
| 820 |
+
for i, qty in enumerate(quantities):
|
| 821 |
+
if qty > 0:
|
| 822 |
+
item_name, details = flat_list[i]
|
| 823 |
+
price = details["price"]
|
| 824 |
+
spec = details.get("spec", "")
|
| 825 |
+
item_note = f" ({spec})" if spec else ""
|
| 826 |
+
total_price = price * qty
|
| 827 |
+
total_order_price += total_price
|
| 828 |
+
items_desc.append(f"- ✅ **{item_name}**{item_note} x {qty} = {total_price} 元")
|
| 829 |
+
|
| 830 |
+
md = "### 🛒 購物車明細確認\n"
|
| 831 |
+
md += f"**顧客姓名**:{c_name} \n"
|
| 832 |
+
md += f"**取貨方式**:{p_method}" + (f" (地點:{d_location})" if p_method == "送貨" else "") + " \n"
|
| 833 |
+
md += f"**預定交期**:{d_month}{d_day} {d_time} \n"
|
| 834 |
+
md += "**備註留言**:" + (nts if nts else "無") + " \n\n"
|
| 835 |
+
md += "**【已選商品】**\n"
|
| 836 |
+
md += "\n".join(items_desc)
|
| 837 |
+
md += f"\n\n💰 **結帳總金額:NT$ {total_order_price}**"
|
| 838 |
+
|
| 839 |
+
return md, gr.update(visible=True)
|
| 840 |
+
|
| 841 |
def add_order(current_user, c_name, p_method, d_location, d_month, d_day, d_time, nts, *qty_args):
|
| 842 |
try:
|
| 843 |
user_level = "全部"
|
|
|
|
| 859 |
|
| 860 |
reset_qtys = [gr.update(value="0") for _ in range(len(flat_list))]
|
| 861 |
|
|
|
|
|
|
|
|
|
|
| 862 |
timestamp = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M:%S")
|
| 863 |
total_order_price = 0
|
| 864 |
items_desc = []
|
|
|
|
| 865 |
|
| 866 |
for i, qty in enumerate(quantities):
|
| 867 |
if qty > 0:
|
|
|
|
| 868 |
item_name, details = flat_list[i]
|
| 869 |
price = details["price"]
|
| 870 |
cost = details.get("cost", 0)
|
|
|
|
| 880 |
|
| 881 |
orders_db.append({
|
| 882 |
"訂單編號": order_id,
|
| 883 |
+
"狀態": "處理中",
|
| 884 |
"時間": timestamp,
|
| 885 |
"預定交期": delivery_date,
|
| 886 |
"取貨方式": p_method,
|
|
|
|
| 894 |
"總成本": total_cost,
|
| 895 |
"備註": final_note
|
| 896 |
})
|
|
|
|
| 897 |
desc = f"{item_name}{item_note}x{qty}"
|
| 898 |
items_desc.append(desc)
|
| 899 |
|
|
|
|
|
|
|
|
|
|
| 900 |
save_orders()
|
| 901 |
+
msg = f"🎉 訂單已成功送出!{c_name} 共訂購了 {', '.join(items_desc)},總計 {total_order_price} 元。"
|
| 902 |
|
| 903 |
+
return [gr.update(value=msg), gr.update(visible=False), gr.update(value="### 🛒 購物車明細\n*訂單已送出,請重新選擇商品*")] + reset_qtys
|
| 904 |
|
| 905 |
except Exception as e:
|
| 906 |
err_msg = f"❌ 系統異常:{str(e)}"
|
| 907 |
+
reset_qtys = [gr.update(value="0") for _ in range(len(flat_list))]
|
| 908 |
+
return [gr.update(value=err_msg), gr.update(visible=False), gr.update(value="### 🛒 購物車明細\n*發生錯誤*")] + reset_qtys
|
| 909 |
+
|
| 910 |
+
def update_order_status(order_id, new_status, current_filter, current_time_filter, current_item_filter, current_delivery_filter):
|
| 911 |
+
if order_id == "__CANCEL__": return gr.update(), gr.update(), gr.update()
|
| 912 |
+
order_id = str(order_id).strip()
|
| 913 |
+
if not order_id: return gr.update(value="❌ 錯誤:請先點擊上方表格選擇訂單!"), gr.update(), gr.update()
|
| 914 |
|
| 915 |
+
found = False
|
| 916 |
+
for o in orders_db:
|
| 917 |
+
if o.get("訂單編號") == order_id:
|
| 918 |
+
o["狀態"] = new_status
|
| 919 |
+
found = True
|
| 920 |
+
|
| 921 |
+
if not found:
|
| 922 |
+
return gr.update(value=f"❌ 找不到訂單編號:{order_id}"), gr.update(), gr.update()
|
| 923 |
|
| 924 |
+
save_orders()
|
| 925 |
+
return (
|
| 926 |
+
gr.update(value=f"✅ 成功將訂單 {order_id} 標記為『{new_status}』"),
|
| 927 |
+
gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 928 |
+
gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter))
|
| 929 |
+
)
|
| 930 |
|
| 931 |
def delete_single_order(order_id, current_filter, current_time_filter, current_item_filter, current_delivery_filter):
|
| 932 |
if order_id == "__CANCEL__":
|
|
|
|
| 944 |
return gr.update(value=f"❌ 找不到訂單編號:{order_id}"), gr.update(), gr.update(), gr.update()
|
| 945 |
|
| 946 |
save_orders()
|
|
|
|
| 947 |
return (
|
| 948 |
+
gr.update(value=f"✅ 成功永久刪除訂單:{order_id}"),
|
| 949 |
gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 950 |
gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 951 |
gr.update(value="")
|
|
|
|
| 1035 |
return True, f"✅ 成功: {command}\n> {result.stdout.strip()}"
|
| 1036 |
return False, f"❌ 失敗: {command}\n> {result.stderr.strip()}"
|
| 1037 |
|
| 1038 |
+
def backup_and_push_to_github():
|
| 1039 |
log_messages = ["🚀 開始備份...\n" + "-"*40]
|
| 1040 |
+
log_messages.append("💾 記憶體狀態已是最新的,準備儲存檔案。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1041 |
|
| 1042 |
if not orders_db:
|
| 1043 |
+
df = pd.DataFrame(columns=["訂單編號", "狀態", "訂單時間", "預定交期", "取貨方式", "送貨地點", "顧客姓名", "商品", "單價", "成本", "數量", "總價", "總成本", "備註"])
|
| 1044 |
else:
|
| 1045 |
export_data = []
|
| 1046 |
for o in orders_db:
|
| 1047 |
export_data.append({
|
| 1048 |
"訂單編號": o.get("訂單編號", ""),
|
| 1049 |
+
"狀態": o.get("狀態", "處理中"),
|
| 1050 |
"訂單時間": o.get("時間", "") or o.get("訂單時間", ""),
|
| 1051 |
"預定交期": o.get("預定交期", ""),
|
| 1052 |
"取貨方式": o.get("取貨方式", "自取"),
|
|
|
|
| 1118 |
except:
|
| 1119 |
return ""
|
| 1120 |
|
| 1121 |
+
def autofill_menu_form(evt: gr.SelectData, df_data):
|
| 1122 |
try:
|
| 1123 |
row_idx = evt.index[0]
|
| 1124 |
+
return (
|
| 1125 |
+
df_data.iloc[row_idx, 0], # seq
|
| 1126 |
+
df_data.iloc[row_idx, 1], # enable
|
| 1127 |
+
df_data.iloc[row_idx, 2], # level
|
| 1128 |
+
df_data.iloc[row_idx, 3], # category
|
| 1129 |
+
df_data.iloc[row_idx, 4], # name
|
| 1130 |
+
df_data.iloc[row_idx, 5], # spec
|
| 1131 |
+
df_data.iloc[row_idx, 6], # price
|
| 1132 |
+
df_data.iloc[row_idx, 7], # cost
|
| 1133 |
+
df_data.iloc[row_idx, 8] # note
|
| 1134 |
+
)
|
| 1135 |
except:
|
| 1136 |
+
return 999, True, "全部", "未分類", "", "", 0, 0, ""
|
| 1137 |
+
|
| 1138 |
+
def autofill_member_form(evt: gr.SelectData, df_data):
|
| 1139 |
+
try:
|
| 1140 |
+
row_idx = evt.index[0]
|
| 1141 |
+
return (
|
| 1142 |
+
df_data.iloc[row_idx, 0], # acc
|
| 1143 |
+
df_data.iloc[row_idx, 1], # pwd
|
| 1144 |
+
df_data.iloc[row_idx, 2], # lvl
|
| 1145 |
+
df_data.iloc[row_idx, 3], # name
|
| 1146 |
+
df_data.iloc[row_idx, 4] # loc
|
| 1147 |
+
)
|
| 1148 |
+
except:
|
| 1149 |
+
return "", "", "1", "", ""
|
| 1150 |
|
| 1151 |
# ----------------------------
|
| 1152 |
# 🖥️ 網頁介面 (UI) 與 終極防護注射
|
|
|
|
| 1199 |
.login-box { max-width: 400px; margin: 0 auto !important; padding: 20px; border: 1px solid #e5e7eb; border-radius: 10px; background: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
|
| 1200 |
"""
|
| 1201 |
|
|
|
|
| 1202 |
kill_badge_js = """
|
| 1203 |
function() {
|
|
|
|
| 1204 |
if (window.location.search.includes("openExternalBrowser")) {
|
| 1205 |
const newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
| 1206 |
window.history.replaceState({path: newUrl}, "", newUrl);
|
| 1207 |
}
|
|
|
|
| 1208 |
const nukeHF = () => {
|
|
|
|
| 1209 |
['huggingface-space-header', 'huggingface-workspace-badge', 'huggingface-space-badge'].forEach(tag => {
|
| 1210 |
document.querySelectorAll(tag).forEach(el => el.remove());
|
| 1211 |
});
|
|
|
|
|
|
|
| 1212 |
if (document.body) {
|
| 1213 |
Array.from(document.body.children).forEach(el => {
|
| 1214 |
if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || el.tagName === 'LINK') return;
|
|
|
|
|
|
|
| 1215 |
if (el.classList.contains('gradio-container-wrap') || el.querySelector('.gradio-container') || el.id === 'custom-css-injector') return;
|
|
|
|
|
|
|
| 1216 |
const html = el.innerHTML || '';
|
| 1217 |
if (html.includes('huggingface.co') || html.includes('Sign in') || html.includes('Duplicate Space') || html.includes('Log in')) {
|
| 1218 |
el.style.setProperty('display', 'none', 'important');
|
| 1219 |
el.remove();
|
| 1220 |
}
|
| 1221 |
});
|
|
|
|
|
|
|
| 1222 |
document.body.style.setProperty('padding-top', '0px', 'important');
|
| 1223 |
document.body.style.setProperty('margin-top', '0px', 'important');
|
| 1224 |
}
|
|
|
|
|
|
|
| 1225 |
document.querySelectorAll('.gradio-container-header, footer').forEach(el => el.remove());
|
|
|
|
| 1226 |
if (document.documentElement) {
|
| 1227 |
document.documentElement.style.setProperty('padding-top', '0px', 'important');
|
| 1228 |
}
|
| 1229 |
};
|
|
|
|
|
|
|
| 1230 |
const style = document.createElement('style');
|
| 1231 |
style.innerHTML = `
|
| 1232 |
+
huggingface-space-header, huggingface-workspace-badge, huggingface-space-badge {
|
| 1233 |
+
display: none !important; opacity: 0 !important; position: absolute !important; pointer-events: none !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1234 |
}
|
| 1235 |
.gradio-container-header, footer { display: none !important; }
|
| 1236 |
`;
|
| 1237 |
document.head.appendChild(style);
|
|
|
|
|
|
|
| 1238 |
setInterval(nukeHF, 50);
|
|
|
|
|
|
|
| 1239 |
new MutationObserver(nukeHF).observe(document.documentElement, { childList: true, subtree: true });
|
|
|
|
| 1240 |
nukeHF();
|
| 1241 |
return [];
|
| 1242 |
}
|
| 1243 |
"""
|
| 1244 |
|
|
|
|
| 1245 |
with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo_ui:
|
|
|
|
|
|
|
| 1246 |
gr.HTML(f"<style>{custom_css}</style>", elem_id="custom-css-injector")
|
| 1247 |
|
|
|
|
| 1248 |
menu_trigger = gr.State(value=0)
|
| 1249 |
current_user_state = gr.State(value="")
|
| 1250 |
|
| 1251 |
gr.Markdown("<h1 style='text-align: center;'>🛒 簡易訂單管理系統 (LINE 整合版)</h1>")
|
| 1252 |
|
|
|
|
|
|
|
|
|
|
| 1253 |
with gr.Column(visible=True, elem_classes="login-box") as login_container:
|
| 1254 |
gr.Markdown("<h2 style='text-align: center;'>🔐 會員登入</h2>")
|
| 1255 |
login_acc = gr.Textbox(label="會員帳號", placeholder="請輸入帳號")
|
|
|
|
| 1257 |
login_btn = gr.Button("登入系統", variant="primary", size="lg")
|
| 1258 |
login_msg = gr.Markdown(value="")
|
| 1259 |
|
|
|
|
|
|
|
|
|
|
| 1260 |
with gr.Column(visible=False) as main_container:
|
| 1261 |
with gr.Row(elem_classes="menu-row"):
|
| 1262 |
user_greeting = gr.Markdown(value="")
|
|
|
|
| 1264 |
logout_btn = gr.Button("🚪 登出系統", size="sm", min_width=100, scale=0)
|
| 1265 |
|
| 1266 |
with gr.Tabs() as main_tabs:
|
|
|
|
|
|
|
| 1267 |
with gr.TabItem("📝 現場/網頁新增訂單"):
|
|
|
|
|
|
|
| 1268 |
@gr.render(inputs=[current_user_state, menu_trigger])
|
| 1269 |
def render_order_form(current_user, m_trigger):
|
| 1270 |
if not current_user:
|
|
|
|
| 1318 |
|
| 1319 |
quantity_components = []
|
| 1320 |
pic_dir = os.path.join(BASE_DIR, "pic")
|
| 1321 |
+
if not os.path.exists(pic_dir): os.makedirs(pic_dir, exist_ok=True)
|
|
|
|
| 1322 |
|
| 1323 |
category_order, items_by_cat, flat_list = get_frontend_menu_items(user_level)
|
| 1324 |
|
|
|
|
| 1346 |
for ext in ['.jpg', '.jpeg', '.png', '.JPG', '.PNG']:
|
| 1347 |
temp_path = os.path.join(pic_dir, f"{item_name}{ext}")
|
| 1348 |
if os.path.exists(temp_path):
|
| 1349 |
+
found_img_path = temp_path; break
|
|
|
|
| 1350 |
|
| 1351 |
if found_img_path:
|
| 1352 |
try:
|
| 1353 |
with open(found_img_path, "rb") as img_file:
|
| 1354 |
encoded_string = base64.b64encode(img_file.read()).decode('utf-8')
|
| 1355 |
mime_type = "image/png" if found_img_path.lower().endswith(".png") else "image/jpeg"
|
| 1356 |
+
img_html = f'<div style="width: 60px; height: 60px; border-radius: 8px; overflow: hidden; margin: 0 auto; pointer-events: none; background: white;"><img src="data:{mime_type};base64,{encoded_string}" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;"></div>'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1357 |
gr.HTML(value=img_html)
|
| 1358 |
+
except:
|
| 1359 |
first_char = item_name[0] if item_name else "品"
|
| 1360 |
+
gr.HTML(value=f'<div style="width: 60px; height: 60px; background-color: #e2e8f0; color: #475569; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-size: 24px; font-weight: bold; margin: 0 auto; pointer-events: none;">{first_char}</div>')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1361 |
else:
|
| 1362 |
first_char = item_name[0] if item_name else "品"
|
| 1363 |
+
gr.HTML(value=f'<div style="width: 60px; height: 60px; background-color: #e2e8f0; color: #475569; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-size: 24px; font-weight: bold; margin: 0 auto; pointer-events: none;">{first_char}</div>')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1364 |
|
| 1365 |
with gr.Column(scale=1, min_width=150, elem_classes="center-col"):
|
| 1366 |
spec_html = f"<span style='font-size: 0.85em; color: #ef4444; padding: 2px 6px; background: #fee2e2; border-radius: 4px;'>{spec}</span>" if spec else ""
|
| 1367 |
+
info_html = f"<div style='display: flex; width: 100%; align-items: center; text-align: center; margin: auto 0;'><div style='flex: 1; font-weight: bold; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>{item_name}</div><div style='flex: 1;'>{spec_html}</div><div style='flex: 1; color: gray; font-size: 0.9em; white-space: nowrap;'>NT$ {price}</div></div>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1368 |
gr.HTML(info_html)
|
| 1369 |
|
| 1370 |
with gr.Column(scale=0, min_width=140, elem_classes="center-col"):
|
|
|
|
| 1373 |
qty_box = gr.Textbox(value="0", show_label=False, interactive=True, elem_classes="qty-input", container=False, min_width=45)
|
| 1374 |
plus_btn = gr.Button("➕", elem_classes="action-btn", variant="secondary", min_width=36)
|
| 1375 |
|
| 1376 |
+
minus_btn.click(fn=None, inputs=[qty_box], outputs=[qty_box], js="(v) => { let n = parseInt(v || 0); return Math.max(0, n - 1).toString(); }")
|
| 1377 |
+
plus_btn.click(fn=None, inputs=[qty_box], outputs=[qty_box], js="(v) => { let n = parseInt(v || 0); return (n + 1).toString(); }")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1378 |
quantity_components.append(qty_box)
|
| 1379 |
|
| 1380 |
notes = gr.Textbox(label="備註", placeholder="例如:少冰微糖...")
|
| 1381 |
+
|
| 1382 |
+
gr.Markdown("---")
|
| 1383 |
+
cart_summary = gr.Markdown("### 🛒 購物車明細\n*尚未計算,請點擊下方按鈕確認*")
|
| 1384 |
+
calc_btn = gr.Button("💰 結算總金額與明細", variant="secondary", size="lg")
|
| 1385 |
+
submit_btn = gr.Button("🚀 確認無誤,正式送出訂單", variant="primary", size="lg", visible=False)
|
| 1386 |
status_msg = gr.Textbox(label="系統狀態", interactive=False)
|
| 1387 |
|
| 1388 |
inputs_list = [current_user_state, customer_name, pickup_method, delivery_location, delivery_month, delivery_day, delivery_time, notes] + quantity_components
|
|
|
|
| 1389 |
|
| 1390 |
+
calc_btn.click(fn=calc_cart_summary, inputs=inputs_list, outputs=[cart_summary, submit_btn])
|
| 1391 |
+
submit_btn.click(fn=add_order, inputs=inputs_list, outputs=[status_msg, submit_btn, cart_summary] + quantity_components)
|
| 1392 |
|
|
|
|
| 1393 |
with gr.TabItem("📊 系統管理與總覽", visible=False, id="admin_tab") as admin_tab:
|
| 1394 |
with gr.Accordion("☁️ 雲端備份與還原 (點擊展開/收合)", open=True):
|
| 1395 |
with gr.Row():
|
|
|
|
| 1407 |
delivery_filter = gr.Dropdown(choices=["所有交期"], value="所有交期", label="🕒 篩選預定交期", interactive=True)
|
| 1408 |
refresh_btn = gr.Button("🔄 抓取最新訂單", variant="secondary")
|
| 1409 |
|
| 1410 |
+
orders_table = gr.Dataframe(value=get_orders_data(), headers=["訂單編號", "狀態", "訂單時間", "預定交期", "取貨方式", "送貨地點", "顧客姓名", "商品", "單價", "成本", "數量", "總價", "總成本", "備註"], interactive=False)
|
| 1411 |
|
| 1412 |
gr.Markdown("---")
|
| 1413 |
+
gr.Markdown("### 🚦 訂單狀態管理 (點擊表格自動帶入)")
|
| 1414 |
with gr.Row(elem_classes="menu-row"):
|
| 1415 |
with gr.Column(scale=2):
|
| 1416 |
+
delete_target = gr.Textbox(label="操作對象 (訂單編號)", placeholder="👉 點擊上方表格中的訂單")
|
| 1417 |
with gr.Column(scale=1):
|
| 1418 |
+
mark_done_btn = gr.Button("✅ 標記為 已完成", variant="primary")
|
| 1419 |
with gr.Column(scale=1):
|
| 1420 |
+
mark_cancel_btn = gr.Button("⏸️ 標記為 已取消", variant="secondary")
|
| 1421 |
+
with gr.Column(scale=1):
|
| 1422 |
+
delete_single_btn = gr.Button("🗑️ 永久刪除", variant="stop")
|
| 1423 |
|
| 1424 |
+
admin_status_msg = gr.Textbox(label="狀態提示", interactive=False)
|
| 1425 |
+
clear_btn = gr.Button("🚨 清空所有歷史訂單", variant="stop")
|
| 1426 |
|
| 1427 |
with gr.TabItem("📝 菜單管理"):
|
| 1428 |
+
gr.Markdown("⚠️ **點擊下方表格內任何一筆資料,即可在最底下的「編輯表單」中修改或刪除。**")
|
| 1429 |
|
| 1430 |
with gr.Row():
|
| 1431 |
menu_cat_filter = gr.Dropdown(choices=get_menu_cat_choices(), value="全部分類", label="🔍 篩選分類", interactive=True)
|
| 1432 |
menu_lvl_filter = gr.Dropdown(choices=get_menu_lvl_choices(), value="全部等級", label="🏅 篩選等級", interactive=True)
|
| 1433 |
menu_item_filter = gr.Dropdown(choices=get_menu_item_choices(), value="所有品項", label="🍔 篩選品項", interactive=True)
|
| 1434 |
+
menu_refresh_btn = gr.Button("🔄 刷新表格", variant="secondary")
|
| 1435 |
|
| 1436 |
menu_table = gr.Dataframe(
|
| 1437 |
value=get_menu_df(),
|
| 1438 |
headers=["流水號", "啟用", "適用等級", "分類", "品項", "規格", "價格", "成本", "備註"],
|
| 1439 |
datatype=["number", "bool", "str", "str", "str", "str", "number", "number", "str"],
|
| 1440 |
+
interactive=False, # 改為禁止直接在表格內打字,防呆防錯
|
| 1441 |
column_widths=["6%", "6%", "8%", "12%", "20%", "15%", "8%", "8%", "17%"]
|
| 1442 |
)
|
|
|
|
| 1443 |
|
| 1444 |
gr.Markdown("---")
|
| 1445 |
+
gr.Markdown("### 📝 品項編輯區 (點擊上方表格帶入資料,或直接填寫新增)")
|
| 1446 |
+
with gr.Group():
|
| 1447 |
+
with gr.Row():
|
| 1448 |
+
edit_seq = gr.Number(label="流水號", value=999, precision=0)
|
| 1449 |
+
edit_enable = gr.Checkbox(label="上架啟用", value=True)
|
| 1450 |
+
edit_lvl = gr.Textbox(label="適用等級", value="全部")
|
| 1451 |
+
edit_cat = gr.Textbox(label="分類", value="未分類")
|
| 1452 |
+
with gr.Row():
|
| 1453 |
+
edit_name = gr.Textbox(label="品項名稱", placeholder="必填")
|
| 1454 |
+
edit_spec = gr.Textbox(label="規格", placeholder="選填")
|
| 1455 |
+
edit_price = gr.Number(label="價格(NT$)", value=0)
|
| 1456 |
+
edit_cost = gr.Number(label="成本(NT$)", value=0)
|
| 1457 |
+
edit_note = gr.Textbox(label="備註", placeholder="內部備註")
|
| 1458 |
+
|
| 1459 |
+
gr.Markdown("💡 **修改品項名稱/規格** 視同「新增」。若您是要幫品項改名,請先按儲存後,再點擊舊品項按下刪除。")
|
| 1460 |
+
with gr.Row():
|
| 1461 |
+
save_menu_btn = gr.Button("💾 儲存 / 新增此品項", variant="primary")
|
| 1462 |
+
menu_delete_btn = gr.Button("🗑️ 刪除此品項", variant="stop")
|
| 1463 |
+
clear_menu_form_btn = gr.Button("🔄 清空表單 (準備新增)", variant="secondary")
|
| 1464 |
|
| 1465 |
with gr.TabItem("👥 會員資料管理"):
|
| 1466 |
+
gr.Markdown("⚠️ **點擊下方表格內任何一筆資料,即可在最底下的「編輯表單」中修改或刪除。**")
|
| 1467 |
|
| 1468 |
members_table = gr.Dataframe(
|
| 1469 |
value=get_members_df(),
|
| 1470 |
headers=["會員登入帳號", "密碼", "會員等級", "顧客姓名", "送貨地點"],
|
| 1471 |
datatype=["str", "str", "str", "str", "str"],
|
| 1472 |
+
interactive=False,
|
| 1473 |
column_widths=["20%", "20%", "10%", "25%", "25%"]
|
| 1474 |
)
|
| 1475 |
+
|
| 1476 |
+
gr.Markdown("---")
|
| 1477 |
+
gr.Markdown("### 👤 會員編輯區")
|
| 1478 |
+
with gr.Group():
|
| 1479 |
+
with gr.Row():
|
| 1480 |
+
mem_acc = gr.Textbox(label="會員登入帳號", placeholder="必填 (做為帳號)")
|
| 1481 |
+
mem_pwd = gr.Textbox(label="密碼")
|
| 1482 |
+
mem_lvl = gr.Textbox(label="會員等級", value="1")
|
| 1483 |
+
with gr.Row():
|
| 1484 |
+
mem_name = gr.Textbox(label="顧客姓名")
|
| 1485 |
+
mem_loc = gr.Textbox(label="送貨地點")
|
| 1486 |
+
|
| 1487 |
+
with gr.Row():
|
| 1488 |
+
save_members_btn = gr.Button("💾 儲存 / 新增會員", variant="primary")
|
| 1489 |
+
del_members_btn = gr.Button("🗑️ 刪除此會員", variant="stop")
|
| 1490 |
+
clear_mem_form_btn = gr.Button("🔄 清空表單", variant="secondary")
|
| 1491 |
+
|
| 1492 |
members_status = gr.Markdown()
|
| 1493 |
|
| 1494 |
with gr.TabItem("🔑 安全性設定"):
|
|
|
|
| 1502 |
update_pwd_btn = gr.Button("💾 確認更新密碼", variant="primary")
|
| 1503 |
pwd_update_status = gr.Markdown()
|
| 1504 |
|
| 1505 |
+
# --- Admin 事件綁定 ---
|
| 1506 |
+
# 訂單過濾
|
| 1507 |
+
for f_cmp in [customer_filter, time_filter, item_filter, delivery_filter]:
|
| 1508 |
+
f_cmp.change(
|
| 1509 |
+
fn=lambda c, t, i, d: (gr.update(value=get_orders_data(c, t, i, d)), gr.update(value=get_revenue(c, t, i, d))),
|
| 1510 |
+
inputs=[customer_filter, time_filter, item_filter, delivery_filter], outputs=[orders_table, revenue_display]
|
| 1511 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1512 |
|
| 1513 |
+
refresh_btn.click(fn=refresh_data, inputs=[customer_filter, time_filter, item_filter, delivery_filter], outputs=[orders_table, revenue_display, customer_filter, time_filter, item_filter, delivery_filter])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1514 |
|
| 1515 |
+
# 訂單操作
|
| 1516 |
+
orders_table.select(fn=autofill_delete_target, inputs=[orders_table], outputs=[delete_target])
|
| 1517 |
+
mark_done_btn.click(fn=lambda o, c, t, i, d: update_order_status(o, "已完成", c, t, i, d), inputs=[delete_target, customer_filter, time_filter, item_filter, delivery_filter], outputs=[admin_status_msg, orders_table, revenue_display])
|
| 1518 |
+
mark_cancel_btn.click(fn=lambda o, c, t, i, d: update_order_status(o, "已取消", c, t, i, d), inputs=[delete_target, customer_filter, time_filter, item_filter, delivery_filter], outputs=[admin_status_msg, orders_table, revenue_display])
|
| 1519 |
|
| 1520 |
delete_single_btn.click(
|
| 1521 |
+
fn=delete_single_order, inputs=[delete_target, customer_filter, time_filter, item_filter, delivery_filter], outputs=[admin_status_msg, orders_table, revenue_display, delete_target],
|
| 1522 |
+
js="(t,c,f,i,d) => confirm('⚠️ 確定永久刪除訂單 [' + t + '] 嗎?') ? [t,c,f,i,d] : ['__CANCEL__',c,f,i,d]"
|
|
|
|
|
|
|
| 1523 |
)
|
|
|
|
| 1524 |
clear_btn.click(
|
| 1525 |
+
fn=clear_orders, inputs=[customer_filter], outputs=[admin_status_msg, orders_table, revenue_display, customer_filter, time_filter, item_filter, delivery_filter],
|
| 1526 |
+
js="(f) => confirm('🚨 極度危險:確定清空所有訂單?') ? [f] : ['__CANCEL__']"
|
|
|
|
|
|
|
| 1527 |
)
|
| 1528 |
|
| 1529 |
+
# 菜單過濾
|
| 1530 |
+
for mf in [menu_cat_filter, menu_lvl_filter, menu_item_filter]:
|
| 1531 |
+
mf.change(fn=get_menu_df, inputs=[menu_cat_filter, menu_lvl_filter, menu_item_filter], outputs=[menu_table])
|
| 1532 |
+
menu_refresh_btn.click(fn=refresh_menu_filters, inputs=[menu_cat_filter, menu_lvl_filter, menu_item_filter], outputs=[menu_table, menu_cat_filter, menu_lvl_filter, menu_item_filter])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1533 |
|
| 1534 |
+
# 菜單表單操作
|
| 1535 |
+
menu_table.select(fn=autofill_menu_form, inputs=[menu_table], outputs=[edit_seq, edit_enable, edit_lvl, edit_cat, edit_name, edit_spec, edit_price, edit_cost, edit_note])
|
| 1536 |
+
clear_menu_form_btn.click(fn=lambda: (999, True, "全部", "未分類", "", "", 0, 0, ""), inputs=[], outputs=[edit_seq, edit_enable, edit_lvl, edit_cat, edit_name, edit_spec, edit_price, edit_cost, edit_note])
|
|
|
|
|
|
|
| 1537 |
|
| 1538 |
+
save_menu_btn.click(
|
| 1539 |
+
fn=save_single_menu_item,
|
| 1540 |
+
inputs=[edit_seq, edit_enable, edit_lvl, edit_cat, edit_name, edit_spec, edit_price, edit_cost, edit_note, menu_cat_filter, menu_lvl_filter, menu_item_filter],
|
| 1541 |
+
outputs=[global_sys_msg, menu_table, menu_cat_filter, menu_lvl_filter, menu_item_filter, menu_trigger]
|
| 1542 |
)
|
| 1543 |
|
| 1544 |
menu_delete_btn.click(
|
| 1545 |
fn=delete_menu_item,
|
| 1546 |
+
inputs=[gr.Textbox(visible=False), menu_cat_filter, menu_lvl_filter, menu_item_filter], # JS 會把 Textbox 值替換為拼裝好的 target_str
|
| 1547 |
+
outputs=[global_sys_msg, menu_table, gr.Textbox(visible=False), menu_trigger, menu_cat_filter, menu_lvl_filter, menu_item_filter],
|
| 1548 |
+
js="(dummy, c, l, i) => { const n = document.querySelector('input[aria-label=\"品項名稱\"]').value; const s = document.querySelector('input[aria-label=\"規格\"]').value; if(!n) return ['__CANCEL__',c,l,i]; const t = s ? n + ' | ' + s : n; return confirm('⚠️ 刪除 [' + t + '] ?') ? [t,c,l,i] : ['__CANCEL__',c,l,i]; }"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1549 |
)
|
| 1550 |
|
| 1551 |
+
# 會員表單操作
|
| 1552 |
+
members_table.select(fn=autofill_member_form, inputs=[members_table], outputs=[mem_acc, mem_pwd, mem_lvl, mem_name, mem_loc])
|
| 1553 |
+
clear_mem_form_btn.click(fn=lambda: ("","", "1", "", ""), inputs=[], outputs=[mem_acc, mem_pwd, mem_lvl, mem_name, mem_loc])
|
| 1554 |
+
|
| 1555 |
+
save_members_btn.click(fn=save_single_member, inputs=[mem_acc, mem_pwd, mem_lvl, mem_name, mem_loc], outputs=[members_status, members_table])
|
| 1556 |
+
del_members_btn.click(
|
| 1557 |
+
fn=delete_single_member, inputs=[mem_acc], outputs=[members_status, members_table],
|
| 1558 |
+
js="(acc) => { if(!acc) return acc; return confirm('⚠️ 確定刪除會員 ' + acc + ' 嗎?') ? acc : ''; }"
|
| 1559 |
)
|
| 1560 |
|
| 1561 |
+
# 備份與雜項
|
| 1562 |
+
github_btn.click(fn=backup_and_push_to_github, inputs=[], outputs=[github_log_output])
|
| 1563 |
+
restore_btn.click(fn=restore_from_backup, inputs=[], outputs=[global_sys_msg, menu_table, members_table, menu_trigger, menu_cat_filter, menu_lvl_filter, menu_item_filter])
|
| 1564 |
+
update_pwd_btn.click(fn=change_password, inputs=[old_pwd_input, new_pwd_input], outputs=[pwd_update_status])
|
| 1565 |
|
| 1566 |
+
# 登入與登出
|
| 1567 |
+
login_btn.click(fn=do_login, inputs=[login_acc, login_pwd], outputs=[login_container, main_container, admin_tab, login_msg, current_user_state, user_greeting, global_sys_msg])
|
| 1568 |
+
login_pwd.submit(fn=do_login, inputs=[login_acc, login_pwd], outputs=[login_container, main_container, admin_tab, login_msg, current_user_state, user_greeting, global_sys_msg])
|
| 1569 |
+
logout_btn.click(fn=logout, inputs=[], outputs=[login_container, main_container, admin_tab, login_acc, login_pwd, login_msg, current_user_state, user_greeting, global_sys_msg])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1570 |
|
|
|
|
| 1571 |
demo_ui.load(fn=None, js=kill_badge_js)
|
| 1572 |
|
|
|
|
|
|
|
|
|
|
| 1573 |
app = gr.mount_gradio_app(custom_api, demo_ui.queue(), path="/")
|
| 1574 |
|
| 1575 |
if __name__ == "__main__":
|