schillerCFK commited on
Commit
0b1cbc1
·
verified ·
1 Parent(s): 0f33e7e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +248 -0
app.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_CHANNEL_ACCESS_TOKEN = RAW_ACCESS_TOKEN.replace(" ", "").strip()
24
+ LINE_CHANNEL_SECRET = RAW_SECRET.replace(" ", "").strip()
25
+
26
+ try:
27
+ line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
28
+ handler = WebhookHandler(LINE_CHANNEL_SECRET)
29
+ except Exception as e:
30
+ print(f"❌ LINE API 初始化失敗:{e}")
31
+
32
+ custom_api = FastAPI()
33
+
34
+ # ----------------------------
35
+ # 🛒 系統資料與設定
36
+ # ----------------------------
37
+ orders_db = []
38
+ MENU = {
39
+ "招牌咖啡": 80,
40
+ "拿鐵咖啡": 100,
41
+ "珍珠奶茶": 60,
42
+ "高山青茶": 40,
43
+ "手工餅乾": 50
44
+ }
45
+
46
+ # ----------------------------
47
+ # 🤖 LINE Bot 邏輯
48
+ # ----------------------------
49
+ @custom_api.post("/callback")
50
+ async def callback(request: Request):
51
+ signature = request.headers.get("X-Line-Signature", "")
52
+ body = await request.body()
53
+ body_str = body.decode("utf-8")
54
+ try:
55
+ handler.handle(body_str, signature)
56
+ except InvalidSignatureError:
57
+ raise HTTPException(status_code=400, detail="Invalid signature")
58
+ return "OK"
59
+
60
+ @handler.add(MessageEvent, message=TextMessage)
61
+ def handle_message(event):
62
+ user_msg = event.message.text.strip()
63
+ user_id = event.source.user_id
64
+
65
+ reply_text = "歡迎使用點餐系統!☕\n請輸入例如:『我要訂 拿鐵咖啡 2』\n(請注意中間要有空格喔!)"
66
+
67
+ if "我要訂" in user_msg:
68
+ try:
69
+ parts = user_msg.split()
70
+ item = parts[1]
71
+ quantity = int(parts[2])
72
+
73
+ if item in MENU:
74
+ price = MENU[item]
75
+ total = price * quantity
76
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
77
+
78
+ orders_db.append({
79
+ "時間": timestamp,
80
+ "顧客姓名": f"LINE用戶({user_id[-4:]})",
81
+ "商品": item,
82
+ "單價": price,
83
+ "數量": quantity,
84
+ "總價": total,
85
+ "備註": "來自 LINE 點餐"
86
+ })
87
+ reply_text = f"✅ 訂單成立!\n您訂購了 {item} x {quantity}。\n總金額為 {total} 元,請稍候為您準備!"
88
+ else:
89
+ reply_text = f"❌ 找不到商品『{item}』,請確認菜單名稱!\n目前有:{', '.join(MENU.keys())}"
90
+ except Exception:
91
+ reply_text = "❌ 點餐格式錯誤。\n請確認格式為:『我要訂 招牌咖啡 1』"
92
+
93
+ try:
94
+ line_bot_api.reply_message(event.reply_token, TextSendMessage(text=reply_text))
95
+ except Exception as e:
96
+ print(f"回覆失敗: {e}")
97
+
98
+ # ----------------------------
99
+ # 💻 網頁後台邏輯
100
+ # ----------------------------
101
+ def get_orders_df():
102
+ if not orders_db:
103
+ return pd.DataFrame(columns=["時間", "顧客姓名", "商品", "單價", "數量", "總價", "備註"])
104
+ return pd.DataFrame(orders_db)
105
+
106
+ def get_revenue():
107
+ if not orders_db:
108
+ return "### 💰 目前總營收:NT$ 0"
109
+ total = sum(order["總價"] for order in orders_db)
110
+ return f"### 💰 目前總營收:NT$ {total}"
111
+
112
+ def add_order(customer_name, notes, *quantities):
113
+ if not customer_name.strip():
114
+ return "❌ 錯誤:請輸入顧客姓名", get_orders_df(), get_revenue()
115
+
116
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
117
+ total_order_price = 0
118
+ items_desc = []
119
+ has_ordered_items = False
120
+ menu_items = list(MENU.items())
121
+
122
+ for i, qty in enumerate(quantities):
123
+ if qty > 0:
124
+ has_ordered_items = True
125
+ item, price = menu_items[i]
126
+ total_price = price * qty
127
+ total_order_price += total_price
128
+ orders_db.append({
129
+ "時間": timestamp, "顧客姓名": customer_name, "商品": item,
130
+ "單價": price, "數量": qty, "總價": total_price, "備註": notes
131
+ })
132
+ items_desc.append(f"{item}x{qty}")
133
+
134
+ if not has_ordered_items:
135
+ return "❌ 錯誤:請至少設定數量大於 0", get_orders_df(), get_revenue()
136
+
137
+ msg = f"✅ 成功新增訂單:{customer_name} 訂購了 {', '.join(items_desc)},總計 {total_order_price} 元。"
138
+ return msg, get_orders_df(), get_revenue()
139
+
140
+ def clear_orders():
141
+ orders_db.clear()
142
+ return "🗑️ 所有訂單已清空", get_orders_df(), get_revenue()
143
+
144
+ def verify_password(pwd):
145
+ if pwd == "0000":
146
+ return gr.update(visible=False), gr.update(visible=True), ""
147
+ return gr.update(visible=True), gr.update(visible=False), "❌ **密碼錯誤。**"
148
+
149
+ def logout():
150
+ return gr.update(visible=True), gr.update(visible=False), "", ""
151
+
152
+ def run_git_cmd(command):
153
+ result = subprocess.run(command, shell=True, text=True, capture_output=True)
154
+ if result.returncode == 0:
155
+ return True, f"✅ 成功: {command}\n> {result.stdout.strip()}"
156
+ return False, f"❌ 失敗: {command}\n> {result.stderr.strip()}"
157
+
158
+ def backup_and_push_to_github():
159
+ log_messages = ["🚀 開始備份...\n" + "-"*40]
160
+ df = get_orders_df()
161
+ backup_filename = "orders_backup.csv"
162
+ df.to_csv(backup_filename, index=False, encoding="utf-8-sig")
163
+ log_messages.append(f"💾 已儲存: {backup_filename}")
164
+
165
+ success, msg = run_git_cmd("git add .")
166
+ log_messages.append(msg)
167
+
168
+ commit_msg = f"自動備份: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
169
+ success, msg = run_git_cmd(f'git commit -m "{commit_msg}"')
170
+ log_messages.append(msg)
171
+
172
+ if not success and ("nothing to commit" in msg or "無檔案要提交" in msg):
173
+ log_messages.append("ℹ️ 無變更。\n✅ 結束。")
174
+ return "\n\n".join(log_messages)
175
+
176
+ success, msg = run_git_cmd("git push origin main")
177
+ log_messages.append(msg)
178
+ if success:
179
+ log_messages.append("🎉 雲端備份完成!")
180
+ return "\n\n".join(log_messages)
181
+
182
+ # ----------------------------
183
+ # 🖥️ 網頁介面 (UI)
184
+ # ----------------------------
185
+ custom_css = """
186
+ .menu-row { border-bottom: 1px solid #e5e7eb; padding-bottom: 15px; margin-bottom: 10px !important; }
187
+ .github-log textarea { font-family: monospace; background-color: #1e1e1e; color: #00ff00; }
188
+ """
189
+
190
+ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統", css=custom_css) as demo_ui:
191
+ gr.Markdown("<h1 style='text-align: center;'>🛒 簡易訂單管理系統 (LINE 整合版)</h1>")
192
+
193
+ with gr.Tabs():
194
+ with gr.TabItem("📝 現場新增訂單"):
195
+ with gr.Row():
196
+ with gr.Column():
197
+ customer_name = gr.Textbox(label="顧客姓名", placeholder="請輸入姓名")
198
+ gr.Markdown("#### 🛍️ 選擇商品與數量")
199
+ quantity_components = []
200
+
201
+ for item, price in MENU.items():
202
+ with gr.Row(elem_classes="menu-row"):
203
+ gr.Markdown(f"**{item}** <br><span style='color: gray;'>NT$ {price}</span>")
204
+ qty = gr.Number(label="數量", value=0, precision=0, minimum=0)
205
+ quantity_components.append(qty)
206
+
207
+ notes = gr.Textbox(label="備註", placeholder="例如:少冰微糖...")
208
+ submit_btn = gr.Button("🚀 送出訂單", variant="primary")
209
+ status_msg = gr.Textbox(label="系統狀態", interactive=False)
210
+
211
+ with gr.TabItem("📊 系統管理與總覽"):
212
+ with gr.Column(visible=True) as login_pane:
213
+ gr.Markdown("### 🔒 系統管理員登入")
214
+ admin_pwd = gr.Textbox(label="請輸入密碼", type="password")
215
+ login_btn = gr.Button("登入", variant="primary")
216
+ login_status = gr.Markdown()
217
+
218
+ with gr.Column(visible=False) as overview_pane:
219
+ logout_btn = gr.Button("🚪 登出", size="sm")
220
+ with gr.Row():
221
+ with gr.Column(scale=2):
222
+ gr.Markdown("### 📊 訂單詳細數據")
223
+ revenue_display = gr.Markdown(get_revenue())
224
+ refresh_btn = gr.Button("🔄 抓取最新訂單", variant="secondary")
225
+ with gr.Column(scale=1):
226
+ gr.Markdown("### ☁️ 雲端備份")
227
+ github_btn = gr.Button("🔄 備份至 GitHub", variant="primary")
228
+
229
+ orders_table = gr.Dataframe(value=get_orders_df(), headers=["時間", "顧客姓名", "商品", "單價", "數量", "總價", "備註"], interactive=False, wrap=True)
230
+ github_log_output = gr.Textbox(label="執行日誌", interactive=False, lines=4, elem_classes="github-log")
231
+ clear_btn = gr.Button("🗑️ 清空所有訂單", variant="stop")
232
+
233
+ # 事件綁定
234
+ inputs_list = [customer_name, notes] + quantity_components
235
+ submit_btn.click(fn=add_order, inputs=inputs_list, outputs=[status_msg, orders_table, revenue_display])
236
+ login_btn.click(fn=verify_password, inputs=admin_pwd, outputs=[login_pane, overview_pane, login_status])
237
+ logout_btn.click(fn=logout, inputs=[], outputs=[login_pane, overview_pane, login_status, admin_pwd])
238
+ clear_btn.click(fn=clear_orders, inputs=[], outputs=[status_msg, orders_table, revenue_display])
239
+ github_btn.click(fn=backup_and_push_to_github, inputs=[], outputs=[github_log_output])
240
+ refresh_btn.click(fn=lambda: (get_orders_df(), get_revenue()), inputs=[], outputs=[orders_table, revenue_display])
241
+
242
+ # ----------------------------
243
+ # 🚀 啟動伺服器
244
+ # ----------------------------
245
+ app = gr.mount_gradio_app(custom_api, demo_ui, path="/")
246
+
247
+ if __name__ == "__main__":
248
+ uvicorn.run(app, host="0.0.0.0", port=7860)