DeepLearning101 commited on
Commit
ec81d8b
·
verified ·
1 Parent(s): e965db3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -214
app.py CHANGED
@@ -4,26 +4,28 @@ import requests
4
  from supabase import create_client, Client
5
  from datetime import datetime, timedelta, timezone
6
 
7
- # 設定台北時區
8
  TAIPEI_TZ = timezone(timedelta(hours=8))
9
-
10
- # --- 1. 連線設定 ---
11
- # 請確認 HF Secrets 裡都有設定這些變數
12
  LINE_ACCESS_TOKEN = os.getenv("LINE_ACCESS_TOKEN")
13
  LINE_ADMIN_ID = os.getenv("LINE_ADMIN_ID")
14
  SUPABASE_URL = os.getenv("SUPABASE_URL")
15
  SUPABASE_KEY = os.getenv("SUPABASE_KEY")
16
 
17
- # 建立 Supabase 連線
18
  if SUPABASE_URL and SUPABASE_KEY:
19
  supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
20
- else:
21
- print("⚠️ 警告:SUPABASE 環境變數未設定")
22
 
23
- # --- 2. 輔助函式 (日期與時間) ---
 
 
 
 
 
 
 
 
 
24
  def get_date_options():
25
  options = []
26
- # 這裡一定要加時區,不然會抓到 UTC 時間
27
  today = datetime.now(TAIPEI_TZ)
28
  weekdays = ["(一)", "(二)", "(三)", "(四)", "(五)", "(六)", "(日)"]
29
  for i in range(30):
@@ -33,263 +35,140 @@ def get_date_options():
33
  return options
34
 
35
  def update_time_slots(date_str):
36
- if not date_str:
37
- return gr.update(choices=[]), "請先選擇日期"
38
  try:
39
  clean_date_str = date_str.split(" ")[0]
40
  date_obj = datetime.strptime(clean_date_str, "%Y-%m-%d")
41
  weekday = date_obj.weekday()
42
- except:
43
- return gr.update(choices=[]), "日期格式錯誤"
44
-
45
- slots = ["18:30", "19:00", "19:30", "20:00", "20:30",
46
- "21:00", "21:30", "22:00", "22:30", "23:00", "23:30",
47
- "00:00", "00:30", "01:00"]
48
-
49
- if weekday == 4 or weekday == 5:
50
- slots.extend(["01:30", "02:00", "02:30"])
51
- status_msg = f"✨ 已選擇 {date_str} (週末營業至 03:00)"
52
- else:
53
- slots.extend(["01:30"])
54
- status_msg = f"🌙 已選擇 {date_str} (平日營業至 02:00)"
55
-
56
- return gr.update(choices=slots, value=slots[0] if slots else None), status_msg
57
 
58
- # --- 3. LINE 通知函式 ---
59
- def send_line_notify(data):
60
- if not LINE_ACCESS_TOKEN or not LINE_ADMIN_ID:
61
- return
62
 
63
- # 簡單的文字通知
64
- message = (
65
- f"🔥 新訂位通知 🔥\n"
66
- f"姓名:{data['name']}\n"
67
- f"電話:{data['tel']}\n"
68
- f"日期:{data['date']} {data['time']}\n"
69
- f"人數:{data['pax']} 位\n"
70
- f"Email:{data.get('email', '-')}\n"
71
- f"備註:{data.get('remarks', '無')}"
72
- )
73
 
74
  try:
75
- requests.post(
76
- "https://api.line.me/v2/bot/message/push",
77
- headers={
78
- "Authorization": f"Bearer {LINE_ACCESS_TOKEN}",
79
- "Content-Type": "application/json"
80
- },
81
- json={
82
- "to": LINE_ADMIN_ID,
83
- "messages": [{"type": "text", "text": message}]
84
- }
85
- )
86
- except Exception as e:
87
- print(f"LINE 發送失敗: {e}")
 
 
88
 
89
- # --- 4. 核心邏輯:處理訂位 ---
90
- def handle_booking(name, tel, email, date_str, time, pax, remarks):
91
  if not name or not tel or not date_str or not time:
