Spaces:
Sleeping

File size: 13,776 Bytes
e675b35
a202e05
 
 
 
 
8666aec
 
dceb3c4
e675b35
e5fb853
a202e05
 
 
8abf63f
dceb3c4
8abf63f
e5fb853
 
8abf63f
dceb3c4
e5fb853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946c08b
 
 
e5fb853
946c08b
e5fb853
 
 
 
 
 
 
 
dceb3c4
 
8abf63f
dceb3c4
e675b35
 
 
e5fb853
 
 
 
 
 
 
 
 
 
 
 
 
e675b35
 
e5fb853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e675b35
e5fb853
a202e05
dceb3c4
 
a202e05
e5fb853
8abf63f
e5fb853
8abf63f
fae2938
8abf63f
 
 
 
 
946c08b
e5fb853
8abf63f
 
 
e5fb853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a202e05
 
e675b35
 
e5fb853
 
 
 
 
e675b35
 
6d3ee3d
 
 
 
e5fb853
 
 
 
e675b35
946c08b
e5fb853
 
 
 
 
 
 
 
 
 
 
a202e05
fae2938
946c08b
e5fb853
6d3ee3d
e5fb853
 
 
fae2938
e5fb853
a202e05
946c08b
dceb3c4
e5fb853
 
 
8abf63f
e5fb853
8abf63f
 
e5fb853
 
8abf63f
 
 
 
e5fb853
8abf63f
e5fb853
 
 
a202e05
fae2938
 
e5fb853
 
a202e05
 
e5fb853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946c08b
e5fb853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946c08b
e5fb853
 
 
 
 
 
 
 
 
 
 
946c08b
e5fb853
 
 
946c08b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5fb853
946c08b
e5fb853
 
 
 
 
946c08b
e5fb853
 
946c08b
e5fb853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a202e05
e5fb853
 
 
 
 
946c08b
e5fb853
 
 
 
 
 
 
8666aec
e5fb853
8666aec
 
e5fb853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed58b01
e5fb853
ed58b01
e5fb853
 
 
 
 
 
ed58b01
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
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)