Spaces:
Sleeping

ScanItem / app.py
HsiehMinChieh
Claude Fable 5
fix: harden POS checkout (server-side pricing, cash validation) and atomic data persistence
946c08b
Raw History Blame Contribute Delete
13.8 kB
from fastapi import FastAPI, Request, Response, UploadFile, File
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from datetime import datetime
import uvicorn
import csv
import io
import os
import shutil
import json
app = 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_records
if 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
}
# 先寫暫存檔再原子替換,避免寫到一半當機導致 data.json 毀損
tmp_file = DATA_FILE + ".tmp"
with open(tmp_file, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
os.replace(tmp_file, DATA_FILE)
except Exception as e:
print(f"❌ 寫入 {DATA_FILE} 失敗: {e}")
# 啟動時讀取儲存的盤點與銷售數據
load_data()
# --- 2. 載入商品對照表 ---
def load_products():
global product_db
product_db = {}
if os.path.exists("products.csv"):
try:
with open("products.csv", mode="r", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader, None)
# 尋找是否包含價格欄位 (例如 "價格", "單價", "price", "unit price")
price_index = -1
if 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 = idx
break
for 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.0
elif len(row) >= 3:
try:
price = float(row[2].strip())
except ValueError:
price = 0.0
product_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:
roc_year = int(content[10:13])
month = content[13:15]
day = content[15:17]
full_date = f"{roc_year + 1911}/{month}/{day}"
except ValueError:
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: str
class InventoryUpdateItem(BaseModel):
code: str
action: str # 'inc', 'dec', 'set'
value: int = 1
class InventoryDeleteItem(BaseModel):
code: str
class CartItem(BaseModel):
code: str
name: str
price: float
quantity: int
class 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")
async 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")
async def clear_data():
global scan_records, inventory
scan_records = []
inventory = {}
save_data()
return {"status": "success", "message": "盤點日誌與盤點清單已全部清空", "stats": get_stats_summary()}
# --- 盤點模式 API ---
@app.post("/api/scan")
async def receive_scan(item: ScanItem):
code = item.qr_content.strip()
if not code:
return {"status": "error", "message": "條碼內容不可為空"}
p_name = "未知物品"
p_price = 0.0
if 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.0
time_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)) + 1
inventory[code]["last_updated"] = time_str
else:
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")
async def update_inventory_qty(item: InventoryUpdateItem):
global inventory
code = item.code.strip()
if code not in inventory:
p_name = "未知物品"
p_price = 0.0
if 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.value
elif 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")
async def delete_inventory_item(item: InventoryDeleteItem):
global inventory
code = 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")
async def pos_checkout(req: CheckoutRequest):
global inventory, sales_records
if not req.items:
return {"status": "error", "message": "購物車內無商品,無法結帳"}
if any(item.quantity <= 0 for item in req.items):
return {"status": "error", "message": "商品數量必須大於 0"}
# 價格以伺服器端商品庫為準,避免前端傳入被竄改的價格
def server_price(item):
if item.code in product_db:
return product_db[item.code]["price"]
if item.code in inventory:
return inventory[item.code]["price"]
return item.price # 未知商品(如手動輸入)才信任前端價格
total = sum(server_price(item) * item.quantity for item in req.items)
if req.cash_received < total:
return {"status": "error", "message": f"實收金額不足,尚缺 {total - req.cash_received:g} 元"}
change = req.cash_received - total
# 加上微秒避免同一秒內兩筆交易單號重複
tx_id = "TX-" + datetime.now().strftime("%Y%m%d%H%M%S%f")
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": server_price(item),
"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_str
new_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")
async def clear_sales_history():
global sales_records
sales_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: # inventory
writer.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_content
return 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)