92
  return "⚠️ 請完整填寫必填欄位 (姓名、電話、日期、時間)"
 
 
 
 
93
 
94
- # --- 1. 防呆機制:檢查是否重複提交 ---
95
  try:
96
- # 搜尋該電話在該時段的訂單
97
- existing = supabase.table("bookings").select("id")\
98
- .eq("tel", tel)\
99
- .eq("date", date_str)\
100
- .eq("time", time)\
101
- .neq("status", "顧客已取消")\
102
- .execute()
103
-
104
- if existing.data and len(existing.data) > 0:
105
- return "⚠️ 系統偵測到您已預約過此時段,請勿重複提交。"
106
- except Exception as e:
107
- print(f"Check duplicate error: {e}")
108
- pass
109
 
110
- # --- 準備資料 ---
111
  data = {
112
- "name": name,
113
- "tel": tel,
114
- "email": email,
115
- "date": date_str,
116
- "time": time,
117
- "pax": pax,
118
- "remarks": remarks,
119
- "status": "待處理"
120
  }
121
 
122
  try:
123
- # 2. 寫入資料庫
124
  supabase.table("bookings").insert(data).execute()
125
 
126
- # 3. 發送 LINE 通知
127
- send_line_notify(data)
128
-
129
- # 4. 回傳成功訊息
130
- return """
131
- <div style='text-align: center; color: #fff; padding: 20px; border: 1px solid #d4af37; border-radius: 8px; background: #222;'>
132
- <h2 style='color: #d4af37; margin: 0;'>Request Received</h2>
133
- <p style='margin: 10px 0;'>🥂 預約申請已提交</p>
134
- <p style='font-size: 0.9em; color: #aaa;'>系統將發送確認信至您的 Email。</p>
135
- <p style='font-size: 0.85em; color: #ff5252; margin-top: 5px;'>
136
- (若未收到,請檢查您的<b>垃圾信件匣</b>)
137
- </p>
138
- </div>
139
- """
140
- except Exception as e:
141
- print(f"Error: {e}")
142
- return f"❌ 系統錯誤: {str(e)}"
143
 
144
- # --- 5. 核心邏輯:處理確認連結 (Webhook) ---
145
- # ⚠️ 修正重點:這裡是 check_confirmation,不是 send_confirmation_email
 
 
146
  def check_confirmation(request: gr.Request):
147
- """
148
- 當網址帶有 ?id=xx&action=confirm 或 ?id=xx&action=cancel 時觸發
149
- """
150
  if not request: return ""
151
- params = request.query_params
152
- action = params.get('action')
153
- bid = params.get('id')
154
 
155
- # --- 情況 A: 確認訂位 ---
156
  if action == 'confirm' and bid:
157
  try:
158
- # 更新資料庫狀態
159
  supabase.table("bookings").update({"status": "顧客已確認"}).eq("id", bid).execute()
160
-
161
- return f"""
162
- <script>
163
- document.addEventListener('DOMContentLoaded', function() {{
164
- alert('✅ 感謝您!訂位已確認 (編號 {bid})');
165
- }});
166
- </script>
167
- <div style='padding:20px; background:#d4af37; color:black; text-align:center; margin-bottom:20px; border-radius:8px; font-weight:bold;'>
168
- 🎉 感謝您的確認!我們期待您的光臨。 (訂單編號: {bid})
169
- </div>
170
- """
171
- except Exception as e:
172
- print(f"Confirm Error: {e}")
173
- return ""
174
-
175
- # --- 情況 B: 取消訂位 ---
176
  elif action == 'cancel' and bid:
177
  try:
178
- # 更新資料庫狀態
179
  supabase.table("bookings").update({"status": "顧客已取消"}).eq("id", bid).execute()
180
-
181
- return f"""
182
- <script>
183
- document.addEventListener('DOMContentLoaded', function() {{
184
- alert('已為您取消訂位 (編號 {bid})');
185
- }});
186
- </script>
187
- <div style='padding:20px; background:#333; border: 1px solid #ff5252; color:#ff5252; text-align:center; margin-bottom:20px; border-radius:8px;'>
188
- 🚫 訂位已取消。<br>期待您下次有機會再來訪。
189
- </div>
190
- """
191
- except Exception as e:
192
- print(f"Cancel Error: {e}")
193
- return ""
194
-
195
  return ""
