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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -65
app.py CHANGED
@@ -4,7 +4,7 @@ import requests
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")
@@ -14,16 +14,14 @@ SUPABASE_KEY = os.getenv("SUPABASE_KEY")
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)
@@ -42,7 +40,6 @@ def update_time_slots(date_str):
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"])
@@ -55,61 +52,48 @@ def update_time_slots(date_str):
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')
@@ -118,57 +102,74 @@ def check_confirmation(request: gr.Request):
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()
 
4
  from supabase import create_client, Client
5
  from datetime import datetime, timedelta, timezone
6
 
7
+ # --- 設定 ---
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")
 
14
  if SUPABASE_URL and SUPABASE_KEY:
15
  supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
16
 
17
+ # --- 📅 座位控管設定 (在此修改特殊節日上限) ---
18
+ DEFAULT_LIMIT = 30
19
  SPECIAL_DAYS = {
20
+ "2026-12-31": 10, # 跨年夜
21
+ "2026-02-14": 15 # 情人節
 
 
22
  }
23
 
24
+ # --- 輔助函式 ---
25
  def get_date_options():
26
  options = []
27
  today = datetime.now(TAIPEI_TZ)
 
40
  weekday = date_obj.weekday()
41
  except: return gr.update(choices=[]), "日期格式錯誤"
42
 
 
43
  slots = ["18:00", "18:30", "19:00", "19:30", "20:00", "20:30",
44
  "21:00", "21:30", "22:00", "22:30", "23:00", "23:30", "00:00", "00:30", "01:00"]
45
  if weekday == 4 or weekday == 5: slots.extend(["01:30", "02:00", "02:30"])
 
52
  res = supabase.table("bookings").select("pax").eq("date", date_str).neq("status", "顧客已取消").execute()
53
  current_total = sum([item['pax'] for item in res.data])
54
  remaining = daily_limit - current_total
55
+ status_msg = f" {date_str} (剩餘座位: {remaining} 位)"
56
+ except: status_msg = f"✨ {date_str}"
 
57
 
58
  return gr.update(choices=slots, value=slots[0] if slots else None), status_msg
59
 
60
+ # --- 核心邏輯 ---
61
  def get_line_id_from_url(request: gr.Request):
62
+ if request: return request.query_params.get("line_id", "")
 
 
63
  return ""
64
 
65
  def handle_booking(name, tel, email, date_str, time, pax, remarks, line_id):
66
  if not name or not tel or not date_str or not time:
67
+ return "⚠️ 請完整填寫必填欄位"
68
 
69
+ # 座位檢查
70
  clean_date = date_str.split(" ")[0]
71
  daily_limit = SPECIAL_DAYS.get(clean_date, DEFAULT_LIMIT)
 
72
  try:
73
  res = supabase.table("bookings").select("pax").eq("date", date_str).neq("status", "顧客已取消").execute()
74
+ if sum([i['pax'] for i in res.data]) + pax > daily_limit:
75
+ return "⚠️ 抱歉,該時段剩餘座位不足,請調整人數或日期。"
76
+ except: pass
 
 
77
 
78
+ # 防重複
79
  try:
80
  existing = supabase.table("bookings").select("id").eq("tel", tel).eq("date", date_str).eq("time", time).neq("status", "顧客已取消").execute()
81
+ if existing.data: return "⚠️ 您已預約過此時段,請勿重複提交。"
82
  except: pass
83
 
84
+ data = {"name": name, "tel": tel, "email": email, "date": date_str, "time": time, "pax": pax, "remarks": remarks, "status": "待處理", "user_id": line_id}
 
 
 
 
 
85
 
86
  try:
87
  supabase.table("bookings").insert(data).execute()
 
 
88
  if LINE_ACCESS_TOKEN and LINE_ADMIN_ID:
89
+ src = "🟢 LINE用戶" if line_id else "⚪ 訪客"
90
+ msg = f"🔥 新訂位 ({src})\n{name} / {tel}\n{date_str} {time} ({pax}人)"
91
  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}]})
