schillerCFK commited on
Commit
f7c8355
·
verified ·
1 Parent(s): c9f76c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -117
app.py CHANGED
@@ -9,6 +9,7 @@ import shutil
9
  import sqlite3
10
  import hashlib
11
  import time
 
12
  import html # 🌟 新增:用於防禦 XSS 攻擊
13
  from datetime import datetime, timezone, timedelta
14
 
@@ -89,6 +90,13 @@ def init_db():
89
  with get_db_connection() as conn:
90
  cursor = conn.cursor()
91
  cursor.execute('CREATE TABLE IF NOT EXISTS orders (order_id TEXT PRIMARY KEY, status TEXT, time TEXT, delivery_time TEXT, pickup_method TEXT, location TEXT, customer TEXT, item TEXT, price INTEGER, cost INTEGER, qty INTEGER, total INTEGER, total_cost INTEGER, note TEXT)')
 
 
 
 
 
 
 
92
  cursor.execute('CREATE TABLE IF NOT EXISTS menu (seq INTEGER, enable BOOLEAN, level TEXT, category TEXT, name TEXT, spec TEXT, price INTEGER, cost INTEGER, note TEXT, img TEXT, inventory INTEGER DEFAULT 999)')
93
 
94
  try: cursor.execute("ALTER TABLE menu ADD COLUMN img TEXT")
@@ -138,8 +146,10 @@ def init_db():
138
  cost = o.get("cost", 0)
139
  tc = o.get("total_cost", int(cost) * int(qty))
140
  nt = o.get("note") or o.get("備註", "")
141
- cursor.execute("INSERT INTO orders VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
142
- (oid, st, tm, dt, pm, loc, cust, item, pr, cost, qty, tot, tc, nt))
 
 
143
  except Exception as e: print(f"還原訂單失敗: {e}")
144
 
145
  # 還原:會員資料
@@ -291,12 +301,10 @@ def get_header_html(is_login=False):
291
  if os.path.exists(logo_path):
292
  try:
293
  with open(logo_path, "rb") as f: b64_str = base64.b64encode(f.read()).decode('utf-8')
294
- # 確保圖片在不同裝置下能彈性縮放,不會破版
295
  logo_html = f'<img src="data:image/png;base64,{b64_str}" style="max-height: clamp(40px, 8vw, 70px); width: auto; object-fit: contain; border-radius: 8px;">'
296
  except: pass
297
 
298
  if is_login:
299
- # 登入介面專用:乾淨、居中、強制單列
300
  return f'''
301
  <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding-bottom: 15px; border-bottom: 2px dashed #e2e8f0; margin-bottom: 20px;">
302
  <div style="display: flex; align-items: center; justify-content: center; gap: 12px; flex-wrap: nowrap; width: 100%;">
@@ -307,7 +315,6 @@ def get_header_html(is_login=False):
307
  </div>
308
  '''
309
 
310
- # 系統內部專用:帶有聯絡資訊,允許在極小螢幕自動換行 (flex-wrap)
311
  return f'<div class="custom-header header-container" style="flex-wrap: wrap;"><div class="header-logo" style="flex: 1; min-width: 250px; display: flex; justify-content: center;"><div style="display: flex; align-items: center; justify-content: center; gap: 10px; flex-wrap: nowrap;">{logo_html}<h2 style="margin:0; font-size: clamp(1.8rem, 5vw, 2.5rem); font-family: \'STXingkai\', \'DFKai-SB\', cursive; color:#ea580c; white-space: nowrap;">鑫生魚片</h2></div></div><div class="header-info" style="flex: 2; min-width: 280px; text-align: center;"><div style="color:#475569; display: inline-block; text-align: left; line-height: 1.5;"><strong>📞 預訂專線:</strong>0965-379-437<br><strong>📍 門市地址:</strong>桃園市龜山區中興路434號<br><strong>🕒 營業時間:</strong>10:30-14:30 | 16:00-21:00 (週一公休)</div></div></div>'
312
 
313
  def do_login(acc, pwd):
@@ -325,7 +332,6 @@ def do_login(acc, pwd):
325
  return {"acc": acc, "level": level, "name": user["name"]}
326
  return {"acc": "guest_error", "level": -1, "name": ""}
327
 
328
- # 設定與會員邏輯
329
  def save_ui_config(font_family, text_size, image_size, card_opacity, bg_image_url, bg_image_opacity):
330
  with db_lock:
331
  with get_db_connection() as conn:
@@ -380,10 +386,8 @@ def get_members_df():
380
  def handle_member_selection(evt: gr.SelectData, current_data):
381
  try:
382
  row_idx = evt.index[0]
383
- if isinstance(current_data, pd.DataFrame):
384
- acc_id = str(current_data.iloc[row_idx]["帳號"])
385
- else:
386
- acc_id = str(current_data[row_idx][2])
387
 
388
  with get_db_connection() as conn:
389
  m = conn.execute("SELECT * FROM members WHERE acc=?", (acc_id,)).fetchone()
@@ -394,20 +398,25 @@ def handle_member_selection(evt: gr.SelectData, current_data):
394
  except: pass
395
  return "", "", "", "***", "0 (一般會員)"
396
 
397
- # 菜單與庫存邏輯
398
  def get_inv_choices():
399
  choices = []
400
  with get_db_connection() as conn:
401
- for m in conn.execute("SELECT category, name FROM menu").fetchall():
402
  c_lower = str(m["category"]).lower()
403
  if not ("step 2" in c_lower or "step2" in c_lower or "金額" in c_lower):
404
- choices.append(m["name"])
405
  return choices
406
 
407
  def get_inv_df():
408
  with db_lock:
409
  with get_db_connection() as conn:
410
- p_map = {row[0]: row[1] for row in conn.execute("SELECT item, SUM(qty) FROM orders WHERE status='待出餐' GROUP BY item").fetchall()}
 
 
 
 
 
411
  menu_items = conn.execute("SELECT * FROM menu ORDER BY seq").fetchall()
412
 
413
  data = []
@@ -415,12 +424,16 @@ def get_inv_df():
415
  c_l = str(m["category"]).lower()
416
  if "step 2" in c_l or "step2" in c_l or "金額" in c_l: continue
417
  name, inv = m["name"], int(m["inventory"])
 
 
 
418
  if "step 1" in c_l or "step1" in c_l or "魚種" in c_l:
419
  p, av = 0, inv
420
  i_s = str(inv) if inv < 900 else "無限制"
421
  av_s = i_s
422
  else:
423
- p = p_map.get(name, 0); av = inv - p
 
424
  i_s, av_s = (str(inv) if inv < 900 else "無限制"), (str(av) if inv < 900 else "無限制")
425
 
426
  data.append([m["category"], name, m["spec"], i_s, str(p) if inv < 900 else "-", av_s])
@@ -433,12 +446,13 @@ def get_menu_df():
433
  data.append([int(m["seq"]), "是" if m["enable"] else "否", str(m["category"]), str(m["name"]), str(m["spec"]), int(m["price"]), int(m["cost"]), int(m["inventory"])])
434
  return pd.DataFrame(data, columns=["排序", "啟用", "分類", "品名", "規格", "價格", "成本", "庫存"])
435
 
 
436
  def update_menu_item(seq, enable, cat, name, spec, price, cost, inv, img_file):
437
- if not name: return "❌ 品名必填", gr.update(), None, gr.update()
438
 
439
  img_name = None
440
  with get_db_connection() as conn:
441
- row = conn.execute("SELECT img FROM menu WHERE name=?", (name,)).fetchone()
442
  if row: img_name = row['img']
443
 
444
  if img_file and isinstance(img_file, str) and RUNTIME_DATA_DIR not in img_file:
@@ -448,26 +462,38 @@ def update_menu_item(seq, enable, cat, name, spec, price, cost, inv, img_file):
448
 
449
  with db_lock:
450
  with get_db_connection() as conn:
451
- if conn.execute("SELECT 1 FROM menu WHERE name=?", (name,)).fetchone():
452
- conn.execute("UPDATE menu SET seq=?, enable=?, category=?, spec=?, price=?, cost=?, img=?, inventory=? WHERE name=?", (int(seq), enable=="是", str(cat), str(spec), int(price), int(cost), img_name, int(inv), str(name)))
453
  else:
454
- conn.execute("INSERT INTO menu VALUES (?,?,?,?,?,?,?,?,?,?,?)", (int(seq), enable=="是", "全部", str(cat), str(name), str(spec), int(price), int(cost), "", img_name, int(inv)))
455
  conn.commit()
456
  trigger_background_backup()
457
- return f"✅ {name} 儲存成功!", gr.update(value=get_menu_df()), None, gr.update(value=get_menu_html())
458
 