196
 
197
- # --- 6. 介面設定 (Theme & CSS) ---
198
- theme = gr.themes.Soft(
199
- primary_hue="amber",
200
- neutral_hue="zinc",
201
- font=[gr.themes.GoogleFont("Playfair Display"), "ui-sans-serif", "sans-serif"],
202
- ).set(
203
- body_background_fill="#0F0F0F",
204
- block_background_fill="#1a1a1a",
205
- block_border_width="1px",
206
- block_border_color="#333",
207
- input_background_fill="#262626",
208
- input_border_color="#444",
209
- body_text_color="#E0E0E0",
210
- block_title_text_color="#d4af37",
211
- button_primary_background_fill="#d4af37",
212
- button_primary_text_color="#000000",
213
- )
214
 
215
- custom_css = """
216
- footer {display: none !important;}
217
- .gradio-container, .block, .row, .column { overflow: visible !important; }
218
- .options, .wrap .options {
219
- background-color: #262626 !important;
220
- border: 1px solid #d4af37 !important;
221
- z-index: 10000 !important;
222
- box-shadow: 0 5px 15px rgba(0,0,0,0.5);
223
- }
224
- .item, .options .item { color: #E0E0E0 !important; padding: 8px 12px !important; }
225
- .item:hover, .item.selected, .options .item:hover { background-color: #d4af37 !important; color: black !important; }
226
- input:focus, .dropdown-trigger:focus-within { border-color: #d4af37 !important; box-shadow: 0 0 8px rgba(212, 175, 55, 0.4) !important; }
227
- h3 { border-bottom: 1px solid #444; padding-bottom: 5px; margin-bottom: 10px; }
228
- .legal-footer {
229
- text-align: center; margin-top: 15px; padding-top: 15px; border-top: 1px solid #333; color: #666; font-size: 0.75rem; line-height: 1.5; font-family: sans-serif;
230
- }
231
- .legal-footer strong { color: #888; }
232
- """
233
-
234
- # --- 7. 介面佈局 (完整版) ---
235
  with gr.Blocks(theme=theme, css=custom_css, title="Booking") as demo:
236
-
237
- # [隱藏] 用來接收 URL 確認參數的區塊
238
  confirm_msg_box = gr.HTML()
239
 
240
- # 頁面載入時,執行 check_confirmation
241
- demo.load(check_confirmation, inputs=None, outputs=confirm_msg_box)
 
242
 
243
  with gr.Row():
244
  with gr.Column():
245
- gr.Markdown("### 📅 預約資訊 Booking Info")
246
-
247
  date_options = get_date_options()
248
- booking_date = gr.Dropdown(choices=date_options, label="選擇日期 Select Date", interactive=True)
249
- pax_count = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="用餐人數 Guest Count")
250
-
251
  with gr.Column():
252
- gr.Markdown("### 🕰️ 選擇時段 Time Slot")
253
  status_box = gr.Markdown("請先選擇日期...", visible=True)
254
- time_slot = gr.Dropdown(choices=[], label="可用時段 Available Time", interactive=True)
255
-
256
  gr.HTML("<div style='height: 10px'></div>")
257
-
258
- gr.Markdown("### 👤 聯絡人資料 Contact,收到確認 E-Mail 並點擊 確認出席 才算訂位成功")
259
  with gr.Group():
260
  with gr.Row():
261
- cust_name = gr.Textbox(label="訂位姓名 Name *", placeholder="ex. 王小明")
262
- cust_tel = gr.Textbox(label="手機號碼 Phone *", placeholder="ex. 0912-xxx-xxx")
263
-
264
  with gr.Row():
265
- cust_email = gr.Textbox(label="電子信箱 E-mail (接收確認信用,請記得檢查垃圾信件匣。)", placeholder="example@gmail.com")
266
  with gr.Row():
