import os os.environ["HF_HUB_CACHE"] = "/tmp/hf_cache" os.makedirs("/tmp/hf_cache", exist_ok=True) from fastapi import FastAPI from routes import dem_pyc, tong_doanh_thu_pyc, dem_pyc_hoan_thanh, doanh_thu_theo_thang, doanh_thu_dich_vu, tai_pdf, danh_sach_pdf, quy_trinh, danh_muc_thiet_bi # hoặc import từ file dem_pyc nếu không có thư mục routes from routes import ds_pyc_tat_ca, ds_pyc_hoan_thanh, doanh_thu_chi_tiet, pyc_chua_hoan_thanh, ty_le_dich_vu, doanh_thu_tong_hop, ds_pyc_cho_xu_ly, doanh_thu_tong, doanh_thu_noi_bo from routes import cap_nhat_hoa_chat, quan_ly_hoa_chat, canh_bao_hoa_chat, hien_thi_hskh, cap_nhat_hskh, lay_thong_tin_pyc, upload_pyc, upload_kemtheo from routes import banggia6, banggia2, banggia4, banggia3, danh_sach_thu_muc_khach_hang, banggia5 from routes.chatbot_routes import router as chatbot_router app = FastAPI() app.include_router(dem_pyc.router) app.include_router(tong_doanh_thu_pyc.router) app.include_router(dem_pyc_hoan_thanh.router) app.include_router(doanh_thu_theo_thang.router) app.include_router(doanh_thu_dich_vu.router) app.include_router(ds_pyc_tat_ca.router) app.include_router(ds_pyc_hoan_thanh.router) app.include_router(doanh_thu_chi_tiet.router) app.include_router(pyc_chua_hoan_thanh.router) app.include_router(ty_le_dich_vu.router) app.include_router(doanh_thu_tong_hop.router) app.include_router(ds_pyc_cho_xu_ly.router) app.include_router(doanh_thu_tong.router) app.include_router(doanh_thu_noi_bo.router) app.include_router(tai_pdf.router) app.include_router(danh_sach_pdf.router) app.include_router(quy_trinh.router) app.include_router(danh_muc_thiet_bi.router) app.include_router(cap_nhat_hoa_chat.router) app.include_router(quan_ly_hoa_chat.router) app.include_router(canh_bao_hoa_chat.router) app.include_router(hien_thi_hskh.router) app.include_router(cap_nhat_hskh.router) app.include_router(lay_thong_tin_pyc.router) app.include_router(upload_pyc.router) app.include_router(upload_kemtheo.router) app.include_router(banggia6.router) app.include_router(banggia2.router) app.include_router(banggia4.router) app.include_router(banggia3.router) app.include_router(danh_sach_thu_muc_khach_hang.router) app.include_router(banggia5.router) app.include_router(chatbot_router) @app.get("/") def root(): return {"message": "✅ Backend is running"} # ====== chatbot / rag / actions ====== from typing import List, Optional from pydantic import BaseModel from fastapi import APIRouter, Body import re, datetime, httpx from openai import OpenAI from rag_indexer import build_index, search as rag_search from actions import router as tabular_router from intents import is_table_query, extract_keywords # ================== CHATBOT – GPT-5 + RAG + ACTION ================== OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") MODEL_NAME = os.environ.get("OPENAI_MODEL","gpt-5") client = OpenAI(api_key=OPENAI_API_KEY) # -------- ReIndex (quét dataset & lập chỉ mục) -------- router_rag = APIRouter() @router_rag.post("/reindex") def reindex(): out = build_index() return {"status":"ok", **out} # -------- Chat dựa trên dữ liệu nội bộ (RAG) ---------- class AskReq(BaseModel): question: str history: Optional[List[dict]] = [] def _llm_complete(prompt: str) -> str: rsp = client.chat.completions.create( model=MODEL_NAME, temperature=0.2, messages=[{"role":"system","content": "Bạn là trợ lý nội bộ. Chỉ trả lời dựa trên NGỮ CẢNH nếu có; nếu thiếu thông tin thì nói rõ không đủ trong dữ liệu nội bộ."}, {"role":"user","content":prompt}] ) return rsp.choices[0].message.content.strip() @router_rag.post("/chat_rag") def chat_rag(req: AskReq): hits = rag_search(req.question, top_k=6) ctx = "\n".join([f"- {h['repo_path']}: {h['preview']}" for h in hits]) or "(không tìm thấy ngữ cảnh phù hợp)" hist = "\n".join([f"[{m.get('role','user')}] {m.get('content','')}" for m in (req.history or [])][-6:]) prompt = f""" NGỮ CẢNH (trích từ dữ liệu nội bộ): {ctx} LỊCH SỬ: {hist} YÊU CẦU: - Trả lời bằng tiếng Việt, dựa trên NGỮ CẢNH ở trên. - Nếu NGỮ CẢNH không đủ hoặc không liên quan, nói rõ: "Mình chưa thấy đủ thông tin trong dữ liệu nội bộ." - Cuối câu trả lời, liệt kê 'Nguồn' (các repo_path nổi bật). CÂU HỎI: {req.question} """ ans = _llm_complete(prompt) sources = list({h['repo_path'] for h in hits})[:5] return {"reply": ans, "sources": sources, "hits": hits} app.include_router(router_rag) # -------- Chat thường -------- router_chat = APIRouter() class ChatReq(BaseModel): messages: List[dict] @router_chat.post("/chat") def chat(req: ChatReq): sys_prompt = {"role":"system","content":"Bạn là chatbot nội bộ, trả lời ngắn gọn, rõ ràng bằng tiếng Việt."} msgs = [sys_prompt] + (req.messages[-15:] if req.messages else []) rsp = client.chat.completions.create(model=MODEL_NAME, messages=msgs, temperature=0.2) return {"reply": rsp.choices[0].message.content} app.include_router(router_chat) # -------- Chat tự phân loại (ACTION / RAG / GENERAL) -------- router_smart = APIRouter() class SmartReq(BaseModel): message: str history: Optional[List[dict]] = [] class SmartResp(BaseModel): intent: str reply: str sources: Optional[List[str]] = None KEY_PYC_PENDING = [ r"PYC\s*chưa\s*hoàn\s*thành", r"chưa\s*hoàn\s*thành", r"chờ\s*xử\s*lý", r"cho\s*xu\s*ly" # <== thêm 2 regex này ] KEY_REVENUE = [r"doanh\s*thu", r"tháng\s*\d{1,2}", r"\b\d{1,2}\/\d{4}\b"] def _has(t, pats): return any(re.search(p, t, flags=re.I) for p in pats) def _mon_year(t:str): t=t.lower() m=re.search(r"tháng\s*(\d{1,2})(?:[\/\-](\d{4}))?",t) if m: return int(m.group(1)), int(m.group(2)) if m.group(2) else datetime.date.today().year m2=re.search(r"\b(\d{1,2})\/(\d{4})\b",t) if m2: return int(m2.group(1)), int(m2.group(2)) return None,None # thêm ngay dưới _mon_year(t: str) def _mon_year_from_history(history): if not history: return (None, None) # duyệt ngược để lấy câu gần nhất có "tháng" for msg in reversed(history): t = msg.get("content", "") or "" m, y = _mon_year(t) if m: return (m, y) return (None, None) async def _GET(path, params): for base in ["","http://127.0.0.1:7860","http://127.0.0.1:8000"]: url = f"{base}{path}" if base else path try: async with httpx.AsyncClient(timeout=60) as c: r=await c.get(url, params=params) if r.status_code==200: return r.json() except: pass return {"error": f"GET fail {path}"} async def _POST(path, payload): for base in ["","http://127.0.0.1:7860","http://127.0.0.1:8000"]: url = f"{base}{path}" if base else path try: async with httpx.AsyncClient(timeout=60) as c: r=await c.post(url, json=payload) if r.status_code==200: return r.json() except: pass return {"error": f"POST fail {path}"} def _format_rows(rows: List[dict], max_cols: int = 6) -> str: if not rows: return "Không tìm thấy dòng phù hợp." # mỗi row {"source": "...", "row": {...}} lines = [] for i, item in enumerate(rows, 1): src = item.get("source","") row = item.get("row", {}) # lấy vài cột đầu cols = list(row.keys())[:max_cols] parts = [f"{k}: {row[k]}" for k in cols] lines.append(f"{i}. ({src}) " + " | ".join(parts)) return "\n".join(lines) @router_smart.post("/chat_smart", response_model=SmartResp) async def chat_smart(req: SmartReq = Body(...)): text = (req.message or "").strip() if not text: return SmartResp(intent="general", reply="Bạn hãy nhập câu hỏi hoặc yêu cầu nhé.") # ACTION: PYC chưa hoàn thành if _has(text, KEY_PYC_PENDING): data = await _GET("/pyc_chua_hoan_thanh", {}) if "error" in data: return SmartResp(intent="action.list_pyc_pending", reply="Không lấy được danh sách.") rows = data if isinstance(data,list) else data.get("rows") or data.get("data") or [] if not rows: return SmartResp(intent="action.list_pyc_pending", reply="Hiện không có PYC chưa hoàn thành.") top = rows[:10] if isinstance(top[0], dict): lines = [] for r in top: so = r.get("SỐ PYC") or r.get("so_pyc") or r.get("pyc") or "" kh = r.get("Tên khách hàng") or r.get("ten_khach_hang") or r.get("khach_hang") or "" lines.append(f"- {so} | {kh}") return SmartResp(intent="action.list_pyc_pending", reply="\n".join(lines)) return SmartResp(intent="action.list_pyc_pending", reply="\n".join([f"- {r}" for r in top])) # ACTION: Doanh thu tháng (trả đúng 1 tháng) if _has(text, KEY_REVENUE): mon, yr = _mon_year(text) if not mon: # thử lấy từ lịch sử hội thoại mon, yr = _mon_year_from_history(req.history) if not mon: return SmartResp(intent="action.revenue_month.ask", reply="Bạn muốn xem doanh thu **tháng nào**? (vd: tháng 7/2025)") data = await _GET("/doanh_thu_theo_thang", {"month": mon, "year": yr}) if "error" in data: return SmartResp(intent="action.revenue_month", reply="Không lấy được doanh thu.") # 3 trường hợp: API trả 'tong_doanh_thu' / 'total' / mảng 'doanh_thu' theo 12 tháng total = data.get("tong_doanh_thu") or data.get("total") or data.get("sum") if total is None and isinstance(data.get("doanh_thu"), list): arr = data["doanh_thu"] idx = mon - 1 if 0 <= idx < len(arr): total = arr[idx] if total is None: return SmartResp(intent="action.revenue_month", reply=f"Kết quả: {data}") year_show = yr or datetime.date.today().year try: total_fmt = f"{int(total):,}" except: total_fmt = str(total) return SmartResp(intent="action.revenue_month", reply=f"Doanh thu tháng {str(mon).zfill(2)}/{year_show}: **{total_fmt} VND**") # === GIÁ / BẢNG GIÁ (bắt cả không dấu) === txt_no = re.sub(r"[^\w\s]", " ", text.lower()) txt_no = (txt_no.replace("á","a").replace("à","a").replace("ã","a").replace("ả","a").replace("ạ","a") .replace("â","a").replace("ă","a").replace("đ","d") .replace("ó","o").replace("ò","o").replace("ô","o").replace("ơ","o").replace("õ","o").replace("ọ","o") .replace("é","e").replace("è","e").replace("ê","e").replace("ẽ","e").replace("ẹ","e") .replace("í","i").replace("ì","i").replace("ĩ","i").replace("ị","i") .replace("ú","u").replace("ù","u").replace("ũ","u").replace("ụ","u").replace("ư","u")) if re.search(r"\b(bao gia|bang gia|gia)\b", txt_no): nhom = None if "hoa ly" in txt_no or "hóa lý" in text.lower(): nhom = "hóa lý" elif "dien" in txt_no or "điện" in text.lower(): nhom = "điện" elif "co do dai" in txt_no or "cơ độ dài" in text.lower() or "ap suat" in txt_no or "áp suất" in text.lower(): nhom = "cơ/áp suất" elif "nhiet" in txt_no or "y te" in txt_no or "nhiệt" in text.lower() or "y tế" in text.lower(): nhom = "nhiệt/y tế" elif "dung tich" in txt_no or "luu luong" in txt_no: nhom = "dung tích/lưu lượng" elif "khoi luong" in txt_no or "khối lượng" in text.lower(): nhom = "khối lượng" if nhom: return SmartResp(intent="action.open_price_table", reply=f"Mở **Bảng giá tham khảo** ({nhom}). Vào mục *Bảng giá tham khảo* ở menu.") else: return SmartResp(intent="action.open_price_table", reply="Mở **Bảng giá tham khảo**. Vào mục *Bảng giá tham khảo* ở menu để chọn nhóm.") # === PHIẾU YÊU CẦU === if "phiếu yêu cầu" in text.lower() or "phieu yeu cau" in txt_no or "pyc" in txt_no: return SmartResp(intent="action.pyc", reply="Bạn muốn xem **PYC chờ xử lý**, **đã hoàn thành** hay **tất cả**? Vào menu *Phiếu yêu cầu* để chọn.") # ACTION: PYC chờ xử lý / chưa hoàn thành if _has(text, KEY_PYC_PENDING) or text.strip().lower() in {"pyc chờ xử lý","pyc cho xu ly"}: # ưu tiên API liệt kê PYC chờ xử lý nếu có data = await _GET("/ds_pyc_cho_xu_ly", {}) # bạn có route này if "error" in data or not data: # fallback sang API PYC chưa hoàn thành data = await _GET("/pyc_chua_hoan_thanh", {}) rows = data if isinstance(data, list) else data.get("rows") or data.get("data") or [] if not rows: return SmartResp(intent="action.list_pyc_pending", reply="Hiện không có PYC chờ xử lý.") # render gọn top 10 out = [] for r in rows[:10]: if isinstance(r, dict): so = r.get("SỐ PYC") or r.get("so_pyc") or r.get("pyc") or "" kh = r.get("Tên khách hàng") or r.get("ten_khach_hang") or r.get("khach_hang") or "" out.append(f"- {so} | {kh}") else: out.append(f"- {r}") return SmartResp(intent="action.list_pyc_pending", reply="\n".join(out)) # ACTION: Câu hỏi dạng bảng (bảng giá/thiết bị/khách hàng/hóa chất…) if is_table_query(text): # rút từ khóa gọn để search kws = extract_keywords(text) q = " ".join(kws) if kws else text data = await _GET("/tabular_search", {"q": q, "limit": 10}) rows = data.get("data", []) if rows: return SmartResp(intent="action.tabular_search", reply=_format_rows(rows)) # fallback: RAG data_rag = await _POST("/chat_rag", {"question": text, "history": req.history or []}) if data_rag.get("reply"): return SmartResp(intent="rag.query", reply=data_rag["reply"], sources=data_rag.get("sources")) # === TÀI LIỆU / PDF === if re.search(r"(tài\s*liệu|tai\s*lieu|pdf|quy\s*trình|quy\s*trinh|document)", text, flags=re.I): # nếu có API danh sách PDF thì liệt kê nhanh top 8 data = await _GET("/danh_sach_pdf", {}) items = [] if isinstance(data, dict): arr = data.get("files") or data.get("data") or [] else: arr = data or [] for p in arr[:8]: name = p if isinstance(p, str) else (p.get("name") or p.get("path") or "") if name: items.append(f"• {name}") reply = "Mở **Tài liệu (PDF)**. " + ("Dưới đây là một số tệp:\n" + "\n".join(items) if items else "") return SmartResp(intent="action.docs", reply=reply) # RAG: nếu nhắc tới tài liệu/quy trình/báo giá… if re.search(r"(quy\s*trình|tài\s*liệu|báo\s*giá|PYC|hợp\s*đồng)", text, flags=re.I): data = await _POST("/chat_rag", {"question": text, "history": req.history or []}) if data.get("reply"): return SmartResp(intent="rag.query", reply=data["reply"], sources=data.get("sources")) # GENERAL msgs = (req.history or []) + [{"role":"user","content":text}] out = await _POST("/chat", {"messages": msgs}) reply = out.get("reply") or "Xin lỗi, mình chưa trả lời được." return SmartResp(intent="general", reply=reply) app.include_router(router_smart) # ================== HẾT PHẦN CHATBOT ================== # ================== PYC INCREMENTAL (tích hợp trực tiếp) ================== # Đọc Excel trong dataset Hugging Face: doluong6/Quatest1/Phieu_yeu_cau/ # Chỉ xử lý file mới kể từ lần trước, gộp vào cache (~ /tmp/hf_cache/pyc_cache.json) import os, re, json from typing import Dict, List, Optional, Tuple from fastapi import APIRouter, Query from pydantic import BaseModel from huggingface_hub import list_repo_files, hf_hub_download from openpyxl import load_workbook # --------- Cấu hình chính --------- REPO_ID = os.environ.get("REPO_ID", "doluong6/Quatest1") HF_TOKEN = os.environ.get("HF_TOKEN") # để trống nếu dataset public HF_CACHE = os.environ.get("HF_HUB_CACHE", "/tmp/hf_cache") os.makedirs(HF_CACHE, exist_ok=True) PYC_SCOPE = os.environ.get("PYC_FOLDER", "Phieu_yeu_cau/") if not PYC_SCOPE.endswith("/"): PYC_SCOPE += "/" # Cột theo template PYC COL_QTY = "BM" # số lượng COL_PRICE = "BP" # đơn giá COL_KD = "AV" # "P" => KĐ COL_HC = "AY" # "P" => HC COL_DTN = "BB" # "P" => ĐTN COL_DAY = "BM3" # ngày (số) COL_MONTH = "BS3" # tháng (chuỗi số 1..12) COL_CUST = "I8" # tên khách hàng START_ROW = 24 # dòng bắt đầu duyệt dịch vụ CACHE_PATH = os.path.join(HF_CACHE, "pyc_cache.json") router_pyc_inc = APIRouter(prefix="/pyc_incremental", tags=["PYC-incremental"]) # --------- Tiện ích --------- def _safe_float(x) -> float: try: return float(x) except Exception: return 0.0 def _to_month_int(x) -> Optional[int]: if x is None: return None s = str(x).strip() if not s.isdigit(): return None m = int(s) return m if 1 <= m <= 12 else None def _period_of(day: Optional[int]) -> Optional[str]: if day is None: return None return "1_15" if day <= 15 else "16_31" def _iter_services(ws): r = START_ROW while True: qty = ws[f"{COL_QTY}{r}"].value if qty is None: break price = ws[f"{COL_PRICE}{r}"].value kd = str(ws[f"{COL_KD}{r}"].value or "").strip().upper() == "P" hc = str(ws[f"{COL_HC}{r}"].value or "").strip().upper() == "P" dtn= str(ws[f"{COL_DTN}{r}"].value or "").strip().upper() == "P" yield _safe_float(qty), _safe_float(price), kd, hc, dtn r += 1 def _extract_number(basename: str) -> Optional[int]: # lấy số trong tên file: PYC_0158.xlsx, 0158.xlsx, pyc-158.xlsx, ... m = re.search(r"(\d{3,5})", basename) return int(m.group(1)) if m else None def _download(repo_path: str) -> str: return hf_hub_download( REPO_ID, repo_path, repo_type="dataset", token=HF_TOKEN, cache_dir=HF_CACHE ) # --------- Cache --------- def _load_cache() -> Dict: if os.path.exists(CACHE_PATH): try: with open(CACHE_PATH, "r", encoding="utf-8") as f: return json.load(f) except Exception: pass return { "version": 1, "repo_id": REPO_ID, "scope": PYC_SCOPE, # files: { repo_path: { "num": 158, "month":7, "day":12, "customer":"...", # "totals":{"KĐ":..,"HC":..,"ĐTN":..}, # "revenue":{"KĐ":..,"HC":..,"ĐTN":..} } } "files": {} } def _save_cache(cache: Dict): tmp = CACHE_PATH + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(cache, f, ensure_ascii=False) os.replace(tmp, CACHE_PATH) def _list_repo_files() -> List[str]: files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN) return [f for f in files if f.startswith(PYC_SCOPE) and f.lower().endswith(".xlsx") and not os.path.basename(f).startswith("~$")] def _process_file(local_path: str): """ Trả (totals, revenue, month, day, customer) """ wb = load_workbook(local_path, data_only=True) ws = wb.active day_val = ws[COL_DAY].value month_val = ws[COL_MONTH].value cust_val = str(ws[COL_CUST].value or "").strip() day = int(day_val) if isinstance(day_val, (int, float)) else None month = _to_month_int(month_val) totals = {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0} revenue= {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0} for sl, gia, kd, hc, dtn in _iter_services(ws): if kd: totals["KĐ"] += sl revenue["KĐ"] += sl * gia if hc: totals["HC"] += sl revenue["HC"] += sl * gia if dtn: totals["ĐTN"] += sl revenue["ĐTN"] += sl * gia for k in totals: totals[k] = round(totals[k], 2) for k in revenue: revenue[k] = round(revenue[k], 0) return totals, revenue, month, day, cust_val def _refresh_cache(cache: Dict) -> Dict: """ Quét repo, chỉ xử lý file MỚI (chưa có trong cache). Sắp theo số tăng dần. """ existing = set(cache["files"].keys()) all_files = _list_repo_files() new_files = [rp for rp in all_files if rp not in existing] def _sort_key(rp: str): n = _extract_number(os.path.basename(rp)) or 10**9 return (n, rp) new_files.sort(key=_sort_key) added = 0 for rp in new_files: try: lp = _download(rp) totals, revenue, month, day, cust = _process_file(lp) num = _extract_number(os.path.basename(rp)) cache["files"][rp] = { "num": num, "month": month, "day": day, "customer": cust, "totals": totals, "revenue": revenue } added += 1 except Exception as e: cache["files"][rp] = {"error": str(e)} if added: _save_cache(cache) return {"added": added, "known": len(cache["files"])} # --------- Schemas --------- class IncStateResp(BaseModel): repo_id: str scope: str known: int newest_num: Optional[int] = None added: int class IncStatsResp(BaseModel): month: Optional[int] = None period: Optional[str] = None # '1_15' | '16_31' | None totals: Dict[str, float] revenue: Dict[str, float] customers: List[str] files: List[str] # --------- Endpoints --------- @router_pyc_inc.post("/refresh", response_model=IncStateResp) def pyc_inc_refresh(): """ Incremental refresh: chỉ xử lý file mới kể từ lần trước. Frontend nên gọi endpoint này khi mở mục để cập nhật nhanh. """ cache = _load_cache() out = _refresh_cache(cache) nums = [v.get("num") for v in cache["files"].values() if isinstance(v, dict) and v.get("num") is not None] newest = max(nums) if nums else None return {"repo_id": cache["repo_id"], "scope": cache["scope"], "known": out["known"], "added": out["added"], "newest_num": newest} @router_pyc_inc.get("/stats", response_model=IncStatsResp) def pyc_inc_stats( month: Optional[int] = Query(default=None, ge=1, le=12), period: Optional[str] = Query(default=None, regex=r"^(1_15|16_31)$"), refresh_first: bool = Query(default=True) ): """ Lấy thống kê nhanh từ cache. Nếu refresh_first=true → xử lý file mới trước khi trả kết quả. """ cache = _load_cache() if refresh_first: _refresh_cache(cache) totals = {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0} revenue= {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0} customers = set() used_files = [] def _ok(meta) -> bool: return isinstance(meta, dict) and "error" not in meta for rp, meta in cache["files"].items(): if not _ok(meta): continue if month is not None and meta.get("month") != month: continue if period is not None and _period_of(meta.get("day")) != period: continue t = meta.get("totals", {}); r = meta.get("revenue", {}) for k in totals: totals[k] += float(t.get(k, 0)) for k in revenue: revenue[k] += float(r.get(k, 0)) if meta.get("customer"): customers.add(meta["customer"]) used_files.append(rp) for k in totals: totals[k] = round(totals[k], 2) for k in revenue: revenue[k] = round(revenue[k], 0) return { "month": month, "period": period, "totals": totals, "revenue": revenue, "customers": sorted(customers), "files": used_files } @router_pyc_inc.get("/list") def pyc_inc_list( month: Optional[int] = Query(default=None, ge=1, le=12), period: Optional[str] = Query(default=None, regex=r"^(1_15|16_31)$"), limit: int = Query(default=200, ge=1, le=1000), refresh_first: bool = Query(default=False) ): """ Danh sách file đã biết (từ cache), có thể lọc theo month/period. """ cache = _load_cache() if refresh_first: _refresh_cache(cache) out = [] for rp, meta in cache["files"].items(): if not isinstance(meta, dict) or "error" in meta: continue if month is not None and meta.get("month") != month: continue if period is not None and _period_of(meta.get("day")) != period: continue out.append({ "repo_path": rp, "num": meta.get("num"), "month": meta.get("month"), "day": meta.get("day"), "customer": meta.get("customer"), "totals": meta.get("totals"), "revenue": meta.get("revenue") }) out.sort(key=lambda x: (x.get("num") if x.get("num") is not None else 10**9, x["repo_path"])) return {"count": len(out), "items": out[:limit]} @router_pyc_inc.post("/reset") def pyc_inc_reset(): """ XÓA cache → lần sau /refresh sẽ build lại từ đầu. """ if os.path.exists(CACHE_PATH): os.remove(CACHE_PATH) return {"status": "ok", "msg": "Cache cleared"} # Đăng ký router mới app.include_router(router_pyc_inc) # ================== HẾT PHẦN PYC INCREMENTAL ==================