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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# routes/pyc_incremental_api.py
|
| 2 |
+
import os, re, json
|
| 3 |
+
from typing import Dict, List, Optional, Tuple
|
| 4 |
+
from fastapi import APIRouter, Query
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
from huggingface_hub import list_repo_files, hf_hub_download
|
| 7 |
+
from openpyxl import load_workbook
|
| 8 |
+
|
| 9 |
+
# ================= CẤU HÌNH =================
|
| 10 |
+
REPO_ID = os.environ.get("REPO_ID", "doluong6/Quatest1")
|
| 11 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") # để trống nếu dataset public
|
| 12 |
+
HF_CACHE = os.environ.get("HF_HUB_CACHE", "/tmp/hf_cache")
|
| 13 |
+
os.makedirs(HF_CACHE, exist_ok=True)
|
| 14 |
+
|
| 15 |
+
PYC_SCOPE = os.environ.get("PYC_FOLDER", "Phieu_yeu_cau/")
|
| 16 |
+
if not PYC_SCOPE.endswith("/"): PYC_SCOPE += "/"
|
| 17 |
+
|
| 18 |
+
# Cấu hình cột (đúng theo logic bạn dùng)
|
| 19 |
+
COL_QTY = "BM"
|
| 20 |
+
COL_PRICE = "BP"
|
| 21 |
+
COL_KD = "AV" # "P" => KĐ
|
| 22 |
+
COL_HC = "AY" # "P" => HC
|
| 23 |
+
COL_DTN = "BB" # "P" => ĐTN
|
| 24 |
+
COL_DAY = "BM3" # ngày (số)
|
| 25 |
+
COL_MONTH = "BS3" # tháng (1..12 dạng chuỗi số)
|
| 26 |
+
COL_CUST = "I8" # tên khách hàng
|
| 27 |
+
START_ROW = 24
|
| 28 |
+
|
| 29 |
+
# File cache
|
| 30 |
+
CACHE_PATH = os.path.join(HF_CACHE, "pyc_cache.json")
|
| 31 |
+
|
| 32 |
+
router = APIRouter(prefix="/pyc2", tags=["PYC-incremental"])
|
| 33 |
+
|
| 34 |
+
# ================= TIỆN ÍCH =================
|
| 35 |
+
def _safe_float(x) -> float:
|
| 36 |
+
try:
|
| 37 |
+
return float(x)
|
| 38 |
+
except Exception:
|
| 39 |
+
return 0.0
|
| 40 |
+
|
| 41 |
+
def _to_month_int(x) -> Optional[int]:
|
| 42 |
+
if x is None: return None
|
| 43 |
+
s = str(x).strip()
|
| 44 |
+
if not s.isdigit(): return None
|
| 45 |
+
m = int(s)
|
| 46 |
+
return m if 1 <= m <= 12 else None
|
| 47 |
+
|
| 48 |
+
def _period_of(day: Optional[int]) -> Optional[str]:
|
| 49 |
+
if day is None: return None
|
| 50 |
+
return "1_15" if day <= 15 else "16_31"
|
| 51 |
+
|
| 52 |
+
def _iter_services(ws):
|
| 53 |
+
r = START_ROW
|
| 54 |
+
while True:
|
| 55 |
+
qty = ws[f"{COL_QTY}{r}"].value
|
| 56 |
+
if qty is None: break
|
| 57 |
+
price = ws[f"{COL_PRICE}{r}"].value
|
| 58 |
+
kd = str(ws[f"{COL_KD}{r}"].value or "").strip().upper() == "P"
|
| 59 |
+
hc = str(ws[f"{COL_HC}{r}"].value or "").strip().upper() == "P"
|
| 60 |
+
dtn= str(ws[f"{COL_DTN}{r}"].value or "").strip().upper() == "P"
|
| 61 |
+
yield _safe_float(qty), _safe_float(price), kd, hc, dtn
|
| 62 |
+
r += 1
|
| 63 |
+
|
| 64 |
+
def _extract_number(basename: str) -> Optional[int]:
|
| 65 |
+
"""
|
| 66 |
+
Lấy số thứ tự từ tên file: PYC_0158.xlsx, 0158.xlsx, pyc-158.xlsx, ...
|
| 67 |
+
Trả int hoặc None nếu không tìm thấy.
|
| 68 |
+
"""
|
| 69 |
+
m = re.search(r"(\d{3,5})", basename)
|
| 70 |
+
return int(m.group(1)) if m else None
|
| 71 |
+
|
| 72 |
+
def _download(repo_path: str) -> str:
|
| 73 |
+
return hf_hub_download(
|
| 74 |
+
REPO_ID, repo_path, repo_type="dataset",
|
| 75 |
+
token=HF_TOKEN, cache_dir=HF_CACHE
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# ================= CACHE =================
|
| 79 |
+
def _load_cache() -> Dict:
|
| 80 |
+
if os.path.exists(CACHE_PATH):
|
| 81 |
+
try:
|
| 82 |
+
with open(CACHE_PATH, "r", encoding="utf-8") as f:
|
| 83 |
+
return json.load(f)
|
| 84 |
+
except Exception:
|
| 85 |
+
pass
|
| 86 |
+
return {
|
| 87 |
+
"version": 1,
|
| 88 |
+
"repo_id": REPO_ID,
|
| 89 |
+
"scope": PYC_SCOPE,
|
| 90 |
+
# files: dict keyed by repo_path
|
| 91 |
+
# { repo_path: { "num": 158, "month":7, "day":12, "customer":"...",
|
| 92 |
+
# "totals": {"KĐ":..,"HC":..,"ĐTN":..},
|
| 93 |
+
# "revenue":{"KĐ":..,"HC":..,"ĐTN":..} } }
|
| 94 |
+
"files": {}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
def _save_cache(cache: Dict):
|
| 98 |
+
tmp = CACHE_PATH + ".tmp"
|
| 99 |
+
with open(tmp, "w", encoding="utf-8") as f:
|
| 100 |
+
json.dump(cache, f, ensure_ascii=False)
|
| 101 |
+
os.replace(tmp, CACHE_PATH)
|
| 102 |
+
|
| 103 |
+
def _list_repo_files() -> List[str]:
|
| 104 |
+
files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
|
| 105 |
+
files = [f for f in files
|
| 106 |
+
if f.startswith(PYC_SCOPE)
|
| 107 |
+
and f.lower().endswith(".xlsx")
|
| 108 |
+
and not os.path.basename(f).startswith("~$")]
|
| 109 |
+
return files
|
| 110 |
+
|
| 111 |
+
def _process_file(local_path: str) -> Tuple[Dict, Dict, Optional[int], Optional[int], str]:
|
| 112 |
+
"""
|
| 113 |
+
Trả (totals, revenue, month, day, customer)
|
| 114 |
+
"""
|
| 115 |
+
wb = load_workbook(local_path, data_only=True)
|
| 116 |
+
ws = wb.active
|
| 117 |
+
# header info
|
| 118 |
+
day_val = ws[COL_DAY].value
|
| 119 |
+
month_val = ws[COL_MONTH].value
|
| 120 |
+
cust_val = str(ws[COL_CUST].value or "").strip()
|
| 121 |
+
day = int(day_val) if isinstance(day_val, (int, float)) else None
|
| 122 |
+
month = _to_month_int(month_val)
|
| 123 |
+
|
| 124 |
+
totals = {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
|
| 125 |
+
revenue= {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
|
| 126 |
+
|
| 127 |
+
for sl, gia, kd, hc, dtn in _iter_services(ws):
|
| 128 |
+
if kd:
|
| 129 |
+
totals["KĐ"] += sl
|
| 130 |
+
revenue["KĐ"] += sl * gia
|
| 131 |
+
if hc:
|
| 132 |
+
totals["HC"] += sl
|
| 133 |
+
revenue["HC"] += sl * gia
|
| 134 |
+
if dtn:
|
| 135 |
+
totals["ĐTN"] += sl
|
| 136 |
+
revenue["ĐTN"] += sl * gia
|
| 137 |
+
|
| 138 |
+
# làm gọn số
|
| 139 |
+
for k in totals: totals[k] = round(totals[k], 2)
|
| 140 |
+
for k in revenue: revenue[k] = round(revenue[k], 0)
|
| 141 |
+
return totals, revenue, month, day, cust_val
|
| 142 |
+
|
| 143 |
+
def _refresh_cache(cache: Dict) -> Dict:
|
| 144 |
+
"""
|
| 145 |
+
Quét danh sách file trên repo, chỉ xử lý file MỚI (chưa có trong cache).
|
| 146 |
+
Sắp xếp theo số thứ tự tăng dần để gộp đúng trình tự.
|
| 147 |
+
"""
|
| 148 |
+
existing = set(cache["files"].keys())
|
| 149 |
+
all_files = _list_repo_files()
|
| 150 |
+
new_files = [rp for rp in all_files if rp not in existing]
|
| 151 |
+
|
| 152 |
+
# sắp theo số (nếu không có số thì đẩy sau)
|
| 153 |
+
def _sort_key(rp: str):
|
| 154 |
+
n = _extract_number(os.path.basename(rp)) or 10**9
|
| 155 |
+
return (n, rp)
|
| 156 |
+
new_files.sort(key=_sort_key)
|
| 157 |
+
|
| 158 |
+
added = 0
|
| 159 |
+
for rp in new_files:
|
| 160 |
+
try:
|
| 161 |
+
lp = _download(rp)
|
| 162 |
+
totals, revenue, month, day, cust = _process_file(lp)
|
| 163 |
+
num = _extract_number(os.path.basename(rp))
|
| 164 |
+
cache["files"][rp] = {
|
| 165 |
+
"num": num,
|
| 166 |
+
"month": month,
|
| 167 |
+
"day": day,
|
| 168 |
+
"customer": cust,
|
| 169 |
+
"totals": totals,
|
| 170 |
+
"revenue": revenue,
|
| 171 |
+
}
|
| 172 |
+
added += 1
|
| 173 |
+
except Exception as e:
|
| 174 |
+
# ghi dấu lỗi để sau có thể xem
|
| 175 |
+
cache["files"][rp] = {"error": str(e)}
|
| 176 |
+
if added:
|
| 177 |
+
_save_cache(cache)
|
| 178 |
+
return {"added": added, "known": len(cache["files"])}
|
| 179 |
+
|
| 180 |
+
# ================= SCHEMAS =================
|
| 181 |
+
class StateResp(BaseModel):
|
| 182 |
+
repo_id: str
|
| 183 |
+
scope: str
|
| 184 |
+
known: int
|
| 185 |
+
newest_num: Optional[int] = None
|
| 186 |
+
added: int
|
| 187 |
+
|
| 188 |
+
class StatsResp(BaseModel):
|
| 189 |
+
month: Optional[int] = None
|
| 190 |
+
period: Optional[str] = None # '1_15' | '16_31' | None
|
| 191 |
+
totals: Dict[str, float]
|
| 192 |
+
revenue: Dict[str, float]
|
| 193 |
+
customers: List[str]
|
| 194 |
+
files: List[str]
|
| 195 |
+
|
| 196 |
+
# ================= ENDPOINTS =================
|
| 197 |
+
@router.post("/refresh", response_model=StateResp)
|
| 198 |
+
def refresh():
|
| 199 |
+
"""
|
| 200 |
+
Quét repo và xử lý incremental (chỉ file mới).
|
| 201 |
+
Trả về số file mới được thêm.
|
| 202 |
+
"""
|
| 203 |
+
cache = _load_cache()
|
| 204 |
+
out = _refresh_cache(cache)
|
| 205 |
+
newest = None
|
| 206 |
+
# tìm số lớn nhất đã biết
|
| 207 |
+
nums = [v.get("num") for v in cache["files"].values() if isinstance(v, dict) and v.get("num") is not None]
|
| 208 |
+
if nums:
|
| 209 |
+
newest = max(nums)
|
| 210 |
+
return {"repo_id": cache["repo_id"], "scope": cache["scope"],
|
| 211 |
+
"known": out["known"], "added": out["added"], "newest_num": newest}
|
| 212 |
+
|
| 213 |
+
@router.get("/stats", response_model=StatsResp)
|
| 214 |
+
def stats(
|
| 215 |
+
month: Optional[int] = Query(default=None, ge=1, le=12),
|
| 216 |
+
period: Optional[str] = Query(default=None, regex=r"^(1_15|16_31)$"),
|
| 217 |
+
refresh_first: bool = Query(default=True)
|
| 218 |
+
):
|
| 219 |
+
"""
|
| 220 |
+
Lấy thống kê tổng hợp từ cache (rất nhanh). Nếu refresh_first=true, API sẽ
|
| 221 |
+
chạy incremental trước (nhanh) để đảm bảo có file mới nhất.
|
| 222 |
+
"""
|
| 223 |
+
cache = _load_cache()
|
| 224 |
+
if refresh_first:
|
| 225 |
+
_refresh_cache(cache)
|
| 226 |
+
|
| 227 |
+
totals = {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
|
| 228 |
+
revenue= {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
|
| 229 |
+
customers = set()
|
| 230 |
+
used_files = []
|
| 231 |
+
|
| 232 |
+
for rp, meta in cache["files"].items():
|
| 233 |
+
if not isinstance(meta, dict) or "error" in meta:
|
| 234 |
+
continue
|
| 235 |
+
m = meta.get("month")
|
| 236 |
+
d = meta.get("day")
|
| 237 |
+
if month is not None and m != month:
|
| 238 |
+
continue
|
| 239 |
+
if period is not None and _period_of(d) != period:
|
| 240 |
+
continue
|
| 241 |
+
|
| 242 |
+
t = meta.get("totals", {})
|
| 243 |
+
r = meta.get("revenue", {})
|
| 244 |
+
for k in totals: totals[k] += float(t.get(k, 0))
|
| 245 |
+
for k in revenue: revenue[k] += float(r.get(k, 0))
|
| 246 |
+
if meta.get("customer"): customers.add(meta["customer"])
|
| 247 |
+
used_files.append(rp)
|
| 248 |
+
|
| 249 |
+
for k in totals: totals[k] = round(totals[k], 2)
|
| 250 |
+
for k in revenue: revenue[k] = round(revenue[k], 0)
|
| 251 |
+
return {
|
| 252 |
+
"month": month,
|
| 253 |
+
"period": period,
|
| 254 |
+
"totals": totals,
|
| 255 |
+
"revenue": revenue,
|
| 256 |
+
"customers": sorted(customers),
|
| 257 |
+
"files": used_files
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
@router.get("/list")
|
| 261 |
+
def list_files(
|
| 262 |
+
month: Optional[int] = Query(default=None, ge=1, le=12),
|
| 263 |
+
period: Optional[str] = Query(default=None, regex=r"^(1_15|16_31)$"),
|
| 264 |
+
limit: int = Query(default=200, ge=1, le=1000),
|
| 265 |
+
refresh_first: bool = Query(default=False)
|
| 266 |
+
):
|
| 267 |
+
"""
|
| 268 |
+
Trả danh sách file đã biết (từ cache), có thể lọc theo month/period.
|
| 269 |
+
"""
|
| 270 |
+
cache = _load_cache()
|
| 271 |
+
if refresh_first:
|
| 272 |
+
_refresh_cache(cache)
|
| 273 |
+
out = []
|
| 274 |
+
for rp, meta in cache["files"].items():
|
| 275 |
+
if not isinstance(meta, dict) or "error" in meta:
|
| 276 |
+
continue
|
| 277 |
+
if month is not None and meta.get("month") != month:
|
| 278 |
+
continue
|
| 279 |
+
if period is not None and _period_of(meta.get("day")) != period:
|
| 280 |
+
continue
|
| 281 |
+
out.append({
|
| 282 |
+
"repo_path": rp,
|
| 283 |
+
"num": meta.get("num"),
|
| 284 |
+
"month": meta.get("month"),
|
| 285 |
+
"day": meta.get("day"),
|
| 286 |
+
"customer": meta.get("customer"),
|
| 287 |
+
"totals": meta.get("totals"),
|
| 288 |
+
"revenue": meta.get("revenue")
|
| 289 |
+
})
|
| 290 |
+
# sắp theo số
|
| 291 |
+
out.sort(key=lambda x: (x.get("num") if x.get("num") is not None else 10**9, x["repo_path"]))
|
| 292 |
+
return {"count": len(out), "items": out[:limit]}
|
| 293 |
+
|
| 294 |
+
@router.post("/reset")
|
| 295 |
+
def reset_cache():
|
| 296 |
+
"""
|
| 297 |
+
XÓA cache & build lại từ đầu ở lần gọi /refresh tiếp theo.
|
| 298 |
+
"""
|
| 299 |
+
if os.path.exists(CACHE_PATH):
|
| 300 |
+
os.remove(CACHE_PATH)
|
| 301 |
+
return {"status": "ok", "msg": "Cache cleared"}
|