92
+
93
+ 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>"""
94
  except Exception as e: return f"❌ 系統錯誤: {str(e)}"
95
 
96
+ # --- Webhook (確認/取消) ---
97
  def check_confirmation(request: gr.Request):
98
  if not request: return ""
99
  action = request.query_params.get('action')
 
102
  if action == 'confirm' and bid:
103
  try:
104
  supabase.table("bookings").update({"status": "顧客已確認"}).eq("id", bid).execute()
105
+ return f"""<script>alert('✅ 訂位已確認 (編號 {bid})');</script><div style='padding:20px; background:#d4af37; color:black; text-align:center; border-radius:8px;'>🎉 感謝確認!</div>"""
106
  except: return ""
107
  elif action == 'cancel' and bid:
108
  try:
109
  supabase.table("bookings").update({"status": "顧客已取消"}).eq("id", bid).execute()
110
+ return f"""<script>alert('已取消訂位 (編號 {bid})');</script><div style='padding:20px; background:#333; color:#ff5252; text-align:center; border:1px solid #ff5252; border-radius:8px;'>🚫 訂位已取消。</div>"""
111
  except: return ""
112
  return ""
113
 
114
+ # --- 7. 介面佈局 (完整版) ---
 
 
 
115
  with gr.Blocks(theme=theme, css=custom_css, title="Booking") as demo:
116
+
117
+ # [隱藏] 用來接收 URL 確認參數的區塊
118
  confirm_msg_box = gr.HTML()
119
 
120
+ # 頁面載入時,執行 check_confirmation
121
+ demo.load(check_confirmation, inputs=None, outputs=confirm_msg_box)
 
122
 
123
  with gr.Row():
124
  with gr.Column():
125
+ gr.Markdown("### 📅 預約資訊 Booking Info")
126
+
127
  date_options = get_date_options()
128
+ booking_date = gr.Dropdown(choices=date_options, label="選擇日期 Select Date", interactive=True)
129
+ pax_count = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="用餐人數 Guest Count")
130
+
131
  with gr.Column():
132
+ gr.Markdown("### 🕰️ 選擇時段 Time Slot")
133
  status_box = gr.Markdown("請先選擇日期...", visible=True)
134
+ time_slot = gr.Dropdown(choices=[], label="可用時段 Available Time", interactive=True)
135
+
136
  gr.HTML("<div style='height: 10px'></div>")
137
+
138
+ gr.Markdown("### 👤 聯絡人資料 Contact,收到確認 E-Mail 並點擊 確認出席 才算訂位成功")
139
  with gr.Group():
140
  with gr.Row():
141
+ cust_name = gr.Textbox(label="訂位姓名 Name *", placeholder="ex. 王小明")
142
+ cust_tel = gr.Textbox(label="手機號碼 Phone *", placeholder="ex. 0912-xxx-xxx")
143
+
144
  with gr.Row():
145
+ cust_email = gr.Textbox(label="電子信箱 E-mail (接收確認信用,請記得檢查垃圾信件匣。)", placeholder="example@gmail.com")
146
  with gr.Row():
147
+ cust_remarks = gr.Textbox(label="備註 Remarks (過敏/慶生/特殊需求)", lines=2)
148
 
149
  gr.HTML("<div style='height: 15px'></div>")
150
+
151
+ submit_btn = gr.Button("確認預約 Request Booking (系統會記錄是否曾 No Show)", size="lg", variant="primary")
152
  output_msg = gr.HTML()
153
+
154
+ # 頁尾警語
155
+ gr.HTML("""
156
+ <div class="legal-footer">
157
+ <p style="margin-bottom: 5px;">© 2026 CIE CIE TAIPEI. All Rights Reserved.</p>
158
+ <p>內容涉及酒類產品訊息,請勿轉發分享給未達法定購買年齡者;未滿十八歲請勿飲酒。<br>
159
+ <strong>喝酒不開車,開車不喝酒。</strong></p>
160
+ </div>
161
+ """)
162
+
163
+ # --- 互動事件綁定 ---
164
+ # 1. 日期改變 -> 更新時段
165
  booking_date.change(update_time_slots, inputs=booking_date, outputs=[time_slot, status_box])
166
+
167
+ # 2. 送出按鈕 -> 處理訂位
168
+ submit_btn.click(
169
+ handle_booking,
170
+ inputs=[cust_name, cust_tel, cust_email, booking_date, time_slot, pax_count, cust_remarks],
171
+ outputs=output_msg
172
+ )
173
 
174
  if __name__ == "__main__":
175
  demo.launch()