267
- cust_remarks = gr.Textbox(label="備註 Remarks (過敏/慶生/特殊需求)", lines=2)
268
 
269
  gr.HTML("<div style='height: 15px'></div>")
270
-
271
- submit_btn = gr.Button("確認預約 Request Booking (系統會記錄是否曾 No Show)", size="lg", variant="primary")
272
  output_msg = gr.HTML()
273
-
274
- # 頁尾警語
275
- gr.HTML("""
276
- <div class="legal-footer">
277
- <p style="margin-bottom: 5px;">© 2026 CIE CIE TAIPEI. All Rights Reserved.</p>
278
- <p>內容涉及酒類產品訊息,請勿轉發分享給未達法定購買年齡者;未滿十八歲請勿飲酒。<br>
279
- <strong>喝酒不開車,開車不喝酒。</strong></p>
280
- </div>
281
- """)
282
 
283
- # --- 互動事件綁定 ---
284
- # 1. 日期改變 -> 更新時段
285
  booking_date.change(update_time_slots, inputs=booking_date, outputs=[time_slot, status_box])
286
-
287
- # 2. 送出按鈕 -> 處理訂位
288
- submit_btn.click(
289
- handle_booking,
290
- inputs=[cust_name, cust_tel, cust_email, booking_date, time_slot, pax_count, cust_remarks],
291
- outputs=output_msg
292
- )
293
 
294
  if __name__ == "__main__":
295
  demo.launch()
 
4
  from supabase import create_client, Client
5
  from datetime import datetime, timedelta, timezone
6
 
7
+ # --- 1. 設定與初始化 ---
8
  TAIPEI_TZ = timezone(timedelta(hours=8))
 
 
 
9
  LINE_ACCESS_TOKEN = os.getenv("LINE_ACCESS_TOKEN")
10
  LINE_ADMIN_ID = os.getenv("LINE_ADMIN_ID")
11
  SUPABASE_URL = os.getenv("SUPABASE_URL")
12
  SUPABASE_KEY = os.getenv("SUPABASE_KEY")
13
 
 
14
  if SUPABASE_URL and SUPABASE_KEY:
15
  supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
 
 
16
 
17
+ # --- 2. 座位控管設定 (老闆可在此修改) ---
18
+ DEFAULT_LIMIT = 30 # 平日預設總座位數
19
+ SPECIAL_DAYS = {
20
+ "2026-02-14": 10, # 情人節
21
+ "2026-02-15": 5, #
22
+ "2026-02-16": 5, #
23
+ "2026-02-17": 5, #
24
+ }
25
+
26
+ # --- 3. 輔助函式 ---
27
  def get_date_options():
28
  options = []
 
29
  today = datetime.now(TAIPEI_TZ)
30
  weekdays = ["(一)", "(二)", "(三)", "(四)", "(五)", "(六)", "(日)"]
31
  for i in range(30):
 
35
  return options
36
 
37
  def update_time_slots(date_str):
38
+ if not date_str: return gr.update(choices=[]), "請先選擇日期"
 
39
  try:
40
  clean_date_str = date_str.split(" ")[0]
41
  date_obj = datetime.strptime(clean_date_str, "%Y-%m-%d")
42
  weekday = date_obj.weekday()
43
+ except: return gr.update(choices=[]), "日期格式錯誤"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ # 時段設定
46
+ slots = ["18:00", "18:30", "19:00", "19:30", "20:00", "20:30",
47
+ "21:00", "21:30", "22:00", "22:30", "23:00", "23:30", "00:00", "00:30", "01:00"]
48
+ if weekday == 4 or weekday == 5: slots.extend(["01:30", "02:00", "02:30"])
49
 
50
+ # 檢查剩餘座位
51
+ clean_date = date_str.split(" ")[0]
52
+ daily_limit = SPECIAL_DAYS.get(clean_date, DEFAULT_LIMIT)
 
 
 
 
 
 
 
53
 
54
  try:
55
+ res = supabase.table("bookings").select("pax").eq("date", date_str).neq("status", "顧客已取消").execute()
56
+ current_total = sum([item['pax'] for item in res.data])
57
+ remaining = daily_limit - current_total
58
+ status_msg = f"📅 {date_str} (剩餘座位: {remaining} 位)"
59
+ except:
60
+ status_msg = f"📅 {date_str}"
61
+
62
+ return gr.update(choices=slots, value=slots[0] if slots else None), status_msg
63
+
64
+ # --- 4. 核心邏輯 ---
65
+ def get_line_id_from_url(request: gr.Request):
66
+ """從網址參數讀取 line_id"""
67
+ if request:
68
+ return request.query_params.get("line_id", "")
69
+ return ""
70
 
71
+ def handle_booking(name, tel, email, date_str, time, pax, remarks, line_id):
 
72
  if not name or not tel or not date_str or not time:
73
  return "⚠️ 請完整填寫必填欄位 (姓名、電話、日期、時間)"
74
+
75
+ # A. 檢查座位上限
76
+ clean_date = date_str.split(" ")[0]
77
+ daily_limit = SPECIAL_DAYS.get(clean_date, DEFAULT_LIMIT)
78
 
 
79
  try:
80
+ res = supabase.table("bookings").select("pax").eq("date", date_str).neq("status", "顧客已取消").execute()
81
+ current_total = sum([item['pax'] for item in res.data])
82
+
83
+ if current_total + pax > daily_limit:
84
+ return f"⚠️ 抱歉,該時段剩餘座位不足 (剩 {daily_limit - current_total} 位),無法容納您的訂位。"
85
+ except: pass
86
+
87
+ # B. 防重複提交
88
+ try:
89
+ existing = supabase.table("bookings").select("id").eq("tel", tel).eq("date", date_str).eq("time", time).neq("status", "顧客已取消").execute()
90
+ if existing.data: return "⚠️ 系統偵測到您已預約過此時段,請勿重複提交。"
91
+ except: pass
 
92
 
93
+ # C. 寫入資料庫
94
  data = {
95
+ "name": name, "tel": tel, "email": email, "date": date_str, "time": time,
96
+ "pax": pax, "remarks": remarks, "status": "待處理",
97
+ "user_id": line_id # 存入 LINE ID
 
 
 
 
 
98
  }
99
 
100
  try:
 
101
  supabase.table("bookings").insert(data).execute()
102
 
103
+ # D. 發送 LINE Notify 給老闆
104
+ if LINE_ACCESS_TOKEN and LINE_ADMIN_ID:
105
+ source_type = "🟢 LINE用戶" if line_id else "⚪ 一般訪客"
106
+ msg = f"🔥 新訂位 ({source_type})\n姓名:{name}\n電話:{tel}\n時間:{date_str} {time}\n人數:{pax}位"
107
+ requests.post("https://api.line.me/v2/bot/message/push", headers={"Authorization": f"Bearer {LINE_ACCESS_TOKEN}", "Content-Type": "application/json"}, json={"to": LINE_ADMIN_ID, "messages": [{"type": "text", "text": msg}]})
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
+ return """<div style='text-align: center; color: #fff; padding: 20px; border: 1px solid #d4af37; border-radius: 8px; background: #222;'><h2 style='color: #d4af37; margin: 0;'>Request Received</h2><p style='margin: 10px 0;'>🥂 預約申請已提交</p><p style='font-size: 0.9em; color: #aaa;'>請留意您的 Email 確認信。</p></div>"""
110
+ except Exception as e: return f"❌ 系統錯誤: {str(e)}"
111
+
112
+ # --- 5. 處理確認/取消連結 (Webhook) ---
113
  def check_confirmation(request: gr.Request):
 
 
 
114
  if not request: return ""
115
+ action = request.query_params.get('action')
116
+ bid = request.query_params.get('id')
 
117
 
 
118
  if action == 'confirm' and bid:
119
  try:
 
120
  supabase.table("bookings").update({"status": "顧客已確認"}).eq("id", bid).execute()
121
+ return f"""<script>alert('✅ 訂位已確認 (編號 {bid})');</script><div style='padding:20px; background:#d4af37; color:black; text-align:center; border-radius:8px; font-weight:bold;'>🎉 感謝您的確認!��們期待您的光臨。</div>"""
122
+ except: return ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  elif action == 'cancel' and bid:
124
  try:
 
