Spaces:
Sleeping

QLHT6 / app.py
doluong6's picture
Update app.py
68dfe1c verified
Raw History Blame Contribute Delete
32.8 kB
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from huggingface_hub import list_repo_files
from collections import defaultdict
from openpyxl import load_workbook
from huggingface_hub import hf_hub_download
import tempfile
from datetime import datetime
from fastapi.responses import JSONResponse
import os
import io
import base64
import pandas as pd
import matplotlib.pyplot as plt
from fastapi import APIRouter, HTTPException, Query
from urllib.parse import unquote
import traceback
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
from fastapi import APIRouter, Request, HTTPException
from huggingface_hub import upload_file
from fastapi import APIRouter, UploadFile, File, HTTPException
from huggingface_hub import upload_file
from io import BytesIO
from fastapi import Form
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
REPO_ID = "doluong6/Quatest1"
HF_TOKEN = os.environ.get("HF_TOKEN")
@app.get("/dem_pyc_tat_ca")
def dem_pyc_tat_ca():
try:
all_files = list_repo_files(
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN
)
# Lọc file PYC chỉ trong thư mục Phieu_yeu_cau của từng khách hàng
pyc_files = [
f for f in all_files
if f.startswith("Khach_hang/")
and "/6. Phieu yeu cau/" in f
and f.lower().endswith(".xlsx")
and len(f.split("/")) == 4 # Đảm bảo cấu trúc: Khach_hang/<KHACH>/Phieu_yeu_cau/<file.xlsx>
]
# Lọc file GCN trong thư mục Scan (đã hoàn thành)
gcn_files = [
f for f in all_files
if f.startswith("Khach_hang/")
and "/Scan/" in f
and "GCN" in os.path.basename(f).upper()
]
# Gom PYC theo khách hàng
thong_ke_pyc = defaultdict(list)
for f in pyc_files:
parts = f.split("/")
if len(parts) >= 3:
ten_khach = parts[1]
thong_ke_pyc[ten_khach].append(f)
# Gom GCN theo khách hàng
thong_ke_gcn = defaultdict(list)
for f in gcn_files:
parts = f.split("/")
if len(parts) >= 3:
ten_khach = parts[1]
thong_ke_gcn[ten_khach].append(f)
ket_qua = {}
tong_pyc = 0
tong_dang_xu_ly = 0
for khach, ds_pyc in thong_ke_pyc.items():
so_pyc = len(ds_pyc)
so_gcn = len(thong_ke_gcn.get(khach, []))
so_dxl = max(so_pyc - so_gcn, 0)
ket_qua[khach] = {
"tong_pyc": so_pyc,
"so_hoan_thanh": so_gcn,
"dang_xu_ly": so_dxl,
"danh_sach_pyc": ds_pyc
}
tong_pyc += so_pyc
tong_dang_xu_ly += so_dxl
return {
"tong_so_pyc": tong_pyc,
"tong_dang_xu_ly": tong_dang_xu_ly,
"khach_hang": ket_qua
}
except Exception as e:
return {"error": str(e)}
@app.get("/tong_doanh_thu_pyc")
async def tong_doanh_thu_pyc():
try:
all_files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
# ✅ Chỉ lấy file PYC trong thư mục "6. Phieu yeu cau"
pyc_files = [
f for f in all_files
if f.startswith("Khach_hang/")
and "/6. Phieu yeu cau/" in f
and f.endswith(".xlsx")
and len(f.split("/")) == 4 # Đảm bảo đúng cấu trúc: Khach_hang/<KHACH>/6. Phieu yeu cau/<file.xlsx>
]
tong_doanh_thu = 0
for file_path in pyc_files:
try:
local_path = hf_hub_download(
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN,
filename=file_path,
cache_dir="/tmp"
)
wb = load_workbook(local_path, data_only=True)
# ✅ Ưu tiên tìm sheet chứa "phương tiện"
sheet = None
for s in wb.sheetnames:
if "phương tiện" in s.lower():
sheet = wb[s]
break
if sheet is None:
sheet = wb.active
# ✅ Quét cột BX (cột 76), từ dòng 24 trở đi
for row in sheet.iter_rows(min_row=24, min_col=76, max_col=76):
cell = row[0]
val = cell.value
if isinstance(val, (int, float)):
tong_doanh_thu += val
elif isinstance(val, str):
try:
cleaned = float(val.replace(".", "").replace(",", "").strip())
tong_doanh_thu += cleaned
except:
pass
except Exception as e:
print(f"❌ Lỗi đọc file {file_path}: {e}")
return {"tong_doanh_thu": round(tong_doanh_thu, 2)}
except Exception as e:
return {"error": str(e)}
@app.get("/dem_pyc_hoan_thanh")
def dem_pyc_hoan_thanh():
try:
all_files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
hoan_thanh_files = [
f for f in all_files
if f.startswith("Khach_hang/")
and "/Scan/" in f
and "GCN" in os.path.basename(f).upper() # kiểm tra tên file chứa "GCN"
]
thong_ke = defaultdict(list)
for f in hoan_thanh_files:
parts = f.split("/")
if len(parts) >= 3:
ten_khach = parts[1]
thong_ke[ten_khach].append(f)
return {
"tong_so_hoan_thanh": len(hoan_thanh_files),
"khach_hang": {
khach: {
"so_hoan_thanh": len(files),
"danh_sach": files
}
for khach, files in thong_ke.items()
}
}
except Exception as e:
return {"error": str(e)}
@app.get("/pyc_chua_hoan_thanh")
def pyc_chua_hoan_thanh():
try:
all_files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
# Tìm các khách hàng có GCN
gcn_files = [
f for f in all_files
if f.startswith("Khach_hang/")
and "/Scan/" in f
and "GCN" in os.path.basename(f).upper()
]
khach_co_gcn = set(f.split("/")[1] for f in gcn_files if len(f.split("/")) >= 3)
# Tìm các file phiếu yêu cầu
pyc_files = [
f for f in all_files
if f.startswith("Khach_hang/")
and "/Phieu_yeu_cau/" in f
and f.endswith(".xlsx")
]
ket_qua = []
for file in pyc_files:
parts = file.split("/")
if len(parts) < 3:
continue
ten_khach = parts[1]
if ten_khach in khach_co_gcn:
continue # bỏ qua khách đã có GCN
try:
local = hf_hub_download(
repo_id=REPO_ID,
repo_type="dataset",
filename=file,
token=HF_TOKEN,
cache_dir="/tmp"
)
wb = load_workbook(local, data_only=True)
sheet = wb.active
# Mã phiếu yêu cầu: ô D3
pyc_code = str(sheet["D3"].value or "").strip()
# Khách hàng: I8 đến CD8
cols_kh = [
"I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X",
"Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK",
"AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX",
"AY","AZ","BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK",
"BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX",
"BY","BZ","CA","CB","CC","CD"
]
khach_hang = "".join(str(sheet[f"{col}8"].value or "") for col in cols_kh).strip()
# Ngày tạo phiếu: BM3:BN3 (ngày), BS3:BT3 (tháng), BX3:CA3 (năm)
ngay = "".join(str(sheet[f"{col}3"].value or "") for col in ["BM", "BN"]).strip()
thang = "".join(str(sheet[f"{col}3"].value or "") for col in ["BS", "BT"]).strip()
nam = "".join(str(sheet[f"{col}3"].value or "") for col in ["BX", "BY", "BZ", "CA"]).strip()
ngay_tao = f"{ngay}/{thang}/{nam}".strip("/")
ket_qua.append({
"Phiếu yêu cầu": pyc_code or "Không rõ",
"Khách hàng": khach_hang or "Không rõ",
"Ngày tạo phiếu": ngay_tao or "Không rõ"
})
except Exception as e:
print(f"Lỗi đọc {file}: {e}")
continue
return ket_qua
except Exception as e:
return {"error": str(e)}
@app.get("/ty_le_dich_vu")
def ty_le_dich_vu():
try:
# Tải file Excel từ dataset
local_path = hf_hub_download(
repo_id=REPO_ID,
repo_type="dataset",
filename="thong_ke_dich_vu.xlsx",
token=HF_TOKEN,
cache_dir="/tmp"
)
wb = load_workbook(local_path, data_only=True)
sheet = wb.active
result = {}
for row in range(2, 5): # Dòng 2–4 chứa dữ liệu
loai = sheet[f"A{row}"].value # Cột A: "Dịch vụ"
ty_le = sheet[f"C{row}"].value # Cột C: "Tỷ lệ (%)"
if loai and ty_le is not None:
result[loai.strip()] = float(ty_le)
return {
"Kiem_dinh": result.get("KĐ", 0),
"Hieu_chuan": result.get("HC", 0),
"Do_thu_nghiem": result.get("ĐTN", 0)
}
except Exception as e:
return {"error": str(e)}
@app.get("/ds_pyc_cho_xu_ly")
def ds_pyc_cho_xu_ly():
try:
all_files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
pyc_files = [
f for f in all_files
if f.startswith("Khach_hang/")
and "/Phieu_yeu_cau/" in f
and f.endswith(".xlsx")
]
ket_qua = []
ten_nguoi_lap_hop_le = [
"Nguyễn Duy Thảo", "Lê Danh Huy", "Nguyễn Mạnh Cường", "Trần Văn Dương", "Nguyễn Ngọc Vinh"
]
for file in pyc_files:
try:
ten_khach = file.split("/")[1]
thu_muc_pyc = file.split("/")[2]
# === KIỂM TRA ĐÃ CÓ GCN HAY CHƯA ===
has_gcn = any(
f.startswith(f"Khach_hang/{ten_khach}/{thu_muc_pyc}/Giay_chung_nhan/")
and "GCN" in f.upper()
for f in all_files
)
if has_gcn:
continue # bỏ qua phiếu đã có GCN (đã hoàn thành)
# === ĐỌC THÔNG TIN PYC ===
local = hf_hub_download(
repo_id=REPO_ID,
repo_type="dataset",
filename=file,
token=HF_TOKEN,
cache_dir="/tmp"
)
wb = load_workbook(local, data_only=True)
sheet = wb.active
ten_file = file.split("/")[-1]
nguoi_lap = sheet["AH51"].value
ngay = sheet["BM3"].value
thang = sheet["BS3"].value
nam = sheet["BX3"].value
if nguoi_lap not in ten_nguoi_lap_hop_le:
continue
ngay_lap = f"{int(ngay):02}/{int(thang):02}/{nam}" if all([ngay, thang, nam]) else "Không rõ"
thiet_bi_list = []
for row in range(24, 100):
ten_tb = sheet[f"D{row}"].value
so_luong = sheet[f"BM{row}"].value
if ten_tb and "tên loại dịch vụ" not in str(ten_tb).lower():
thiet_bi_list.append({
"Thiết bị": str(ten_tb).strip(),
"Số lượng": int(so_luong) if isinstance(so_luong, (int, float)) else 1
})
ket_qua.append({
"Khách hàng": ten_khach,
"File PYC": ten_file,
"Người lập": nguoi_lap,
"Ngày lập": ngay_lap,
"Danh sách thiết bị": thiet_bi_list
})
except Exception as e:
print(f"Lỗi đọc file {file}: {e}")
continue
return JSONResponse(content=ket_qua)
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=500)
@app.get("/doanh_thu_dich_vu")
def doanh_thu_dich_vu():
try:
FILE_NAME = "thong_ke_dich_vu.xlsx"
# Tải file Excel từ Hugging Face dataset
excel_path = hf_hub_download(
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN,
filename=FILE_NAME,
local_dir="/tmp"
)
df = pd.read_excel(excel_path)
# Vẽ biểu đồ từ cột "Tổng doanh thu"
labels = df["Dịch vụ"]
values = df["Tổng doanh thu"]
plt.figure(figsize=(6, 6))
colors = ['#4caf50', '#2196f3', '#ff9800']
plt.pie(values, labels=labels, autopct='%1.1f%%', colors=colors, startangle=140)
plt.title("Tỷ lệ doanh thu theo dịch vụ")
plt.axis('equal')
plt.tight_layout()
# Lưu vào buffer base64
buf = io.BytesIO()
plt.savefig(buf, format="png")
plt.close()
buf.seek(0)
b64_image = base64.b64encode(buf.read()).decode("utf-8")
return {
"data": df.to_dict(orient="records"),
"image_base64": b64_image
}
except Exception as e:
return {"error": str(e)}
@app.get("/doanh_thu_tong")
def doanh_thu_tong():
try:
local_file = hf_hub_download(
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN,
filename="Theo doi DTNB & DT 2025.xlsx",
cache_dir="/tmp"
)
wb = load_workbook(local_file, data_only=True)
# Lấy giá trị F100 và G100 từ sheet "Nội bộ"
sheet_nb = wb["Nội bộ"]
f100 = sheet_nb["F100"].value or 0
g100 = sheet_nb["G100"].value or 0
# Tính tổng cột F và I từ Tháng 1 đến Tháng 12
tong_F = tong_I = 0
for i in range(1, 13):
sheet_name = f"Tháng {i}"
if sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
for row in sheet.iter_rows(min_row=2):
f_val = row[5].value # Cột F
i_val = row[8].value # Cột I
if isinstance(f_val, (int, float)):
tong_F += f_val
if isinstance(i_val, (int, float)):
tong_I += i_val
tong_cong = f100 + g100 + tong_F + tong_I
return {"tong_doanh_thu": round(tong_cong, 2)}
except Exception as e:
return {"error": str(e)}
@app.get("/doanh_thu_theo_thang")
def doanh_thu_theo_thang():
try:
HF_TOKEN = os.getenv("HF_TOKEN")
REPO_ID = "doluong6/Quatest1"
FILENAME = "Theo doi DTNB & DT 2025.xlsx"
# Tải file Excel từ dataset
file_path = hf_hub_download(
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN,
filename=FILENAME,
cache_dir="/tmp"
)
wb = load_workbook(file_path, data_only=True)
doanh_thu = {}
for i in range(1, 13):
sheet_name = f"Tháng {i}"
if sheet_name not in wb.sheetnames:
continue
sheet = wb[sheet_name]
# Lấy các giá trị số trong cột F (bỏ None, chuỗi)
col_F = [cell.value for cell in sheet["F"] if isinstance(cell.value, (int, float))]
tong = sum(col_F)
doanh_thu[f"Tháng {i}"] = round(tong, 2)
return doanh_thu
except Exception as e:
return {"error": str(e)}
@app.get("/doanh_thu_noi_bo")
async def doanh_thu_noi_bo():
try:
HF_TOKEN = os.environ.get("HF_TOKEN")
ds = hf_hub_download(
repo_id="doluong6/Quatest1",
filename="Theo doi DTNB & DT 2025.xlsx",
repo_type="dataset",
token=HF_TOKEN,
cache_dir="/tmp"
)
wb = openpyxl.load_workbook(ds, data_only=True)
ws = wb["Nội bộ"]
data = []
tong_cd = 0
tong_di = 0
for row in ws.iter_rows(min_row=4):
phong = row[1].value # cột B
chuyen_den = row[5].value # cột F
chuyen_di = row[6].value # cột G
# ✅ Bỏ dòng trống và chỉ lấy các dòng có doanh thu > 0
if not phong:
continue
cd = chuyen_den if isinstance(chuyen_den, (int, float)) else 0
di = chuyen_di if isinstance(chuyen_di, (int, float)) else 0
if cd + di <= 0:
continue # Bỏ nếu không có doanh thu
data.append({
"Phòng": phong,
"Chuyển đến": cd,
"Chuyển đi": di
})
tong_cd += cd
tong_di += di
return {
"data": data,
"tong": {
"Tổng chuyển đến": tong_cd,
"Tổng chuyển đi": tong_di
}
}
except Exception as e:
print("❌ Lỗi xử lý doanh_thu_noi_bo:", e)
traceback.print_exc()
return JSONResponse(status_code=500, content={"error": str(e)})
@app.get("/xem_pdf")
def xem_pdf(file_name: str):
try:
HF_TOKEN = os.environ.get("HF_TOKEN")
if not HF_TOKEN:
raise Exception("❌ Thiếu HF_TOKEN")
repo_id = "doluong6/Quatest1"
repo_type = "dataset"
folder = "Tai_lieu"
normalized_request_name = unidecode(file_name).lower().strip()
print(f"📄 Đang tìm file: {normalized_request_name}")
# Lấy danh sách file
files = list_repo_files(repo_id=repo_id, repo_type=repo_type, token=HF_TOKEN)
tai_lieu_files = [f for f in files if f.startswith(folder + "/") and f.lower().endswith(".pdf")]
# Tìm file phù hợp
matched_file = None
for f in tai_lieu_files:
original_name = os.path.basename(f)
normalized_file_name = unidecode(original_name).lower().strip()
if normalized_file_name == normalized_request_name:
matched_file = f
break
if not matched_file:
raise HTTPException(status_code=404, detail=f"❌ Không tìm thấy file: {file_name}")
print(f"✅ Tải file: {matched_file}")
# ✅ Đảm bảo sử dụng cache dir hợp lệ
cache_dir = "/tmp/hf_cache"
os.makedirs(cache_dir, exist_ok=True)
os.environ["HF_HUB_CACHE"] = cache_dir
# ✅ Tải file
local_path = hf_hub_download(
repo_id=repo_id,
filename=matched_file,
repo_type=repo_type,
token=HF_TOKEN,
cache_dir=cache_dir
)
return FileResponse(local_path, media_type="application/pdf")
except Exception as e:
print("❌ LỖI:", traceback.format_exc())
return JSONResponse(status_code=500, content={"detail": str(e)})
@app.get("/danh_sach_pdf")
async def danh_sach_pdf():
try:
HF_TOKEN = os.environ.get("HF_TOKEN")
all_files = list_repo_files("doluong6/Quatest1", repo_type="dataset", token=HF_TOKEN)
pdfs = [f.split("/")[-1] for f in all_files if f.startswith("Tai_lieu/") and f.lower().endswith(".pdf")]
return JSONResponse(content={"pdfs": pdfs})
except Exception as e:
raise HTTPException(status_code=500, detail=f"Lỗi khi lấy danh sách PDF: {str(e)}")
@app.get("/quy_trinh")
async def quy_trinh():
try:
HF_TOKEN = os.environ.get("HF_TOKEN")
repo_id = "doluong6/Quatest1"
all_files = list_repo_files(
repo_id=repo_id,
repo_type="dataset",
token=HF_TOKEN
)
# Lọc các file thuộc thư mục Quy_trinh/ và có đuôi PDF, DOCX, XLSX
pdfs = [
f.split("/")[-1]
for f in all_files
if f.startswith("Quy_trinh/") and f.lower().endswith((".pdf", ".docx", ".xlsx"))
]
return {"pdfs": pdfs}
except Exception as e:
return {"pdfs": [], "error": str(e)}
@app.get("/danh_muc_thiet_bi")
async def danh_muc_thiet_bi():
try:
HF_TOKEN = os.environ.get("HF_TOKEN")
file_path = hf_hub_download(
repo_id="doluong6/Quatest1",
filename="Quan_ly_thiet_bi.xlsx",
repo_type="dataset",
token=HF_TOKEN,
cache_dir="/tmp"
)
# Đọc sheet
df = pd.read_excel(file_path, sheet_name="DUNG CU SU DUNG")
df = df.dropna(how='all') # Bỏ dòng trống
df = df.dropna(axis=1, how='all') # Bỏ cột trống
df = df.fillna("") # Thay NaN bằng chuỗi rỗng
# Trả về dạng list of dict
data = df.to_dict(orient="records")
return data
except Exception as e:
raise HTTPException(status_code=500, detail=f"Lỗi đọc danh mục thiết bị: {str(e)}")
def chuan_hoa_ngay(value):
if pd.isna(value):
return None
if isinstance(value, datetime):
return value
if isinstance(value, str):
for fmt in ("%d/%m/%Y", "%d-%m-%Y", "%Y-%m-%d", "%Y/%m/%d"):
try:
return datetime.strptime(value.strip(), fmt)
except:
continue
return None
@app.get("/quan_ly_hoa_chat")
async def quan_ly_hoa_chat():
try:
HF_TOKEN = os.environ.get("HF_TOKEN")
if not HF_TOKEN:
raise ValueError("Biến môi trường HF_TOKEN chưa được thiết lập.")
# Tải file từ Hugging Face dataset
file_path = hf_hub_download(
repo_id="doluong6/Quatest1",
filename="Quan_ly_hoa_chat.xlsx",
repo_type="dataset",
token=HF_TOKEN,
cache_dir="/tmp"
)
# Đọc dữ liệu từ sheet
df = pd.read_excel(file_path, sheet_name="HOA CHAT SU DUNG")
for col in df.columns:
if pd.api.types.is_datetime64_any_dtype(df[col]):
df[col] = df[col].dt.strftime('%Y-%m-%d')
df = df.fillna("")
# Chuyển STT về số nguyên (loại bỏ .0)
if "STT" in df.columns:
df["STT"] = df["STT"].apply(lambda x: str(int(float(x))) if str(x).replace('.', '', 1).isdigit() else str(x))
# Chuẩn hóa ngày hết hạn + tính tình trạng
def xu_ly_tinh_trang(row):
try:
het_han = pd.to_datetime(row['NGÀY HẾT HẠN'], errors='coerce')
today = pd.Timestamp.today()
if pd.isna(het_han):
return "KHÔNG RÕ"
diff = (het_han - today).days
if diff < 0:
return "HẾT HẠN"
elif diff <= 30:
return f"CÒN: {diff} NGÀY ⚠"
else:
return f"CÒN: {diff} NGÀY"
except:
return "KHÔNG RÕ"
df["TÌNH TRẠNG"] = df.apply(xu_ly_tinh_trang, axis=1)
# Trả về kết quả
columns = df.columns.tolist()
rows = df.astype(str).values.tolist()
return {"columns": columns, "rows": rows}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Lỗi đọc danh sách hóa chất: {str(e)}\n{traceback.format_exc()}")
@app.post("/cap_nhat_hoa_chat")
async def cap_nhat_hoa_chat(request: Request):
try:
# Nhận dữ liệu từ frontend
body = await request.json()
columns = body["columns"]
data = body["data"]
# Tạo DataFrame mới
df = pd.DataFrame(data, columns=columns)
# Chuẩn hóa STT
if "STT" in df.columns:
df["STT"] = df["STT"].apply(lambda x: str(int(float(x))) if str(x).replace('.', '', 1).isdigit() else x)
# Xử lý cột ngày: chuyển về 'YYYY-MM-DD' hoặc ""
for col in df.columns:
if "ngày" in col.lower():
df[col] = df[col].apply(lambda x: pd.to_datetime(x, errors="coerce").strftime('%Y-%m-%d')
if pd.notna(pd.to_datetime(x, errors="coerce")) else "")
# Ghi vào file Excel tạm
file_path = "/tmp/Quan_ly_hoa_chat.xlsx"
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "HOA CHAT SU DUNG"
for r in dataframe_to_rows(df, index=False, header=True):
ws.append(r)
wb.save(file_path)
# Upload lên Hugging Face Dataset
token = os.environ.get("HF_TOKEN")
if not token:
raise ValueError("Biến môi trường HF_TOKEN chưa được thiết lập.")
upload_file(
path_or_fileobj=file_path,
path_in_repo="Quan_ly_hoa_chat.xlsx",
repo_id="doluong6/Quatest1",
repo_type="dataset",
token=token
)
return {"message": "✅ Đã lưu dữ liệu mới thành công!"}
except Exception as e:
print("❌ Lỗi khi cập nhật hóa chất:\n", traceback.format_exc())
raise HTTPException(status_code=500, detail=f"Lỗi khi lưu: {str(e)}")
# Sau khi upload_file(...)
# Gửi cảnh báo nếu có hóa chất sắp hết hạn
try:
df_cb = df[df["TÌNH TRẠNG"].str.contains("HẾT HẠN|⚠", na=False)]
if not df_cb.empty:
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
api_key = os.environ["SENDGRID_API_KEY"]
email_nguoinhan = "doluong6@quatest1.com.vn" # ✅ bạn có thể thay đổi địa chỉ nhận
html_noi_dung = "<p>📢 <b>Cảnh báo hóa chất hết hạn hoặc sắp hết hạn:</b></p><ul>"
for _, row in df_cb.iterrows():
ten = row.get("TÊN HÓA CHẤT", "Không rõ")
han = row.get("NGÀY HẾT HẠN", "")
tt = row.get("TÌNH TRẠNG", "")
html_noi_dung += f"<li><b>{ten}</b> – Hạn: {han} – <span style='color:red'>{tt}</span></li>"
html_noi_dung += "</ul><br><p>Vui lòng kiểm tra và xử lý kịp thời.</p>"
message = Mail(
from_email="doluong6.quatest1@gmail.com",
to_emails=email_nguoinhan,
subject="⏰ Cảnh báo hóa chất hết/sắp hết hạn",
html_content=html_noi_dung
)
sg = SendGridAPIClient(api_key)
sg.send(message)
except Exception as e:
print("⚠ Gửi mail cảnh báo lỗi:", e)
@app.get("/hien_thi_hskh")
async def hien_thi_hskh():
try:
HF_TOKEN = os.environ["HF_TOKEN"]
file_path = hf_hub_download(
repo_id="doluong6/Quatest1",
filename="QLHS_LUU_2025.xlsx",
repo_type="dataset",
token=HF_TOKEN,
cache_dir="/tmp"
)
df = pd.read_excel(file_path, sheet_name="HSKH")
df = df.fillna("")
# ✅ Làm sạch tiêu đề cột: bỏ xuống dòng và khoảng trắng dư
df.columns = [str(col).replace("\n", " ").strip() for col in df.columns]
return {
"columns": df.columns.tolist(),
"rows": df.astype(str).values.tolist()
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/cap_nhat_hskh")
async def cap_nhat_hskh(request: Request):
try:
body = await request.json()
columns = body["columns"]
rows = body["rows"]
df = pd.DataFrame(rows, columns=columns)
file_path = hf_hub_download(
repo_id="doluong6/Quatest1",
filename="QLHS_LUU_2025.xlsx",
repo_type="dataset",
token=os.environ["HF_TOKEN"],
cache_dir="/tmp"
)
wb = openpyxl.load_workbook(file_path)
if "HSKH" in wb.sheetnames:
std = wb["HSKH"]
wb.remove(std)
ws = wb.create_sheet("HSKH")
for i, row in enumerate([columns] + rows):
for j, val in enumerate(row):
ws.cell(row=i+1, column=j+1, value=val)
temp_path = os.path.join(tempfile.gettempdir(), "QLHS_LUU_2025.xlsx")
wb.save(temp_path)
upload_file(
path_or_fileobj=temp_path,
path_in_repo="QLHS_LUU_2025.xlsx",
repo_id="doluong6/Quatest1",
repo_type="dataset",
token=os.environ["HF_TOKEN"]
)
return {"message": "✅ Cập nhật sheet HSKH thành công!"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Lỗi cập nhật HSKH: {str(e)}")
@app.post("/upload_pyc")
async def upload_pyc(file: UploadFile = File(...)):
try:
filename = file.filename
content = await file.read()
# === Đọc file Excel ===
wb = load_workbook(filename=BytesIO(content), data_only=True)
ws = wb.active
ten_khach = str(ws["I8"].value or "Khach_hang_khong_ten").strip()
ma_phieu = str(ws["D3"].value or "KHONG_CO_MA").strip().replace("/", "-")
thang = str(ws["BS3"].value or "00").zfill(2)
nam = str(ws["BX3"].value or "2025")
ten_khach_sach = ten_khach.replace("/", "-").replace("\\", "-").replace(" ", "_")
thu_muc_khach = f"{ten_khach_sach}_{nam}-{thang}_{ma_phieu}"
path_pyc_repo = f"Khach_hang/{thu_muc_khach}/Phieu_yeu_cau/{filename}"
# === Ghi file PYC lên repo ===
tmp_pyc = f"/tmp/{filename}"
with open(tmp_pyc, "wb") as f:
f.write(content)
upload_file(
path_or_fileobj=tmp_pyc,
path_in_repo=path_pyc_repo,
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN,
commit_message=f"Upload PYC {filename}"
)
return {"message": f"✅ Đã upload `{filename}` thành công và lưu vào thư mục `{thu_muc_khach}`."}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Lỗi xử lý: {e}")
@app.post("/upload_kemtheo")
async def upload_kemtheo(
khach_hang: str = Form(...),
loai_tai_lieu: str = Form(...), # Ví dụ: Scan, Hop_dong_thanh_ly, Ho_so_cong_tac, Giay_chung_nhan
file: UploadFile = File(...)
):
try:
# Lưu file tạm vào thư mục hệ thống
with tempfile.TemporaryDirectory() as temp_dir:
temp_file_path = os.path.join(temp_dir, file.filename)
with open(temp_file_path, "wb") as f:
content = await file.read()
f.write(content)
# Định dạng đường dẫn trên Hugging Face dataset
remote_path = f"Khach_hang/{khach_hang}/{loai_tai_lieu}/{file.filename}"
# Upload lên Hugging Face dataset
upload_file(
path_or_fileobj=temp_file_path,
path_in_repo=remote_path,
repo_id="doluong6/Quatest1",
repo_type="dataset",
token=os.environ.get("HF_TOKEN"),
commit_message=f"📎 Upload {loai_tai_lieu} cho {khach_hang}: {file.filename}"
)
return {"status": "success", "message": f"Đã upload {file.filename} vào {remote_path}"}
except Exception as e:
return {"status": "error", "message": str(e)}