Update app.py
Browse files26 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213315 unmodified lines14915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620726 unmodified linesreturn pd.DataFrame(res.data)def send_confirmation_hybrid(booking_id):try:# 1. 抓取資料res = supabase.table("bookings").select("*").eq("id", booking_id).execute()if not res.data: return "❌ 找不到訂單"booking = res.data[0]email, user_id = booking.get('email'), booking.get('user_id')log_msg = ""confirm_link = f"{PUBLIC_SPACE_URL}/?id={booking_id}&action=confirm"cancel_link = f"{PUBLIC_SPACE_URL}/?id={booking_id}&action=cancel"# 2. 發送 Email (偵錯版)if not GAS_MAIL_URL:log_msg += "⚠️ 未設GAS_URL "elif email and "@" in email:try:# 簡單的 HTML 信件html = f"""<div style="padding: 20px; background: #111; color: #d4af37; border-radius: 8px;"><h2>Cié Cié Taipei 訂位確認</h2><p>{booking['name']} 您好,已為您保留:</p><ul style="color: #eee;"><li>日期:{booking['date']}</li><li>時間:{booking['time']}</li><li>人數:{booking['pax']} 位</li></ul><a href="{confirm_link}" style="background:#d4af37; color:#000; padding:10px 20px; text-decoration:none; border-radius:5px;">確認出席</a><a href="{cancel_link}" style="color:#ff5252; padding:10px 20px;">取消</a></div>"""r = requests.post(GAS_MAIL_URL, json={"to": email, "subject": "訂位確認", "htmlBody": html, "name": "Cié Cié Taipei"})log_msg += f"✅ Mail({r.status_code}) "except Exception as e:log_msg += f"❌ MailErr "# 3. 發送 LINE (維持原樣)if user_id and len(str(user_id)) > 10 and LINE_ACCESS_TOKEN:try:# 這裡省略詳細 Flex Message 代碼以節省篇幅,維持您原本的邏輯即可# 簡單發個文字測試requests.post("https://api.line.me/v2/bot/message/push",headers={"Authorization": f"Bearer {LINE_ACCESS_TOKEN}"},json={"to": user_id, "messages": [{"type": "text", "text": f"✅ 訂位確認\n{booking['date']} {booking['time']}\n請回覆確認,謝謝!"}]})log_msg += "✅ LINE "except:log_msg += "❌ LINEErr"# 4. 更新狀態supabase.table("bookings").update({"status": "已發確認信"}).eq("id", booking_id).execute()return log_msgexcept Exception as e: return f"Error: {e}"# 🔥🔥🔥 核心改變:將 Dataframe 轉為 HTML 卡片 🔥🔥🔥def render_booking_cards():df = get_bookings()if df.empty:return "<div style='text-align:center; padding:20px; color:#888;'>📅 目前沒有訂位資料</div>"cards_html = "<div style='display: flex; flex-direction: column; gap: 15px; padding-bottom: 50px;'>"for index, row in df.iterrows():# 定義狀態顏色status = row.get('status', '待處理')if '確認' in status: border_color = '#2ecc71' # 綠色elif '取消' in status: border_color = '#e74c3c' # 紅色elif '已發' in status: border_color = '#f1c40f' # 黃色else: border_color = '#95a5a6' # 灰色# 卡片 HTML 結構card = f"""<div style="background: #262626;border-left: 5px solid {border_color};border-radius: 8px;padding: 15px;color: #eee;box-shadow: 0 2px 5px rgba(0,0,0,0.3);font-family: sans-serif;"><div style="display:flex; justify-content:space-between; margin-bottom:8px;"><span style="font-size:1.2em; font-weight:bold; color:#d4af37;">{row['time']} <span style="color:#fff; font-size:0.9em;">{row['name']}</span></span><span style="font-size:0.8em; padding:2px 6px; border-radius:4px; background:#333; color:{border_color};">{status}</span></div><div style="display:flex; gap:15px; color:#aaa; font-size:0.9em; margin-bottom:8px;"><span>📅 {row['date']}</span><span>👤 {row['pax']} 位</span><span>🆔 {row['id']}</span></div><div style="background:#1a1a1a; padding:8px; border-radius:4px; font-size:0.9em; color:#ccc; margin-bottom:10px;">📝 {row.get('remarks') or '無備註'}</div><div style="display:flex; justify-content:space-between; align-items:center; font-size:0.9em;"><a href="tel:{row['tel']}" style="color:#3498db; text-decoration:none;">📞 {row['tel']}</a><span style="color:#666; font-size:0.8em;">{row['email']}</span></div></div>"""15 unmodified lineserror_msg: "<span style='color: red'>❌ 帳號或密碼錯誤</span>"}# --- CSS (極簡化,因為現在用卡片了,不需要處理表格捲軸) ---custom_css = """body, .gradio-container { background-color: #0F0F0F; color: #fff; }#booking_display { max-height: 80vh; overflow-y: auto; } /* 讓卡片區可以垂直捲動 */"""# --- 介面 ---with gr.Blocks(title="Admin", css=custom_css) as demo:# 1. 登入with gr.Group(visible=True) as login_row:gr.Markdown("# 🔒 請登入後台")with gr.Row():username_input = gr.Textbox(label="帳號", placeholder="Enter username")password_input = gr.Textbox(label="密碼", type="password", placeholder="Enter password")login_btn = gr.Button("登入", variant="primary")error_msg = gr.Markdown("")# 2. 後台with gr.Group(visible=False) as admin_row:gr.Markdown("# 🍷 訂位管理 (Card View)")with gr.Row():refresh_btn = gr.Button("🔄 重新整理列表")# 🔥 顯示卡片的地方 (用 HTML 渲染)booking_display = gr.HTML(label="訂位列表", elem_id="booking_display")gr.Markdown("### 🛠️ 操作區")with gr.Row():id_input = gr.Number(label="輸入訂單 ID", precision=0)action_btn = gr.Button("📧 發送確認信 (Hybrid)", variant="primary")log_output = gr.Textbox(label="執行結果")# 事件綁定# 1. 登入後自動載入列表login_btn.click(check_login, inputs=[username_input, password_input], outputs=[login_row, admin_row, error_msg]).then(render_booking_cards, outputs=booking_display)# 2. 重新整理refresh_btn.click(render_booking_cards, outputs=booking_display)# 3. 發送確認信 -> 發送後自動更新列表 (變色)action_btn.click(send_confirmation_hybrid,inputs=id_input,outputs=log_output).then(render_booking_cards,outputs=booking_display)if __name__ == "__main__":demo.launch()26 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616715 unmodified lines18318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927026 unmodified linesreturn pd.DataFrame(res.data)def send_confirmation_hybrid(booking_id):if not booking_id: return "❌ 無效 ID"try:# 1. 抓取資料res = supabase.table("bookings").select("*").eq("id", booking_id).execute()if not res.data: return "❌ 找不到訂單"booking = res.data[0]email, user_id = booking.get('email'), booking.get('user_id')log_msg = f"🆔 {booking_id}: "confirm_link = f"{PUBLIC_SPACE_URL}/?id={booking_id}&action=confirm"cancel_link = f"{PUBLIC_SPACE_URL}/?id={booking_id}&action=cancel"# 2. 發送 Emailif email and "@" in email and GAS_MAIL_URL:try:html = f"""<div style="background:#111; color:#d4af37; padding:20px; border-radius:8px; font-family:sans-serif;"><h2 style="border-bottom:1px solid #333; padding-bottom:10px;">Cié Cié Taipei 訂位確認</h2><p style="color:#eee; font-size:16px;">{booking['name']} 您好,已為您保留座位:</p><div style="background:#222; padding:15px; border-radius:6px; margin:15px 0;"><ul style="color:#ddd; padding-left:20px; line-height:1.8;"><li>📅 日期:<strong style="color:#fff;">{booking['date']}</strong></li><li>⏰ 時間:<strong style="color:#fff;">{booking['time']}</strong></li><li>👥 人數:<strong style="color:#fff;">{booking['pax']} 位</strong></li></ul></div><div style="margin-top:20px;"><a href="{confirm_link}" style="background:#d4af37; color:#000; padding:10px 20px; text-decoration:none; border-radius:4px; font-weight:bold; margin-right:10px;">✅ 確認出席</a><a href="{cancel_link}" style="border:1px solid #ff5252; color:#ff5252; padding:9px 19px; text-decoration:none; border-radius:4px;">🚫 取消</a></div></div>"""requests.post(GAS_MAIL_URL, json={"to": email, "subject": "訂位確認 - Cié Cié Taipei", "htmlBody": html, "name": "Cié Cié Taipei"})log_msg += "✅ Mail "except: log_msg += "❌ MailErr "# 3. 發送 LINEif user_id and len(str(user_id)) > 10 and LINE_ACCESS_TOKEN:try:requests.post("https://api.line.me/v2/bot/message/push",headers={"Authorization": f"Bearer {LINE_ACCESS_TOKEN}"},json={"to": user_id, "messages": [{"type": "text", "text": f"✅ 訂位確認\n{booking['date']} {booking['time']}\n請回覆確認,謝謝!"}]})log_msg += "✅ LINE "except: log_msg += "❌ LINEErr"# 4. 更新狀態supabase.table("bookings").update({"status": "已發確認信"}).eq("id", booking_id).execute()return log_msgexcept Exception as e: return f"Error: {e}"# 🔥🔥🔥 2.0 版卡片渲染:設計感 + 操作按鈕 🔥🔥🔥def render_booking_cards():df = get_bookings()if df.empty:return "<div style='text-align:center; padding:40px; color:#666; font-size:1.2em;'>📭 目前沒有訂位資料</div>"cards_html = "<div style='display: flex; flex-direction: column; gap: 16px; padding-bottom: 60px;'>"for index, row in df.iterrows():# 狀態樣式邏輯status = row.get('status', '待處理')status_bg = "#333"status_color = "#ccc"if '確認' in status:status_bg = "rgba(46, 204, 113, 0.2)"; status_color = "#2ecc71" # 綠elif '取消' in status:status_bg = "rgba(231, 76, 60, 0.2)"; status_color = "#e74c3c" # 紅elif '已發' in status:status_bg = "rgba(241, 196, 15, 0.2)"; status_color = "#f1c40f" # 黃# 動作按鈕:如果是「已取消」或「已確認」,按鈕就反灰,避免誤按is_disabled = '取消' in status or '確認' in statusbtn_style = "opacity: 0.5; cursor: not-allowed;" if is_disabled else "cursor: pointer; hover:brightness(1.2);"btn_onclick = "" if is_disabled else f"cardAction({row['id']})"btn_text = "已處理" if is_disabled else "🚀 發送確認"card = f"""<div class="booking-card" style="background: linear-gradient(145deg, #2a2a2a, #222);border: 1px solid #333;border-radius: 12px;padding: 16px;position: relative;box-shadow: 0 4px 15px rgba(0,0,0,0.3);transition: transform 0.2s;font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;"><div style="display:flex; justify-content:space-between; align-items:start; margin-bottom:12px;"><div><div style="color:#d4af37; font-size:1.4em; font-weight:800; letter-spacing:0.5px; line-height:1.2;">{row['time']} <span style="font-size:0.6em; color:#888; font-weight:400;">{row['date'][5:]}</span></div><div style="color:#fff; font-size:1.1em; font-weight:600; margin-top:4px;">{row['name']} <span style="font-size:0.8em; color:#aaa; font-weight:400;">({row['pax']}位)</span></div></div><div style="background: {status_bg};color: {status_color};padding: 4px 10px;border-radius: 20px;font-size: 0.75em;font-weight: 600;border: 1px solid {status_color}44;">{status}</div></div><div style="background:rgba(0,0,0,0.2); border-radius:8px; padding:10px; font-size:0.85em; color:#aaa; line-height:1.6;"><div style="display:flex; gap:10px; margin-bottom:4px;"><span>📞 <a href="tel:{row['tel']}" style="color:#aaa; text-decoration:none; border-bottom:1px dotted #666;">{row['tel']}</a></span></div><div style="color:#666; font-size:0.8em; margin-bottom:4px;">✉️ {row['email'] or '無 Email'}</div><div style="color:#ccc; border-top:1px solid #333; margin-top:6px; padding-top:6px;">📝 {row.get('remarks') or '<span style="color:#555">無備註</span>'}</div></div><div style="margin-top:15px; display:flex; justify-content:space-between; align-items:center;"><span style="font-size:0.7em; color:#444; font-family:monospace;">ID: {row['id']}</span><button onclick="{btn_onclick}" style="background: #d4af37;color: #000;border: none;padding: 8px 16px;border-radius: 6px;font-weight: bold;font-size: 0.85em;transition: all 0.2s;{btn_style}">{btn_text}</button></div></div>"""15 unmodified lineserror_msg: "<span style='color: red'>❌ 帳號或密碼錯誤</span>"}# --- 🟢 [JS] 讓卡片按鈕能觸發 Python 事件 ---js_logic = """function() {// 定義全局函數,讓 HTML 中的 onclick 可以呼叫window.cardAction = function(id) {// 1. 找到隱藏的 ID 輸入框const idInput = document.querySelector('#hidden_id_input input');if (idInput) {// 設定值並觸發 input 事件 (讓 Gradio 知道值變了)idInput.value = id;idInput.dispatchEvent(new Event('input', { bubbles: true }));}// 2. 找到隱藏的發送按鈕並點擊setTimeout(() => {const sendBtn = document.querySelector('#hidden_send_btn');if (sendBtn) sendBtn.click();}, 100);}}"""# --- CSS 優化 ---custom_css = """body, .gradio-container { background-color: #0F0F0F; color: #fff; }/* 讓卡片容器可以滾動但隱藏捲軸 */#booking_display {max-height: 85vh;overflow-y: auto;padding-right: 5px;}#booking_display::-webkit-scrollbar { width: 5px; }#booking_display::-webkit-scrollbar-thumb { background: #333; border-radius: 5px; }"""# --- 介面 ---with gr.Blocks(title="Admin", css=custom_css) as demo:# 1. 登入層with gr.Group(visible=True) as login_row:gr.Markdown("# 🔒 Login")with gr.Row():username_input = gr.Textbox(label="User")password_input = gr.Textbox(label="Pass", type="password")login_btn = gr.Button("Enter", variant="primary")error_msg = gr.Markdown("")# 2. 後台層with gr.Group(visible=False) as admin_row:with gr.Row(variant="panel"):gr.Markdown("## 🍷 Dashboard")refresh_btn = gr.Button("🔄", size="sm") # 簡化按鈕# 🔥 卡片顯示區booking_display = gr.HTML(elem_id="booking_display")# 🟢 隱藏的操作區 (由 JS 自動控制)with gr.Column(visible=False):hidden_id_input = gr.Number(elem_id="hidden_id_input", precision=0)hidden_send_btn = gr.Button("Send", elem_id="hidden_send_btn")log_output = gr.Textbox(label="最近操作記錄", lines=1)# 事件綁定login_btn.click(check_login, inputs=[username_input, password_input], outputs=[login_row, admin_row, error_msg]).then(render_booking_cards, outputs=booking_display)refresh_btn.click(render_booking_cards, outputs=booking_display)# 🔥 隱藏按鈕被 JS 點擊後 -> ���行發送 -> 更新 Log -> 重新渲染卡片hidden_send_btn.click(send_confirmation_hybrid,inputs=hidden_id_input,outputs=log_output).then(render_booking_cards,outputs=booking_display)# 載入 JSdemo.load(None, js=js_logic)if __name__ == "__main__":demo.launch()
app.py+146-83