125
  supabase.table("bookings").update({"status": "顧客已取消"}).eq("id", bid).execute()
126
+ return f"""<script>alert('已為您取消訂位 (編號 {bid})');</script><div style='padding:20px; background:#333; border:1px solid #ff5252; color:#ff5252; text-align:center; border-radius:8px;'>🚫 訂位已取消。<br>期待您下次有機會再來訪。</div>"""
127
+ except: return ""
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  return ""
129
 
130
+ # --- 6. 介面佈局 ---
131
+ theme = gr.themes.Soft(primary_hue="amber", neutral_hue="zinc").set(body_background_fill="#0F0F0F", block_background_fill="#1a1a1a", block_border_width="1px", block_border_color="#333", input_background_fill="#262626", input_border_color="#444", body_text_color="#E0E0E0", block_title_text_color="#d4af37", button_primary_background_fill="#d4af37", button_primary_text_color="#000000")
132
+ custom_css = "footer {display: none !important;} .gradio-container, .block, .row, .column { overflow: visible !important; } .options, .wrap .options { background-color: #262626 !important; border: 1px solid #d4af37 !important; z-index: 10000 !important; } .item:hover, .options .item:hover { background-color: #d4af37 !important; color: black !important; } .legal-footer { text-align: center; margin-top: 15px; padding-top: 15px; border-top: 1px solid #333; color: #666; font-size: 0.75rem; }"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  with gr.Blocks(theme=theme, css=custom_css, title="Booking") as demo:
135
+ # 接收 URL 參數的隱藏元件
136
+ line_id_box = gr.Textbox(visible=False)
137
  confirm_msg_box = gr.HTML()
138
 
139
+ # 載入時執行 JS 抓參數
140
+ demo.load(get_line_id_from_url, None, line_id_box)
141
+ demo.load(check_confirmation, None, confirm_msg_box)
142
 
143
  with gr.Row():
144
  with gr.Column():
145
+ gr.Markdown("### 📅 預約資訊")
 
146
  date_options = get_date_options()
147
+ booking_date = gr.Dropdown(choices=date_options, label="日期 Select Date", interactive=True)
148
+ pax_count = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="人數 Guest Count")
 
149
  with gr.Column():
150
+ gr.Markdown("### 🕰️ 選擇時段")
151
  status_box = gr.Markdown("請先選擇日期...", visible=True)
152
+ time_slot = gr.Dropdown(choices=[], label="時段 Available Time", interactive=True)
153
+
154
  gr.HTML("<div style='height: 10px'></div>")
155
+ gr.Markdown("### 👤 聯絡資料")
 
156
  with gr.Group():
157
  with gr.Row():
158
+ cust_name = gr.Textbox(label="姓名 Name", placeholder="ex. 王小明")
159
+ cust_tel = gr.Textbox(label="電話 Phone", placeholder="09xx-xxx-xxx")
 
160
  with gr.Row():
161
+ cust_email = gr.Textbox(label="Email (接收確認信)", placeholder="example@gmail.com")
162
  with gr.Row():
163
+ cust_remarks = gr.Textbox(label="備註 Remarks", lines=2)
164
 
165
  gr.HTML("<div style='height: 15px'></div>")
166
+ submit_btn = gr.Button("確認預約 Request Booking", size="lg", variant="primary")
 
167
  output_msg = gr.HTML()
168
+ gr.HTML("""<div class="legal-footer"><p>© 2026 CIE CIE TAIPEI. <br>未滿十八歲請勿飲酒。喝酒不開車。</p></div>""")
 
 
 
 
 
 
 
 
169
 
 
 
170
  booking_date.change(update_time_slots, inputs=booking_date, outputs=[time_slot, status_box])
171
+ submit_btn.click(handle_booking, inputs=[cust_name, cust_tel, cust_email, booking_date, time_slot, pax_count, cust_remarks, line_id_box], outputs=output_msg)
 
 
 
 
 
 
172
 
173
  if __name__ == "__main__":
174
  demo.launch()