HsiehMinChieh commited on
Commit ·
e5fb853
1
Parent(s): 8894e6e
feat: integrate dual-mode POS and inventory system with data.json persistence and dynamic UI
Browse filesFiles changed (3)
- __pycache__/app.cpython-314.pycAdded
- app.py+306-29
- templates/index.html+1788-242
7 unmodified lines89101112131415161718192021221 unmodified line2425262728293031323334353637383940414243442 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111127 unmodified linesimport ioimport osimport shutilapp = FastAPI()# 全域變數product_db = {}scan_records = []templates = Jinja2Templates(directory="templates")# --- 1. 載入對照表 ---def load_products():global product_dbproduct_db = {}1 unmodified linetry:with open("products.csv", mode="r", encoding="utf-8") as f:reader = csv.reader(f)next(reader, None)for row in reader:if len(row) >= 2:product_db[row[0].strip()] = row[1].strip()print(f"✅ 已載入 {len(product_db)} 筆商品資料")except Exception as e:print(f"❌ 讀取 CSV 失敗: {e}")load_products()class ScanItem(BaseModel):qr_content: str# --- 2. 發票解析 ---def parse_invoice(content):if len(content) > 20 and content[0:2].isalpha() and content[2:10].isdigit():inv_num = content[0:10]try:2 unmodified linesday = content[15:17]full_date = f"{roc_year + 1911}/{month}/{day}"except:full_date = "日期未知"return f"🧾 電子發票 ({inv_num})", f"開立日: {full_date}"return None, None@app.get("/", response_class=HTMLResponse)async def read_root(request: Request):return templates.TemplateResponse("index.html", {"request": request,"records": scan_records[:15],"db_count": len(product_db)})# --- 新增:取得所有商品資料 (供前端產生標籤用) ---@app.get("/api/products")async def get_all_products():return {"status": "success", "data": product_db}@app.post("/api/upload_csv")async def upload_csv(file: UploadFile = File(...)):with open("products.csv", "wb") as buffer:shutil.copyfileobj(file.file, buffer)load_products()return {"status": "success", "message": f"更新成功!目前資料庫有 {len(product_db)} 筆商品。", "count": len(product_db)}@app.post("/api/clear")async def clear_data():global scan_recordsscan_records = []return {"status": "success", "message": "紀錄已清空"}@app.post("/api/scan")async def receive_scan(item: ScanItem):code = item.qr_content.strip()p_name = "未知物品"if code in product_db:p_name = product_db[code]else:inv_name, inv_date = parse_invoice(code)if inv_name:p_name = f"{inv_name} - {inv_date}"new_record = {"content": code,"name": p_name,"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}scan_records.insert(0, new_record)return {"status": "success", "data": new_record}@app.get("/download")async def download_csv():stream = io.StringIO()writer = csv.writer(stream)writer.writerow(["掃描內容", "物品名稱", "掃描時間"])for record in scan_records:writer.writerow([record["content"], record["name"], record["time"]])csv_content = stream.getvalue()final_content = "\ufeff" + csv_contentreturn Response(content=final_content, media_type="text/csv", headers={"Content-Disposition": "attachment; filename=scan_results.csv"})if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)7 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263641 unmodified line666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121132 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883897 unmodified linesimport ioimport osimport shutilimport jsonapp = FastAPI()# 全域變數product_db = {}scan_records = []inventory = {}sales_records = []templates = Jinja2Templates(directory="templates")# --- 1. 資料持久化與載入 ---DATA_FILE = "data.json"def load_data():global scan_records, inventory, sales_recordsif os.path.exists(DATA_FILE):try:with open(DATA_FILE, "r", encoding="utf-8") as f:data = json.load(f)scan_records = data.get("scan_records", [])inventory = data.get("inventory", {})sales_records = data.get("sales_records", [])print(f"✅ 已載入歷史數據:{len(scan_records)} 筆盤點日誌、{len(inventory)} 筆商品庫存、{len(sales_records)} 筆銷售明細")except Exception as e:print(f"❌ 讀取 {DATA_FILE} 失敗: {e}")scan_records = []inventory = {}sales_records = []else:scan_records = []inventory = {}sales_records = []def save_data():try:data = {"scan_records": scan_records,"inventory": inventory,"sales_records": sales_records}with open(DATA_FILE, "w", encoding="utf-8") as f:json.dump(data, f, ensure_ascii=False, indent=2)except Exception as e:print(f"❌ 寫入 {DATA_FILE} 失敗: {e}")# 啟動時讀取儲存的盤點與銷售數據load_data()# --- 2. 載入商品對照表 ---def load_products():global product_dbproduct_db = {}1 unmodified linetry:with open("products.csv", mode="r", encoding="utf-8") as f:reader = csv.reader(f)header = next(reader, None)# 尋找是否包含價格欄位 (例如 "價格", "單價", "price", "unit price")price_index = -1if header:# 清理 BOM 與空白header = [col.replace('\ufeff', '').strip() for col in header]for idx, col in enumerate(header):col_lower = col.lower()if "價" in col or "price" in col_lower:price_index = idxbreakfor row in reader:if len(row) >= 2:code = row[0].strip()name = row[1].strip()price = 0.0# 讀取價格if price_index != -1 and len(row) > price_index:try:price = float(row[price_index].strip())except ValueError:price = 0.0elif len(row) >= 3:try:price = float(row[2].strip())except ValueError:price = 0.0product_db[code] = {"name": name, "price": price}print(f"✅ 已載入 {len(product_db)} 筆商品對照資料")except Exception as e:print(f"❌ 讀取 CSV 商品表失敗: {e}")load_products()# --- 3. 發票格式解析 ---def parse_invoice(content):# 電子發票左 QR code:前二位英文字母 + 八位數字,長度大於 20 字元if len(content) > 20 and content[0:2].isalpha() and content[2:10].isdigit():inv_num = content[0:10]try:2 unmodified linesday = content[15:17]full_date = f"{roc_year + 1911}/{month}/{day}"except:full_date = "未知日期"return f"🧾 電子發票 ({inv_num})", f"開立日: {full_date}"return None, None# --- 4. 輔助計量函式 ---def get_stats_summary():total_scans = len(scan_records)unique_items = len(inventory)total_qty = sum(int(item.get("quantity", 0)) for item in inventory.values())total_sales = sum(float(tx.get("total", 0)) for tx in sales_records)tx_count = len(sales_records)return {"total_scans": total_scans,"unique_items": unique_items,"total_qty": total_qty,"total_sales": total_sales,"tx_count": tx_count}# --- 5. Pydantic 模型定義 ---class ScanItem(BaseModel):qr_content: strclass InventoryUpdateItem(BaseModel):code: straction: str # 'inc', 'dec', 'set'value: int = 1class InventoryDeleteItem(BaseModel):code: strclass CartItem(BaseModel):code: strname: strprice: floatquantity: intclass CheckoutRequest(BaseModel):items: list[CartItem]cash_received: float# --- 6. 路由 API 定義 ---@app.get("/", response_class=HTMLResponse)async def read_root(request: Request):return templates.TemplateResponse("index.html", {"request": request,"records": scan_records[:30],"inventory": inventory,"sales": sales_records[:30],"db_count": len(product_db),"stats": get_stats_summary()})@app.get("/api/products")async def get_all_products():return {"status": "success", "data": product_db}@app.get("/api/stats")def get_stats_endpoint():return {"status": "success", "stats": get_stats_summary()}@app.post("/api/upload_csv")def upload_csv(file: UploadFile = File(...)):try:with open("products.csv", "wb") as buffer:shutil.copyfileobj(file.file, buffer)load_products()return {"status": "success","message": f"商品庫更新成功!目前資料庫有 {len(product_db)} 筆對照資料。","count": len(product_db)}except Exception as e:return {"status": "error", "message": f"更新失敗:{str(e)}"}@app.post("/api/clear")def clear_data():global scan_records, inventoryscan_records = []inventory = {}save_data()return {"status": "success", "message": "盤點日誌與盤點清單已全部清空", "stats": get_stats_summary()}# --- 盤點模式 API ---@app.post("/api/scan")def receive_scan(item: ScanItem):code = item.qr_content.strip()if not code:return {"status": "error", "message": "條碼內容不可為空"}p_name = "未知物品"p_price = 0.0if code in product_db:p_name = product_db[code]["name"]p_price = product_db[code]["price"]else:inv_name, inv_date = parse_invoice(code)if inv_name:p_name = f"{inv_name} - {inv_date}"p_price = 0.0time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")# 寫入時間流記錄new_record = {"content": code,"name": p_name,"price": p_price,"time": time_str}scan_records.insert(0, new_record)# 更新累計庫存if code in inventory:inventory[code]["quantity"] = int(inventory[code].get("quantity", 0)) + 1inventory[code]["last_updated"] = time_strelse:inventory[code] = {"name": p_name,"price": p_price,"quantity": 1,"last_updated": time_str}save_data()return {"status": "success","data": new_record,"inventory_item": inventory[code],"stats": get_stats_summary()}@app.post("/api/inventory/update")def update_inventory_qty(item: InventoryUpdateItem):global inventorycode = item.code.strip()if code not in inventory:p_name = "未知物品"p_price = 0.0if code in product_db:p_name = product_db[code]["name"]p_price = product_db[code]["price"]inventory[code] = {"name": p_name,"price": p_price,"quantity": 0,"last_updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}if item.action == "inc":inventory[code]["quantity"] += item.valueelif item.action == "dec":inventory[code]["quantity"] = max(0, inventory[code]["quantity"] - item.value)elif item.action == "set":inventory[code]["quantity"] = max(0, item.value)inventory[code]["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")save_data()return {"status": "success", "inventory_item": inventory[code], "stats": get_stats_summary()}@app.post("/api/inventory/delete")def delete_inventory_item(item: InventoryDeleteItem):global inventorycode = item.code.strip()if code in inventory:del inventory[code]save_data()return {"status": "success", "message": "商品已從盤點清單中刪除", "stats": get_stats_summary()}return {"status": "error", "message": "盤點清單中未找到此條碼"}# --- POS 收銀模式 API ---@app.post("/api/pos/checkout")def pos_checkout(req: CheckoutRequest):global inventory, sales_recordsif not req.items:return {"status": "error", "message": "購物車內無商品,無法結帳"}total = sum(item.price * item.quantity for item in req.items)change = max(0.0, req.cash_received - total)tx_id = "TX-" + datetime.now().strftime("%Y%m%d%H%M%S")time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")tx_items = []for item in req.items:tx_items.append({"code": item.code,"name": item.name,"price": item.price,"quantity": item.quantity})# 收銀售出時,自動從「盤點庫存」中扣減數量code = item.code.strip()if code in inventory:inventory[code]["quantity"] = max(0, inventory[code]["quantity"] - item.quantity)inventory[code]["last_updated"] = time_strnew_sale = {"tx_id": tx_id,"time": time_str,"items": tx_items,"total": total,"cash_received": req.cash_received,"change": change}sales_records.insert(0, new_sale)save_data()return {"status": "success","message": "結帳成功!已寫入交易並扣減盤點庫存","sale": new_sale,"stats": get_stats_summary()}@app.get("/api/sales")def get_sales_history():return {"status": "success", "data": sales_records, "stats": get_stats_summary()}@app.post("/api/sales/clear")def clear_sales_history():global sales_recordssales_records = []save_data()return {"status": "success", "message": "銷售歷史紀錄已全部清空", "stats": get_stats_summary()}# --- 7. CSV 下載匯出 ---@app.get("/download")def download_csv(type: str = "inventory"):stream = io.StringIO()writer = csv.writer(stream)if type == "raw":writer.writerow(["掃描內容", "物品名稱", "單價", "掃描時間"])for record in scan_records:writer.writerow([record["content"], record["name"], record.get("price", 0.0), record["time"]])filename = "raw_scan_log.csv"elif type == "sales":writer.writerow(["交易單號", "交易時間", "銷售商品與數量", "總金額", "實收金額", "找零"])for record in sales_records:items_str = "; ".join([f"{item['name']}(x{item['quantity']})" for item in record["items"]])writer.writerow([record["tx_id"], record["time"], items_str, record["total"], record["cash_received"], record["change"]])filename = "sales_report.csv"else: # inventorywriter.writerow(["條碼", "商品名稱", "價格", "盤點數量", "最後更新時間"])for code, record in inventory.items():writer.writerow([code, record["name"], record.get("price", 0.0), record.get("quantity", 0), record["last_updated"]])filename = "inventory_summary.csv"csv_content = stream.getvalue()# 新增 UTF-8 BOM 避免 Excel 開啟亂碼final_content = "\ufeff" + csv_contentreturn Response(content=final_content,media_type="text/csv",headers={"Content-Disposition": f"attachment; filename={filename}"})if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)
2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463472 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>全能盤點系統 Ultimate</title><script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script><script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.0/dist/JsBarcode.all.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script><style>body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; padding: 20px; max-width: 600px; margin: 0 auto; background: #f4f7f6; color: #333; }h2 { text-align: center; color: #333; margin-bottom: 15px; }/* Tabs */.tab-container { display: flex; justify-content: center; margin-bottom: 20px; background: #e9ecef; border-radius: 50px; padding: 5px; }.tab-btn { flex: 1; padding: 10px; border: none; background: transparent; cursor: pointer; border-radius: 50px; font-weight: bold; color: #666; transition: all 0.3s; }.tab-btn.active { background: white; color: #007bff; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }.tab-content { display: none; animation: fadeIn 0.3s; }.tab-content.active { display: block; }/* 一般介面樣式 */.mode-switch-area { background: #fff3cd; color: #856404; padding: 10px; border-radius: 8px; margin-bottom: 15px; border: 1px solid #ffeeba; display: flex; align-items: center; justify-content: center; gap: 10px; font-weight: bold;}.mode-switch-area input { transform: scale(1.5); cursor: pointer; }.manual-input-area { margin-bottom: 20px; display: flex; gap: 10px; }.manual-input { flex: 1; padding: 15px; font-size: 1.2rem; border: 2px solid #007bff; border-radius: 8px; outline: none; }.action-area { display: flex; gap: 10px; justify-content: center; margin-bottom: 20px; flex-wrap: wrap;}.btn { padding: 10px 20px; border-radius: 50px; font-weight: bold; cursor: pointer; border: none; color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1); display: flex; align-items: center; gap: 5px;}.btn-camera { background: #007bff; }.btn-stop { background: #dc3545; display: none; }.btn-download { background: #28a745; text-decoration: none; }.btn-clear { background: #6c757d; }.btn-upload { background: #6c757d; font-size: 0.9em; padding: 5px 15px; border-radius: 4px; }.btn-print { background: #6610f2; }#reader-container { display: none; margin-bottom: 20px; }#reader { width: 100%; border-radius: 12px; overflow: hidden; background: #000; }.result-area { background: white; padding: 0 20px; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }.log-item { border-bottom: 1px solid #f0f0f0; padding: 15px 0; display: flex; justify-content: space-between; align-items: center; }.product-name { font-size: 1.1em; font-weight: 700; color: #2c3e50; }.product-code { font-size: 0.85em; color: #999; margin-top: 4px; font-family: monospace; word-break: break-all;}.log-time { font-size: 0.8em; color: #aaa; white-space: nowrap; margin-left:10px;}.success-msg { background: #d1e7dd; color: #0f5132; padding: 15px; border-radius: 12px; text-align: center; margin-top: 15px; display: none; border: 1px solid #badbcc; }.warning-msg { background: #fff3cd; color: #856404; border-color: #ffeeba; }.error-msg { background: #f8d7da; color: #842029; border-color: #f5c2c7; }.admin-panel { background: #fff; padding: 15px; border-radius: 12px; margin-bottom: 20px; border: 1px solid #eee; }.upload-box { margin-top: 10px; display: flex; gap: 10px; align-items: center; }/* --- 標籤產生器樣式 --- */.generator-controls { background: #fff; padding: 15px; border-radius: 12px; margin-bottom: 20px; text-align: center; border: 1px solid #eee; }.label-grid {display: grid;grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));gap: 15px;margin-top: 20px;}.label-card {background: white;border: 1px solid #ddd;padding: 15px;text-align: center;border-radius: 8px;page-break-inside: avoid; /* 避免列印時被切斷 */}.label-title { font-weight: bold; margin-bottom: 5px; font-size: 1.1em; color: #000;}.label-code { font-family: monospace; color: #666; margin-top: 5px; font-size: 0.9em; }.barcode-svg { max-width: 100%; height: auto; }.qr-div { display: flex; justify-content: center; margin: 10px 0; }/* --- 列印專用 CSS (重點) --- */@media print {body { background: white; padding: 0; margin: 0; max-width: 100%; }.no-print, .tab-container, h2, .generator-controls, .admin-panel { display: none !important; }.label-grid { display: block; } /* 或維持 grid 取決於您的紙張 */.label-card {float: left;width: 45%; /* 大約一排兩個 */margin: 1%;border: 1px dashed #ccc;box-shadow: none;}}@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }</style></head><body><h2 class="no-print">📦 全能盤點系統 Ultimate</h2><div class="tab-container no-print"><button class="tab-btn active" onclick="switchTab('scanner')">📱 掃描作業</button><button class="tab-btn" onclick="switchTab('generator')">🖨️ 產生標籤</button><button class="tab-btn" onclick="switchTab('guide')">📖 說明</button></div><div id="view-scanner" class="tab-content active"><div class="mode-switch-area no-print"><label style="display:flex; align-items:center; gap:10px; cursor:pointer;"><input type="checkbox" id="invoice-mode-toggle">🧾 僅限掃描發票 (過濾雜訊)</label></div><div class="manual-input-area no-print"><input type="text" id="scanner-input" class="manual-input" placeholder="掃描槍輸入 / 手動輸入" autofocus></div><div class="action-area no-print"><button onclick="startCamera()" id="btn-start" class="btn btn-camera">📷 啟動鏡頭</button><button onclick="stopCamera()" id="btn-stop" class="btn btn-stop">❌ 關閉鏡頭</button><a href="/download" class="btn btn-download">📥 下載 CSV</a><button onclick="clearRecords()" class="btn btn-clear">🗑️ 清除</button></div><div id="reader-container" class="no-print"><div id="reader"></div></div><div id="status-msg" class="success-msg no-print">✅ 掃描成功 <strong id="msg-product-name">商品名稱</strong></div><div class="result-area no-print"><div id="log-list">{% for record in records %}<div class="log-item"><div class="log-info"><span class="product-name" style="{{ 'color:red' if record.name == '未知物品' else '' }}">{{ record.name }}</span><div class="product-code">{{ record.content }}</div></div><span class="log-time">{{ record.time.split(' ')[1] }}</span></div>{% endfor %}</div></div><br><details class="admin-panel no-print"><summary>⚙️ 資料庫設定</summary><div class="upload-box"><input type="file" id="csv-file" accept=".csv" /><button onclick="uploadCSV()" class="btn btn-upload">更新資料庫</button></div><p style="margin-top:10px; font-size:0.8em; color:#666;">目前商品數:<strong id="db-count">{{ db_count }}</strong></p></details></div><div id="view-generator" class="tab-content"><div class="generator-controls no-print"><p>請選擇您想要產生的格式,然後點擊「載入」</p><label><input type="radio" name="codeType" value="barcode" checked> 條碼 (Barcode)</label> <label><input type="radio" name="codeType" value="qrcode"> QR Code</label><br><br><button onclick="loadAndGenerate()" class="btn btn-camera" style="display:inline-block;">🔄 讀取 CSV 並產生標籤</button><button onclick="window.print()" class="btn btn-print" style="display:inline-block;">🖨️ 列印標籤</button></div><div id="label-container" class="label-grid"><p style="text-align:center; width:100%; color:#888;">請點擊上方按鈕產生標籤</p></div></div><div id="view-guide" class="tab-content"><div class="guide-section"><div class="guide-title">🖨️ 如何列印標籤?</div><div class="guide-text">1. 確保您已上傳 CSV 檔案。<br>2. 切換到「產生標籤」分頁。<br>3. 點擊「讀取 CSV 並產生標籤」。<br>4. 點擊「列印」按鈕 (或按 Ctrl+P)。<br>5. 在列印預覽中,建議勾選「列印背景圖形」,並將邊界設為「無」或「最小」。</div><div class="guide-title">🗑️ 如何清除資料?</div><div class="guide-text">點擊「清除」按鈕可以清空目前的掃描��表。</div></div></div><script>function switchTab(tabName) {document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));document.getElementById(`view-${tabName}`).classList.add('active');const btnIndex = tabName === 'scanner' ? 0 : (tabName === 'generator' ? 1 : 2);document.querySelectorAll('.tab-btn')[btnIndex].classList.add('active');if(tabName === 'scanner') document.getElementById('scanner-input').focus();}// --- 標籤產生邏輯 ---function loadAndGenerate() {const container = document.getElementById('label-container');const codeType = document.querySelector('input[name="codeType"]:checked').value;container.innerHTML = '<p style="text-align:center; width:100%;">載入中...</p>';fetch('/api/products').then(res => res.json()).then(resp => {const data = resp.data;container.innerHTML = ''; // 清空if (Object.keys(data).length === 0) {container.innerHTML = '<p style="text-align:center; width:100%;">資料庫是空的,請先上傳 CSV。</p>';return;}for (const [code, name] of Object.entries(data)) {const card = document.createElement('div');card.className = 'label-card';const title = document.createElement('div');title.className = 'label-title';title.innerText = name;card.appendChild(title);// 產生條碼或 QR Codeif (codeType === 'barcode') {const canvas = document.createElement('svg'); // 用 SVG 畫質較好canvas.className = 'barcode-svg';card.appendChild(canvas);try {JsBarcode(canvas, code, {format: "CODE128",displayValue: true,fontSize: 14,height: 50,margin: 0});} catch(e) {console.error("Barcode Error", e);const errDiv = document.createElement('div');errDiv.innerText = "無法產生條碼 (可能含中文字)";errDiv.style.color = "red";errDiv.style.fontSize = "0.8em";card.appendChild(errDiv);}} else {const qrDiv = document.createElement('div');qrDiv.className = 'qr-div';card.appendChild(qrDiv);try {new QRCode(qrDiv, {text: code,width: 100,height: 100});} catch(e) {}const codeText = document.createElement('div');codeText.className = 'label-code';codeText.innerText = code;card.appendChild(codeText);}container.appendChild(card);}}).catch(err => {alert("載入失敗");console.error(err);});}// --- 掃描與其他邏輯 (同前) ---function showMessage(type, text) {const msg = document.getElementById('status-msg');const nameSpan = document.getElementById('msg-product-name');msg.className = 'success-msg no-print';msg.style.display = 'block';nameSpan.innerText = text;if (type === 'error') msg.classList.add('error-msg');else if (type === 'warning') msg.classList.add('warning-msg');else msg.style.background = "#d1e7dd";}function clearRecords() {if(!confirm("⚠️ 警告:確定要清空所有紀錄嗎?")) return;fetch('/api/clear', { method: 'POST' }).then(res => res.json()).then(data => { alert(data.message); window.location.reload(); });}function processScanData(code) {if(!code || code.trim() === "") return;const isInvoiceMode = document.getElementById('invoice-mode-toggle').checked;if (code.startsWith("**")) { showMessage('warning', '⚠️ 這是明細碼,請掃左邊!'); return; }if (isInvoiceMode) {if (!(code.length > 20 && /^[A-Z]{2}/.test(code))) { showMessage('error', '⛔ 這不是發票,已忽略'); return; }}fetch('/api/scan', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ qr_content: code })}).then(res => res.json()).then(data => {const pName = data.data.name;if(pName === "未知物品") showMessage('error', '🔴 未知物品');else showMessage('success', pName);setTimeout(() => { window.location.reload(); }, 800);}).catch(err => alert("連線錯誤"));}const inputField = document.getElementById('scanner-input');window.onload = function() { inputField.focus(); };inputField.addEventListener('keypress', function (e) {if (e.key === 'Enter') { processScanData(inputField.value); inputField.value = ''; }});let html5QrcodeScanner = null;function onCameraScanSuccess(decodedText) {if(html5QrcodeScanner) html5QrcodeScanner.pause();processScanData(decodedText);}function startCamera() {document.getElementById('reader-container').style.display = 'block';document.getElementById('btn-start').style.display = 'none';document.getElementById('btn-stop').style.display = 'block';document.getElementById('status-msg').style.display = 'none';const formats = [Html5QrcodeSupportedFormats.QR_CODE, Html5QrcodeSupportedFormats.EAN_13, Html5QrcodeSupportedFormats.EAN_8, Html5QrcodeSupportedFormats.CODE_128, Html5QrcodeSupportedFormats.CODE_39, Html5QrcodeSupportedFormats.UPC_A];html5QrcodeScanner = new Html5QrcodeScanner("reader", { fps: 10, qrbox: {width: 250, height: 200}, videoConstraints: { facingMode: "environment" }, formatsToSupport: formats }, false);html5QrcodeScanner.render(onCameraScanSuccess, (error) => {});}function stopCamera() {if (html5QrcodeScanner) {html5QrcodeScanner.clear().then(() => {document.getElementById('reader-container').style.display = 'none';document.getElementById('btn-start').style.display = 'block';document.getElementById('btn-stop').style.display = 'none';html5QrcodeScanner = null;inputField.focus();});}}function uploadCSV() {const fileInput = document.getElementById('csv-file');if (fileInput.files.length === 0) { alert("請先選擇檔案"); return; }const formData = new FormData();formData.append("file", fileInput.files[0]);const btn = document.querySelector('.btn-upload');btn.innerText = "上傳中..."; btn.disabled = true;fetch('/api/upload_csv', { method: 'POST', body: formData }).then(res => res.json()).then(data => {alert(data.message); document.getElementById('db-count').innerText = data.count;}).finally(() => { btn.innerText = "更新資料庫"; btn.disabled = false; });}</script></body>2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218932 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>⚡ 全能 POS 兼盤點系統 Ultimate</title><!-- 引入高解析度字型 --><link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=Noto+Sans+TC:wght@300;400;500;700;900&display=swap" rel="stylesheet"><script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script><script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.0/dist/JsBarcode.all.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script><style>:root {--bg-gradient: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);--glass-bg: rgba(30, 41, 59, 0.7);--glass-border: rgba(255, 255, 255, 0.08);--text-primary: #f8fafc;--text-secondary: #94a3b8;--primary-indigo: #6366f1;--primary-indigo-hover: #4f46e5;--success-emerald: #10b981;--success-emerald-hover: #059669;--danger-rose: #f43f5e;--danger-rose-hover: #e11d48;--warning-amber: #f59e0b;}* {box-sizing: border-box;margin: 0;padding: 0;font-family: 'Plus Jakarta Sans', 'Noto Sans TC', -apple-system, sans-serif;-webkit-font-smoothing: antialiased;}body {background: var(--bg-gradient);color: var(--text-primary);min-height: 100vh;padding-bottom: 60px;}.container {max-width: 1000px;margin: 0 auto;padding: 20px;}/* --- Header & Stats Board --- */header {display: flex;justify-content: space-between;align-items: center;margin-bottom: 25px;padding: 10px 0;border-bottom: 1px solid var(--glass-border);}header h1 {font-size: 1.8rem;font-weight: 800;background: linear-gradient(120deg, #818cf8, #34d399);-webkit-background-clip: text;-webkit-text-fill-color: transparent;display: flex;align-items: center;gap: 10px;}.stats-board {display: grid;grid-template-columns: repeat(3, 1fr);gap: 15px;margin-bottom: 25px;}.stat-card {background: var(--glass-bg);border: 1px solid var(--glass-border);border-radius: 16px;padding: 15px;text-align: center;backdrop-filter: blur(12px);box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3);transition: transform 0.3s, box-shadow 0.3s;}.stat-card:hover {transform: translateY(-2px);box-shadow: 0 15px 30px -5px rgba(99, 102, 241, 0.15);}.stat-label {font-size: 0.85rem;color: var(--text-secondary);font-weight: 500;margin-bottom: 6px;}.stat-value {font-size: 1.6rem;font-weight: 700;color: var(--text-primary);}.stat-value.highlight {color: var(--success-emerald);}/* --- Navigation Tabs --- */.nav-tabs {display: flex;background: rgba(15, 23, 42, 0.6);border: 1px solid var(--glass-border);border-radius: 50px;padding: 6px;margin-bottom: 25px;overflow-x: auto;backdrop-filter: blur(8px);}.tab-link {flex: 1;padding: 12px 18px;border: none;background: transparent;color: var(--text-secondary);font-weight: 600;font-size: 0.95rem;cursor: pointer;border-radius: 50px;transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);display: flex;align-items: center;justify-content: center;gap: 8px;white-space: nowrap;}.tab-link.active {background: linear-gradient(135deg, var(--primary-indigo) 0%, #4f46e5 100%);color: var(--text-primary);box-shadow: 0 4px 15px rgba(99, 102, 241, 0.35);}.tab-panel {display: none;animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);}.tab-panel.active {display: block;}/* --- Layout Cards --- */.glass-card {background: var(--glass-bg);border: 1px solid var(--glass-border);border-radius: 20px;padding: 20px;backdrop-filter: blur(16px);box-shadow: 0 15px 35px rgba(0, 0, 0, 0.25);margin-bottom: 20px;}.card-header {display: flex;justify-content: space-between;align-items: center;margin-bottom: 15px;border-bottom: 1px solid rgba(255, 255, 255, 0.05);padding-bottom: 10px;}.card-title {font-size: 1.15rem;font-weight: 700;display: flex;align-items: center;gap: 8px;}/* --- General Inputs & Buttons --- */.input-group {display: flex;gap: 12px;margin-bottom: 20px;}.styled-input {flex: 1;background: rgba(15, 23, 42, 0.6);border: 1px solid var(--glass-border);border-radius: 12px;padding: 14px 18px;font-size: 1.1rem;color: var(--text-primary);outline: none;transition: all 0.3s;}.styled-input:focus {border-color: var(--primary-indigo);box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);}.btn {padding: 12px 24px;border: none;border-radius: 12px;font-weight: 600;cursor: pointer;transition: all 0.3s;display: inline-flex;align-items: center;justify-content: center;gap: 8px;text-decoration: none;color: var(--text-primary);box-shadow: 0 4px 10px rgba(0,0,0,0.15);}.btn-primary { background: linear-gradient(135deg, var(--primary-indigo) 0%, #4f46e5 100%); }.btn-primary:hover { background: var(--primary-indigo-hover); transform: translateY(-1px); }.btn-success { background: linear-gradient(135deg, var(--success-emerald) 0%, #059669 100%); }.btn-success:hover { background: var(--success-emerald-hover); transform: translateY(-1px); }.btn-danger { background: linear-gradient(135deg, var(--danger-rose) 0%, #e11d48 100%); }.btn-danger:hover { background: var(--danger-rose-hover); transform: translateY(-1px); }.btn-secondary { background: rgba(71, 85, 105, 0.6); border: 1px solid var(--glass-border); }.btn-secondary:hover { background: rgba(71, 85, 105, 0.8); }.btn-icon { width: 36px; height: 36px; padding: 0; border-radius: 50%; }/* --- Camera Scanner UI --- */#scanner-container {display: none;border-radius: 16px;overflow: hidden;border: 2px solid var(--primary-indigo);margin-bottom: 20px;box-shadow: 0 10px 30px rgba(99, 102, 241, 0.2);position: relative;}#reader {width: 100%;background: #000;}/* --- Mode Switch Banner --- */.mode-banner {background: rgba(245, 158, 11, 0.15);border: 1px solid rgba(245, 158, 11, 0.3);border-radius: 12px;padding: 12px;margin-bottom: 20px;display: flex;align-items: center;gap: 10px;font-size: 0.95rem;color: #fbd38d;}.mode-banner input {width: 18px;height: 18px;cursor: pointer;accent-color: var(--warning-amber);}/* --- Live Notification Alert --- */.alert-notification {background: rgba(16, 185, 129, 0.2);border: 1px solid rgba(16, 185, 129, 0.4);color: #a7f3d0;border-radius: 12px;padding: 15px;margin-bottom: 20px;display: none;align-items: center;justify-content: center;gap: 10px;font-weight: 600;text-align: center;animation: pulseGlow 1.5s infinite;}.alert-notification.error {background: rgba(244, 63, 94, 0.2);border: 1px solid rgba(244, 63, 94, 0.4);color: #fecdd3;}.alert-notification.warning {background: rgba(245, 158, 11, 0.2);border: 1px solid rgba(245, 158, 11, 0.4);color: #fef3c7;}/* --- Tabs Split Views (Sub-panels) --- */.split-view {display: grid;grid-template-columns: 1.2fr 0.8fr;gap: 20px;}@media (max-width: 768px) {.split-view {grid-template-columns: 1fr;}.stats-board {grid-template-columns: 1fr;gap: 10px;}}.view-toggle {display: flex;background: rgba(15, 23, 42, 0.4);border-radius: 8px;padding: 3px;margin-bottom: 15px;}.view-btn {flex: 1;padding: 8px 12px;border: none;background: transparent;color: var(--text-secondary);font-weight: 600;font-size: 0.85rem;cursor: pointer;border-radius: 6px;transition: all 0.2s;}.view-btn.active {background: rgba(99, 102, 241, 0.2);color: var(--text-primary);border: 1px solid rgba(99, 102, 241, 0.3);}/* --- Scrollable Lists & Tables --- */.scroll-list {max-height: 480px;overflow-y: auto;padding-right: 5px;}/* 自訂拉條 */.scroll-list::-webkit-scrollbar,body::-webkit-scrollbar {width: 6px;}.scroll-list::-webkit-scrollbar-track,body::-webkit-scrollbar-track {background: rgba(0, 0, 0, 0.1);}.scroll-list::-webkit-scrollbar-thumb,body::-webkit-scrollbar-thumb {background: rgba(255, 255, 255, 0.1);border-radius: 3px;}.log-item-row {display: flex;justify-content: space-between;align-items: center;padding: 12px 16px;background: rgba(30, 41, 59, 0.4);border: 1px solid rgba(255, 255, 255, 0.04);border-radius: 12px;margin-bottom: 10px;transition: background 0.2s, transform 0.2s;animation: slideInItem 0.3s cubic-bezier(0.16, 1, 0.3, 1);}.log-item-row:hover {background: rgba(30, 41, 59, 0.6);transform: scale(1.005);}.log-item-info {display: flex;flex-direction: column;gap: 3px;}.log-item-title {font-weight: 700;font-size: 1rem;color: var(--text-primary);}.log-item-subtitle {font-size: 0.8rem;color: var(--text-secondary);font-family: monospace;word-break: break-all;}.log-item-time {font-size: 0.8rem;color: var(--text-secondary);white-space: nowrap;}/* --- Table Styling (Inventory / Sales) --- */.styled-table {width: 100%;border-collapse: collapse;text-align: left;}.styled-table th {padding: 12px 10px;color: var(--text-secondary);font-weight: 600;font-size: 0.85rem;border-bottom: 1px solid rgba(255, 255, 255, 0.05);}.styled-table td {padding: 14px 10px;border-bottom: 1px solid rgba(255, 255, 255, 0.03);font-size: 0.95rem;}.styled-table tbody tr:hover {background: rgba(255, 255, 255, 0.01);}.qty-control {display: flex;align-items: center;gap: 8px;}.qty-btn {width: 28px;height: 28px;border-radius: 6px;border: 1px solid rgba(255, 255, 255, 0.1);background: rgba(148, 163, 184, 0.1);color: var(--text-primary);font-size: 1rem;font-weight: bold;cursor: pointer;display: flex;align-items: center;justify-content: center;transition: all 0.2s;}.qty-btn:hover {background: var(--primary-indigo);border-color: var(--primary-indigo);}.qty-val {font-weight: 700;font-size: 1rem;width: 30px;text-align: center;}/* --- POS Shopping Cart UI --- */.cart-container {display: flex;flex-direction: column;height: 480px;}.cart-list {flex: 1;overflow-y: auto;margin-bottom: 15px;border-bottom: 1px solid rgba(255, 255, 255, 0.05);padding-right: 5px;}.cart-total-box {background: rgba(15, 23, 42, 0.6);border-radius: 14px;padding: 15px;border: 1px solid var(--glass-border);margin-bottom: 15px;}.cart-total-row {display: flex;justify-content: space-between;align-items: center;margin-bottom: 8px;}.cart-total-label {font-size: 0.95rem;color: var(--text-secondary);}.cart-total-val {font-size: 1.6rem;font-weight: 800;color: var(--success-emerald);}.cash-calculator {display: grid;grid-template-columns: 1fr 1fr;gap: 12px;margin-bottom: 15px;}.calc-box {display: flex;flex-direction: column;gap: 5px;}.calc-label {font-size: 0.8rem;color: var(--text-secondary);}.calc-input {width: 100%;background: rgba(15, 23, 42, 0.8);border: 1px solid var(--glass-border);border-radius: 8px;padding: 10px;color: var(--text-primary);font-size: 1.1rem;font-weight: 700;outline: none;}.calc-val {padding: 10px;font-size: 1.1rem;font-weight: 700;color: var(--warning-amber);background: rgba(15, 23, 42, 0.4);border-radius: 8px;border: 1px solid var(--glass-border);}/* --- Receipt & Dialog Modal --- */.modal-overlay {position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(15, 23, 42, 0.8);backdrop-filter: blur(8px);display: none;justify-content: center;align-items: center;z-index: 1000;animation: fadeIn 0.3s;}.modal-card {background: #ffffff;color: #1e293b;border-radius: 16px;padding: 24px;width: 90%;max-width: 400px;box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);animation: scaleIn 0.3s cubic-bezier(0.16, 1, 0.3, 1);}.receipt-ticket {background: #f8fafc;border: 1px dashed #cbd5e1;padding: 15px;font-family: monospace;font-size: 0.85rem;color: #334155;margin-bottom: 20px;}.receipt-title {text-align: center;font-size: 1.1rem;font-weight: bold;margin-bottom: 10px;color: #0f172a;}.receipt-divider {border-top: 1px dashed #94a3b8;margin: 8px 0;}.receipt-row {display: flex;justify-content: space-between;margin-bottom: 4px;}/* --- Label Studio Card Grid --- */.label-grid {display: grid;grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));gap: 15px;margin-top: 20px;}.label-card {background: white;color: #000;border: 1px solid #e2e8f0;padding: 15px;text-align: center;border-radius: 12px;box-shadow: 0 4px 6px rgba(0,0,0,0.05);page-break-inside: avoid;}.label-card .label-title {font-weight: 800;font-size: 1.05rem;margin-bottom: 6px;color: #1e293b;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}.label-card .label-price {font-weight: 700;color: #e11d48;margin-bottom: 6px;font-size: 0.95rem;}.label-card .barcode-svg {max-width: 100%;height: auto;}.label-card .qr-wrapper {display: flex;justify-content: center;margin: 8px 0;}.label-card .label-code {font-family: monospace;font-size: 0.8rem;color: #64748b;margin-top: 6px;}/* --- Printing Styling --- */@media print {body { background: white !important; color: black !important; padding: 0 !important; margin: 0 !important; }.no-print, header, .nav-tabs, .stats-board, .glass-card, .btn, .input-group, .modal-card .btn {display: none !important;}.modal-overlay {background: white !important;position: static !important;display: block !important;backdrop-filter: none !important;}.modal-card {box-shadow: none !important;padding: 0 !important;width: 100% !important;max-width: 100% !important;background: white !important;}.receipt-ticket {border: none !important;background: white !important;padding: 0 !important;}.label-grid {display: block !important;}.label-card {float: left !important;width: 48% !important;margin: 1% !important;border: 1px dashed #ccc !important;box-shadow: none !important;page-break-inside: avoid !important;}}/* --- Animations --- */@keyframes slideUp {from { opacity: 0; transform: translateY(12px); }to { opacity: 1; transform: translateY(0); }}@keyframes fadeIn {from { opacity: 0; }to { opacity: 1; }}@keyframes scaleIn {from { opacity: 0; transform: scale(0.95); }to { opacity: 1; transform: scale(1); }}@keyframes slideInItem {from { opacity: 0; transform: translateY(-8px); }to { opacity: 1; transform: translateY(0); }}@keyframes pulseGlow {0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); }70% { box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }}.highlight-flash {animation: rowFlash 1s ease;}@keyframes rowFlash {0% { background: rgba(99, 102, 241, 0.4); }100% { background: rgba(30, 41, 59, 0.4); }}</style></head><body><div class="container"><!-- --- Header --- --><header class="no-print"><h1>⚡ 全能 POS 兼盤點系統 <span style="font-size:0.7em; background:#4f46e5; padding:2px 8px; border-radius:8px; font-weight:normal; letter-spacing:1px; color:#fff;">ULTIMATE</span></h1><span style="font-size:0.85rem; color:var(--text-secondary);" id="current-time"></span></header><!-- --- Stats Summary Board --- --><div class="stats-board no-print"><div class="stat-card"><div class="stat-label">📊 累計盤點總量</div><div class="stat-value" id="stat-total-qty">{{ stats.total_qty }}</div></div><div class="stat-card"><div class="stat-label">🛒 今日收銀金額</div><div class="stat-value highlight" id="stat-total-sales">${{ '{:,.0f}'.format(stats.total_sales) }}</div></div><div class="stat-card"><div class="stat-label">🧾 交易結帳單數</div><div class="stat-value" id="stat-tx-count">{{ stats.tx_count }}</div></div></div><!-- --- Main Navigation Tabs --- --><div class="nav-tabs no-print"><button class="tab-link active" onclick="switchTab('scanner')">📱 盤點作業</button><button class="tab-link" onclick="switchTab('pos')">🛒 收銀 POS</button><button class="tab-link" onclick="switchTab('sales')">📈 銷售報表</button><button class="tab-link" onclick="switchTab('generator')">🖨️ 產生標籤</button><button class="tab-link" onclick="switchTab('settings')">⚙️ 系統設定</button></div><!-- --- Status Broadcast Banner --- --><div id="status-alert" class="alert-notification no-print"></div><!-- ==================== TABS 1: 盤點作業 ==================== --><div id="view-scanner" class="tab-panel active"><div class="split-view"><!-- Left panel: Camera & Manual input --><div><div class="glass-card no-print"><div class="card-header"><div class="card-title">📷 條碼讀取區域</div><span style="font-size:0.8rem; color:var(--text-secondary);">支援相機鏡頭或紅外線條碼掃描槍</span></div><div class="mode-banner"><label style="display:flex; align-items:center; gap:8px; cursor:pointer;"><input type="checkbox" id="invoice-mode-toggle">🧾 僅限掃描發票 (自動忽略非發票條碼雜訊)</label></div><div class="input-group"><input type="text" id="scanner-input" class="styled-input" placeholder="點擊此處使用掃描槍 / 手動輸入條碼" autofocus></div><div style="display:flex; gap:10px;"><button onclick="startCamera('reader-inventory', onInventoryCameraSuccess)" id="btn-start-inventory" class="btn btn-primary" style="flex:1;">📷 啟動相機鏡頭</button><button onclick="stopCamera()" id="btn-stop-inventory" class="btn btn-danger" style="display:none; flex:1;">❌ 關閉鏡頭</button></div></div><div id="scanner-container" class="no-print"><div id="reader-inventory"></div></div><!-- Chronological log list --><div class="glass-card no-print"><div class="card-header"><div class="card-title">🕒 即時盤點日誌 (實時流)</div><a href="/download?type=raw" class="btn btn-secondary" style="font-size:0.8rem; padding:6px 12px; border-radius:8px;">📥 導出日誌 CSV</a></div><div class="scroll-list" id="log-list">{% if records %}{% for record in records %}<div class="log-item-row"><div class="log-item-info"><span class="log-item-title" style="{{ 'color:#f43f5e' if record.name == '未知物品' else '' }}">{{ record.name }}</span><span class="log-item-subtitle">{{ record.content }}</span></div><span class="log-item-time">{{ record.time.split(' ')[1] }}</span></div>{% endfor %}{% else %}<p style="text-align:center; color:var(--text-secondary); padding:20px 0;" id="empty-log-text">暫無掃描紀錄,請開始掃描</p>{% endif %}</div></div></div><!-- Right panel: Aggregated inventory view --><div><div class="glass-card"><div class="card-header"><div class="card-title">📋 盤點統計清單</div><div class="no-print" style="display:flex; gap:6px;"><a href="/download?type=inventory" class="btn btn-success" style="font-size:0.8rem; padding:6px 12px; border-radius:8px;">📥 導出匯總</a></div></div><div class="scroll-list"><table class="styled-table"><thead><tr><th>品名 / 條碼</th><th style="text-align:center; width:95px;">數量</th><th class="no-print" style="text-align:center; width:45px;">操作</th></tr></thead><tbody id="inventory-table-body">{% if inventory %}{% for code, record in inventory.items() %}<tr id="inv-row-{{ code }}"><td><div style="font-weight:700; color:var(--text-primary);">{{ record.name }}</div><div style="font-size:0.75rem; color:var(--text-secondary); font-family:monospace; margin-top:2px;">{{ code }}</div></td><td style="text-align:center;"><div class="qty-control"><button class="qty-btn no-print" onclick="adjustInventoryQty('{{ code }}', 'dec')">-</button><span class="qty-val" id="inv-qty-{{ code }}">{{ record.quantity }}</span><button class="qty-btn no-print" onclick="adjustInventoryQty('{{ code }}', 'inc')">+</button></div></td><td class="no-print" style="text-align:center;"><button onclick="deleteInventoryItem('{{ code }}')" class="qty-btn" style="color:var(--danger-rose); font-size:0.8rem; margin:0 auto;">🗑️</button></td></tr>{% endfor %}{% else %}<tr id="empty-inventory-row"><td colspan="3" style="text-align:center; color:var(--text-secondary); padding:40px 0;">尚未盤點任何商品</td></tr>{% endif %}</tbody></table></div></div></div></div></div><!-- ==================== TABS 2: 收銀 POS ==================== --><div id="view-pos" class="tab-panel"><div class="split-view"><!-- Left panel: Shopping Cart list --><div class="glass-card"><div class="card-header"><div class="card-title">🛒 當前購物車清單</div><button onclick="clearCart()" class="btn btn-secondary no-print" style="font-size:0.8rem; padding:6px 12px; border-radius:8px;">🗑️ 清空購物車</button></div><div class="cart-container"><div class="cart-list"><table class="styled-table"><thead><tr><th>商品品名 / 條碼</th><th style="text-align:right; width:70px;">單價</th><th style="text-align:center; width:95px;">數量</th><th style="text-align:right; width:80px;">小計</th></tr></thead><tbody id="cart-table-body"><tr id="empty-cart-row"><td colspan="4" style="text-align:center; color:var(--text-secondary); padding:80px 0;">購物車為空,請掃描條碼加入商品</td></tr></tbody></table></div><!-- Running totals --><div class="cart-total-box"><div class="cart-total-row"><span class="cart-total-label">總商品數量</span><span style="font-weight:700; font-size:1.1rem;" id="cart-qty-total">0 件</span></div><div class="cart-total-row"><span class="cart-total-label">應收總金額</span><span class="cart-total-val" id="cart-amount-total">$0</span></div></div><!-- Cashier calculations --><div class="cash-calculator no-print"><div class="calc-box"><span class="calc-label">💵 顧客實收金額</span><input type="number" id="pos-cash-received" class="calc-input" placeholder="0" min="0" oninput="calculateChange()"></div><div class="calc-box"><span class="calc-label">🪙 應找零錢</span><div id="pos-change-due" class="calc-val">$0</div></div></div><button onclick="checkoutPOS()" id="btn-checkout" class="btn btn-success no-print" style="width:100%; padding:15px; font-size:1.2rem; border-radius:14px; font-weight:bold;">🤝 確認結帳並列印收據</button></div></div><!-- Right panel: Scanner & Manual lookup for POS --><div class="glass-card no-print"><div class="card-header"><div class="card-title">🏷️ 商品銷售讀取器</div></div><div class="input-group"><input type="text" id="pos-input" class="styled-input" placeholder="點擊使用掃描槍 / 手動鍵入條碼"></div><div style="display:flex; gap:10px; margin-bottom:20px;"><button onclick="startCamera('reader-pos', onPOSCameraSuccess)" id="btn-start-pos" class="btn btn-primary" style="flex:1;">📷 啟動相機銷售鏡頭</button><button onclick="stopCamera()" id="btn-stop-pos" class="btn btn-danger" style="display:none; flex:1;">❌ 關閉鏡頭</button></div><div id="pos-scanner-container" style="display:none; border-radius:12px; overflow:hidden; border:2px solid var(--primary-indigo); margin-top:10px;"><div id="reader-pos"></div></div><!-- Mini item quick selector --><div style="margin-top:20px;"><div style="font-size:0.85rem; color:var(--text-secondary); margin-bottom:10px; font-weight:600;">⚡ 快速點選商品庫 (方便測試)</div><div style="display:flex; flex-direction:column; gap:8px; max-height:220px; overflow-y:auto; padding-right:4px;" id="quick-pick-container"><p style="text-align:center; color:var(--text-secondary); font-size:0.8rem; padding:15px;">載入商品庫中...</p></div></div></div></div></div><!-- ==================== TABS 3: 銷售報表 ==================== --><div id="view-sales" class="tab-panel"><div class="glass-card"><div class="card-header"><div class="card-title">📈 營業交易歷史明細</div><div class="no-print" style="display:flex; gap:10px;"><a href="/download?type=sales" class="btn btn-success" style="font-size:0.8rem; padding:6px 12px;">📥 匯出銷售 CSV</a><button onclick="clearSalesHistory()" class="btn btn-danger" style="font-size:0.8rem; padding:6px 12px;">🗑️ 清空交易紀錄</button></div></div><div class="scroll-list"><table class="styled-table"><thead><tr><th>交易單號</th><th>交易時間</th><th>銷售明細</th><th style="text-align:right; width:90px;">應收總額</th><th style="text-align:right; width:90px;">實收金額</th><th style="text-align:right; width:80px;">找零</th></tr></thead><tbody id="sales-table-body">{% if sales %}{% for sale in sales %}<tr><td style="font-family:monospace; font-weight:bold;">{{ sale.tx_id }}</td><td style="font-size:0.85rem; color:var(--text-secondary);">{{ sale.time }}</td><td><div style="display:flex; flex-direction:column; gap:2px; font-size:0.9rem;">{% for item in sale.items %}<div>🔹 {{ item.name }} (x{{ item.quantity }}) - ${% if item.price is defined %}{{ '{:,.0f}'.format(item.price * item.quantity) }}{% else %}0{% endif %}</div>{% endfor %}</div></td><td style="text-align:right; font-weight:700; color:var(--success-emerald);">${{ '{:,.0f}'.format(sale.total) }}</td><td style="text-align:right;">${{ '{:,.0f}'.format(sale.cash_received) }}</td><td style="text-align:right; color:var(--warning-amber);">${{ '{:,.0f}'.format(sale.change) }}</td></tr>{% endfor %}{% else %}<tr id="empty-sales-row"><td colspan="6" style="text-align:center; color:var(--text-secondary); padding:60px 0;">目前無銷售歷史交易</td></tr>{% endif %}</tbody></table></div></div></div><!-- ==================== TABS 4: 產生標籤 ==================== --><div id="view-generator" class="tab-panel"><div class="glass-card no-print"><div class="card-header"><div class="card-title">🖨️ 商品標籤列印設計</div></div><p style="font-size:0.9rem; color:var(--text-secondary); margin-bottom:15px;">從您上傳的商品 CSV 庫中,自動大量產生一維條碼或 QR 二維碼標籤紙,方便直接貼在庫存箱或商品上。</p><div style="margin-bottom:20px; display:flex; gap:20px; align-items:center; flex-wrap:wrap;"><div style="display:flex; gap:15px;"><label style="cursor:pointer; display:flex; align-items:center; gap:6px;"><input type="radio" name="codeType" value="barcode" checked style="accent-color:var(--primary-indigo);"> 條碼 (CODE128)</label><label style="cursor:pointer; display:flex; align-items:center; gap:6px;"><input type="radio" name="codeType" value="qrcode" style="accent-color:var(--primary-indigo);"> 二維碼 (QR Code)</label></div><div style="display:flex; gap:10px;"><button onclick="generateLabels()" class="btn btn-primary">🔄 產生標籤預覽</button><button onclick="window.print()" class="btn btn-success">🖨️ 列印標籤</button></div></div></div><!-- Preview print sheet area --><div id="label-container" class="label-grid"><p style="text-align:center; width:100%; color:var(--text-secondary); padding:40px 0;">請點選上方「產生標籤預覽」按鈕產生排版</p></div></div><!-- ==================== TABS 5: 系統設定 ==================== --><div id="view-settings" class="tab-panel"><div class="glass-card"><div class="card-header"><div class="card-title">⚙️ 系統設定與商品庫管理</div></div><!-- Product database upload --><div style="margin-bottom:25px; padding-bottom:25px; border-bottom:1px solid rgba(255, 255, 255, 0.05);"><h3 style="font-size:1.05rem; font-weight:700; margin-bottom:8px;">📁 更���商品對照資料庫 (CSV 上傳)</h3><p style="font-size:0.85rem; color:var(--text-secondary); margin-bottom:15px;">請上傳一個 CSV 檔案,欄位格式必須為:<strong>條碼, 商品名稱, 價格(選填)</strong>。支援 UTF-8 編碼。<br>如果不包含價格,系統預設價格將自動設為 0 元。</p><div style="display:flex; gap:15px; align-items:center; flex-wrap:wrap;"><input type="file" id="csv-file" accept=".csv" style="display:none;" onchange="updateFileNameLabel()"><button onclick="document.getElementById('csv-file').click()" class="btn btn-secondary">📂 選擇 CSV 檔案</button><span id="csv-file-name" style="font-size:0.9rem; color:var(--text-secondary);">尚未選擇檔案</span><button onclick="uploadCSV()" id="btn-upload-csv" class="btn btn-primary">⚡ 上傳並載入對照表</button></div><p style="margin-top:15px; font-size:0.9rem;">目前對照資料庫商品總筆數:<strong style="color:var(--primary-indigo);" id="db-count-label">{{ db_count }}</strong> 筆</p></div><!-- Database operations --><div><h3 style="font-size:1.05rem; font-weight:700; margin-bottom:12px; color:var(--danger-rose);">⚠️ 資料危險管理區</h3><p style="font-size:0.85rem; color:var(--text-secondary); margin-bottom:15px;">執行此處操作將會徹底刪除對應的磁碟資料庫檔案,請務必小心!</p><div style="display:flex; gap:12px; flex-wrap:wrap;"><button onclick="clearRecords()" class="btn btn-danger">🗑️ 徹底清空盤點庫存與日誌</button><button onclick="clearSalesHistory()" class="btn btn-danger">🗑️ 徹底清空收銀銷售明細</button></div></div></div></div></div> <!-- end container --><!-- ==================== RECEIPT PRINT DIALOG MODAL ==================== --><div id="receipt-modal" class="modal-overlay"><div class="modal-card"><div class="receipt-ticket"><div class="receipt-title">🧾 電子收銀收據</div><div style="text-align:center; font-size:0.75rem; color:#64748b;" id="receipt-tx-id">TX-00000000</div><div style="text-align:center; font-size:0.75rem; color:#64748b; margin-bottom:10px;" id="receipt-time">2026-05-28 16:00:00</div><div class="receipt-divider"></div><div id="receipt-items-list"><!-- Dynamic insert --></div><div class="receipt-divider"></div><div class="receipt-row" style="font-weight:bold; font-size:0.95rem; color:#0f172a;"><span>應付總額:</span><span id="receipt-total-amount">$0</span></div><div class="receipt-row" style="color:#64748b;"><span>實收現金:</span><span id="receipt-cash-received">$0</span></div><div class="receipt-row" style="font-weight:bold; color:#475569;"><span>應找零錢:</span><span id="receipt-change-due">$0</span></div><div class="receipt-divider"></div><div style="text-align:center; font-size:0.75rem; color:#94a3b8; margin-top:10px;">🌟 謝謝惠顧!歡迎再次光臨 🌟</div></div><div style="display:flex; gap:10px;" class="no-print"><button onclick="window.print()" class="btn btn-success" style="flex:1;">🖨️ 直接列印小票</button><button onclick="closeReceiptModal()" class="btn btn-secondary" style="flex:1;">❌ 關閉視窗</button></div></div></div><!-- ==================== FRONTEND JAVASCRIPT ==================== --><script>// 全域狀態管理let localProductDB = {}; // 從伺服器下載的商品庫對照快取let shoppingCart = []; // POS 購物車let html5QrcodeScanner = null; // 相機實體let activeScannerId = null; // 當前活動相機的容器 ID// 啟動初始化window.addEventListener('DOMContentLoaded', () => {fetchStats();fetchAllProducts();updateTime();setInterval(updateTime, 1000);// 綁定輸入框 Enter 事件const scannerInput = document.getElementById('scanner-input');scannerInput.focus();scannerInput.addEventListener('keypress', function(e) {if (e.key === 'Enter') {processInventoryBarcode(this.value);this.value = '';}});const posInput = document.getElementById('pos-input');posInput.addEventListener('keypress', function(e) {if (e.key === 'Enter') {processPOSBarcode(this.value);this.value = '';}});});function updateTime() {const timeSpan = document.getElementById('current-time');if (timeSpan) {const now = new Date();timeSpan.innerText = '🕒 ' + now.toLocaleString('zh-TW', { hour12: false });}}// --- 1. Tab 切換邏輯 ---function switchTab(tabName) {// 切換 CSSdocument.querySelectorAll('.tab-panel').forEach(el => el.classList.remove('active'));document.querySelectorAll('.tab-link').forEach(el => el.classList.remove('active'));document.getElementById(`view-${tabName}`).classList.add('active');// 點選 active 標籤const tabs = document.querySelectorAll('.tab-link');const map = { 'scanner': 0, 'pos': 1, 'sales': 2, 'generator': 3, 'settings': 4 };tabs[map[tabName]].classList.add('active');// 關閉可能已啟動的相機stopCamera();// 焦點輔助if (tabName === 'scanner') {document.getElementById('scanner-input').focus();} else if (tabName === 'pos') {document.getElementById('pos-input').focus();renderQuickPick();}}// --- 2. 廣播式橫幅通知 ---function triggerAlert(type, message) {const alertBox = document.getElementById('status-alert');alertBox.innerText = message;alertBox.className = 'alert-notification no-print ' + type;alertBox.style.display = 'flex';// 3秒後自動淡出setTimeout(() => {alertBox.style.display = 'none';}, 3500);}// --- 3. 獲取核心統計數據 ---function fetchStats() {fetch('/api/stats').then(res => res.json()).then(resp => {if(resp.status === 'success') {updateStatsUI(resp.stats);}});}function updateStatsUI(stats) {document.getElementById('stat-total-qty').innerText = stats.total_qty;document.getElementById('stat-total-sales').innerText = '$' + Number(stats.total_sales).toLocaleString('zh-TW', {maximumFractionDigits: 0});document.getElementById('stat-tx-count').innerText = stats.tx_count;}// 載入商品對照庫function fetchAllProducts() {fetch('/api/products').then(res => res.json()).then(resp => {if (resp.status === 'success') {localProductDB = resp.data;renderQuickPick();}});}// --- 4. 盤點掃描核心邏輯 (Zero reload) ---function processInventoryBarcode(code) {code = code.trim();if(!code) return;// 發票過濾const isInvoiceMode = document.getElementById('invoice-mode-toggle').checked;if (isInvoiceMode) {if (!(code.length > 20 && /^[A-Z]{2}/.test(code))) {triggerAlert('error', '⛔ 這不是發票,已過濾');return;}}// 發送至後端fetch('/api/scan', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ qr_content: code })}).then(res => res.json()).then(resp => {if(resp.status === 'success') {triggerAlert('success', `✅ 已盤點:${resp.data.name}`);// 1. 動態更新即時日誌流updateLiveLogUI(resp.data);// 2. 動態更新盤點總計列表updateInventoryTableUI(code, resp.inventory_item);// 3. 更新頂部統計看板updateStatsUI(resp.stats);} else {triggerAlert('error', resp.message);}}).catch(err => {triggerAlert('error', '❌ 連線失敗,請檢查網路');});}function updateLiveLogUI(record) {const list = document.getElementById('log-list');const emptyTxt = document.getElementById('empty-log-text');if(emptyTxt) emptyTxt.remove();const item = document.createElement('div');item.className = 'log-item-row highlight-flash';const info = document.createElement('div');info.className = 'log-item-info';const title = document.createElement('span');title.className = 'log-item-title';if (record.name === '未知物品') {title.style.color = '#f43f5e';}title.innerText = record.name;const subtitle = document.createElement('span');subtitle.className = 'log-item-subtitle';subtitle.innerText = record.content;info.appendChild(title);info.appendChild(subtitle);const time = document.createElement('span');time.className = 'log-item-time';time.innerText = record.time.split(' ')[1];item.appendChild(info);item.appendChild(time);list.insertBefore(item, list.firstChild);// 最多保留 30 筆日誌if (list.children.length > 30) {list.removeChild(list.lastChild);}}function updateInventoryTableUI(code, invItem) {const tbody = document.getElementById('inventory-table-body');const emptyRow = document.getElementById('empty-inventory-row');if(emptyRow) emptyRow.remove();const existingRow = document.getElementById(`inv-row-${code}`);if(existingRow) {// 如果已經存在該列,直接更新數量並閃爍動畫const qtySpan = document.getElementById(`inv-qty-${code}`);qtySpan.innerText = invItem.quantity;existingRow.classList.add('highlight-flash');setTimeout(() => existingRow.classList.remove('highlight-flash'), 1000);} else {// 如果是新商品,插入一列新行const tr = document.createElement('tr');tr.id = `inv-row-${code}`;tr.className = 'highlight-flash';tr.innerHTML = `<td><div style="font-weight:700; color:var(--text-primary);">${invItem.name}</div><div style="font-size:0.75rem; color:var(--text-secondary); font-family:monospace; margin-top:2px;">${code}</div></td><td style="text-align:center;"><div class="qty-control"><button class="qty-btn no-print" onclick="adjustInventoryQty('${code}', 'dec')">-</button><span class="qty-val" id="inv-qty-${code}">${invItem.quantity}</span><button class="qty-btn no-print" onclick="adjustInventoryQty('${code}', 'inc')">+</button></div></td><td class="no-print" style="text-align:center;"><button onclick="deleteInventoryItem('${code}')" class="qty-btn" style="color:var(--danger-rose); font-size:0.8rem; margin:0 auto;">🗑️</button></td>`;tbody.insertBefore(tr, tbody.firstChild);setTimeout(() => tr.classList.remove('highlight-flash'), 1000);}}// 修改盤點清單上的數量 +/-function adjustInventoryQty(code, action) {fetch('/api/inventory/update', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ code: code, action: action, value: 1 })}).then(res => res.json()).then(resp => {if(resp.status === 'success') {const qtySpan = document.getElementById(`inv-qty-${code}`);if(qtySpan) {qtySpan.innerText = resp.inventory_item.quantity;updateStatsUI(resp.stats);}}});}// 刪除整列盤點商品function deleteInventoryItem(code) {if(!confirm("⚠️ 確定要從盤點清單中刪除此商品嗎?")) return;fetch('/api/inventory/delete', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ code: code })}).then(res => res.json()).then(resp => {if(resp.status === 'success') {const row = document.getElementById(`inv-row-${code}`);if(row) {row.remove();updateStatsUI(resp.stats);triggerAlert('warning', '已從盤點統計中移除商品');// 若全清空,補回空行const tbody = document.getElementById('inventory-table-body');if (tbody.children.length === 0) {tbody.innerHTML = `<tr id="empty-inventory-row"><td colspan="3" style="text-align:center; color:var(--text-secondary); padding:40px 0;">尚未盤點任何商品</td></tr>`;}}}});}// --- 5. 收銀 POS 購物車核心邏輯 ---function renderQuickPick() {const container = document.getElementById('quick-pick-container');if(!container) return;container.innerHTML = '';const entries = Object.entries(localProductDB);if(entries.length === 0) {container.innerHTML = '<p style="text-align:center; color:var(--text-secondary); font-size:0.8rem; padding:15px;">商品庫為空,請先前往系統設定上傳對照表 CSV</p>';return;}entries.forEach(([code, prod]) => {const btn = document.createElement('div');btn.style.display = 'flex';btn.style.justify = 'space-between';btn.style.alignItems = 'center';btn.style.padding = '8px 12px';btn.style.background = 'rgba(255, 255, 255, 0.03)';btn.style.borderRadius = '8px';btn.style.border = '1px solid rgba(255, 255, 255, 0.05)';btn.style.cursor = 'pointer';btn.style.fontSize = '0.9rem';btn.onclick = () => processPOSBarcode(code);btn.innerHTML = `<div style="display:flex; flex-direction:column;"><span style="font-weight:700; color:var(--text-primary);">${prod.name}</span><span style="font-size:0.75rem; color:var(--text-secondary); font-family:monospace;">${code}</span></div><span style="font-weight:bold; color:var(--success-emerald); font-size:0.95rem;">$${prod.price}</span>`;container.appendChild(btn);});}function processPOSBarcode(code) {code = code.trim();if(!code) return;let prod = { name: "未知商品", price: 0.0 };if(localProductDB[code]) {prod = localProductDB[code];}// 新增至購物車快取const cartItem = shoppingCart.find(item => item.code === code);if (cartItem) {cartItem.quantity += 1;triggerAlert('success', `➕ 購物車累計:${prod.name} (x${cartItem.quantity})`);} else {shoppingCart.push({code: code,name: prod.name,price: prod.price,quantity: 1});triggerAlert('success', `🛒 已加入購物車:${prod.name}`);}renderCart();}function renderCart() {const tbody = document.getElementById('cart-table-body');tbody.innerHTML = '';if(shoppingCart.length === 0) {tbody.innerHTML = `<tr id="empty-cart-row"><td colspan="4" style="text-align:center; color:var(--text-secondary); padding:80px 0;">購物車為空,請掃描條碼加入商品</td></tr>`;document.getElementById('cart-qty-total').innerText = '0 件';document.getElementById('cart-amount-total').innerText = '$0';calculateChange();return;}let totalQty = 0;let totalAmount = 0;shoppingCart.forEach(item => {const subtotal = item.price * item.quantity;totalQty += item.quantity;totalAmount += subtotal;const tr = document.createElement('tr');tr.innerHTML = `<td><div style="font-weight:700; color:var(--text-primary);">${item.name}</div><div style="font-size:0.75rem; color:var(--text-secondary); font-family:monospace; margin-top:2px;">${item.code}</div></td><td style="text-align:right; font-weight:600;">$${item.price}</td><td style="text-align:center;"><div class="qty-control" style="justify-content:center;"><button class="qty-btn" onclick="adjustCartQty('${item.code}', -1)">-</button><span class="qty-val">${item.quantity}</span><button class="qty-btn" onclick="adjustCartQty('${item.code}', 1)">+</button></div></td><td style="text-align:right; font-weight:700; color:var(--success-emerald);">$${subtotal}</td>`;tbody.appendChild(tr);});document.getElementById('cart-qty-total').innerText = `${totalQty} 件`;document.getElementById('cart-amount-total').innerText = `$${totalAmount}`;calculateChange();}function adjustCartQty(code, val) {const cartItem = shoppingCart.find(item => item.code === code);if (cartItem) {cartItem.quantity += val;if(cartItem.quantity <= 0) {shoppingCart = shoppingCart.filter(item => item.code !== code);}renderCart();}}function clearCart() {if(shoppingCart.length === 0) return;if(!confirm("⚠️ 確定要清空整部購物車嗎?")) return;shoppingCart = [];renderCart();triggerAlert('warning', '購物車已清空');}// 計算應找零錢function calculateChange() {const totalText = document.getElementById('cart-amount-total').innerText;const total = parseFloat(totalText.replace('$', '')) || 0;const cash = parseFloat(document.getElementById('pos-cash-received').value) || 0;const change = Math.max(0, cash - total);document.getElementById('pos-change-due').innerText = `$${change}`;}// 收銀 POS 結帳function checkoutPOS() {if(shoppingCart.length === 0) {alert("購物車內無商品!");return;}const totalText = document.getElementById('cart-amount-total').innerText;const total = parseFloat(totalText.replace('$', '')) || 0;const cash = parseFloat(document.getElementById('pos-cash-received').value) || 0;if (cash < total) {alert(`金額不足!還缺 ${total - cash} 元`);return;}// 發送結帳請求fetch('/api/pos/checkout', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({items: shoppingCart,cash_received: cash})}).then(res => res.json()).then(resp => {if (resp.status === 'success') {// 更新頂部數據看板updateStatsUI(resp.stats);// 顯示列印收據 ModalshowReceiptModal(resp.sale);// 清空本地購物車shoppingCart = [];renderCart();document.getElementById('pos-cash-received').value = '';document.getElementById('pos-change-due').innerText = '$0';// 更新銷售歷史 DOMupdateSalesTableUI(resp.sale);} else {alert("結帳失敗:" + resp.message);}}).catch(err => {alert("結帳異常,請檢查網路連線");});}// 彈出精美收據小票視窗function showReceiptModal(sale) {document.getElementById('receipt-tx-id').innerText = sale.tx_id;document.getElementById('receipt-time').innerText = sale.time;const listDiv = document.getElementById('receipt-items-list');listDiv.innerHTML = '';sale.items.forEach(item => {const row = document.createElement('div');row.className = 'receipt-row';row.innerHTML = `<span>${item.name} (x${item.quantity})</span><span>$${item.price * item.quantity}</span>`;listDiv.appendChild(row);});document.getElementById('receipt-total-amount').innerText = `$${sale.total}`;document.getElementById('receipt-cash-received').innerText = `$${sale.cash_received}`;document.getElementById('receipt-change-due').innerText = `$${sale.change}`;document.getElementById('receipt-modal').style.display = 'flex';}function closeReceiptModal() {document.getElementById('receipt-modal').style.display = 'none';}function updateSalesTableUI(sale) {const tbody = document.getElementById('sales-table-body');const emptyRow = document.getElementById('empty-sales-row');if(emptyRow) emptyRow.remove();const tr = document.createElement('tr');let itemsHTML = '<div style="display:flex; flex-direction:column; gap:2px; font-size:0.9rem;">';sale.items.forEach(item => {itemsHTML += `<div>🔹 ${item.name} (x${item.quantity}) - $${item.price * item.quantity}</div>`;});itemsHTML += '</div>';tr.innerHTML = `<td style="font-family:monospace; font-weight:bold;">${sale.tx_id}</td><td style="font-size:0.85rem; color:var(--text-secondary);">${sale.time}</td><td>${itemsHTML}</td><td style="text-align:right; font-weight:700; color:var(--success-emerald);">$${sale.total}</td><td style="text-align:right;">$${sale.cash_received}</td><td style="text-align:right; color:var(--warning-amber);">$${sale.change}</td>`;tbody.insertBefore(tr, tbody.firstChild);}// --- 6. 清理資料庫 ---function clearRecords() {if(!confirm("⚠️ 警告:確定要清空所有盤點紀錄與日誌嗎?這將會刪除 scans.json 庫存!")) return;fetch('/api/clear', { method: 'POST' }).then(res => res.json()).then(resp => {alert(resp.message);window.location.reload();});}function clearSalesHistory() {if(!confirm("⚠️ 警告:確定要清空所有銷售歷史紀錄嗎?這會刪除銷售金額統計!")) return;fetch('/api/sales/clear', { method: 'POST' }).then(res => res.json()).then(resp => {alert(resp.message);window.location.reload();});}// --- 7. 相機鏡頭操作核心 (不重整網頁相容 EAN/QR) ---function onInventoryCameraSuccess(decodedText) {// 短暫暫停一下避免重覆讀取if(html5QrcodeScanner) {html5QrcodeScanner.pause(true);setTimeout(() => {if (html5QrcodeScanner) html5QrcodeScanner.resume();}, 2000);}processInventoryBarcode(decodedText);}function onPOSCameraSuccess(decodedText) {if(html5QrcodeScanner) {html5QrcodeScanner.pause(true);setTimeout(() => {if (html5QrcodeScanner) html5QrcodeScanner.resume();}, 2000);}processPOSBarcode(decodedText);}function startCamera(containerId, successCallback) {stopCamera(); // 若有正在開的則關閉activeScannerId = containerId;let btnStartId = containerId === 'reader-inventory' ? 'btn-start-inventory' : 'btn-start-pos';let btnStopId = containerId === 'reader-inventory' ? 'btn-stop-inventory' : 'btn-stop-pos';let frameContainerId = containerId === 'reader-inventory' ? 'scanner-container' : 'pos-scanner-container';document.getElementById(frameContainerId).style.display = 'block';document.getElementById(btnStartId).style.display = 'none';document.getElementById(btnStopId).style.display = 'block';const formats = [Html5QrcodeSupportedFormats.QR_CODE,Html5QrcodeSupportedFormats.EAN_13,Html5QrcodeSupportedFormats.EAN_8,Html5QrcodeSupportedFormats.CODE_128,Html5QrcodeSupportedFormats.CODE_39,Html5QrcodeSupportedFormats.UPC_A];html5QrcodeScanner = new Html5QrcodeScanner(containerId, {fps: 10,qrbox: { width: 280, height: 180 },videoConstraints: { facingMode: "environment" },formatsToSupport: formats}, false);html5QrcodeScanner.render(successCallback, (error) => {});}function stopCamera() {if (html5QrcodeScanner) {const scanner = html5QrcodeScanner;html5QrcodeScanner = null;scanner.clear().then(() => {document.getElementById('scanner-container').style.display = 'none';document.getElementById('pos-scanner-container').style.display = 'none';document.getElementById('btn-start-inventory').style.display = 'block';document.getElementById('btn-stop-inventory').style.display = 'none';document.getElementById('btn-start-pos').style.display = 'block';document.getElementById('btn-stop-pos').style.display = 'none';if (activeScannerId === 'reader-inventory') {document.getElementById('scanner-input').focus();} else {document.getElementById('pos-input').focus();}}).catch(err => {console.error("關閉相機失敗", err);});}}// --- 8. 標籤大量產生與印表排版 ---function generateLabels() {const container = document.getElementById('label-container');const codeType = document.querySelector('input[name="codeType"]:checked').value;container.innerHTML = '<p style="text-align:center; width:100%; color:var(--text-secondary);">產生排版中,請稍候...</p>';fetch('/api/products').then(res => res.json()).then(resp => {container.innerHTML = '';const data = resp.data;if (Object.keys(data).length === 0) {container.innerHTML = '<p style="text-align:center; width:100%; color:var(--danger-rose);">商品資料庫是空的,請先在系統設定中上傳對照表 CSV 檔案。</p>';return;}for (const [code, item] of Object.entries(data)) {const card = document.createElement('div');card.className = 'label-card';const title = document.createElement('div');title.className = 'label-title';title.innerText = item.name;card.appendChild(title);const price = document.createElement('div');price.className = 'label-price';price.innerText = item.price > 0 ? `NT$ ${item.price}` : '特價商品';card.appendChild(price);if (codeType === 'barcode') {const canvas = document.createElement('svg');canvas.className = 'barcode-svg';card.appendChild(canvas);try {JsBarcode(canvas, code, {format: "CODE128",displayValue: false, // 自訂顯示下方即可height: 50,margin: 0});} catch(e) {const errDiv = document.createElement('div');errDiv.innerText = "無法產生一維條碼";errDiv.style.color = "red";errDiv.style.fontSize = "0.75rem";card.appendChild(errDiv);}} else {const qrWrap = document.createElement('div');qrWrap.className = 'qr-wrapper';card.appendChild(qrWrap);try {new QRCode(qrWrap, {text: code,width: 90,height: 90});} catch(e) {}}const codeText = document.createElement('div');codeText.className = 'label-code';codeText.innerText = code;card.appendChild(codeText);container.appendChild(card);}}).catch(err => {alert("載入商品庫失敗");});}// --- 9. 商品庫 CSV 上傳與解析輔助 ---function updateFileNameLabel() {const input = document.getElementById('csv-file');const label = document.getElementById('csv-file-name');if (input.files.length > 0) {label.innerText = input.files[0].name;} else {label.innerText = '尚未選擇檔案';}}function uploadCSV() {const fileInput = document.getElementById('csv-file');if (fileInput.files.length === 0) {alert("請先選擇要上傳的 CSV 檔案");return;}const formData = new FormData();formData.append("file", fileInput.files[0]);const btn = document.getElementById('btn-upload-csv');btn.innerText = "上傳並載入中...";btn.disabled = true;fetch('/api/upload_csv', {method: 'POST',body: formData}).then(res => res.json()).then(resp => {alert(resp.message);if (resp.status === 'success') {document.getElementById('db-count-label').innerText = resp.count;fetchAllProducts(); // 重新下載快取}}).catch(err => {alert("上傳對照表連線錯誤,請檢查伺服器狀態");}).finally(() => {btn.innerText = "⚡ 上傳並載入對照表";btn.disabled = false;});}</script></body>
__pycache__/app.cpython-314.pycAdded
app.py+306-29
templates/index.html+1788-242