'
def do_login(acc, pwd):
acc = safe_str(acc)
pwd = safe_str(pwd)
if not acc:
return {"acc": "guest_error", "level": -1, "name": ""}
if acc == "admin" and hash_pwd(pwd) == ADMIN_PASSWORD:
return {"acc": "admin", "level": 9, "name": "最高管理員"}
if acc == "kitchen" and (pwd == "0000" or hash_pwd(pwd) == hash_pwd("0000")):
return {"acc": "kitchen", "level": 8, "name": "後廚端"}
with get_db_connection() as conn:
user = conn.execute("SELECT * FROM members WHERE acc=?", (acc,)).fetchone()
if user and user["pwd"] == hash_pwd(pwd):
return {"acc": acc, "level": safe_int(user["level"]), "name": user["name"]}
return {"acc": "guest_error", "level": -1, "name": ""}
def save_ui_config(font_family, text_size, image_size, card_opacity, bg_image_url, bg_image_opacity):
with db_lock:
with get_db_connection() as conn:
conn.execute("INSERT OR REPLACE INTO config (key, value) VALUES ('font_family', ?)", (font_family,))
conn.execute("INSERT OR REPLACE INTO config (key, value) VALUES ('text_size', ?)", (str(text_size),))
conn.execute("INSERT OR REPLACE INTO config (key, value) VALUES ('image_size', ?)", (str(image_size),))
conn.execute("INSERT OR REPLACE INTO config (key, value) VALUES ('card_opacity', ?)", (str(card_opacity),))
conn.execute("INSERT OR REPLACE INTO config (key, value) VALUES ('bg_image_opacity', ?)", (str(bg_image_opacity),))
if bg_image_url and str(bg_image_url).strip(): conn.execute("INSERT OR REPLACE INTO config (key, value) VALUES ('bg_image_url', ?)", (str(bg_image_url).strip(),))
else: conn.execute("DELETE FROM config WHERE key='bg_image_url'")
conn.commit()
load_config_to_memory(); trigger_background_backup()
return "✅ 介面設定已儲存!"
def save_single_member(name, phone, acc, pwd, level_str):
acc = safe_str(acc)
if not acc: return "❌ 帳號必填", gr.update()
with get_db_connection() as conn:
row = conn.execute("SELECT pwd FROM members WHERE acc=?", (acc,)).fetchone()
old_pwd = row['pwd'] if row else ""
pwd_to_save = hash_pwd(pwd) if safe_str(pwd) and safe_str(pwd) != "***" else old_pwd
if not pwd_to_save: pwd_to_save = hash_pwd("1234")
try: level_val = str(level_str).split(" ")[0]
except: level_val = "0"
with db_lock:
with get_db_connection() as conn:
conn.execute("INSERT OR REPLACE INTO members VALUES (?,?,?,?,?,?)", (acc, pwd_to_save, level_val, name, "", phone))
conn.commit()
trigger_background_backup()
return f"✅ {name} 儲存成功", gr.update(value=get_members_df())
def delete_single_member(acc):
acc = safe_str(acc)
if not acc: return "❌ 選擇帳號", gr.update()
with db_lock:
with get_db_connection() as conn:
conn.execute("DELETE FROM members WHERE acc=?", (acc,))
conn.commit()
trigger_background_backup()
return f"🗑️ {acc} 已刪除", gr.update(value=get_members_df())
def get_members_df():
data = []
with get_db_connection() as conn:
for r in conn.execute("SELECT * FROM members").fetchall():
lvl = str(r["level"])
lvl_str = {"9": "9 (管理者)", "8": "8 (後廚)"}.get(lvl, "0 (一般會員)")
data.append([r["name"], r["phone"], r["acc"], "***", lvl_str])
return pd.DataFrame(data, columns=["姓名","電話","帳號","密碼","權限"])
def handle_member_selection(evt: gr.SelectData, current_data):
try:
row_idx = evt.index[0]
if isinstance(current_data, pd.DataFrame): acc_id = str(current_data.iloc[row_idx]["帳號"])
else: acc_id = str(current_data[row_idx][2])
with get_db_connection() as conn:
m = conn.execute("SELECT * FROM members WHERE acc=?", (acc_id,)).fetchone()
if m:
lvl = str(m["level"])
lvl_str = {"9": "9 (管理者)", "8": "8 (後廚)"}.get(lvl, "0 (一般會員)")
return str(m["name"]), str(m["phone"]), m["acc"], "***", lvl_str
except: pass
return "", "", "", "***", "0 (一般會員)"
def get_inv_choices():
choices = []
with get_db_connection() as conn:
for m in conn.execute("SELECT category, name, spec FROM menu").fetchall():
c = str(m["category"] or "")
n = str(m["name"] or "")
s = str(m["spec"] or "")
c_lower = c.lower()
if not ("step 2" in c_lower or "step2" in c_lower or "金額" in c_lower):
if s: choices.append(f"[{c}] {n} | 規格: {s}")
else: choices.append(f"[{c}] {n}")
return choices
def parse_inv_choice(n_str):
match = re.match(r"^\[(.*?)\] (.*?)(?: \| 規格: (.*))?$", str(n_str or ""))
if not match: return None, None, None
c = match.group(1)
nm = match.group(2)
sp = match.group(3) or ""
return c, nm, sp
def get_inv_df():
with db_lock:
with get_db_connection() as conn:
p_map = {}
for row in conn.execute("SELECT category, item, spec, SUM(qty) as sq FROM orders WHERE status='待出餐' GROUP BY category, item, spec").fetchall():
row_dict = dict(row)
c, n, s = str(row_dict.get("category", "")), str(row_dict.get("item", "")), str(row_dict.get("spec", ""))
p_map[f"{c}|{n}|{s}"] = safe_int(row_dict.get("sq"))
menu_items = conn.execute("SELECT * FROM menu ORDER BY seq").fetchall()
data = []
for row in menu_items:
m = dict(row)
c = str(m.get("category", ""))
c_l = c.lower()
if "step 2" in c_l or "step2" in c_l or "金額" in c_l: continue
name = str(m.get("name", ""))
spec = str(m.get("spec", ""))
inv = safe_int(m.get("inventory", 999))
key = f"{c}|{name}|{spec}"
if "step 1" in c_l or "step1" in c_l or "魚種" in c_l:
p, av = 0, inv
i_s = str(inv) if inv < 900 else "無限制"
av_s = i_s
else:
p = safe_int(p_map.get(key, 0))
av = inv - p
i_s, av_s = (str(inv) if inv < 900 else "無限制"), (str(av) if inv < 900 else "無限制")
data.append([c, name, spec, i_s, str(p) if inv < 900 else "-", av_s])
return pd.DataFrame(data, columns=["分類", "品名", "規格", "庫存數量", "預訂數量", "可售數量"])
def get_menu_df():
data = []
with get_db_connection() as conn:
for row in conn.execute("SELECT * FROM menu ORDER BY seq").fetchall():
m = dict(row)
p = safe_int(m.get("price", 0))
c = safe_int(m.get("cost", 0))
inv = safe_int(m.get("inventory", 999))
data.append([safe_int(m.get("seq", 999)), "是" if m.get("enable") else "否", str(m.get("category", "")), str(m.get("name", "")), str(m.get("spec", "")), p, c, inv])
return pd.DataFrame(data, columns=["排序", "啟用", "分類", "品名", "規格", "價格", "成本", "庫存"])
def update_menu_item(seq, enable, cat, name, spec, price, cost, inv, img_file):
cat = safe_str(cat)
name = safe_str(name)
spec = safe_str(spec)
if not name or not cat:
return "❌ 分類與品名皆為必填!(同品名若有不同規格/分類,將視為不同品項)", gr.update(), None, gr.update()
img_name = None
with get_db_connection() as conn:
row = conn.execute("SELECT img FROM menu WHERE category=? AND name=? AND IFNULL(spec, '')=?", (cat, name, spec)).fetchone()
if row: img_name = dict(row).get('img')
if img_file and isinstance(img_file, str) and RUNTIME_DATA_DIR not in img_file:
img_name = f"{name}_{uuid.uuid4().hex[:4]}.png"
try: shutil.copy(img_file, os.path.join(IMAGE_DIR, img_name))
except: pass
with db_lock:
with get_db_connection() as conn:
if conn.execute("SELECT 1 FROM menu WHERE category=? AND name=? AND IFNULL(spec, '')=?", (cat, name, spec)).fetchone():
conn.execute("UPDATE menu SET seq=?, enable=?, price=?, cost=?, img=?, inventory=?, spec=? WHERE category=? AND name=? AND IFNULL(spec, '')=?", (safe_int(seq, 999), enable=="是", safe_int(price), safe_int(cost), img_name, safe_int(inv, 999), spec, cat, name, spec))
else:
conn.execute("INSERT INTO menu VALUES (?,?,?,?,?,?,?,?,?,?,?)", (safe_int(seq, 999), enable=="是", "全部", cat, name, spec, safe_int(price), safe_int(cost), "", img_name, safe_int(inv, 999)))
conn.commit()
trigger_background_backup()
spec_display = f" ({spec})" if spec else ""
return f"✅ 【{name}{spec_display}】 儲存成功!", gr.update(value=get_menu_df()), None, gr.update(value=get_menu_html())
def delete_menu_item(cat, name, spec):
cat = safe_str(cat)
name = safe_str(name)
spec = safe_str(spec)
if not name: return "❌ 請先選擇品項", gr.update(), gr.update()
with db_lock:
with get_db_connection() as conn:
conn.execute("DELETE FROM menu WHERE category=? AND name=? AND IFNULL(spec, '')=?", (cat, name, spec))
conn.commit()
trigger_background_backup()
return f"🗑️ 已刪除 【{name}】", gr.update(value=get_menu_df()), gr.update(value=get_menu_html())
def handle_menu_selection(evt: gr.SelectData, current_data):
try:
row_idx = evt.index[0]
if isinstance(current_data, pd.DataFrame):
cat = str(current_data.iloc[row_idx]["分類"])
name = str(current_data.iloc[row_idx]["品名"])
spec = str(current_data.iloc[row_idx]["規格"])
else:
cat = str(current_data[row_idx][2])
name = str(current_data[row_idx][3])
spec = str(current_data[row_idx][4])
cat = "" if pd.isna(cat) or cat == "None" else str(cat)
name = "" if pd.isna(name) or name == "None" else str(name)
spec = "" if pd.isna(spec) or spec == "None" else str(spec)
with get_db_connection() as conn:
t = conn.execute("SELECT * FROM menu WHERE category=? AND name=? AND IFNULL(spec, '')=?", (cat, name, spec)).fetchone()
if t:
m = dict(t)
ip = os.path.join(IMAGE_DIR, m["img"]) if m.get("img") else None
return safe_int(m.get("seq", 999)), "是" if m.get("enable") else "否", str(m.get("category", "")), str(m.get("name", "")), str(m.get("spec", "")), safe_int(m.get("price", 0)), safe_int(m.get("cost", 0)), safe_int(m.get("inventory", 999)), gr.update(value=ip if ip and os.path.exists(ip) else None)
except Exception as e:
print(f"Selection error: {e}")
return 999, "是", "", "", "", 0, 0, 999, None
def get_menu_html():
try:
with get_db_connection() as conn:
enabled_menu = conn.execute("SELECT * FROM menu WHERE enable=1 ORDER BY seq").fetchall()
p_map = {}
for row in conn.execute("SELECT category, item, spec, SUM(qty) as sq FROM orders WHERE status='待出餐' GROUP BY category, item, spec").fetchall():
r_dict = dict(row)
c, n, s = str(r_dict.get("category", "")), str(r_dict.get("item", "")), str(r_dict.get("spec", ""))
p_map[f"{c}|{n}|{s}"] = safe_int(r_dict.get("sq"))
tabs = []
sections_by_tab = {}
items_by_cat = {}
step1_items = []
for row in enabled_menu:
m = dict(row)
c = str(m.get("category", ""))
c_l = c.lower()
is_s1 = "step 1" in c_l or "step1" in c_l or "魚種" in c_l
is_s2 = "step 2" in c_l or "step2" in c_l or "金額" in c_l
if is_s1:
step1_items.append(m)
continue
if is_s2:
tab_name = "🐟 生魚片客製 (Step 1 & 2)"
else:
tab_name = c
if tab_name not in tabs: tabs.append(tab_name)
if tab_name not in sections_by_tab: sections_by_tab[tab_name] = []
if c not in sections_by_tab[tab_name]: sections_by_tab[tab_name].append(c)
items_by_cat.setdefault(c, []).append(m)
tabs_html = "
"
tabs_html += ""
for tab_name in tabs:
tab_id = hashlib.md5(tab_name.encode()).hexdigest()[:8]
tabs_html += f""
tabs_html += "
"
modal_html = "
"
modal_html += "
🐟 請選擇客製魚種
"
modal_html += "
搭配餐點:
"
modal_html += ""
modal_html += "
"
for sm in step1_items:
nm_raw = str(sm.get('name') or '')
sp_raw = str(sm.get('spec') or '')
display_raw = f"{nm_raw} ({sp_raw})" if sp_raw else nm_raw
disp_safe = safe_html_str(display_raw)
inv = safe_int(sm.get("inventory", 999))
if inv <= 0:
modal_html += f""
else:
modal_html += f""
modal_html += "
"
for tab_name in tabs:
tab_id = hashlib.md5(tab_name.encode()).hexdigest()[:8]
for c in sections_by_tab[tab_name]:
html_content += f"
{safe_html_str(c)}
"
c_l = c.lower()
is_s2 = "step 2" in c_l or "step2" in c_l or "金額" in c_l
for m in items_by_cat[c]:
src = ""
if m.get("img") and os.path.exists(os.path.join(IMAGE_DIR, m["img"])):
try:
with open(os.path.join(IMAGE_DIR, m["img"]), "rb") as f: src = f"data:image/png;base64,{base64.b64encode(f.read()).decode('utf-8')}"
except: pass
n_raw = str(m.get('name') or '')
sp_raw = str(m.get('spec') or '')
unique_key = f"{str(m.get('category') or '')}|{n_raw}|{sp_raw}"
hash_id = hashlib.md5(unique_key.encode()).hexdigest()[:8]
disp_name = safe_html_str(n_raw)
disp_spec = safe_html_str(sp_raw)
item_price = safe_int(m.get('price'))
data_embed = f""
inv = safe_int(m.get("inventory", 999))
av = inv - p_map.get(unique_key, 0) if not is_s2 else inv
is_sold = inv < 900 and av <= 0
if is_sold:
cls = "menu-card sold-out-card"
overlay = "
"
except Exception as e:
traceback.print_exc()
return f"
菜單渲染發生錯誤:{str(e)}
"
def add_order(c_name, p_method, d_loc, d_date, d_time, nts, order_json):
safe_c_name = safe_html_str(c_name)
safe_nts = safe_html_str(nts)
try: data = json.loads(order_json)
except: data = {}
with get_db_connection() as conn:
enabled = conn.execute("SELECT * FROM menu WHERE enable=1").fetchall()
p_map = {}
for row in conn.execute("SELECT category, item, spec, SUM(qty) as sq FROM orders WHERE status='待出餐' GROUP BY category, item, spec").fetchall():
r_dict = dict(row)
c, n, s = str(r_dict.get("category", "")), str(r_dict.get("item", "")), str(r_dict.get("spec", ""))
p_map[f"{c}|{n}|{s}"] = safe_int(r_dict.get("sq"))
flat = {}
for m_row in enabled:
m = dict(m_row)
n_raw = str(m.get('name') or '')
disp_name = safe_html_str(n_raw)
flat[disp_name] = m
to_add = []
for raw_key, qty in data.items():
qty = safe_int(qty)
if qty <= 0: continue
parts = raw_key.split("|||")
unique_key = parts[0]
custom_note = parts[1] if len(parts) > 1 else ""
if unique_key in flat:
m = flat[unique_key]
c_l = str(m.get("category", "")).lower()
if not ("step 1" in c_l or "step1" in c_l or "魚種" in c_l):
inv = safe_int(m.get("inventory", 999))
if inv < 900 and (inv - p_map.get(unique_key, 0)) < qty:
spec_str = f" ({m['spec']})" if m.get('spec') else ""
return f"
", order_json
to_add.append({"m": m, "qty": qty, "custom_note": custom_note})
if not to_add: return "
❌ 尚未選擇任何餐點!
", order_json
ts, delivery = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M:%S"), (f"{d_date} {d_time}" if p_method == "預訂" else "盡快")
total_order_price = sum(safe_int(item["m"].get("price", 0)) * item["qty"] for item in to_add)
with db_lock:
with get_db_connection() as conn:
for item in to_add:
m, q, custom_note = item["m"], item["qty"], item["custom_note"]
final_note = safe_nts
if custom_note:
final_note = f"【客製: {custom_note}】 {final_note}".strip()
oid = f"XIN-{uuid.uuid4().hex[:4].upper()}"
conn.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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
''', (oid, "待出餐", ts, delivery, p_method, safe_html_str(d_loc) if p_method=="預訂" else "現場", safe_c_name, m.get("name", ""), safe_int(m.get("price")), safe_int(m.get("cost")), q, safe_int(m.get("price", 0))*q, safe_int(m.get("cost", 0))*q, final_note, m.get("category", ""), m.get("spec", "")))
conn.commit()
trigger_background_backup()
success_html = f"
✅ 下單成功!廚房已收到訂單。 本次總金額:NT$ {total_order_price}
"
return success_html, "{}"
def get_latest_orders_html():
try:
with get_db_connection() as conn:
orders_data = [dict(r) for r in conn.execute("SELECT * FROM orders ORDER BY time DESC").fetchall()]
if not orders_data: return "
尚無訂單
"
today_str = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d")
df = pd.DataFrame(orders_data)
if not df.empty and 'time' in df.columns:
df['date'] = df['time'].astype(str).str[:10]
today_df = df[df['date'] == today_str]
else:
today_df = pd.DataFrame()
total_rev = today_df['total'].sum() if not today_df.empty else 0
total_orders = len(today_df['order_id'].unique()) if not today_df.empty else 0
top_items_html = ""
if not today_df.empty:
top_items = today_df.groupby('item')['qty'].sum().sort_values(ascending=False).head(3)
for item, qty in top_items.items():
top_items_html += f"
{safe_html_str(item)}{qty} 份
"
else:
top_items_html = "
今日尚無銷售紀錄
"
dashboard_html = f"""
今日總營業額
NT$ {total_rev:,}
今日訂單數
{total_orders} 單
🔥 今日熱銷 Top 3
{top_items_html}
"""
df_view = df.head(100).copy()
if df_view.empty: return dashboard_html + "
"
def delete_order_by_id(oid):
if not oid: return gr.update(), gr.update()
try:
with db_lock:
with get_db_connection() as conn:
r = conn.execute("SELECT status, category, item, spec, qty FROM orders WHERE order_id=?", (str(oid),)).fetchone()
if r:
r_dict = dict(r)
if r_dict.get("status") == '已出餐':
c, nm, sp = str(r_dict.get("category", "")), str(r_dict.get("item", "")), str(r_dict.get("spec", ""))
conn.execute("UPDATE menu SET inventory = inventory + ? WHERE category=? AND name=? AND IFNULL(spec, '')=? AND inventory < 900", (r_dict.get("qty", 0), c, nm, sp))
conn.execute("DELETE FROM orders WHERE order_id=?", (str(oid),)); conn.commit()
trigger_background_backup()
return f"✅ 訂單已刪除", get_latest_orders_html()
except Exception as e: return f"❌ 失敗: {e}", gr.update()
def get_kitchen_html():
try:
with get_db_connection() as conn:
pending = conn.execute("SELECT rowid, item, qty, note, time, customer, spec FROM orders WHERE status='待出餐' ORDER BY time ASC, rowid ASC").fetchall()
if not pending: return "