459
- def delete_menu_item(name):
 
460
  if not name: return "❌ 選擇品項", gr.update(), gr.update()
461
  with db_lock:
462
- with get_db_connection() as conn: conn.execute("DELETE FROM menu WHERE name=?", (name,)); conn.commit()
 
 
463
  trigger_background_backup()
464
- return f"🗑️ 已刪除", gr.update(value=get_menu_df()), gr.update(value=get_menu_html())
465
 
466
- def handle_menu_selection(evt: gr.SelectData):
467
  try:
468
  row_idx = evt.index[0]
 
 
 
 
 
 
 
 
 
469
  with get_db_connection() as conn:
470
- t = conn.execute("SELECT * FROM menu ORDER BY seq LIMIT 1 OFFSET ?", (row_idx,)).fetchone()
471
  if t:
472
  ip = os.path.join(IMAGE_DIR, t["img"]) if t["img"] else None
473
  return int(t["seq"]), "是" if t["enable"] else "否", str(t["category"]), str(t["name"]), str(t["spec"]), int(t["price"]), int(t["cost"]), int(t["inventory"]), gr.update(value=ip if ip and os.path.exists(ip) else None)
@@ -477,17 +503,19 @@ def handle_menu_selection(evt: gr.SelectData):
477
  def get_menu_html():
478
  with get_db_connection() as conn:
479
  enabled_menu = conn.execute("SELECT * FROM menu WHERE enable=1 ORDER BY seq").fetchall()
480
- p_map = {row[0]: row[1] for row in conn.execute("SELECT item, SUM(qty) FROM orders WHERE status='待出餐' GROUP BY item").fetchall()}
 
 
 
481
 
482
  tabs = []
483
  sections_by_tab = {}
484
  items_by_cat = {}
485
 
486
- # 🌟 核心分頁邏輯:將 Step 1 與 Step 2 綁定到同一個 Tab,其餘維持獨立
487
  for m in enabled_menu:
488
  c = m["category"]
489
  c_l = c.lower()
490
-
491
  if any(x in c_l for x in ["step 1", "step1", "魚種", "step 2", "step2", "金額"]):
492
  tab_name = "🐟 生魚片客製 (Step 1 & 2)"
493
  else:
@@ -496,32 +524,21 @@ def get_menu_html():
496
  if tab_name not in tabs: tabs.append(tab_name)
497
  if tab_name not in sections_by_tab: sections_by_tab[tab_name] = []
498
  if c not in sections_by_tab[tab_name]: sections_by_tab[tab_name].append(c)
499
-
500
  items_by_cat.setdefault(c, []).append(dict(m))
501
 
502
- # 🌟 動態生成分類分頁標籤 (Tabs)
503
  tabs_html = "<div class='menu-category-tabs'>"
504
  tabs_html += "<button class='cat-tab-btn active' onclick='window.filterMenu(\"all\", this)'>🌟 全部顯示</button>"
505
  for tab_name in tabs:
506
- # 使用 Hash 作為 Tab ID
507
  tab_id = hashlib.md5(tab_name.encode()).hexdigest()[:8]
508
- safe_tab_display = html.escape(tab_name)
509
- tabs_html += f"<button class='cat-tab-btn' onclick='window.filterMenu(\"{tab_id}\", this)'>{safe_tab_display}</button>"
510
  tabs_html += "</div>"
511
 
512
- # 將 Tabs 與菜單內容合併
513
  html_content = tabs_html + "<div class='menu-content-area'>"
514
 
515
- # 按照設定好的 Tab 分組渲染內容
516
  for tab_name in tabs:
517
  tab_id = hashlib.md5(tab_name.encode()).hexdigest()[:8]
518
-
519
  for c in sections_by_tab[tab_name]:
520
- safe_c = html.escape(c)
521
-
522
- # 🌟 每一個區塊加上 data-tab-group,供 JS 做過濾綁定
523
- html_content += f"<div class='menu-section' data-tab-group='{tab_id}'><div class='cat-header'>{safe_c}</div><div class='menu-grid'>"
524
-
525
  c_l = c.lower()
526
  is_s1 = "step 1" in c_l or "step1" in c_l or "魚種" in c_l
527
  is_s2 = "step 2" in c_l or "step2" in c_l or "金額" in c_l
@@ -535,11 +552,14 @@ def get_menu_html():
535
 
536
  safe_n_display = html.escape(m['name'])
537
  safe_spec = html.escape(m['spec'])
538
- safe_n_js = m['name'].replace("'", "\\'")
539
- hash_id = hashlib.md5(m['name'].encode()).hexdigest()[:8]
 
 
 
540
 
541
  inv = int(m.get("inventory", 999))
542
- av = inv - p_map.get(m['name'], 0) if not (is_s1 or is_s2) else inv
543
  is_sold = inv < 900 and av <= 0
544
 
545
  if is_sold:
@@ -548,15 +568,13 @@ def get_menu_html():
548
  act = "<div style='color:#ef4444;font-weight:bold;text-align:center;width:100%'>已售罄</div>"
549
  else:
550
  cls, overlay = "menu-card", ""
551
- if is_s1: act = f"<div class='step1-checkbox-wrapper'><input type='checkbox' class='step1-checkbox' id='chk-{hash_id}' onchange=\"window.toggleCheck('{safe_n_js}', this)\"></div>"
552
- else: act = f"<div class='qty-row'><button class='action-btn' onclick=\"window.updateQty('{safe_n_js}', '{hash_id}', -1)\">➖</button><div class='qty-display' id='qty-{hash_id}'>0</div><button class='action-btn' onclick=\"window.updateQty('{safe_n_js}', '{hash_id}', 1)\">➕</button></div>"
553
 
554
  p_s = f"<small style='color:#64748b;'>{safe_spec}</small>" if (is_s1 or is_s2) else f"<small style='color:#64748b;'>{safe_spec} | <span style='color:#ea580c; font-weight:bold;'>NT$ {m['price']}</span></small>"
555
  html_content += f"<div class='{cls}'>{overlay}<div class='img-col'><img src='{src}'></div><div class='info-col'><strong style='font-size:1.1em; color:#1e293b;'>{safe_n_display}</strong><br>{p_s}</div><div class='action-col'>{act}</div></div>"
556
  html_content += "</div></div>"
557
-
558
- html_content += "</div>"
559
- return html_content
560
 
561
  def add_order(c_name, p_method, d_loc, d_date, d_time, nts, order_json):
562
  safe_c_name = html.escape(str(c_name))
@@ -567,48 +585,66 @@ def add_order(c_name, p_method, d_loc, d_date, d_time, nts, order_json):
567
 
568
  with get_db_connection() as conn:
569
  enabled = conn.execute("SELECT * FROM menu WHERE enable=1").fetchall()
570
- p_map = {row[0]: row[1] for row in conn.execute("SELECT item, SUM(qty) FROM orders WHERE status='待出餐' GROUP BY item").fetchall()}
 
 
 
571
 
572
- flat = {m["name"]: dict(m) for m in enabled}
573
 
574
- for name, qty in data.items():
 
575
  qty = int(qty)
576
- if qty > 0 and name in flat:
577
- m = flat[name]; c_l = str(m.get("category", "")).lower()
578
  if not any(x in c_l for x in ["step 1", "step1", "魚種", "step 2", "step2", "金額"]):
579
  inv = int(m.get("inventory", 999))
580
- if inv < 900 and (inv - p_map.get(name, 0)) < qty: return f"❌ 【{html.escape(name)}】 庫存不足!", order_json
 
581
 
582
  s1, s2, other = [], [], []
583
- for name, qty in data.items():
584
  qty = int(qty)
585
- if qty > 0 and name in flat:
586
- c_l = str(flat[name].get("category", "")).lower()
587
- if "step 1" in c_l or "step1" in c_l or "魚種" in c_l: s1.append(name)
588
- elif "step 2" in c_l or "step2" in c_l or "金額" in c_l: s2.append({"m": flat[name], "qty": qty})
589
- else: other.append({"m": flat[name], "qty": qty})
590
 
591
  if not (s1 or s2 or other): return "❌ 未選擇商品!", order_json
592
- if (s1 and not s2) or (s2 and not s1): return "❌ Step 1 與 2 必須同時選擇!", order_json
593
 
594
  to_add = list(other)
 
 
595
  if s1 and s2:
596
- prefix = " + ".join(s1)
 
597
  for it in s2:
598
- cm = dict(it["m"]); cm["name"] = f"{prefix} {cm['name']}"
599
- to_add.append({"m": cm, "qty": it["qty"]})
600
 
601
  ts, delivery = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M:%S"), (f"{d_date} {d_time}" if p_method == "預訂" else "盡快")
602
 
603
  with db_lock:
604
  with get_db_connection() as conn:
605
  for item in to_add:
606
- m, q = item["m"], item["qty"]; oid = f"XIN-{uuid.uuid4().hex[:4].upper()}"
607
- conn.execute('INSERT INTO orders VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)', (oid, "待出餐", ts, delivery, p_method, html.escape(d_loc) if p_method=="預訂" else "現場", safe_c_name, m["name"], m["price"], m["cost"], q, m["price"]*q, m["cost"]*q, safe_nts))
 
 
 
 
 
 
 
 
 
 
608
  conn.commit()
609
 
610
  trigger_background_backup()
611
- return "✅ 下單成功!", "{}"
612
 
613
  def get_latest_orders_html():
614
  with get_db_connection() as conn:
@@ -648,15 +684,18 @@ def get_latest_orders_html():
648
  </div>
649
  </div>
650
  """
651
- df_view = df.head(100).rename(columns={
 
 
 
 
 
 
 
652
  "order_id": "訂單編號", "status": "狀態", "time": "時間", "delivery_time": "預定交期",
653
- "pickup_method": "取貨方式", "location": "送貨地點", "customer": "顧客姓名",
654
- "item": "商品", "price": "單價", "qty": "數量", "total": "總價"
655
- }).copy()
656
 
657
- df_view["顧客姓名"] = df_view["顧客姓名"].apply(lambda x: html.escape(str(x)))
658
- df_view["商品"] = df_view["商品"].apply(lambda x: html.escape(str(x)))
659
- df_view["操作"] = df_view["訂單編號"].apply(lambda oid: f"<button class='delete-btn' onclick='window.deleteOrder(\"{html.escape(oid)}\")'>🗑️ 刪除</button>")
660
  table_html = f'<div class="table-container">{df_view[["訂單編號","狀態","時間","預定交期","取貨方式","送貨地點","顧客姓名","商品","單價","數量","總價","操作"]].to_html(index=False, classes="order-table", border=0, escape=False)}</div>'
661
  return dashboard_html + table_html
662
 
@@ -665,9 +704,14 @@ def delete_order_by_id(oid):
665
  try:
666
  with db_lock:
667
  with get_db_connection() as conn:
668
- r = conn.execute("SELECT status, item, qty FROM orders WHERE order_id=?", (str(oid),)).fetchone()
669
  if r and r["status"] == '已出餐':
670
- conn.execute("UPDATE menu SET inventory = inventory + ? WHERE name=? AND inventory < 900", (r["qty"], r["item"]))
 
 
 
 
 
671
  conn.execute("DELETE FROM orders WHERE order_id=?", (str(oid),)); conn.commit()
672
  trigger_background_backup()
673
  return f"✅ 訂單已刪除", get_latest_orders_html()
@@ -675,19 +719,17 @@ def delete_order_by_id(oid):
675
 
676
  def get_kitchen_html():
677
  with get_db_connection() as conn:
678
- pending = conn.execute("SELECT rowid, item, qty, note, time, customer FROM orders WHERE status='待出餐' ORDER BY time ASC, rowid ASC").fetchall()
679
- menu_specs = {row["name"]: row["spec"] for row in conn.execute("SELECT name, spec FROM menu").fetchall()}
680
 
681
  if not pending: return "<div style='text-align:center;padding:40px;font-size:1.5em;color:#10b981;background:white;border-radius:12px;box-shadow:0 2px 10px rgba(0,0,0,0.05);'>🎉 目前沒有待出餐訂單,廚房休息中!</div>"
682
 
683
  h = '<div class="ticket-grid">'
684
  for idx, r in enumerate(pending):
685
- rowid, item_name, qty, note, o_time, customer = r
686
- spec = menu_specs.get(item_name, "")
687
  time_str = str(o_time)[11:16]
688
 
689
  safe_item = html.escape(item_name)
690
- safe_spec = html.escape(spec)
691
  safe_customer = html.escape(customer)
692
  safe_note = html.escape(note)
693
 
@@ -717,8 +759,13 @@ def serve_k_order_by_id(rid):
717
  try:
718
  with db_lock:
719
  with get_db_connection() as conn:
720
- r = conn.execute("SELECT item, qty FROM orders WHERE rowid=?", (int(rid),)).fetchone()
721
- if r: conn.execute("UPDATE menu SET inventory = inventory - ? WHERE name=? AND inventory < 900", (r["qty"], r["item"]))
 
 
 
 
 
722
  conn.execute("UPDATE orders SET status='已出餐' WHERE rowid=?", (int(rid),)); conn.commit()
723
  trigger_background_backup()
724
  return "✅ 已出餐", get_kitchen_html()
@@ -782,11 +829,9 @@ def get_dynamic_css():
782
 
783
  .custom-header { display: flex; border-left: 6px solid #ea580c; border-radius: 12px; padding: 15px 20px; margin-bottom: 20px; background: white; box-shadow: 0 4px 10px rgba(0,0,0,0.04); align-items: center; gap: 20px; }
784
 
785
- /* 🌟 顧客點餐畫面的 Sticky 下單區塊與獨立滾動菜單區塊 */
786
  .sticky-top-panel { background: rgba(255,255,255,0.98); padding: 15px; border-radius: 16px; border: 2px solid #ea580c; margin-bottom: 10px; box-shadow: 0 8px 20px rgba(0,0,0,0.08); position: sticky; top: 0; z-index: 100; max-height: 25vh; overflow-y: auto; flex-shrink: 0; }
787
  .scrollable-menu-panel { height: 65vh; overflow-y: auto; padding-right: 10px; position: relative; }
788
 
789
- /* 🌟 新增:專屬分類導覽列 CSS (動態吸頂) */
790
  .menu-category-tabs { display: flex; gap: 10px; overflow-x: auto; padding: 10px 5px; margin-bottom: 15px; position: sticky; top: 0; background: rgba(255,255,255,0.98); z-index: 90; border-bottom: 2px solid #e2e8f0; }
791
  .menu-category-tabs::-webkit-scrollbar { display: none; }
792
  .menu-category-tabs { -ms-overflow-style: none; scrollbar-width: none; }
@@ -827,7 +872,6 @@ def get_dynamic_css():
827
  footer, .built-with, gradio-badge, .show-api, .toast-wrap, .status-indicator { display: none !important; opacity: 0 !important; pointer-events: none !important; }
828
  .hidden-order-data, .hidden-serve-data, .hidden-delete-data, .hidden-date { display: none !important; }
829
 
830
- /* 強力隱藏右上角 Hugging Face / Gradio 浮動 Logo */
831
  html body a[href*='huggingface.co'], html body a[href*='hf.co'] { display: none !important; opacity: 0 !important; pointer-events: none !important; visibility: hidden !important; }
832
  body > div[class*='fixed top-'], body > div[class*='absolute top-'] { display: none !important; opacity: 0 !important; pointer-events: none !important; }
833
 
@@ -857,13 +901,10 @@ window.updateQty = function(n, h, d) {
857
  };
858
  window.toggleCheck = function(n, c) { window.orderState[n] = c.checked ? 1 : 0; updateHiddenField(); };
859
 
860
- // 🌟 新增:純前端 JavaScript 分類分頁過濾器
861
  window.filterMenu = function(catId, btnEl) {
862
- // 1. 切換按鈕的活躍狀態 (Active 樣式)
863
  document.querySelectorAll('.cat-tab-btn').forEach(btn => btn.classList.remove('active'));
864
  if(btnEl) btnEl.classList.add('active');
865
 
866
- // 2. 顯示/隱藏對應的菜單區塊
867
  document.querySelectorAll('.menu-section').forEach(sec => {
868
  if(catId === 'all' || sec.getAttribute('data-tab-group') === catId) {
869
  sec.style.display = 'block';
@@ -894,7 +935,6 @@ window.deleteOrder = function(o) {
894
  document.addEventListener("DOMContentLoaded", function() {
895
  const kill = function() {
896
  document.querySelectorAll('footer, .built-with, gradio-badge, .show-api, .toast-wrap, .status-indicator').forEach(el => el.remove());
897
- // JavaScript 動態斬殺 Hugging Face Logo 節點
898
  document.querySelectorAll('a[href*="huggingface.co"], a[href*="hf.co"]').forEach(el => el.remove());
899
  document.querySelectorAll('body > div.absolute.top-4, body > div.fixed.top-4, body > div.fixed.top-2').forEach(el => el.remove());
900
  };
@@ -928,7 +968,6 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange"), title="鑫生魚片
928
  nav_settings = gr.Button("⚙️ 系統設定")
929
 
930
  with gr.Column(visible=True) as page_order:
931
- # 顧客點餐介面:頂部資訊固定區塊 (約佔 1/4)
932
  with gr.Column(elem_classes="sticky-top-panel"):
933
  with gr.Row():
934
  cn = gr.Textbox(label="桌號 / 顧客姓名", interactive=True, scale=2)
@@ -941,14 +980,12 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange"), title="鑫生魚片
941
  hidden_d_date = gr.Textbox(value=get_today_val(), elem_classes="hidden-date")
942
  d_time = gr.Dropdown(choices=get_booking_times(), label="預定時間", interactive=True)
943
 
944
- # 將回報與送出按鈕上移到固定區塊內
945
  with gr.Row():
946
  res_msg = gr.Textbox(label="下單系統回報", interactive=False, scale=3)
947
  sub_btn = gr.Button("🚀 確認送出訂單", variant="primary", size="lg", scale=2)
948
 
949
  pm.change(lambda v: gr.update(visible=(v=="預訂")), [pm], [booking_row])
950
 
951
- # 菜品區塊改為獨立且可滾動的 Panel (包含動態分類標籤與菜單網格)
952
  with gr.Column(elem_classes="scrollable-menu-panel"):
953
  hidden_order_data = gr.Textbox(value="{}", elem_classes="hidden-order-data")
954
  order_menu_html = gr.HTML("")
@@ -1046,16 +1083,13 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange"), title="鑫生魚片
1046
  if u["acc"]=="guest_error": return [gr.update(visible=True), gr.update(visible=False), "<div style='color:red;text-align:center;'>❌ 帳號或密碼錯誤</div>", ""] + [gr.update(visible=False)]*7 + [gr.update(visible=False)]*7 + [gr.update()]*7
1047
  lvl, msg = u["level"], f"🍣 **歡迎回來,{u['name']}**"
1048
 
1049
- # 權限判定
1050
- s_o = lvl in [0,1,2,9] # 點餐權限
1051
- s_k = lvl in [8,9] # 廚房權限
1052
- s_a = lvl == 9 # 管理權限
1053
 
1054
  return [
1055
  gr.update(visible=False), gr.update(visible=True), "", msg,
1056
- # 7 個分頁 (pages) 的顯示控制
1057
  gr.update(visible=s_o), gr.update(visible=s_k), gr.update(visible=s_a), gr.update(visible=s_a), gr.update(visible=s_a), gr.update(visible=s_a), gr.update(visible=s_a),
1058
- # 7 個導覽按鈕 (nav_buttons) 的顯示與樣式控制
1059
  gr.update(visible=s_o, variant="primary" if s_o else "secondary"),
1060
  gr.update(visible=s_k, variant="primary" if s_k and not s_o else "secondary"),
1061
  gr.update(visible=s_a, variant="secondary"),
@@ -1063,7 +1097,6 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange"), title="鑫生魚片
1063
  gr.update(visible=s_a, variant="secondary"),
1064
  gr.update(visible=s_a, variant="secondary"),
1065
  gr.update(visible=s_a, variant="secondary"),
1066
- # 7 個額外資料載入
1067
  get_menu_html() if s_o else "", get_kitchen_html() if s_k else "", get_menu_df() if s_a else pd.DataFrame(), get_inv_df() if s_a else pd.DataFrame(), gr.update(choices=get_inv_choices()) if s_a else gr.update(), get_members_df() if s_a else pd.DataFrame(), get_latest_orders_html() if s_a else ""
1068
  ]
1069
 
@@ -1073,52 +1106,69 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange"), title="鑫生魚片
1073
  sub_btn.click(add_order, [cn, pm, loc, hidden_d_date, d_time, nts, hidden_order_data], [res_msg, hidden_order_data]).then(None, None, None, js="window.clearOrderUI")
1074
  m_sv.click(update_menu_item, [m_sq, m_en, m_ct, m_nm, m_sp, m_pr, m_cs, m_inv, m_im], [ms_out, mdf, m_im, order_menu_html])
1075
  m_cl.click(lambda: (999, "是", "", "", "", 0, 0, 999, None), None, [m_sq, m_en, m_ct, m_nm, m_sp, m_pr, m_cs, m_inv, m_im])
1076
- m_de.click(delete_menu_item, [m_nm], [ms_out, mdf, order_menu_html])
 
 
1077
  mdf.select(handle_menu_selection, None, [m_sq, m_en, m_ct, m_nm, m_sp, m_pr, m_cs, m_inv, m_im])
1078
 
1079
- # 🌟 會員資料表綁定修復
1080
  mm_df.select(handle_member_selection, inputs=[mm_df], outputs=[mm_n, mm_p, mm_a, mm_w, mm_lvl])
1081
  mm_s.click(save_single_member, [mm_n, mm_p, mm_a, mm_w, mm_lvl], [mm_out, mm_df])
1082
  mm_d.click(delete_single_member, [mm_a], [mm_out, mm_df])
1083
 
1084
- # 庫存更新
1085
  def update_inv_and_refresh(n, q):
1086
  if not n: return "⚠️ 請先選擇品項", gr.update()
 
 
 
1087
  with db_lock:
1088
  with get_db_connection() as conn:
1089
- conn.execute("UPDATE menu SET inventory=? WHERE name=?", (int(q), n))
1090
  conn.commit()
1091
  trigger_background_backup()
1092
- return f"✅ 【{n}】 總庫存已強制覆蓋為 {int(q)}", get_inv_df()
1093
 
1094
  def add_inv_and_refresh(n, add_q):
1095
  if not n: return "⚠️ 請先選擇品項", gr.update(), 0
1096
- if not add_q or int(add_q) == 0: return "⚠️ 請輸入有效的進貨數量", gr.update(), 0
 
 
 
 
1097
  with db_lock:
1098
  with get_db_connection() as conn:
1099
- r = conn.execute("SELECT inventory FROM menu WHERE name=?", (n,)).fetchone()
1100
  if r:
1101
  new_inv = int(r["inventory"]) + int(add_q)
1102
- conn.execute("UPDATE menu SET inventory=? WHERE name=?", (new_inv, n))
1103
  conn.commit()
1104
  else:
1105
  return "⚠️ 找不到該品項", gr.update(), 0
1106
  trigger_background_backup()
1107
- return f"✅ 【{n}】 成功進貨入庫 {int(add_q)} 個!目前總庫存為 {new_inv}", get_inv_df(), 0
1108
 
1109
  def handle_inv_selection(evt: gr.SelectData, current_data):
1110
  try:
1111
  row_idx = evt.index[0]
1112
- if isinstance(current_data, pd.DataFrame): item_name = str(current_data.iloc[row_idx]["品名"])
1113
- else: item_name = str(current_data[row_idx][1])
1114
- return item_name
 
 
 
 
 
 
1115
  except Exception as e: return gr.update()
1116
 
1117
  def fetch_inventory_for_item(n):
1118
  if not n: return gr.update(), 0
 
 
 
1119
  try:
1120
  with get_db_connection() as conn:
1121
- r = conn.execute("SELECT inventory FROM menu WHERE name=?", (n,)).fetchone()
1122
  return int(r["inventory"]) if r else 0, 0
1123
  except: return 0, 0
1124
 
@@ -1126,10 +1176,9 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange"), title="鑫生魚片
1126
  inv_name.change(fetch_inventory_for_item, inputs=[inv_name], outputs=[inv_qty, inv_add_val])
1127
  inv_sv.click(update_inv_and_refresh, [inv_name, inv_qty], [inv_out, inv_df])
1128
  inv_add_btn.click(add_inv_and_refresh, [inv_name, inv_add_val], [inv_out, inv_df, inv_add_val]).then(
1129
- lambda n: next((int(i["inventory"]) for i in get_db_connection().execute("SELECT inventory, name FROM menu").fetchall() if i["name"]==n), 0), [inv_name], [inv_qty]
1130
  )
1131
 
1132
- # 🌟 隱藏按鈕事件
1133
  k_refresh_btn.click(lambda: ("✅ 已刷新最新廚房訂單", get_kitchen_html()), None, [k_msg, k_html])
1134
  hidden_serve_id.change(serve_k_order_by_id, [hidden_serve_id], [k_msg, k_html]).then(lambda: "", None, [hidden_serve_id])
1135
 
 
9
  import sqlite3
10
  import hashlib
11
  import time
12
+ import re
13
  import html # 🌟 新增:用於防禦 XSS 攻擊
14
  from datetime import datetime, timezone, timedelta
15
 
 
90
  with get_db_connection() as conn:
91
  cursor = conn.cursor()
92
  cursor.execute('CREATE TABLE IF NOT EXISTS orders (order_id TEXT PRIMARY KEY, status TEXT, time TEXT, delivery_time TEXT, pickup_method TEXT, location TEXT, customer TEXT, item TEXT, price INTEGER, cost INTEGER, qty INTEGER, total INTEGER, total_cost INTEGER, note TEXT)')
93
+
94
+ # 🌟 動態擴充 orders 資料表以支援複合鍵
95
+ try: cursor.execute("ALTER TABLE orders ADD COLUMN category TEXT")
96
+ except: pass
97
+ try: cursor.execute("ALTER TABLE orders ADD COLUMN spec TEXT")
98
+ except: pass
99
+
100
  cursor.execute('CREATE TABLE IF NOT EXISTS menu (seq INTEGER, enable BOOLEAN, level TEXT, category TEXT, name TEXT, spec TEXT, price INTEGER, cost INTEGER, note TEXT, img TEXT, inventory INTEGER DEFAULT 999)')
101
 
102
  try: cursor.execute("ALTER TABLE menu ADD COLUMN img TEXT")
 
146
  cost = o.get("cost", 0)
147
  tc = o.get("total_cost", int(cost) * int(qty))
148
  nt = o.get("note") or o.get("備註", "")
149
+ cat = o.get("category", "")
150
+ sp = o.get("spec", "")
151
+ cursor.execute("INSERT INTO orders (order_id, status, time, delivery_time, pickup_method, location, customer, item, price, cost, qty, total, total_cost, note, category, spec) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
152
+ (oid, st, tm, dt, pm, loc, cust, item, pr, cost, qty, tot, tc, nt, cat, sp))
153
  except Exception as e: print(f"還原訂單失敗: {e}")
154
 
155
  # 還原:會員資料
 
301
  if os.path.exists(logo_path):
302
  try:
303
  with open(logo_path, "rb") as f: b64_str = base64.b64encode(f.read()).decode('utf-8')
 
304
  logo_html = f'<img src="data:image/png;base64,{b64_str}" style="max-height: clamp(40px, 8vw, 70px); width: auto; object-fit: contain; border-radius: 8px;">'
305
  except: pass
306
 
307
  if is_login:
 
308
  return f'''
309
  <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding-bottom: 15px; border-bottom: 2px dashed #e2e8f0; margin-bottom: 20px;">
310
  <div style="display: flex; align-items: center; justify-content: center; gap: 12px; flex-wrap: nowrap; width: 100%;">
 
315
  </div>
316
  '''
317
 
 
318
  return f'<div class="custom-header header-container" style="flex-wrap: wrap;"><div class="header-logo" style="flex: 1; min-width: 250px; display: flex; justify-content: center;"><div style="display: flex; align-items: center; justify-content: center; gap: 10px; flex-wrap: nowrap;">{logo_html}<h2 style="margin:0; font-size: clamp(1.8rem, 5vw, 2.5rem); font-family: \'STXingkai\', \'DFKai-SB\', cursive; color:#ea580c; white-space: nowrap;">鑫生魚片</h2></div></div><div class="header-info" style="flex: 2; min-width: 280px; text-align: center;"><div style="color:#475569; display: inline-block; text-align: left; line-height: 1.5;"><strong>📞 預訂專線:</strong>0965-379-437<br><strong>📍 門市地址:</strong>桃園市龜山區中興路434號<br><strong>🕒 營業時間:</strong>10:30-14:30 | 16:00-21:00 (週一公休)</div></div></div>'
319
 
320
  def do_login(acc, pwd):
 
332
  return {"acc": acc, "level": level, "name": user["name"]}
333
  return {"acc": "guest_error", "level": -1, "name": ""}
334
 
 
335
  def save_ui_config(font_family, text_size, image_size, card_opacity, bg_image_url, bg_image_opacity):
336
  with db_lock:
337
  with get_db_connection() as conn:
 
386
  def handle_member_selection(evt: gr.SelectData, current_data):
387
  try:
388
  row_idx = evt.index[0]
389
+ if isinstance(current_data, pd.DataFrame): acc_id = str(current_data.iloc[row_idx]["帳號"])
390
+ else: acc_id = str(current_data[row_idx][2])
 
 
391
 
392
  with get_db_connection() as conn:
393
  m = conn.execute("SELECT * FROM members WHERE acc=?", (acc_id,)).fetchone()
 
398
  except: pass
399
  return "", "", "", "***", "0 (一般會員)"
400
 
401
+ # 🌟 庫存邏輯:下拉選單改為複合鍵顯示 [分類] 品名 (規格)
402
  def get_inv_choices():
403
  choices = []
404
  with get_db_connection() as conn:
405
+ for m in conn.execute("SELECT category, name, spec FROM menu").fetchall():
406
  c_lower = str(m["category"]).lower()
407
  if not ("step 2" in c_lower or "step2" in c_lower or "金額" in c_lower):
408
+ choices.append(f"[{m['category']}] {m['name']} ({m['spec']})")
409
  return choices
410
 
411
  def get_inv_df():
412
  with db_lock:
413
  with get_db_connection() as conn:
414
+ p_map = {}
415
+ # 庫存計算嚴格對應 分類/品名/規格
416
+ for row in conn.execute("SELECT category, item, spec, SUM(qty) as sq FROM orders WHERE status='待出餐' GROUP BY category, item, spec").fetchall():
417
+ c, n, s = row["category"] or "", row["item"] or "", row["spec"] or ""
418
+ p_map[f"{c}|{n}|{s}"] = row["sq"]
419
+
420
  menu_items = conn.execute("SELECT * FROM menu ORDER BY seq").fetchall()
421
 
422
  data = []
 
424
  c_l = str(m["category"]).lower()
425
  if "step 2" in c_l or "step2" in c_l or "金額" in c_l: continue
426
  name, inv = m["name"], int(m["inventory"])
427
+ key = f"{m['category']}|{m['name']}|{m['spec']}"
428
+
429
+ # Step 1 庫存脫鉤不自動扣單,維持手動
430
  if "step 1" in c_l or "step1" in c_l or "魚種" in c_l:
431
  p, av = 0, inv
432
  i_s = str(inv) if inv < 900 else "無限制"
433
  av_s = i_s
434
  else:
435
+ p = p_map.get(key, 0)
436
+ av = inv - p
437
  i_s, av_s = (str(inv) if inv < 900 else "無限制"), (str(av) if inv < 900 else "無限制")
438
 
439
  data.append([m["category"], name, m["spec"], i_s, str(p) if inv < 900 else "-", av_s])
 
446
  data.append([int(m["seq"]), "是" if m["enable"] else "否", str(m["category"]), str(m["name"]), str(m["spec"]), int(m["price"]), int(m["cost"]), int(m["inventory"])])
447
  return pd.DataFrame(data, columns=["排序", "啟用", "分類", "品名", "規格", "價格", "成本", "庫存"])
448
 
449
+ # 🌟 新增/更新菜品:完全依賴 分類+品名+規格 複合鍵
450
  def update_menu_item(seq, enable, cat, name, spec, price, cost, inv, img_file):
451
+ if not name or not cat or not spec: return "❌ 分類、品名、規格皆為必填!(此三者構成唯一品項)", gr.update(), None, gr.update()
452
 
453
  img_name = None
454
  with get_db_connection() as conn:
455
+ row = conn.execute("SELECT img FROM menu WHERE category=? AND name=? AND spec=?", (cat, name, spec)).fetchone()
456
  if row: img_name = row['img']
457
 
458
  if img_file and isinstance(img_file, str) and RUNTIME_DATA_DIR not in img_file:
 
462
 
463
  with db_lock:
464
  with get_db_connection() as conn:
465
+ if conn.execute("SELECT 1 FROM menu WHERE category=? AND name=? AND spec=?", (cat, name, spec)).fetchone():
466
+ conn.execute("UPDATE menu SET seq=?, enable=?, price=?, cost=?, img=?, inventory=? WHERE category=? AND name=? AND spec=?", (int(seq), enable=="是", int(price), int(cost), img_name, int(inv), cat, name, spec))
467
  else:
468
+ conn.execute("INSERT INTO menu VALUES (?,?,?,?,?,?,?,?,?,?,?)", (int(seq), enable=="是", str(cat), str(name), str(spec), int(price), int(cost), "", img_name, int(inv)))
469
  conn.commit()
470
  trigger_background_backup()
471
+ return f"✅ 【{name} ({spec})】 儲存成功!", gr.update(value=get_menu_df()), None, gr.update(value=get_menu_html())
472
 
473
+ # 🌟 刪除菜品:完全依賴 分類+品名+規格 複合鍵
474
+ def delete_menu_item(cat, name, spec):
475
  if not name: return "❌ 選擇品項", gr.update(), gr.update()
476
  with db_lock:
477
+ with get_db_connection() as conn:
478
+ conn.execute("DELETE FROM menu WHERE category=? AND name=? AND spec=?", (cat, name, spec))
479
+ conn.commit()
480
  trigger_background_backup()
481
+ return f"🗑️ 已刪除 【{name}】", gr.update(value=get_menu_df()), gr.update(value=get_menu_html())
482
 
483
+ def handle_menu_selection(evt: gr.SelectData, current_data):
484
  try:
485
  row_idx = evt.index[0]
486
+ if isinstance(current_data, pd.DataFrame):
487
+ cat = str(current_data.iloc[row_idx]["分類"])
488
+ name = str(current_data.iloc[row_idx]["品名"])
489
+ spec = str(current_data.iloc[row_idx]["規格"])
490
+ else:
491
+ cat = str(current_data[row_idx][2])
492
+ name = str(current_data[row_idx][3])
493
+ spec = str(current_data[row_idx][4])
494
+
495
  with get_db_connection() as conn:
496
+ t = conn.execute("SELECT * FROM menu WHERE category=? AND name=? AND spec=?", (cat, name, spec)).fetchone()
497
  if t:
498
  ip = os.path.join(IMAGE_DIR, t["img"]) if t["img"] else None
499
  return int(t["seq"]), "是" if t["enable"] else "否", str(t["category"]), str(t["name"]), str(t["spec"]), int(t["price"]), int(t["cost"]), int(t["inventory"]), gr.update(value=ip if ip and os.path.exists(ip) else None)
 
503
  def get_menu_html():
504
  with get_db_connection() as conn:
505
  enabled_menu = conn.execute("SELECT * FROM menu WHERE enable=1 ORDER BY seq").fetchall()
506
+ p_map = {}
507
+ for row in conn.execute("SELECT category, item, spec, SUM(qty) as sq FROM orders WHERE status='待出餐' GROUP BY category, item, spec").fetchall():
508
+ c, n, s = row["category"] or "", row["item"] or "", row["spec"] or ""
509
+ p_map[f"{c}|{n}|{s}"] = row["sq"]
510
 
511
  tabs = []
512
  sections_by_tab = {}
513
  items_by_cat = {}
514
 
515
+ # 🌟 分頁邏輯
516
  for m in enabled_menu:
517
  c = m["category"]
518
  c_l = c.lower()
 
519
  if any(x in c_l for x in ["step 1", "step1", "魚種", "step 2", "step2", "金額"]):
520
  tab_name = "🐟 生魚片客製 (Step 1 & 2)"
521
  else:
 
524
  if tab_name not in tabs: tabs.append(tab_name)
525
  if tab_name not in sections_by_tab: sections_by_tab[tab_name] = []
526
  if c not in sections_by_tab[tab_name]: sections_by_tab[tab_name].append(c)
 
527
  items_by_cat.setdefault(c, []).append(dict(m))
528
 
 
529
  tabs_html = "<div class='menu-category-tabs'>"
530
  tabs_html += "<button class='cat-tab-btn active' onclick='window.filterMenu(\"all\", this)'>🌟 全部顯示</button>"
531
  for tab_name in tabs:
 
532
  tab_id = hashlib.md5(tab_name.encode()).hexdigest()[:8]
533
+ tabs_html += f"<button class='cat-tab-btn' onclick='window.filterMenu(\"{tab_id}\", this)'>{html.escape(tab_name)}</button>"
 
534
  tabs_html += "</div>"
535
 
 
536
  html_content = tabs_html + "<div class='menu-content-area'>"
537
 
 
538
  for tab_name in tabs:
539
  tab_id = hashlib.md5(tab_name.encode()).hexdigest()[:8]
 
540
  for c in sections_by_tab[tab_name]:
541
+ html_content += f"<div class='menu-section' data-tab-group='{tab_id}'><div class='cat-header'>{html.escape(c)}</div><div class='menu-grid'>"
 
 
 
 
542
  c_l = c.lower()
543
  is_s1 = "step 1" in c_l or "step1" in c_l or "魚種" in c_l
544
  is_s2 = "step 2" in c_l or "step2" in c_l or "金額" in c_l
 
552
 
553
  safe_n_display = html.escape(m['name'])
554
  safe_spec = html.escape(m['spec'])
555
+
556
+ # 🌟 前端狀態使用絕對唯一的複合鍵
557
+ unique_key = f"{m['category']}|{m['name']}|{m['spec']}"
558
+ safe_unique_key = unique_key.replace("'", "\\'").replace('"', '\\"')
559
+ hash_id = hashlib.md5(unique_key.encode()).hexdigest()[:8]
560
 
561
  inv = int(m.get("inventory", 999))
562
+ av = inv - p_map.get(unique_key, 0) if not (is_s1 or is_s2) else inv
563
  is_sold = inv < 900 and av <= 0
564
 
565
  if is_sold:
 
568
  act = "<div style='color:#ef4444;font-weight:bold;text-align:center;width:100%'>已售罄</div>"
569
  else:
570
  cls, overlay = "menu-card", ""
571
+ if is_s1: act = f"<div class='step1-checkbox-wrapper'><input type='checkbox' class='step1-checkbox' id='chk-{hash_id}' onchange=\"window.toggleCheck('{safe_unique_key}', this)\"></div>"
572
+ else: act = f"<div class='qty-row'><button class='action-btn' onclick=\"window.updateQty('{safe_unique_key}', '{hash_id}', -1)\">➖</button><div class='qty-display' id='qty-{hash_id}'>0</div><button class='action-btn' onclick=\"window.updateQty('{safe_unique_key}', '{hash_id}', 1)\">➕</button></div>"
573
 
574
  p_s = f"<small style='color:#64748b;'>{safe_spec}</small>" if (is_s1 or is_s2) else f"<small style='color:#64748b;'>{safe_spec} | <span style='color:#ea580c; font-weight:bold;'>NT$ {m['price']}</span></small>"
575
  html_content += f"<div class='{cls}'>{overlay}<div class='img-col'><img src='{src}'></div><div class='info-col'><strong style='font-size:1.1em; color:#1e293b;'>{safe_n_display}</strong><br>{p_s}</div><div class='action-col'>{act}</div></div>"
576
  html_content += "</div></div>"
577
+ return html_content + "</div>"
 
 
578
 
579
  def add_order(c_name, p_method, d_loc, d_date, d_time, nts, order_json):
580
  safe_c_name = html.escape(str(c_name))
 
585
 
586
  with get_db_connection() as conn:
587
  enabled = conn.execute("SELECT * FROM menu WHERE enable=1").fetchall()
588
+ p_map = {}
589
+ for row in conn.execute("SELECT category, item, spec, SUM(qty) as sq FROM orders WHERE status='待出餐' GROUP BY category, item, spec").fetchall():
590
+ c, n, s = row["category"] or "", row["item"] or "", row["spec"] or ""
591
+ p_map[f"{c}|{n}|{s}"] = row["sq"]
592
 
593
+ flat = {f"{m['category']}|{m['name']}|{m['spec']}": dict(m) for m in enabled}
594
 
595
+ # 庫存檢查
596
+ for unique_key, qty in data.items():
597
  qty = int(qty)
598
+ if qty > 0 and unique_key in flat:
599
+ m = flat[unique_key]; c_l = str(m.get("category", "")).lower()
600
  if not any(x in c_l for x in ["step 1", "step1", "魚種", "step 2", "step2", "金額"]):
601
  inv = int(m.get("inventory", 999))
602
+ if inv < 900 and (inv - p_map.get(unique_key, 0)) < qty:
603
+ return f"❌ 【{html.escape(m['name'])} ({html.escape(m['spec'])})】 庫存不足!", order_json
604
 
605
  s1, s2, other = [], [], []
606
+ for unique_key, qty in data.items():
607
  qty = int(qty)
608
+ if qty > 0 and unique_key in flat:
609
+ c_l = str(flat[unique_key].get("category", "")).lower()
610
+ if "step 1" in c_l or "step1" in c_l or "魚種" in c_l: s1.append(unique_key)
611
+ elif "step 2" in c_l or "step2" in c_l or "金額" in c_l: s2.append({"m": flat[unique_key], "qty": qty})
612
+ else: other.append({"m": flat[unique_key], "qty": qty})
613
 
614
  if not (s1 or s2 or other): return "❌ 未選擇商品!", order_json
615
+ if (s1 and not s2) or (s2 and not s1): return "❌ Step 1 (魚種) 與 Step 2 (金額) 必須同時選擇!", order_json
616
 
617
  to_add = list(other)
618
+
619
+ # 🌟 核心優化:將 Step 1 的魚種選擇直接變成 Step 2 訂單的「備註」,不干擾 Step 2 原本的品名與庫存
620
  if s1 and s2:
621
+ # 收集顧客選的所有魚種與規格
622
+ s1_desc = " + ".join([f"{flat[k]['name']}({flat[k]['spec']})" for k in s1])
623
  for it in s2:
624
+ cm = dict(it["m"])
625
+ to_add.append({"m": cm, "qty": it["qty"], "s1_desc": s1_desc})
626
 
627
  ts, delivery = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M:%S"), (f"{d_date} {d_time}" if p_method == "預訂" else "盡快")
628
 
629
  with db_lock:
630
  with get_db_connection() as conn:
631
  for item in to_add:
632
+ m, q = item["m"], item["qty"]
633
+ s1_d = item.get("s1_desc", "")
634
+
635
+ final_note = safe_nts
636
+ if s1_d:
637
+ final_note = f"【客製魚種: {s1_d}】 {final_note}".strip()
638
+
639
+ oid = f"XIN-{uuid.uuid4().hex[:4].upper()}"
640
+ conn.execute('''
641
+ INSERT INTO orders (order_id, status, time, delivery_time, pickup_method, location, customer, item, price, cost, qty, total, total_cost, note, category, spec)
642
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
643
+ ''', (oid, "待出餐", ts, delivery, p_method, html.escape(d_loc) if p_method=="預訂" else "現場", safe_c_name, m["name"], m["price"], m["cost"], q, m["price"]*q, m["cost"]*q, final_note, m["category"], m["spec"]))
644
  conn.commit()
645
 
646
  trigger_background_backup()
647
+ return "✅ 下單成功!廚房已收到您的客製訂單。", "{}"
648
 
649
  def get_latest_orders_html():
650
  with get_db_connection() as conn:
 
684
  </div>
685
  </div>
686
  """
