schillerCFK commited on
Commit
c70e583
·
verified ·
1 Parent(s): 80b0388

Update app.py

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