import sys import os import json import base64 import uuid import warnings import threading import shutil import sqlite3 import hashlib from datetime import datetime, timezone, timedelta # 忽略 Gradio 6.0 的 UserWarning 以免日誌洗版 warnings.filterwarnings("ignore", message="The parameters have been moved from the Blocks constructor.*") # 【終極防護設定】精準設定您的專屬網址 os.environ["GRADIO_CSRF_TRUST_ORIGINS"] = "https://schillercfk-ssys.hf.space" # 【設定台北時區】 TAIPEI_TZ = timezone(timedelta(hours=8)) # 【優化:資料庫執行緒鎖】保護 SQLite 在多執行緒環境下的併發寫入安全 db_lock = threading.Lock() try: import gradio as gr import pandas as pd import subprocess from fastapi import FastAPI, Request, HTTPException from linebot.v3 import WebhookHandler from linebot.v3.exceptions import InvalidSignatureError from linebot.v3.messaging import ( Configuration, ApiClient, MessagingApi, ReplyMessageRequest, TextMessage ) from linebot.v3.webhooks import MessageEvent, TextMessageContent import uvicorn except ImportError as e: print(f"❌ 啟動失敗:缺少必要的套件!請檢查 requirements.txt。詳細錯誤:{e}") sys.exit(1) # ---------------------------- # 📱 LINE Bot 設定區 (資安優化:支援環境變數優先讀取) # ---------------------------- # 優先從環境變數讀取,若無則使用預設金鑰,避免金鑰直接裸露於公開原始碼的風險 LINE_CHANNEL_ACCESS_TOKEN = os.environ.get( "LINE_ACCESS_TOKEN", "HadCmCBmnZtI4LjC1Ad2rBwGZX7x1jZu4A0DXCX+LIjt3SpQq0vVz1kh8U74GB2XPbRdgwfqvFcVRR+i0NodOZ2P6hPC5ZV8EuxPOt+WnAvTJ29P5UBoENQCVAxu/AuRP2xgYKNYOg5voggl73mfkgdB04t89/1O/w1cDnyilFU=" ).replace(" ", "").strip() LINE_CHANNEL_SECRET = os.environ.get( "LINE_CHANNEL_SECRET", "ae66c98db5eca3e75aff2ff28ef62f25" ).replace(" ", "").strip() WEB_ORDER_URL = "https://schillercfk-ssys.hf.space/?openExternalBrowser=1" try: configuration = Configuration(access_token=LINE_CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(LINE_CHANNEL_SECRET) except Exception as e: print(f"❌ LINE API 初始化失敗:{e}") custom_api = FastAPI() # ---------------------------- # 🔒 資安優化:密碼雜湊加密函數 # ---------------------------- def hash_pwd(password): """使用 SHA-256 進行單向加密,提升密碼儲存的安全性""" if len(str(password)) == 64: return password # 若已是 64 碼(雜湊值)則不重複加密 return hashlib.sha256(str(password).encode('utf-8')).hexdigest() # ---------------------------- # 🗄️ 系統資料與資料庫 (SQLite 優化升級) # ---------------------------- BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DB_FILE = os.path.join(BASE_DIR, "system_database.sqlite") # 建立 SQLite 連線 db_conn = sqlite3.connect(DB_FILE, check_same_thread=False) db_cursor = db_conn.cursor() # 初始化資料庫表格 with db_lock: db_cursor.execute('''CREATE TABLE IF NOT EXISTS orders ( order_id TEXT PRIMARY KEY, status TEXT, time TEXT, delivery_time TEXT, pickup_method TEXT, location TEXT, customer TEXT, item TEXT, price INTEGER, cost INTEGER, qty INTEGER, total INTEGER, total_cost INTEGER, note TEXT )''') db_cursor.execute('''CREATE TABLE IF NOT EXISTS menu ( seq INTEGER, enable BOOLEAN, level TEXT, category TEXT, name TEXT, spec TEXT, price INTEGER, cost INTEGER, note TEXT )''') db_cursor.execute('''CREATE TABLE IF NOT EXISTS members ( acc TEXT PRIMARY KEY, pwd TEXT, level TEXT, name TEXT, location TEXT )''') db_cursor.execute('''CREATE TABLE IF NOT EXISTS config ( key TEXT PRIMARY KEY, value TEXT )''') db_conn.commit() # 全域變數 (記憶體快取,供前端高速渲染) orders_db = [] MENU = [] MEMBERS = {} APP_CONFIG = {"bg_source": "default", "bg_url": "", "bg_file": "", "bg_opacity": 0.85} ADMIN_PASSWORD = hash_pwd("0000") # 預設加密密碼 # 舊版檔案路徑 (供無縫升級轉移使用) MENU_FILE = os.path.join(BASE_DIR, "menu.json") PWD_FILE = os.path.join(BASE_DIR, "admin_pwd.json") ORDERS_FILE = os.path.join(BASE_DIR, "orders.json") MEMBERS_FILE = os.path.join(BASE_DIR, "members.json") APP_CONFIG_FILE = os.path.join(BASE_DIR, "app_config.json") BACKUP_FILE = os.path.join(BASE_DIR, "orders_backup.csv") MENU_BACKUP_FILE = os.path.join(BASE_DIR, "menu_backup.csv") MEMBERS_BACKUP_FILE = os.path.join(BASE_DIR, "members_backup.csv") # ============================ # 📦 資料庫存取與無縫轉移邏輯 # ============================ def init_and_load_data(): global orders_db, MENU, MEMBERS, APP_CONFIG, ADMIN_PASSWORD with db_lock: db_cursor.execute("SELECT COUNT(*) FROM menu") m_cnt = db_cursor.fetchone()[0] db_cursor.execute("SELECT COUNT(*) FROM orders") o_cnt = db_cursor.fetchone()[0] # 【智慧轉移機制】如果 SQLite 裡沒有資料,但舊的檔案存在,就執行轉移 if m_cnt == 0 and o_cnt == 0 and (os.path.exists(MENU_FILE) or os.path.exists(MENU_BACKUP_FILE) or os.path.exists(BACKUP_FILE)): print("🔄 偵測到舊版檔案資料,正在進行 SQLite 無縫升級轉移...") migrate_old_data() else: # 從強大的 SQLite 直接載入至記憶體 with db_lock: # 載入訂單 db_cursor.execute("SELECT * FROM orders ORDER BY time DESC") orders_db = [{ "訂單編號": r[0], "狀態": r[1], "時間": r[2], "預定交期": r[3], "取貨方式": r[4], "送貨地點": r[5], "顧客姓名": r[6], "商品": r[7], "單價": r[8], "成本": r[9], "數量": r[10], "總價": r[11], "總成本": r[12], "備註": r[13] } for r in db_cursor.fetchall()] # 載入菜單 db_cursor.execute("SELECT * FROM menu ORDER BY seq") MENU = [{ "seq": r[0], "enable": bool(r[1]), "level": r[2], "category": r[3], "name": r[4], "spec": r[5], "price": r[6], "cost": r[7], "note": r[8] } for r in db_cursor.fetchall()] # 載入會員 db_cursor.execute("SELECT * FROM members") MEMBERS = {r[0]: {"password": r[1], "level": r[2], "name": r[3], "location": r[4]} for r in db_cursor.fetchall()} # 載入設定 db_cursor.execute("SELECT * FROM config") for k, v in db_cursor.fetchall(): if k == 'admin_pwd': ADMIN_PASSWORD = v elif k == 'bg_opacity': APP_CONFIG[k] = float(v) else: APP_CONFIG[k] = v def migrate_old_data(): global orders_db, MENU, MEMBERS, APP_CONFIG, ADMIN_PASSWORD # 載入舊 CSV 訂單 (優先) orders_db.clear() if os.path.exists(BACKUP_FILE): try: df = pd.read_csv(BACKUP_FILE, dtype={"訂單編號": str, "顧客姓名": str, "商品": str, "備註": str, "送貨地點": str, "時間": str, "訂單時間": str, "預定交期": str}) df = df.fillna("") loaded_orders = df.to_dict('records') for o in loaded_orders: orders_db.append({ "訂單編號": str(o.get("訂單編號", "")), "狀態": str(o.get("狀態", "處理中")), "時間": str(o.get("時間", "") or o.get("訂單時間", "")), "預定交期": str(o.get("預定交期", "")), "取貨方式": str(o.get("取貨方式", "自取")), "送貨地點": str(o.get("送貨地點", "")), "顧客姓名": str(o.get("顧客姓名", "")), "商品": str(o.get("商品", "")), "單價": int(float(o.get("單價", 0) or 0)), "成本": int(float(o.get("成本", 0) or 0)), "數量": int(float(o.get("數量", 0) or 0)), "總價": int(float(o.get("總價", 0) or 0)), "總成本": int(float(o.get("總成本", 0) or 0)), "備註": str(o.get("備註", "")) }) except: pass elif os.path.exists(ORDERS_FILE): try: with open(ORDERS_FILE, "r", encoding="utf-8") as f: orders_db = json.load(f) for o in orders_db: o["狀態"] = str(o.get("狀態", "處理中")) except: pass # 載入舊菜單 MENU.clear() if os.path.exists(MENU_BACKUP_FILE): try: df = pd.read_csv(MENU_BACKUP_FILE, dtype={"品項": str, "規格": str, "分類": str, "備註": str, "適用等級": str}) df = df.fillna("") for _, row in df.iterrows(): val_enable = row.get("啟用", True) enable = val_enable.lower() in ["true", "1", "yes", "是", "t"] if isinstance(val_enable, str) else bool(val_enable) item = str(row.get("品項", "")).strip() if item: MENU.append({ "name": item, "price": int(float(row.get("價格", 0) or 0)), "cost": int(float(row.get("成本", 0) or 0)), "enable": enable, "level": str(row.get("適用等級", "全部")).strip() or "全部", "seq": int(row.get("流水號", 999)), "category": str(row.get("分類", "未分類")).strip() or "未分類", "spec": str(row.get("規格", "")).strip(), "note": str(row.get("備註", "")).strip() }) except: pass elif os.path.exists(MENU_FILE): try: with open(MENU_FILE, "r", encoding="utf-8") as f: data = json.load(f) if isinstance(data, dict): for k, v in data.items(): if isinstance(v, dict): v["name"], MENU = k, MENU + [v] else: MENU.append({"name": k, "price": int(v), "cost": 0, "enable": True, "level": "全部", "seq": 999, "category": "未分類", "spec": "", "note": ""}) elif isinstance(data, list): MENU.extend(data) except: pass # 載入舊會員 (並將舊的明文密碼進行加密) MEMBERS.clear() if os.path.exists(MEMBERS_BACKUP_FILE): try: df = pd.read_csv(MEMBERS_BACKUP_FILE, dtype=str).fillna("") for _, row in df.iterrows(): acc = str(row.get("會員登入帳號", "")).strip() if acc: MEMBERS[acc] = { "password": hash_pwd(row.get("密碼", "")), "level": str(row.get("會員等級", "1")).strip(), "name": str(row.get("顧客姓名", "")).strip(), "location": str(row.get("送貨地點", "")).strip() } except: pass elif os.path.exists(MEMBERS_FILE): try: with open(MEMBERS_FILE, "r", encoding="utf-8") as f: old_mem = json.load(f) for acc, info in old_mem.items(): MEMBERS[acc] = { "password": hash_pwd(info.get("password", "")), "level": str(info.get("level", "1")), "name": str(info.get("name", "")), "location": str(info.get("location", "")) } except: pass # 載入舊密碼 if os.path.exists(PWD_FILE): try: with open(PWD_FILE, "r", encoding="utf-8") as f: ADMIN_PASSWORD = hash_pwd(json.load(f).get("password", "0000")) except: pass # 載入舊外觀設定 if os.path.exists(APP_CONFIG_FILE): try: with open(APP_CONFIG_FILE, "r", encoding="utf-8") as f: APP_CONFIG.update(json.load(f)) except: pass # 寫入至 SQLite save_menu_to_db() save_members_to_db() save_config_to_db() with db_lock: db_cursor.execute("DELETE FROM orders") for o in orders_db: db_cursor.execute('''INSERT OR IGNORE INTO orders VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', (o.get("訂單編號"), o.get("狀態"), o.get("時間"), o.get("預定交期"), o.get("取貨方式"), o.get("送貨地點"), o.get("顧客姓名"), o.get("商品"), o.get("單價"), o.get("成本"), o.get("數量"), o.get("總價"), o.get("總成本"), o.get("備註")) ) db_conn.commit() # --- 資料庫儲存與操作函數 (替代舊有的肥大 File I/O) --- def add_order_to_db(o): with db_lock: orders_db.append(o) db_cursor.execute('''INSERT INTO orders VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', (o["訂單編號"], o.get("狀態"), o["時間"], o.get("預定交期"), o.get("取貨方式"), o.get("送貨地點"), o.get("顧客姓名"), o["商品"], o["單價"], o["成本"], o["數量"], o["總價"], o["總成本"], o.get("備註")) ) db_conn.commit() def save_menu_to_db(): with db_lock: db_cursor.execute('DELETE FROM menu') for m in MENU: db_cursor.execute('INSERT INTO menu VALUES (?,?,?,?,?,?,?,?,?)', (m.get("seq"), m.get("enable"), m.get("level"), m.get("category"), m.get("name"), m.get("spec"), m.get("price"), m.get("cost"), m.get("note"))) db_conn.commit() def save_members_to_db(): with db_lock: db_cursor.execute('DELETE FROM members') for acc, info in MEMBERS.items(): db_cursor.execute('INSERT INTO members VALUES (?,?,?,?,?)', (acc, info.get("password"), info.get("level"), info.get("name"), info.get("location"))) db_conn.commit() def save_config_to_db(key=None, value=None): with db_lock: if key and value: db_cursor.execute('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)', (key, str(value))) else: db_cursor.execute('DELETE FROM config WHERE key != "admin_pwd"') for k, v in APP_CONFIG.items(): if k != "_cached_b64": db_cursor.execute('INSERT INTO config VALUES (?, ?)', (k, str(v))) db_conn.commit() # 啟動時載入資料 init_and_load_data() # ---------------------------- # 🎨 動態背景樣式產生函數 # ---------------------------- def generate_bg_css(config=None): if config is None: config = APP_CONFIG opacity = config.get("bg_opacity", 0.85) bg_source = config.get("bg_source", "default") if bg_source == "default": bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop" elif bg_source == "url": bg_url = config.get("bg_url", "") if not bg_url: bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop" elif bg_source == "upload": if "_cached_b64" in config: bg_url = f"data:image/jpeg;base64,{config['_cached_b64']}" else: bg_file = config.get("bg_file", "custom_bg.jpg") bg_path = os.path.join(BASE_DIR, bg_file) if os.path.exists(bg_path): try: with open(bg_path, "rb") as f: b64 = base64.b64encode(f.read()).decode("utf-8") config["_cached_b64"] = b64 bg_url = f"data:image/jpeg;base64,{b64}" except: bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop" else: bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop" else: bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop" return f""" """ # ---------------------------- # 💻 網頁 UI 資料獲取函數 (Data Fetchers) # ---------------------------- def get_frontend_menu_items(user_level="全部"): enabled_items = [] for item_dict in MENU: if not item_dict.get("enable", True): continue item_lvl = str(item_dict.get("level", "全部")).strip() if user_level == "admin" or item_lvl == "全部" or item_lvl == str(user_level): enabled_items.append(item_dict) enabled_items = sorted(enabled_items, key=lambda x: x.get("seq", 999)) category_order = [] items_by_cat = {} for details in enabled_items: cat = details.get("category", "未分類") cat = cat.strip() if cat.strip() else "未分類" if cat not in category_order: category_order.append(cat) items_by_cat.setdefault(cat, []).append((details.get("name", "未命名"), details)) flat_list = [] for cat in category_order: flat_list.extend(items_by_cat[cat]) return category_order, items_by_cat, flat_list def get_menu_cat_choices(): cats = list(dict.fromkeys([m.get("category", "未分類") for m in MENU])) return ["全部分類"] + cats def get_menu_lvl_choices(): lvls = list(dict.fromkeys([str(m.get("level", "全部")) for m in MENU])) return ["全部等級"] + lvls def get_menu_item_choices(): items = list(dict.fromkeys([m.get("name", "") for m in MENU if m.get("name")])) return ["所有品項"] + items def get_menu_df_for_export(): sorted_menu = sorted(MENU, key=lambda x: x.get("seq", 999)) data = [] for v in sorted_menu: data.append([v.get("seq", 999), v.get("enable", True), v.get("level", "全部"), v.get("category", "未分類"), v.get("name", ""), v.get("spec", ""), v.get("price", 0), v.get("cost", 0), v.get("note", "")]) return pd.DataFrame(data, columns=["流水號", "啟用", "適用等級", "分類", "品項", "規格", "價格", "成本", "備註"]) def get_menu_df(cat_filter="全部分類", lvl_filter="全部等級", item_filter="所有品項"): filtered_menu = MENU if cat_filter != "全部分類": filtered_menu = [m for m in filtered_menu if m.get("category", "未分類") == cat_filter] if lvl_filter != "全部等級": filtered_menu = [m for m in filtered_menu if str(m.get("level", "全部")) == lvl_filter] if item_filter != "所有品項": filtered_menu = [m for m in filtered_menu if m.get("name", "") == item_filter] sorted_menu = sorted(filtered_menu, key=lambda x: x.get("seq", 999)) data = [] for v in sorted_menu: data.append([v.get("seq", 999), v.get("enable", True), v.get("level", "全部"), v.get("category", "未分類"), v.get("name", ""), v.get("spec", ""), v.get("price", 0), v.get("cost", 0), v.get("note", "")]) df = pd.DataFrame(data, columns=["流水號", "啟用", "適用等級", "分類", "品項", "規格", "價格", "成本", "備註"]) if not df.empty: df["品項"] = df["品項"].astype(str) return df def get_members_df(): data = [] for acc, info in MEMBERS.items(): data.append([acc, "***", info.get("level", "1"), info.get("name", ""), info.get("location", "")]) df = pd.DataFrame(data, columns=["會員登入帳號", "密碼", "會員等級", "顧客姓名", "送貨地點"], dtype=str) return df def get_customer_choices(): customers = [] for o in orders_db: if o.get("顧客姓名") and o["顧客姓名"] not in customers: customers.append(o["顧客姓名"]) return ["所有顧客"] + customers def get_time_choices(): times = set() for o in orders_db: dt_str = o.get("時間", "") or o.get("訂單時間", "") if len(dt_str) >= 10: times.add(dt_str[:10]); times.add(dt_str[:7]) return ["所有時間"] + sorted(list(times), reverse=True) def get_item_choices(): items = [] for o in orders_db: if o.get("商品") and o["商品"] not in items: items.append(o["商品"]) return ["所有商品"] + items def get_delivery_choices(): deliveries = [] for o in orders_db: d = o.get("預定交期", "") if d and d not in deliveries: deliveries.append(d) return ["所有交期"] + deliveries def get_orders_data(filter_name="所有顧客", filter_time="所有時間", filter_item="所有商品", filter_delivery="所有交期"): filtered_db = orders_db if filter_name != "所有顧客": filtered_db = [o for o in filtered_db if o.get("顧客姓名") == filter_name] if filter_time != "所有時間": filtered_db = [o for o in filtered_db if o.get("時間", "").startswith(filter_time) or o.get("訂單時間", "").startswith(filter_time)] if filter_item != "所有商品": filtered_db = [o for o in filtered_db if o.get("商品") == filter_item] if filter_delivery != "所有交期": filtered_db = [o for o in filtered_db if o.get("預定交期") == filter_delivery] if not filtered_db: return [[""] * 14] return [[ o.get("訂單編號", ""), o.get("狀態", "處理中"), o.get("時間", "") or o.get("訂單時間", ""), o.get("預定交期", ""), o.get("取貨方式", "自取"), o.get("送貨地點", ""), o.get("顧客姓名", ""), o.get("商品", ""), o.get("單價", 0), o.get("成本", 0), o.get("數量", 0), o.get("總價", 0), o.get("總成本", 0), o.get("備註", "") ] for o in filtered_db] def get_revenue(filter_name="所有顧客", filter_time="所有時間", filter_item="所有商品", filter_delivery="所有交期"): filtered_db = orders_db if filter_name != "所有顧客": filtered_db = [o for o in filtered_db if o.get("顧客姓名") == filter_name] if filter_time != "所有時間": filtered_db = [o for o in filtered_db if o.get("時間", "").startswith(filter_time) or o.get("訂單時間", "").startswith(filter_time)] if filter_item != "所有商品": filtered_db = [o for o in filtered_db if o.get("商品") == filter_item] if filter_delivery != "所有交期": filtered_db = [o for o in filtered_db if o.get("預定交期") == filter_delivery] total_revenue = sum(o.get("總價", 0) for o in filtered_db) total_cost = sum(o.get("總成本", 0) for o in filtered_db) profit = total_revenue - total_cost title_parts = [] if filter_name != "所有顧客": title_parts.append(f"【{filter_name}】") if filter_time != "所有時間": title_parts.append(f"【{filter_time}】") if filter_item != "所有商品": title_parts.append(f"【{filter_item}】") if filter_delivery != "所有交期": title_parts.append(f"【{filter_delivery}】") prefix = "💰 " + "".join(title_parts) + " 的總消費" if title_parts else "💰 目前總營收" profit_prefix = "📈 篩選總毛利" if title_parts else "📈 目前總毛利" return f"### {prefix}:NT$ {total_revenue} | {profit_prefix}:NT$ {profit}" # ----------------- # 📝 UI 動作處理操作 (Actions) # ----------------- def save_single_member(acc, pwd, lvl, name, loc): global MEMBERS acc = str(acc).strip() if acc else "" if not acc: return gr.update(value="❌ 錯誤:會員登入帳號不可為空!"), gr.update() pwd_to_save = MEMBERS.get(acc, {}).get("password", "") if pwd and pwd.strip() != "***": pwd_to_save = hash_pwd(pwd.strip()) MEMBERS[acc] = {"password": pwd_to_save, "level": str(lvl).strip() if lvl else "1", "name": str(name).strip() if name else "", "location": str(loc).strip() if loc else ""} save_members_to_db() msg = f"✅ 會員 {acc} 已儲存成功!({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})" return gr.update(value=msg), get_members_df() def delete_single_member(acc): global MEMBERS acc = str(acc).strip() if acc else "" if not acc: return gr.update(value="❌ 錯誤:請先選擇要刪除的會員帳號!"), gr.update() if acc in MEMBERS: del MEMBERS[acc] save_members_to_db() return gr.update(value=f"🗑️ 會員 {acc} 已刪除!"), get_members_df() return gr.update(value=f"❌ 找不到會員 {acc}"), gr.update() def change_password(old_pwd, new_pwd): global ADMIN_PASSWORD if not new_pwd.strip(): return gr.update(value="❌ 新密碼不能為空白!") if hash_pwd(old_pwd) != ADMIN_PASSWORD: return gr.update(value="❌ 舊密碼輸入錯誤,請重新確認!") ADMIN_PASSWORD = hash_pwd(new_pwd.strip()) save_config_to_db('admin_pwd', ADMIN_PASSWORD) return gr.update(value=f"✅ 密碼修改成功!下次登入請使用新密碼。({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})") def calc_cart_summary(current_user, c_name, p_method, d_location, d_month, d_day, d_time, nts, *qty_args): user_level = "全部" if current_user == "admin": user_level = "admin" elif current_user in MEMBERS: user_level = MEMBERS[current_user].get("level", "1") _, _, flat_list = get_frontend_menu_items(user_level) c_name = str(c_name).strip() if c_name else "" quantities = [] for q in qty_args: try: quantities.append(int(q)) except: quantities.append(0) if sum(quantities) == 0: return "❌ **購物車是空的,請先在上方選擇商品數量!**", gr.update(visible=False) if not c_name: return "❌ **請先輸入上方的「顧客姓名」才能結帳!**", gr.update(visible=False) total_order_price = 0 items_desc = [] for i, qty in enumerate(quantities): if qty > 0: item_name, details = flat_list[i] price = details["price"] spec = details.get("spec", "") item_note = f" ({spec})" if spec else "" total_price = price * qty total_order_price += total_price items_desc.append(f"- ✅ **{item_name}**{item_note} x {qty} = {total_price} 元") md = "### 🛒 購物車明細確認\n" md += f"**顧客姓名**:{c_name} \n" md += f"**取貨方式**:{p_method}" + (f" (地點:{d_location})" if p_method == "送貨" else "") + " \n" md += f"**預定交期**:{d_month}{d_day} {d_time} \n" md += "**備註留言**:" + (nts if nts else "無") + " \n\n" md += "**【已選商品】**\n" md += "\n".join(items_desc) md += f"\n\n💰 **結帳總金額:NT$ {total_order_price}**" return md, gr.update(visible=True) def add_order(current_user, c_name, p_method, d_location, d_month, d_day, d_time, nts, *qty_args): try: user_level = "全部" if current_user == "admin": user_level = "admin" elif current_user in MEMBERS: user_level = MEMBERS[current_user].get("level", "1") _, _, flat_list = get_frontend_menu_items(user_level) c_name = str(c_name).strip() if c_name else "" nts = str(nts).strip() if nts else "" delivery_date = f"{d_month}{d_day} {d_time}" if d_time != "盡快" else "盡快" quantities = [] for q in qty_args: try: quantities.append(int(q)) except: quantities.append(0) reset_qtys = [gr.update(value="0") for _ in range(len(flat_list))] timestamp = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M:%S") total_order_price = 0 items_desc = [] for i, qty in enumerate(quantities): if qty > 0: item_name, details = flat_list[i] price = details["price"] cost = details.get("cost", 0) spec = details.get("spec", "") item_note = f"({spec})" if spec else "" total_price = price * qty total_cost = cost * qty total_order_price += total_price order_id = str(uuid.uuid4())[:6].upper() final_note = f"{item_note} {nts}".strip() if item_note else nts # 優化:直接呼叫 DB 操作,取代笨重的 JSON Rewrite add_order_to_db({ "訂單編號": order_id, "狀態": "處理中", "時間": timestamp, "預定交期": delivery_date, "取貨方式": p_method, "送貨地點": d_location if p_method == "送貨" else "", "顧客姓名": c_name, "商品": item_name, "單價": price, "成本": cost, "數量": qty, "總價": total_price, "總成本": total_cost, "備註": final_note }) desc = f"{item_name}{item_note}x{qty}" items_desc.append(desc) if not items_desc: return [gr.update(value="❌ 錯誤:請至少選擇一項商品的數量")] + reset_qtys msg = f"🎉 訂單已成功送出!{c_name} 共訂購了 {', '.join(items_desc)},總計 {total_order_price} 元。" return [gr.update(value=msg), gr.update(visible=False), gr.update(value="### 🛒 購物車明細\n*訂單已送出,請重新選擇商品*")] + reset_qtys except Exception as e: reset_qtys = [gr.update(value="0") for _ in range(len(flat_list))] return [gr.update(value=f"❌ 系統異常:{str(e)}"), gr.update(visible=False), gr.update(value="### 🛒 購物車明細\n*發生錯誤*")] + reset_qtys def update_order_status(order_id, new_status, current_filter, current_time_filter, current_item_filter, current_delivery_filter): if order_id == "__CANCEL__": return gr.update(), gr.update(), gr.update() order_id = str(order_id).strip() if not order_id: return gr.update(value="❌ 錯誤:請先點擊上方表格選擇訂單!"), gr.update(), gr.update() found = False with db_lock: for o in orders_db: if o.get("訂單編號") == order_id: o["狀態"] = new_status found = True if found: db_cursor.execute('UPDATE orders SET status = ? WHERE order_id = ?', (new_status, order_id)) db_conn.commit() if not found: return gr.update(value=f"❌ 找不到訂單編號:{order_id}"), gr.update(), gr.update() return ( gr.update(value=f"✅ 成功將訂單 {order_id} 標記為『{new_status}』"), gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)), gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)) ) def delete_single_order(order_id, current_filter, current_time_filter, current_item_filter, current_delivery_filter): if order_id == "__CANCEL__": return gr.update(), gr.update(), gr.update(), gr.update() global orders_db order_id = str(order_id).strip() if not order_id: return gr.update(value="❌ 錯誤:請輸入要刪除的訂單編號!"), gr.update(), gr.update(), gr.update() with db_lock: original_len = len(orders_db) orders_db = [o for o in orders_db if o.get("訂單編號") != order_id] if len(orders_db) == original_len: return gr.update(value=f"❌ 找不到訂單編號:{order_id}"), gr.update(), gr.update(), gr.update() db_cursor.execute('DELETE FROM orders WHERE order_id = ?', (order_id,)) db_conn.commit() return ( gr.update(value=f"✅ 成功永久刪除訂單:{order_id}"), gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)), gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)), gr.update(value="") ) def clear_orders(filter_val): if filter_val == "__CANCEL__": return gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update() with db_lock: orders_db.clear() db_cursor.execute('DELETE FROM orders') db_conn.commit() return ( gr.update(value="🗑️ 所有訂單已清空"), gr.update(value=get_orders_data("所有顧客", "所有時間", "所有商品", "所有交期")), gr.update(value=get_revenue("所有顧客", "所有時間", "所有商品", "所有交期")), gr.update(choices=["所有顧客"], value="所有顧客"), gr.update(choices=["所有時間"], value="所有時間"), gr.update(choices=["所有商品"], value="所有商品"), gr.update(choices=["所有交期"], value="所有交期") ) def refresh_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter): c_choices = get_customer_choices() if current_filter not in c_choices: current_filter = "所有顧客" t_choices = get_time_choices() if current_time_filter not in t_choices: current_time_filter = "所有時間" i_choices = get_item_choices() if current_item_filter not in i_choices: current_item_filter = "所有商品" d_choices = get_delivery_choices() if current_delivery_filter not in d_choices: current_delivery_filter = "所有交期" return ( gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)), gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)), gr.update(choices=c_choices, value=current_filter), gr.update(choices=t_choices, value=current_time_filter), gr.update(choices=i_choices, value=current_item_filter), gr.update(choices=d_choices, value=current_delivery_filter) ) def do_login(acc, pwd): acc = acc.strip() pwd = pwd.strip() if not acc: return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(value="❌ 請輸入帳號!"), "", gr.update(value=""), gr.update(value="")) if acc == "admin": if hash_pwd(pwd) == ADMIN_PASSWORD: return (gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(value=""), "admin", gr.update(value="👋 **管理員 您好!**"), gr.update(value="")) else: return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(value="❌ 管理員密碼錯誤!"), "", gr.update(value=""), gr.update(value="")) else: # 會員登入防護 if acc in MEMBERS and MEMBERS[acc].get("password") == hash_pwd(pwd): user_name = MEMBERS[acc].get("name", acc) return (gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(value=""), acc, gr.update(value=f"👋 **會員 {user_name} 您好!**"), gr.update(value="")) else: return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(value="❌ 帳號或密碼錯誤!"), "", gr.update(value=""), gr.update(value="")) def logout(): return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(value=""), gr.update(value=""), gr.update(value=""), "", gr.update(value=""), gr.update(value="")) def run_git_cmd(command): result = subprocess.run(command, shell=True, text=True, capture_output=True) if result.returncode == 0: return True, f"✅ 成功: {command}\n> {result.stdout.strip()}" return False, f"❌ 失敗: {command}\n> {result.stderr.strip()}" def backup_and_push_to_github(): log_messages = ["🚀 開始匯出資料庫備份並推送至 GitHub...\n" + "-"*40] # 將 SQLite 狀態還原匯出成 CSV 以便外部使用與備份 if not orders_db: df = pd.DataFrame(columns=["訂單編號", "狀態", "訂單時間", "預定交期", "取貨方式", "送貨地點", "顧客姓名", "商品", "單價", "成本", "數量", "總價", "總成本", "備註"]) else: export_data = [] for o in orders_db: export_data.append({"訂單編號": o.get("訂單編號", ""), "狀態": o.get("狀態", "處理中"), "訂單時間": o.get("時間", "") or o.get("訂單時間", ""), "預定交期": o.get("預定交期", ""), "取貨方式": o.get("取貨方式", "自取"), "送貨地點": o.get("送貨地點", ""), "顧客姓名": o.get("顧客姓名", ""), "商品": o.get("商品", ""), "單價": o.get("單價", 0), "成本": o.get("成本", 0), "數量": o.get("數量", 0), "總價": o.get("總價", 0), "總成本": o.get("總成本", 0), "備註": o.get("備註", "")}) df = pd.DataFrame(export_data) df.to_csv(BACKUP_FILE, index=False, encoding="utf-8-sig") get_menu_df_for_export().to_csv(MENU_BACKUP_FILE, index=False, encoding="utf-8-sig") get_members_df().to_csv(MEMBERS_BACKUP_FILE, index=False, encoding="utf-8-sig") # 匯出 SQLite 主檔 log_messages.append(f"💾 已封裝 SQLite 資料庫: {DB_FILE}") run_git_cmd('git config user.email "bot@example.com"') run_git_cmd('git config user.name "AutoBackupBot"') success, msg = run_git_cmd("git add .") log_messages.append(msg) commit_msg = f"自動備份: {datetime.now(TAIPEI_TZ).strftime('%Y-%m-%d %H:%M:%S')}" success, msg = run_git_cmd(f'git commit -m "{commit_msg}"') log_messages.append(msg) if not success and ("nothing to commit" in msg or "無檔案要提交" in msg): log_messages.append("ℹ️ 無變更。\n✅ 結束。") return gr.update(value="\n\n".join(log_messages)) hf_token = os.environ.get("HF_TOKEN") if hf_token: repo_url = f"https://oauth2:{hf_token}@huggingface.co/spaces/schillercfk/ssys" run_git_cmd(f"git remote set-url origin {repo_url}") else: log_messages.append("⚠️ 警告:未偵測到 HF_TOKEN!若上傳失敗請至 Settings 設定。") success, msg = run_git_cmd("git push origin main") log_messages.append(msg) if success: log_messages.append("🎉 雲端備份完成!\n\n⚠️ 【重要提示】:\n因為資料已推送至雲端,系統將自動重新啟動來套用變更。\n這看起來會像「網頁當機」或「連線中斷」,這是正常的重新佈署過程!\n👉 請稍候約 30 秒至 1 分鐘,然後「重新整理網頁」即可恢復正常。") else: log_messages.append("❌ 上傳失敗:請檢查 Hugging Face 專案 Settings -> Variables and secrets 是否有設定具備 Write 權限的 HF_TOKEN。") return gr.update(value="\n\n".join(log_messages)) def restore_from_backup(): # 備份還原邏輯 (從 CSV 讀取覆寫進 SQLite) global orders_db, MENU, MEMBERS, APP_CONFIG, ADMIN_PASSWORD msg = "" try: with db_lock: db_cursor.execute('DELETE FROM orders') db_cursor.execute('DELETE FROM menu') db_cursor.execute('DELETE FROM members') db_conn.commit() orders_db.clear() MENU.clear() MEMBERS.clear() migrate_old_data() msg += "✅ 成功從備份檔進行 SQLite 資料庫重建!" except Exception as e: msg += f"❌ 資料庫重建失敗:{e}" cats = get_menu_cat_choices() lvls = get_menu_lvl_choices() items = get_menu_item_choices() init_source = APP_CONFIG.get("bg_source", "default") init_source_str = {"default": "預設圖片", "url": "自訂網址", "upload": "上傳圖片"}.get(init_source, "預設圖片") return ( gr.update(value=msg), get_members_df(), datetime.now(TAIPEI_TZ).timestamp(), gr.update(choices=cats, value="全部分類"), gr.update(choices=lvls, value="全部等級"), gr.update(choices=items, value="所有品項"), generate_bg_css(APP_CONFIG), gr.update(value=init_source_str), gr.update(value=APP_CONFIG.get("bg_url", "")), gr.update(value=APP_CONFIG.get("bg_opacity", 0.85)) ) def autofill_delete_target(evt: gr.SelectData, df_data): try: return str(df_data.iloc[evt.index[0], 0]) except: return "" def autofill_member_form(evt: gr.SelectData, df_data): try: row_idx = evt.index[0] return (df_data.iloc[row_idx, 0], df_data.iloc[row_idx, 1], df_data.iloc[row_idx, 2], df_data.iloc[row_idx, 3], df_data.iloc[row_idx, 4]) except: return "", "", "1", "", "" # ---------------------------- # 🖥️ 網頁介面 (UI) # ---------------------------- custom_css = """ /* 強制置中對齊用的 Column */ .center-col { display: flex !important; flex-direction: column !important; justify-content: center !important; align-items: center !important; margin: auto 0 !important; } .menu-row { border-bottom: 1px solid #e5e7eb; padding: 12px 0; align-items: center; flex-wrap: nowrap !important; gap: 8px !important; } .menu-header { border-bottom: 2px solid #cbd5e1; padding: 8px 0; align-items: center; flex-wrap: nowrap !important; gap: 8px !important; background-color: #f8fafc; border-radius: 8px 8px 0 0; margin-bottom: 8px; } .qty-group { display: flex !important; flex-wrap: nowrap !important; flex-direction: row !important; align-items: center !important; justify-content: center !important; gap: 4px !important; width: 100% !important; background: transparent !important; margin: auto !important; } .qty-group > * { min-width: 0 !important; flex: 0 0 auto !important; margin: 0 !important; } .action-btn { font-size: 18px !important; font-weight: bold !important; border-radius: 8px !important; padding: 0 !important; width: 36px !important; height: 36px !important; min-width: 36px !important; display: flex !important; justify-content: center !important; align-items: center !important; flex-shrink: 0 !important; cursor: pointer !important; } .qty-input { min-width: 45px !important; width: 45px !important; flex-shrink: 0 !important; border: none !important; box-shadow: none !important; background: transparent !important; } .qty-input input { text-align: center !important; font-size: 18px !important; font-weight: bold !important; pointer-events: none !important; touch-action: none !important; padding: 0 !important; height: 36px !important; background: transparent !important; } .github-log textarea { font-family: monospace; background-color: #1e1e1e; color: #00ff00; } .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); } .horizontal-menu-admin { display: flex !important; flex-wrap: nowrap !important; overflow-x: auto !important; gap: 16px !important; padding: 16px 8px !important; align-items: stretch !important; scrollbar-width: thin; } .horizontal-menu-admin::-webkit-scrollbar { height: 8px; } .horizontal-menu-admin::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 4px; } .menu-card-admin { min-width: 300px !important; width: 300px !important; flex: 0 0 auto !important; background: rgba(255, 255, 255, 0.95) !important; border: 1px solid #e2e8f0 !important; border-radius: 12px !important; padding: 16px !important; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1) !important; display: flex !important; flex-direction: column !important; gap: 8px !important; } .new-card-admin { background: rgba(248, 250, 252, 0.95) !important; border: 2px dashed #cbd5e1 !important; } """ kill_badge_js = """ function() { if (window.location.search.includes("openExternalBrowser")) { const newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname; window.history.replaceState({path: newUrl}, "", newUrl); } const nukeHF = () => { ['huggingface-space-header', 'huggingface-workspace-badge', 'huggingface-space-badge'].forEach(tag => { document.querySelectorAll(tag).forEach(el => el.remove()); }); if (document.body) { Array.from(document.body.children).forEach(el => { if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || el.tagName === 'LINK') return; if (el.classList.contains('gradio-container-wrap') || el.querySelector('.gradio-container') || el.id === 'custom-css-injector' || el.id === 'dynamic-bg-css-injector') return; const html = el.innerHTML || ''; if (html.includes('huggingface.co') || html.includes('Sign in') || html.includes('Duplicate Space') || html.includes('Log in')) { el.style.setProperty('display', 'none', 'important'); el.remove(); } }); document.body.style.setProperty('padding-top', '0px', 'important'); document.body.style.setProperty('margin-top', '0px', 'important'); } document.querySelectorAll('.gradio-container-header, footer').forEach(el => el.remove()); if (document.documentElement) document.documentElement.style.setProperty('padding-top', '0px', 'important'); }; const style = document.createElement('style'); style.innerHTML = `huggingface-space-header, huggingface-workspace-badge, huggingface-space-badge { display: none !important; opacity: 0 !important; position: absolute !important; pointer-events: none !important; } .gradio-container-header, footer { display: none !important; }`; document.head.appendChild(style); // 【優化】降低掃描頻率至 500ms,減少前端設備(手機)的 CPU 算力消耗與發熱問題 setInterval(nukeHF, 500); new MutationObserver(nukeHF).observe(document.documentElement, { childList: true, subtree: true }); nukeHF(); return []; } """ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo_ui: gr.HTML(f"", elem_id="custom-css-injector") dynamic_bg_html = gr.HTML(elem_id="dynamic-bg-css-injector") menu_trigger = gr.State(value=0) current_user_state = gr.State(value="") gr.Markdown("