687
+ df_view = df.head(100).copy()
688
+
689
+ # 🌟 表格顯示優化:將商品與規格合併顯示更清楚
690
+ df_view["商品"] = df_view.apply(lambda x: f"{html.escape(str(x['item']))} <span style='color:#64748b;font-size:0.9em;'>({html.escape(str(x['spec']))})</span>" if pd.notnull(x.get('spec')) and x.get('spec') else html.escape(str(x['item'])), axis=1)
691
+ df_view["顧客姓名"] = df_view["customer"].apply(lambda x: html.escape(str(x)))
692
+ df_view["操作"] = df_view["order_id"].apply(lambda oid: f"<button class='delete-btn' onclick='window.deleteOrder(\"{html.escape(oid)}\")'>🗑️ 刪除</button>")
693
+
694
+ df_view = df_view.rename(columns={
695
  "order_id": "訂單編號", "status": "狀態", "time": "時間", "delivery_time": "預定交期",
696
+ "pickup_method": "取貨方式", "location": "送貨地點", "price": "單價", "qty": "數量", "total": "總價"
697
+ })
 
698
 
 
 
 
699
  table_html = f'<div class="table-container">{df_view[["訂單編號","狀態","時間","預定交期","取貨方式","送貨地點","顧客姓名","商品","單價","數量","總價","操作"]].to_html(index=False, classes="order-table", border=0, escape=False)}</div>'
