Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,57 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
# ----------------------------
|
| 6 |
-
#
|
| 7 |
# ----------------------------
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
MENU = {
|
| 13 |
"招牌咖啡": 80,
|
| 14 |
"拿鐵咖啡": 100,
|
|
@@ -18,191 +61,227 @@ MENU = {
|
|
| 18 |
}
|
| 19 |
|
| 20 |
# ----------------------------
|
| 21 |
-
#
|
| 22 |
# ----------------------------
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
if not orders_db:
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
return pd.DataFrame(orders_db)
|
| 29 |
|
| 30 |
def get_revenue():
|
| 31 |
-
"""計算目前所有訂單的總營收"""
|
| 32 |
-
if not orders_db:
|
| 33 |
-
return "### 💰 目前總營收:NT$ 0"
|
| 34 |
total = sum(order["總價"] for order in orders_db)
|
| 35 |
return f"### 💰 目前總營收:NT$ {total}"
|
| 36 |
|
| 37 |
-
def
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
def clear_orders():
|
| 78 |
-
"""清空所有訂單"""
|
| 79 |
orders_db.clear()
|
| 80 |
-
return "🗑️ 所有訂單已清空",
|
| 81 |
|
| 82 |
-
# ----------------------------
|
| 83 |
-
# 權限處理邏輯
|
| 84 |
-
# ----------------------------
|
| 85 |
def verify_password(pwd):
|
| 86 |
-
"""驗證管理員密碼"""
|
| 87 |
if pwd == "0000":
|
| 88 |
-
# 密碼正確:隱藏登入區,顯示總覽區,清空錯誤訊息
|
| 89 |
return gr.update(visible=False), gr.update(visible=True), ""
|
| 90 |
-
|
| 91 |
-
# 密碼錯誤:保持現狀,顯示錯誤訊息
|
| 92 |
-
return gr.update(visible=True), gr.update(visible=False), "❌ **密碼錯誤,請重新輸入。**"
|
| 93 |
|
| 94 |
def logout():
|
| 95 |
-
"""登出並恢復到輸入密碼狀態,同時清空密碼欄位"""
|
| 96 |
return gr.update(visible=True), gr.update(visible=False), "", ""
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
# ----------------------------
|
| 99 |
-
#
|
| 100 |
# ----------------------------
|
| 101 |
-
# 加入自訂 CSS 樣式來畫出底部分隔線
|
| 102 |
custom_css = """
|
| 103 |
-
.menu-row {
|
| 104 |
-
|
| 105 |
-
padding-bottom: 15px;
|
| 106 |
-
margin-bottom: 10px !important;
|
| 107 |
-
}
|
| 108 |
"""
|
| 109 |
|
| 110 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統", css=custom_css) as
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
"""
|
| 114 |
-
<h1 style='text-align: center;'>Sch簡易訂單管理系統</h1>
|
| 115 |
-
"""
|
| 116 |
-
)
|
| 117 |
-
|
| 118 |
with gr.Tabs():
|
| 119 |
-
|
| 120 |
-
with gr.TabItem("📝 新增訂單"):
|
| 121 |
with gr.Row():
|
| 122 |
with gr.Column():
|
| 123 |
-
customer_name = gr.Textbox(label="顧客姓名", placeholder="請輸入
|
| 124 |
-
|
| 125 |
gr.Markdown("#### 🛍️ 選擇商品與數量")
|
| 126 |
quantity_components = []
|
| 127 |
-
|
| 128 |
-
# 動態產生每個商品的專屬欄位 (左邊商品名稱,右邊數量)
|
| 129 |
for item, price in MENU.items():
|
| 130 |
-
# 套用自訂的 CSS 類別 "menu-row"
|
| 131 |
with gr.Row(elem_classes="menu-row"):
|
| 132 |
-
# 顯示商品名稱與單價
|
| 133 |
gr.Markdown(f"**{item}** <br><span style='color: gray;'>NT$ {price}</span>")
|
| 134 |
-
|
| 135 |
-
qty = gr.Number(label="數量", value=0, precision=0, minimum=0)
|
| 136 |
quantity_components.append(qty)
|
| 137 |
-
|
| 138 |
-
notes = gr.Textbox(label="備註", placeholder="例如:少冰微糖
|
| 139 |
-
|
| 140 |
submit_btn = gr.Button("🚀 送出訂單", variant="primary")
|
| 141 |
status_msg = gr.Textbox(label="系統狀態", interactive=False)
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
with gr.TabItem("📊 訂單總覽"):
|
| 145 |
-
|
| 146 |
-
# 登入區塊 (預設顯示)
|
| 147 |
with gr.Column(visible=True) as login_pane:
|
| 148 |
gr.Markdown("### 🔒 系統管理員登入")
|
| 149 |
-
admin_pwd = gr.Textbox(label="請輸入
|
| 150 |
login_btn = gr.Button("登入", variant="primary")
|
| 151 |
login_status = gr.Markdown()
|
| 152 |
-
|
| 153 |
-
# 總覽資料區塊 (預設隱藏,登入成功後顯示)
|
| 154 |
with gr.Column(visible=False) as overview_pane:
|
| 155 |
logout_btn = gr.Button("🚪 登出", size="sm")
|
| 156 |
-
gr.
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
)
|
| 168 |
-
|
| 169 |
clear_btn = gr.Button("🗑️ 清空所有訂單", variant="stop")
|
| 170 |
|
| 171 |
-
#
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
inputs=inputs_list,
|
| 181 |
-
outputs=[status_msg, orders_table, revenue_display]
|
| 182 |
-
)
|
| 183 |
-
|
| 184 |
-
# 登入與登出事件:
|
| 185 |
-
login_btn.click(
|
| 186 |
-
fn=verify_password,
|
| 187 |
-
inputs=admin_pwd,
|
| 188 |
-
outputs=[login_pane, overview_pane, login_status]
|
| 189 |
-
)
|
| 190 |
-
|
| 191 |
-
logout_btn.click(
|
| 192 |
-
fn=logout,
|
| 193 |
-
inputs=[],
|
| 194 |
-
outputs=[login_pane, overview_pane, login_status, admin_pwd]
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
# 點擊「清空訂單」時:
|
| 198 |
-
clear_btn.click(
|
| 199 |
-
fn=clear_orders,
|
| 200 |
-
inputs=[],
|
| 201 |
-
outputs=[status_msg, orders_table, revenue_display]
|
| 202 |
-
)
|
| 203 |
|
| 204 |
# ----------------------------
|
| 205 |
-
# 啟
|
| 206 |
# ----------------------------
|
|
|
|
|
|
|
| 207 |
if __name__ == "__main__":
|
| 208 |
-
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
# 【終極防護解除】關閉 Gradio 跨域與 CSRF 阻擋,解決外部瀏覽器與 LINE 內部開啟時的按鈕卡死問題
|
| 5 |
+
os.environ["GRADIO_CSRF_TRUST_ORIGINS"] = "*"
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
import subprocess
|
| 12 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 13 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
+
from linebot import LineBotApi, WebhookHandler
|
| 15 |
+
from linebot.exceptions import InvalidSignatureError
|
| 16 |
+
from linebot.models import MessageEvent, TextMessage, TextSendMessage
|
| 17 |
+
import uvicorn
|
| 18 |
+
except ImportError as e:
|
| 19 |
+
print(f"❌ 啟動失敗:缺少必要的套件!請檢查 requirements.txt。詳細錯誤:{e}")
|
| 20 |
+
sys.exit(1)
|
| 21 |
|
| 22 |
# ----------------------------
|
| 23 |
+
# 📱 LINE Bot 設定區
|
| 24 |
# ----------------------------
|
| 25 |
+
RAW_ACCESS_TOKEN = "HadCmCBmnZtI4LjC1Ad2rBwGZX7x1jZu4A0DXCX+LIjt3SpQq0vVz1kh8U74GB2XPbRdgwfqvFcVRR+i0NodOZ2P6hPC5ZV8EuxPOt+WnAvTJ29P5UBoENQCVAxu/AuRP2xgYKNYOg5voggl73mfkgdB04t89/1O/w1cDnyilFU="
|
| 26 |
+
RAW_SECRET = "ae66c98db5eca3e75aff2ff28ef62f25"
|
| 27 |
+
|
| 28 |
+
# 強制 LINE 使用 Safari/Chrome 外部瀏覽器開啟
|
| 29 |
+
WEB_ORDER_URL = "https://schillercfk-ssys.hf.space/?openExternalBrowser=1"
|
| 30 |
+
|
| 31 |
+
LINE_CHANNEL_ACCESS_TOKEN = RAW_ACCESS_TOKEN.replace(" ", "").strip()
|
| 32 |
+
LINE_CHANNEL_SECRET = RAW_SECRET.replace(" ", "").strip()
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
|
| 36 |
+
handler = WebhookHandler(LINE_CHANNEL_SECRET)
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"❌ LINE API 初始化失敗:{e}")
|
| 39 |
+
|
| 40 |
+
custom_api = FastAPI()
|
| 41 |
|
| 42 |
+
# 【關鍵修復】加入跨域資源共用 (CORS) 中介軟體,確保按鈕送出的訊號不會被手機瀏覽器攔截
|
| 43 |
+
custom_api.add_middleware(
|
| 44 |
+
CORSMiddleware,
|
| 45 |
+
allow_origins=["*"],
|
| 46 |
+
allow_credentials=True,
|
| 47 |
+
allow_methods=["*"],
|
| 48 |
+
allow_headers=["*"],
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# ----------------------------
|
| 52 |
+
# 🛒 系統資料與設定
|
| 53 |
+
# ----------------------------
|
| 54 |
+
orders_db = []
|
| 55 |
MENU = {
|
| 56 |
"招牌咖啡": 80,
|
| 57 |
"拿鐵咖啡": 100,
|
|
|
|
| 61 |
}
|
| 62 |
|
| 63 |
# ----------------------------
|
| 64 |
+
# 🤖 LINE Bot 邏輯
|
| 65 |
# ----------------------------
|
| 66 |
+
@custom_api.post("/callback")
|
| 67 |
+
async def callback(request: Request):
|
| 68 |
+
signature = request.headers.get("X-Line-Signature", "")
|
| 69 |
+
body = await request.body()
|
| 70 |
+
body_str = body.decode("utf-8")
|
| 71 |
+
try:
|
| 72 |
+
handler.handle(body_str, signature)
|
| 73 |
+
except InvalidSignatureError:
|
| 74 |
+
raise HTTPException(status_code=400, detail="Invalid signature")
|
| 75 |
+
return "OK"
|
| 76 |
+
|
| 77 |
+
@handler.add(MessageEvent, message=TextMessage)
|
| 78 |
+
def handle_message(event):
|
| 79 |
+
user_msg = event.message.text.strip()
|
| 80 |
+
user_id = event.source.user_id
|
| 81 |
+
|
| 82 |
+
if "我要訂" in user_msg:
|
| 83 |
+
try:
|
| 84 |
+
parts = user_msg.split()
|
| 85 |
+
item = parts[1]
|
| 86 |
+
quantity = int(parts[2])
|
| 87 |
+
|
| 88 |
+
if item in MENU:
|
| 89 |
+
price = MENU[item]
|
| 90 |
+
total = price * quantity
|
| 91 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 92 |
+
|
| 93 |
+
orders_db.append({
|
| 94 |
+
"時間": timestamp,
|
| 95 |
+
"顧客姓名": f"LINE用戶({user_id[-4:]})",
|
| 96 |
+
"商品": item,
|
| 97 |
+
"單價": price,
|
| 98 |
+
"數量": quantity,
|
| 99 |
+
"總價": total,
|
| 100 |
+
"備註": "來自 LINE 文字點餐"
|
| 101 |
+
})
|
| 102 |
+
reply_text = f"✅ 訂單成立!\n您訂購了 {item} x {quantity}。\n總金額為 {total} 元,請稍候為您準備!"
|
| 103 |
+
else:
|
| 104 |
+
reply_text = f"❌ 找不到商品『{item}』,請確認菜單名稱!\n目前有:{', '.join(MENU.keys())}"
|
| 105 |
+
except Exception:
|
| 106 |
+
reply_text = "❌ 點餐格式錯誤。\n請確認格式為:『我要訂 招牌咖啡 1』"
|
| 107 |
+
|
| 108 |
+
else:
|
| 109 |
+
reply_text = f"歡迎光臨!☕\n\n📱 【網頁快速點餐】\n請點擊下方連結,系統將為您開啟點餐網頁:\n{WEB_ORDER_URL}\n\n💬 【文字點餐】\n您也可以直接輸入例如:『我要訂 拿鐵咖啡 2』 (注意中間要有空格喔!)"
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
line_bot_api.reply_message(event.reply_token, TextSendMessage(text=reply_text))
|
| 113 |
+
except Exception as e:
|
| 114 |
+
print(f"回覆失敗: {e}")
|
| 115 |
+
|
| 116 |
+
# ----------------------------
|
| 117 |
+
# 💻 網頁後台邏輯
|
| 118 |
+
# ----------------------------
|
| 119 |
+
def get_orders_data():
|
| 120 |
+
"""如果資料庫是空的,必須塞入一排空白資料,否則表格會直接讓網頁卡死!"""
|
| 121 |
if not orders_db:
|
| 122 |
+
return [["", "", "", "", "", "", ""]]
|
| 123 |
+
return [[o["時間"], o["顧客姓名"], o["商品"], o["單價"], o["數量"], o["總價"], o["備註"]] for o in orders_db]
|
|
|
|
| 124 |
|
| 125 |
def get_revenue():
|
|
|
|
|
|
|
|
|
|
| 126 |
total = sum(order["總價"] for order in orders_db)
|
| 127 |
return f"### 💰 目前總營收:NT$ {total}"
|
| 128 |
|
| 129 |
+
def refresh_data():
|
| 130 |
+
return get_orders_data(), get_revenue()
|
| 131 |
+
|
| 132 |
+
def add_order(c_name, q0, q1, q2, q3, q4, nts):
|
| 133 |
+
try:
|
| 134 |
+
c_name = str(c_name).strip() if c_name else ""
|
| 135 |
+
nts = str(nts).strip() if nts else ""
|
| 136 |
+
quantities = [q0, q1, q2, q3, q4]
|
| 137 |
+
|
| 138 |
+
if not c_name:
|
| 139 |
+
return "❌ 錯誤:請輸入顧客姓名", get_orders_data(), get_revenue()
|
| 140 |
+
|
| 141 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 142 |
+
total_order_price = 0
|
| 143 |
+
items_desc = []
|
| 144 |
+
has_ordered_items = False
|
| 145 |
+
menu_items = list(MENU.items())
|
| 146 |
+
|
| 147 |
+
for i, qty in enumerate(quantities):
|
| 148 |
+
try:
|
| 149 |
+
qty = int(float(qty)) if qty else 0
|
| 150 |
+
except:
|
| 151 |
+
qty = 0
|
| 152 |
+
|
| 153 |
+
if qty > 0:
|
| 154 |
+
has_ordered_items = True
|
| 155 |
+
item, price = menu_items[i]
|
| 156 |
+
total_price = price * qty
|
| 157 |
+
total_order_price += total_price
|
| 158 |
+
orders_db.append({
|
| 159 |
+
"時間": timestamp, "顧客姓名": c_name, "商品": item,
|
| 160 |
+
"單價": price, "數量": qty, "總價": total_price, "備註": nts
|
| 161 |
+
})
|
| 162 |
+
items_desc.append(f"{item}x{qty}")
|
| 163 |
+
|
| 164 |
+
if not has_ordered_items:
|
| 165 |
+
return "❌ 錯誤:請至少設定一項商品的數量(大於 0)", get_orders_data(), get_revenue()
|
| 166 |
+
|
| 167 |
+
msg = f"✅ 成功新增訂單:{c_name} 訂購了 {', '.join(items_desc)},總計 {total_order_price} 元。"
|
| 168 |
+
return msg, get_orders_data(), get_revenue()
|
| 169 |
+
|
| 170 |
+
except Exception as e:
|
| 171 |
+
return f"❌ 系統發生異常:{str(e)}", get_orders_data(), get_revenue()
|
| 172 |
|
| 173 |
def clear_orders():
|
|
|
|
| 174 |
orders_db.clear()
|
| 175 |
+
return "🗑️ 所有訂單已清空", get_orders_data(), get_revenue()
|
| 176 |
|
|
|
|
|
|
|
|
|
|
| 177 |
def verify_password(pwd):
|
|
|
|
| 178 |
if pwd == "0000":
|
|
|
|
| 179 |
return gr.update(visible=False), gr.update(visible=True), ""
|
| 180 |
+
return gr.update(visible=True), gr.update(visible=False), "❌ **密碼錯誤。**"
|
|
|
|
|
|
|
| 181 |
|
| 182 |
def logout():
|
|
|
|
| 183 |
return gr.update(visible=True), gr.update(visible=False), "", ""
|
| 184 |
|
| 185 |
+
def run_git_cmd(command):
|
| 186 |
+
result = subprocess.run(command, shell=True, text=True, capture_output=True)
|
| 187 |
+
if result.returncode == 0:
|
| 188 |
+
return True, f"✅ 成功: {command}\n> {result.stdout.strip()}"
|
| 189 |
+
return False, f"❌ 失敗: {command}\n> {result.stderr.strip()}"
|
| 190 |
+
|
| 191 |
+
def backup_and_push_to_github():
|
| 192 |
+
log_messages = ["🚀 開始備份...\n" + "-"*40]
|
| 193 |
+
|
| 194 |
+
if not orders_db:
|
| 195 |
+
df = pd.DataFrame(columns=["時間", "顧客姓名", "商品", "單價", "數量", "總價", "備註"])
|
| 196 |
+
else:
|
| 197 |
+
df = pd.DataFrame(orders_db)
|
| 198 |
+
|
| 199 |
+
backup_filename = "orders_backup.csv"
|
| 200 |
+
df.to_csv(backup_filename, index=False, encoding="utf-8-sig")
|
| 201 |
+
log_messages.append(f"💾 已儲存: {backup_filename}")
|
| 202 |
+
|
| 203 |
+
success, msg = run_git_cmd("git add .")
|
| 204 |
+
log_messages.append(msg)
|
| 205 |
+
|
| 206 |
+
commit_msg = f"自動備份: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 207 |
+
success, msg = run_git_cmd(f'git commit -m "{commit_msg}"')
|
| 208 |
+
log_messages.append(msg)
|
| 209 |
+
|
| 210 |
+
if not success and ("nothing to commit" in msg or "無檔案要提交" in msg):
|
| 211 |
+
log_messages.append("ℹ️ 無變更。\n✅ 結束。")
|
| 212 |
+
return "\n\n".join(log_messages)
|
| 213 |
+
|
| 214 |
+
success, msg = run_git_cmd("git push origin main")
|
| 215 |
+
log_messages.append(msg)
|
| 216 |
+
if success:
|
| 217 |
+
log_messages.append("🎉 雲端備份完成!")
|
| 218 |
+
return "\n\n".join(log_messages)
|
| 219 |
+
|
| 220 |
# ----------------------------
|
| 221 |
+
# 🖥️ 網頁介面 (UI)
|
| 222 |
# ----------------------------
|
|
|
|
| 223 |
custom_css = """
|
| 224 |
+
.menu-row { border-bottom: 1px solid #e5e7eb; padding-bottom: 15px; margin-bottom: 10px !important; }
|
| 225 |
+
.github-log textarea { font-family: monospace; background-color: #1e1e1e; color: #00ff00; }
|
|
|
|
|
|
|
|
|
|
| 226 |
"""
|
| 227 |
|
| 228 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統", css=custom_css) as demo_ui:
|
| 229 |
+
gr.Markdown("<h1 style='text-align: center;'>🛒 簡易訂單管理系統 (LINE 整合版)</h1>")
|
| 230 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
with gr.Tabs():
|
| 232 |
+
with gr.TabItem("📝 現場/網頁新增訂單"):
|
|
|
|
| 233 |
with gr.Row():
|
| 234 |
with gr.Column():
|
| 235 |
+
customer_name = gr.Textbox(label="顧客姓名 (或桌號)", placeholder="請輸入姓名或桌號")
|
|
|
|
| 236 |
gr.Markdown("#### 🛍️ 選擇商品與數量")
|
| 237 |
quantity_components = []
|
| 238 |
+
|
|
|
|
| 239 |
for item, price in MENU.items():
|
|
|
|
| 240 |
with gr.Row(elem_classes="menu-row"):
|
|
|
|
| 241 |
gr.Markdown(f"**{item}** <br><span style='color: gray;'>NT$ {price}</span>")
|
| 242 |
+
qty = gr.Number(label="數量", value=0, step=1, minimum=0)
|
|
|
|
| 243 |
quantity_components.append(qty)
|
| 244 |
+
|
| 245 |
+
notes = gr.Textbox(label="備註", placeholder="例如:少冰微糖...")
|
|
|
|
| 246 |
submit_btn = gr.Button("🚀 送出訂單", variant="primary")
|
| 247 |
status_msg = gr.Textbox(label="系統狀態", interactive=False)
|
| 248 |
+
|
| 249 |
+
with gr.TabItem("📊 系統管理與總覽"):
|
|
|
|
|
|
|
|
|
|
| 250 |
with gr.Column(visible=True) as login_pane:
|
| 251 |
gr.Markdown("### 🔒 系統管理員登入")
|
| 252 |
+
admin_pwd = gr.Textbox(label="請輸入密碼", type="password")
|
| 253 |
login_btn = gr.Button("登入", variant="primary")
|
| 254 |
login_status = gr.Markdown()
|
| 255 |
+
|
|
|
|
| 256 |
with gr.Column(visible=False) as overview_pane:
|
| 257 |
logout_btn = gr.Button("🚪 登出", size="sm")
|
| 258 |
+
with gr.Row():
|
| 259 |
+
with gr.Column(scale=2):
|
| 260 |
+
gr.Markdown("### 📊 訂單詳細數據")
|
| 261 |
+
revenue_display = gr.Markdown(value=get_revenue())
|
| 262 |
+
refresh_btn = gr.Button("🔄 抓取最新訂單", variant="secondary")
|
| 263 |
+
with gr.Column(scale=1):
|
| 264 |
+
gr.Markdown("### ☁️ 雲端備份")
|
| 265 |
+
github_btn = gr.Button("🔄 備份至 GitHub", variant="primary")
|
| 266 |
+
|
| 267 |
+
orders_table = gr.Dataframe(value=get_orders_data(), headers=["時間", "顧客姓名", "商品", "單價", "數量", "總價", "備註"], interactive=False)
|
| 268 |
+
github_log_output = gr.Textbox(label="執行日誌", interactive=False, lines=4, elem_classes="github-log")
|
|
|
|
|
|
|
| 269 |
clear_btn = gr.Button("🗑️ 清空所有訂單", variant="stop")
|
| 270 |
|
| 271 |
+
# 事件綁定
|
| 272 |
+
inputs_list = [customer_name] + quantity_components + [notes]
|
| 273 |
+
|
| 274 |
+
submit_btn.click(fn=add_order, inputs=inputs_list, outputs=[status_msg, orders_table, revenue_display])
|
| 275 |
+
login_btn.click(fn=verify_password, inputs=admin_pwd, outputs=[login_pane, overview_pane, login_status])
|
| 276 |
+
logout_btn.click(fn=logout, inputs=[], outputs=[login_pane, overview_pane, login_status, admin_pwd])
|
| 277 |
+
clear_btn.click(fn=clear_orders, inputs=[], outputs=[status_msg, orders_table, revenue_display])
|
| 278 |
+
github_btn.click(fn=backup_and_push_to_github, inputs=[], outputs=[github_log_output])
|
| 279 |
+
refresh_btn.click(fn=refresh_data, inputs=[], outputs=[orders_table, revenue_display])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
# ----------------------------
|
| 282 |
+
# 🚀 啟陪伺服器
|
| 283 |
# ----------------------------
|
| 284 |
+
app = gr.mount_gradio_app(custom_api, demo_ui.queue(), path="/")
|
| 285 |
+
|
| 286 |
if __name__ == "__main__":
|
| 287 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|