700
  return dashboard_html + table_html
701
 
 
704
  try:
705
  with db_lock:
706
  with get_db_connection() as conn:
707
+ r = conn.execute("SELECT status, category, item, spec, qty FROM orders WHERE order_id=?", (str(oid),)).fetchone()
708
  if r and r["status"] == '已出餐':
709
+ # 依據複合鍵歸還庫存
710
+ c, nm, sp = r["category"], r["item"], r["spec"]
711
+ if c is not None and sp is not None:
712
+ conn.execute("UPDATE menu SET inventory = inventory + ? WHERE category=? AND name=? AND spec=? AND inventory < 900", (r["qty"], c, nm, sp))
713
+ else:
714
+ conn.execute("UPDATE menu SET inventory = inventory + ? WHERE name=? AND inventory < 900", (r["qty"], nm))
715
  conn.execute("DELETE FROM orders WHERE order_id=?", (str(oid),)); conn.commit()
716
  trigger_background_backup()
717
  return f"✅ 訂單已刪除", get_latest_orders_html()
 
719
 
720
  def get_kitchen_html():
721
  with get_db_connection() as conn:
722
+ pending = conn.execute("SELECT rowid, item, qty, note, time, customer, spec FROM orders WHERE status='待出餐' ORDER BY time ASC, rowid ASC").fetchall()
 
723
 
724
  if not pending: return "<div style='text-align:center;padding:40px;font-size:1.5em;color:#10b981;background:white;border-radius:12px;box-shadow:0 2px 10px rgba(0,0,0,0.05);'>🎉 目前沒有待出餐訂單,廚房休息中!</div>"
725
 
726
  h = '<div class="ticket-grid">'
727
  for idx, r in enumerate(pending):
728
+ rowid, item_name, qty, note, o_time, customer, order_spec = r
 
729
  time_str = str(o_time)[11:16]
730
 
731
  safe_item = html.escape(item_name)
732
+ safe_spec = html.escape(order_spec if order_spec else "")
733
  safe_customer = html.escape(customer)
734
  safe_note = html.escape(note)
735
 
 
759
  try:
760
  with db_lock:
761
  with get_db_connection() as conn:
762
+ r = conn.execute("SELECT category, item, spec, qty FROM orders WHERE rowid=?", (int(rid),)).fetchone()
763
+ if r:
764
+ c, nm, sp = r["category"], r["item"], r["spec"]
765
+ if c is not None and sp is not None:
766
+ conn.execute("UPDATE menu SET inventory = inventory - ? WHERE category=? AND name=? AND spec=? AND inventory < 900", (r["qty"], c, nm, sp))
767
+ else:
768
+ conn.execute("UPDATE menu SET inventory = inventory - ? WHERE name=? AND inventory < 900", (r["qty"], nm))
769
  conn.execute("UPDATE orders SET status='已出餐' WHERE rowid=?", (int(rid),)); conn.commit()
770
  trigger_background_backup()
771
  return "✅ 已出餐", get_kitchen_html()
 
829
 
830
  .custom-header { display: flex; border-left: 6px solid #ea580c; border-radius: 12px; padding: 15px 20px; margin-bottom: 20px; background: white; box-shadow: 0 4px 10px rgba(0,0,0,0.04); align-items: center; gap: 20px; }
831
 
 
832
  .sticky-top-panel { background: rgba(255,255,255,0.98); padding: 15px; border-radius: 16px; border: 2px solid #ea580c; margin-bottom: 10px; box-shadow: 0 8px 20px rgba(0,0,0,0.08); position: sticky; top: 0; z-index: 100; max-height: 25vh; overflow-y: auto; flex-shrink: 0; }
833
  .scrollable-menu-panel { height: 65vh; overflow-y: auto; padding-right: 10px; position: relative; }
834
 
 
835
  .menu-category-tabs { display: flex; gap: 10px; overflow-x: auto; padding: 10px 5px; margin-bottom: 15px; position: sticky; top: 0; background: rgba(255,255,255,0.98); z-index: 90; border-bottom: 2px solid #e2e8f0; }
836
  .menu-category-tabs::-webkit-scrollbar { display: none; }
837
  .menu-category-tabs { -ms-overflow-style: none; scrollbar-width: none; }
 
872
  footer, .built-with, gradio-badge, .show-api, .toast-wrap, .status-indicator { display: none !important; opacity: 0 !important; pointer-events: none !important; }
873
  .hidden-order-data, .hidden-serve-data, .hidden-delete-data, .hidden-date { display: none !important; }
874
 
 
875
  html body a[href*='huggingface.co'], html body a[href*='hf.co'] { display: none !important; opacity: 0 !important; pointer-events: none !important; visibility: hidden !important; }
876
  body > div[class*='fixed top-'], body > div[class*='absolute top-'] { display: none !important; opacity: 0 !important; pointer-events: none !important; }
877
 
 
901
  };
902
  window.toggleCheck = function(n, c) { window.orderState[n] = c.checked ? 1 : 0; updateHiddenField(); };
903
 
 
904
  window.filterMenu = function(catId, btnEl) {
 
905
  document.querySelectorAll('.cat-tab-btn').forEach(btn => btn.classList.remove('active'));
906
  if(btnEl) btnEl.classList.add('active');
907
 
 
908
  document.querySelectorAll('.menu-section').forEach(sec => {
909
  if(catId === 'all' || sec.getAttribute('data-tab-group') === catId) {
910
  sec.style.display = 'block';
 
935
  document.addEventListener("DOMContentLoaded", function() {
936
  const kill = function() {
937
  document.querySelectorAll('footer, .built-with, gradio-badge, .show-api, .toast-wrap, .status-indicator').forEach(el => el.remove());
 
938
  document.querySelectorAll('a[href*="huggingface.co"], a[href*="hf.co"]').forEach(el => el.remove());
939
  document.querySelectorAll('body > div.absolute.top-4, body > div.fixed.top-4, body > div.fixed.top-2').forEach(el => el.remove());
940
  };
 
968
  nav_settings = gr.Button("⚙️ 系統設定")
969
 
970
  with gr.Column(visible=True) as page_order:
 
971
  with gr.Column(elem_classes="sticky-top-panel"):
972
  with gr.Row():
973
  cn = gr.Textbox(label="桌號 / 顧客姓名", interactive=True, scale=2)
 
980
  hidden_d_date = gr.Textbox(value=get_today_val(), elem_classes="hidden-date")
981
  d_time = gr.Dropdown(choices=get_booking_times(), label="預定時間", interactive=True)
982
 
 
983
  with gr.Row():
984
  res_msg = gr.Textbox(label="下單系統回報", interactive=False, scale=3)
985
  sub_btn = gr.Button("🚀 確認送出訂單", variant="primary", size="lg", scale=2)
986
 
987
  pm.change(lambda v: gr.update(visible=(v=="預訂")), [pm], [booking_row])
988
 
 
989
  with gr.Column(elem_classes="scrollable-menu-panel"):
990
  hidden_order_data = gr.Textbox(value="{}", elem_classes="hidden-order-data")
991
  order_menu_html = gr.HTML("")
 
1083
  if u["acc"]=="guest_error": return [gr.update(visible=True), gr.update(visible=False), "<div style='color:red;text-align:center;'>❌ 帳號或密碼錯誤</div>", ""] + [gr.update(visible=False)]*7 + [gr.update(visible=False)]*7 + [gr.update()]*7
1084
  lvl, msg = u["level"], f"🍣 **歡迎回來,{u['name']}**"
1085
 
1086
+ s_o = lvl in [0,1,2,9]
1087
+ s_k = lvl in [8,9]
1088
+ s_a = lvl == 9
 
1089
 
1090
  return [
1091
  gr.update(visible=False), gr.update(visible=True), "", msg,
 
1092
  gr.update(visible=s_o), gr.update(visible=s_k), gr.update(visible=s_a), gr.update(visible=s_a), gr.update(visible=s_a), gr.update(visible=s_a), gr.update(visible=s_a),
 
1093
  gr.update(visible=s_o, variant="primary" if s_o else "secondary"),
1094
  gr.update(visible=s_k, variant="primary" if s_k and not s_o else "secondary"),
1095
  gr.update(visible=s_a, variant="secondary"),
 
1097
  gr.update(visible=s_a, variant="secondary"),
1098
  gr.update(visible=s_a, variant="secondary"),
1099
  gr.update(visible=s_a, variant="secondary"),
 
1100
  get_menu_html() if s_o else "", get_kitchen_html() if s_k else "", get_menu_df() if s_a else pd.DataFrame(), get_inv_df() if s_a else pd.DataFrame(), gr.update(choices=get_inv_choices()) if s_a else gr.update(), get_members_df() if s_a else pd.DataFrame(), get_latest_orders_html() if s_a else ""
1101
  ]
1102
 
 
1106
  sub_btn.click(add_order, [cn, pm, loc, hidden_d_date, d_time, nts, hidden_order_data], [res_msg, hidden_order_data]).then(None, None, None, js="window.clearOrderUI")
1107
  m_sv.click(update_menu_item, [m_sq, m_en, m_ct, m_nm, m_sp, m_pr, m_cs, m_inv, m_im], [ms_out, mdf, m_im, order_menu_html])
1108
  m_cl.click(lambda: (999, "是", "", "", "", 0, 0, 999, None), None, [m_sq, m_en, m_ct, m_nm, m_sp, m_pr, m_cs, m_inv, m_im])
1109
+
1110
+ # 🌟 刪除菜單現在會傳入 3 個複合鍵參數
1111
+ m_de.click(delete_menu_item, [m_ct, m_nm, m_sp], [ms_out, mdf, order_menu_html])
1112
  mdf.select(handle_menu_selection, None, [m_sq, m_en, m_ct, m_nm, m_sp, m_pr, m_cs, m_inv, m_im])
1113
 
 
1114
  mm_df.select(handle_member_selection, inputs=[mm_df], outputs=[mm_n, mm_p, mm_a, mm_w, mm_lvl])
1115
  mm_s.click(save_single_member, [mm_n, mm_p, mm_a, mm_w, mm_lvl], [mm_out, mm_df])
1116
  mm_d.click(delete_single_member, [mm_a], [mm_out, mm_df])
1117
 
1118
+ # 🌟 庫存更新使用複合解析
1119
  def update_inv_and_refresh(n, q):
1120
  if not n: return "⚠️ 請先選擇品項", gr.update()
1121
+ match = re.match(r"^\[(.*?)\] (.*) \((.*)\)$", n)
1122
+ if not match: return "⚠️ 格式解析失敗", gr.update()
1123
+ c, nm, sp = match.groups()
1124
  with db_lock:
1125
  with get_db_connection() as conn:
1126
+ conn.execute("UPDATE menu SET inventory=? WHERE category=? AND name=? AND spec=?", (int(q), c, nm, sp))
1127
  conn.commit()
1128
  trigger_background_backup()
1129
+ return f"✅ 【{nm}】 總庫存已覆蓋為 {int(q)}", get_inv_df()
1130
 
1131
  def add_inv_and_refresh(n, add_q):
1132
  if not n: return "⚠️ 請先選擇品項", gr.update(), 0
1133
+ if not add_q or int(add_q) == 0: return "⚠️ 數量無效", gr.update(), 0
1134
+ match = re.match(r"^\[(.*?)\] (.*) \((.*)\)$", n)
1135
+ if not match: return "⚠️ 格式解析失敗", gr.update(), 0
1136
+ c, nm, sp = match.groups()
1137
+
1138
  with db_lock:
1139
  with get_db_connection() as conn:
1140
+ r = conn.execute("SELECT inventory FROM menu WHERE category=? AND name=? AND spec=?", (c, nm, sp)).fetchone()
1141
  if r:
1142
  new_inv = int(r["inventory"]) + int(add_q)
1143
+ conn.execute("UPDATE menu SET inventory=? WHERE category=? AND name=? AND spec=?", (new_inv, c, nm, sp))
1144
  conn.commit()
1145
  else:
1146
  return "⚠️ 找不到該品項", gr.update(), 0
1147
  trigger_background_backup()
1148
+ return f"✅ 成功進貨 {int(add_q)}!目前庫存為 {new_inv}", get_inv_df(), 0
1149
 
1150
  def handle_inv_selection(evt: gr.SelectData, current_data):
1151
  try:
1152
  row_idx = evt.index[0]
1153
+ if isinstance(current_data, pd.DataFrame):
1154
+ c = str(current_data.iloc[row_idx]["分類"])
1155
+ n = str(current_data.iloc[row_idx]["品名"])
1156
+ s = str(current_data.iloc[row_idx]["規格"])
1157
+ else:
1158
+ c = str(current_data[row_idx][0])
1159
+ n = str(current_data[row_idx][1])
1160
+ s = str(current_data[row_idx][2])
1161
+ return f"[{c}] {n} ({s})"
1162
  except Exception as e: return gr.update()
1163
 
1164
  def fetch_inventory_for_item(n):
1165
  if not n: return gr.update(), 0
1166
+ match = re.match(r"^\[(.*?)\] (.*) \((.*)\)$", n)
1167
+ if not match: return 0, 0
1168
+ c, nm, sp = match.groups()
1169
  try:
1170
  with get_db_connection() as conn:
1171
+ r = conn.execute("SELECT inventory FROM menu WHERE category=? AND name=? AND spec=?", (c, nm, sp)).fetchone()
1172
  return int(r["inventory"]) if r else 0, 0
1173
  except: return 0, 0
1174
 
 
1176
  inv_name.change(fetch_inventory_for_item, inputs=[inv_name], outputs=[inv_qty, inv_add_val])
1177
  inv_sv.click(update_inv_and_refresh, [inv_name, inv_qty], [inv_out, inv_df])
1178
  inv_add_btn.click(add_inv_and_refresh, [inv_name, inv_add_val], [inv_out, inv_df, inv_add_val]).then(
1179
+ fetch_inventory_for_item, [inv_name], [inv_qty, gr.update()]
1180
  )
1181
 
 
1182
  k_refresh_btn.click(lambda: ("✅ 已刷新最新廚房訂單", get_kitchen_html()), None, [k_msg, k_html])
1183
  hidden_serve_id.change(serve_k_order_by_id, [hidden_serve_id], [k_msg, k_html]).then(lambda: "", None, [hidden_serve_id])
1184