Spaces:
Sleeping
Sleeping
Upload 10 files
Browse filesFiles changed (10)
- app/__init__.py+6-6
- app/auth.py+222-307
- app/cham_cong.py+167-338
- app/inventory.py+146-283
- app/pdf_warranty.pyAdded+124
- app/permissions.pyAdded+177
- app/report.py+235-68
- app/routes.py+19-25
- app/templates_config.pyAdded+12
- app/utils.py+16-1
1234567891011121314151617from fastapi import FastAPIfrom fastapi.staticfiles import StaticFilesfrom app.routes import router as auth_routerdef create_app() -> FastAPI:app = FastAPI(title="Center Hub Portal", version="1.0.0")# Mount static filesapp.mount("/static", StaticFiles(directory="static"), name="static")# Đăng ký các Routerapp.include_router(auth_router, prefix="/auth", tags=["Auth"]) # Đường dẫn sẽ bắt đầu bằng /authPreturn app1234567891011121314151617from pathlib import Pathfrom fastapi import FastAPIfrom fastapi.staticfiles import StaticFilesfrom app.routes import router as auth_router# Lấy đường dẫn thư mục 'app'BASE_DIR = Path(__file__).resolve().parentdef create_app() -> FastAPI:app = FastAPI(title="Center Hub Portal", version="1.0.0")# Chỉ định đúng thư mục app/staticapp.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static")app.include_router(auth_router, prefix="/auth", tags=["Auth"])return app
1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293945 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452461 unmodified line2482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433442 unmodified lines3473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184192 unmodified lines42242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245310 unmodified lines4644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125131 unmodified lineimport uuidfrom pathlib import Pathfrom typing import Optional, Dict, Any, Tuplefrom fastapi import APIRouter, Request, Form, status, HTTPExceptionfrom fastapi.responses import HTMLResponse, RedirectResponsefrom fastapi.templating import Jinja2Templatesfrom starlette.concurrency import run_in_threadpoolfrom config import supabase, supabase_adminlogger = logging.getLogger(__name__)router = APIRouter(prefix="/auth", tags=["Auth"])# Mã định danh cho App Trung tâm trong bảng user_sessionsAPP_CODE = "CENTER"# --- CẤU HÌNH THƯ MỤC TEMPLATES DÙNG CHUNG ---BASE_DIR = Path(__file__).resolve().parentTEMPLATES_DIR = (BASE_DIR.parent / "templates"if (BASE_DIR.parent / "templates").exists()else BASE_DIR / "templates")templates = Jinja2Templates(directory=str(TEMPLATES_DIR))# =========================================================# HELPER FUNCTIONS & DEPENDENCIES# =========================================================def render_template(request: Request,name: str,context: Optional[dict] = None,status_code: int = status.HTTP_200_OK,) -> HTMLResponse:"""Helper dùng chung để render Jinja template."""context = context or {}return templates.TemplateResponse(request=request,name=name,context=context,status_code=status_code,)def is_valid_password(password: str) -> Tuple[bool, Optional[str]]:"""Kiểm tra độ dài và tính hợp lệ cơ bản của mật khẩu."""if not password:return False, "Mật khẩu không được để trống."if len(password) < 6:return False, "Mật khẩu phải có ít nhất 6 ký tự."return True, Nonedef extract_user_from_session(request: Request) -> Optional[Dict[str, Any]]:"""Trích xuất và chuẩn hóa thông tin người dùng từ Cookie Session."""user_id = request.session.get("user_id")session_token = request.session.get("session_token")if not user_id or not session_token:return Noneho_ten = request.session.get("ho_ten") or "Quản trị viên"role = str(request.session.get("role") or "User").strip()# Lấy department từ session, nếu là super/system admin thì luôn là ALLdept = request.session.get("department")if role.lower() in SUPER_ADMIN_ROLES:dept = "ALL"else:dept = dept or "KTSC"return {"auth_id": str(user_id),"id": str(user_id),"email": request.session.get("user_email") or "","username": request.session.get("username") or "","ho_ten": ho_ten,"name": ho_ten,"role": role,"department": dept, # ✅ ĐÃ BỔ SUNG"access_token": request.session.get("access_token"),"session_token": session_token,}async def verify_active_session(user_id: str, session_token: str) -> bool:"""Kiểm tra session_token của App CENTER trong user_sessions bằng supabase_admin."""def _check():res = (supabase_admin.table("user_sessions")5 unmodified lines.execute())return bool(res and res.data)try:return await run_in_threadpool(_check)except Exception as e:logger.error(f"VERIFY SESSION ERROR: {e}")return True # Fallback nếu DB gặp sự cố kết nối tạm thờiasync def require_login(request: Request) -> Dict[str, Any]:"""Dependency bảo vệ các route API (Trả về JSON Error 401 khi hết session hoặc bị kick)."""user = extract_user_from_session(request)if not user:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Phiên làm việc đã hết hạn hoặc bạn chưa đăng nhập.",)is_valid = await verify_active_session(user["auth_id"], user["session_token"])if not is_valid:request.session.clear()raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Tài khoản của bạn đã được đăng nhập từ một thiết bị khác trên ứng dụng này.",)return userasync def get_current_user_or_redirect(request: Request) -> Optional[Dict[str, Any]]:"""Helper kiểm tra đăng nhập cho các route render giao diện HTML."""user = extract_user_from_session(request)if not user:return Noneis_valid = await verify_active_session(user["auth_id"], user["session_token"])if not is_valid:request.session.clear()return Nonereturn user# =========================================================# 1. ĐĂNG NHẬP (SINGLE SESSION PER APP_CODE ENFORCEMENT)# =========================================================SUPER_ADMIN_ROLES = {"super admin", "system admin"}def get_redirect_url_by_role(role: str) -> str:"""Xác định đường dẫn chuyển hướng theo từng cấp Role"""role_clean = str(role or "user").strip().lower()if role_clean == "admin":return "/cham-cong"elif role_clean in SUPER_ADMIN_ROLES:return "/admin"return "/"@router.get("/login", response_class=HTMLResponse)async def login_page(request: Request):"""Hiển thị trang đăng nhập."""if request.session.get("user_id"):user_role = request.session.get("role")redirect_url = get_redirect_url_by_role(user_role)return RedirectResponse(url=redirect_url, status_code=status.HTTP_303_SEE_OTHER)return render_template(request, "auth/login.html", {"error": None})@router.post("/login")async def login(request: Request,email: str = Form(...),password: str = Form(...),):"""Xác thực người dùng và bắt buộc chỉ cho phép 1 phiên làm việc duy nhất theo app_code."""email_clean = email.strip().lower()if not email_clean or not password:return render_template(request,"auth/login.html",{"error": "Vui lòng nhập đầy đủ email và mật khẩu."},status_code=status.HTTP_400_BAD_REQUEST,)try:# 1. Xác thực thông tin qua Supabase Authresponse = await run_in_threadpool(supabase.auth.sign_in_with_password,{"email": email_clean, "password": password})if not response or not response.user:return render_template(request,"auth/login.html",{"error": "Email hoặc mật khẩu không chính xác."},status_code=status.HTTP_401_UNAUTHORIZED,)auth_id = str(response.user.id)# 2. XÓA TẤT CẢ PHIÊN CŨ CỦA CÙNG (user_id, app_code)# Chỉ xóa phiên thuộc ứng dụng hiện tại (APP_CODE), giữ nguyên các app_code khácdef _clear_same_app_sessions():return (supabase_admin.table("user_sessions").delete().eq("user_id", auth_id).eq("app_code", APP_CODE).execute())await run_in_threadpool(_clear_same_app_sessions)# 3. Lấy IP và User Agent để tạo phiên mớix_forwarded_for = request.headers.get("x-forwarded-for")if x_forwarded_for:client_ip = x_forwarded_for.split(",")[0].strip()else:client_ip = request.client.host if request.client else "Unknown"user_agent = request.headers.get("user-agent", "Unknown")[:255]new_session_token = str(uuid.uuid4())# 4. Ghi nhận phiên làm việc mới cho APP_CODE nàydef _insert_new_session():return supabase_admin.table("user_sessions").insert({"user_id": auth_id,"app_code": APP_CODE,"session_token": new_session_token,"ip_address": client_ip,"user_agent": user_agent,}).execute()await run_in_threadpool(_insert_new_session)# 5. Lấy profile quản trị viên từ DBdef _fetch_user_profile():return (supabase_admin.table("quan_tri_vien").select("*")1 unmodified line.limit(1).execute())user_record = await run_in_threadpool(_fetch_user_profile)username = email_clean.split("@")[0]ho_ten = "Quản trị viên"role = "User"department = "KTSC" # Mặc địnhif user_record and user_record.data:user_info = user_record.data[0]username = user_info.get("username") or usernameho_ten = user_info.get("ho_ten") or user_info.get("name") or ho_tenrole = str(user_info.get("role") or "User").strip()department = str(user_info.get("department") or "KTSC").strip()# 🔥 Ép department thành 'ALL' nếu là tài khoản quản trị cấp caoif role.lower() in SUPER_ADMIN_ROLES:department = "ALL"# 6. Cập nhật Session Cookierequest.session.clear()request.session["user_id"] = auth_idrequest.session["session_token"] = new_session_tokenrequest.session["user_email"] = response.user.email or email_cleanrequest.session["username"] = usernamerequest.session["ho_ten"] = ho_tenrequest.session["role"] = rolerequest.session["department"] = department # ✅ LƯU PHÒNG BAN VÀO SESSIONif response.session:request.session["access_token"] = response.session.access_token# Chuyển hướng theo roleredirect_url = get_redirect_url_by_role(role)return RedirectResponse(url=redirect_url, status_code=status.HTTP_303_SEE_OTHER)except Exception as e:logger.error(f"LOGIN ERROR: {e}")error_msg = str(e).lower()if any(k in error_msg for k in ["invalid login credentials", "invalid_credentials", "email not confirmed"]):friendly_error = "Email hoặc mật khẩu không chính xác."else:friendly_error = "Không thể đăng nhập lúc này. Vui lòng thử lại sau."return render_template(request,"auth/login.html",{"error": friendly_error},status_code=status.HTTP_401_UNAUTHORIZED,)# =========================================================# 2. ĐĂNG XUẤT (LOGOUT)# =========================================================@router.get("/logout")async def logout(request: Request):"""Đăng xuất và xóa phiên làm việc hiện tại của App CENTER khỏi user_sessions."""user_id = request.session.get("user_id")session_token = request.session.get("session_token")if user_id and session_token:def _remove_session():return (supabase_admin.table("user_sessions").delete()3 unmodified lines.execute())try:await run_in_threadpool(_remove_session)except Exception as e:logger.error(f"LOGOUT DB ERROR: {e}")request.session.clear()return RedirectResponse(url="/auth/login", status_code=status.HTTP_303_SEE_OTHER)# =========================================================# 3. ĐỔI MẬT KHẨU / QUÊN MẬT KHẨU# =========================================================@router.get("/change-password", response_class=HTMLResponse)async def change_password_page(request: Request):if not request.session.get("user_id"):return RedirectResponse(url="/auth/login", status_code=status.HTTP_303_SEE_OTHER)return render_template(request, "auth/change_password.html", {"error": None, "success": None})2 unmodified linesrequest: Request,current_password: str = Form(...),new_password: str = Form(...),):user_id = request.session.get("user_id")email = request.session.get("user_email")if not user_id or not email:request.session.clear()return RedirectResponse(url="/auth/login", status_code=status.HTTP_303_SEE_OTHER)if not current_password:return render_template(request,"auth/change_password.html",{"error": "Vui lòng nhập mật khẩu hiện tại.", "success": None},status_code=status.HTTP_400_BAD_REQUEST,)valid, password_error = is_valid_password(new_password)if not valid:return render_template(request,"auth/change_password.html",{"error": password_error, "success": None},status_code=status.HTTP_400_BAD_REQUEST,)if current_password == new_password:return render_template(request,"auth/change_password.html",{"error": "Mật khẩu mới không được giống mật khẩu hiện tại.", "success": None},status_code=status.HTTP_400_BAD_REQUEST,)try:test_login = await run_in_threadpool(supabase.auth.sign_in_with_password,{"email": email, "password": current_password})if not test_login or not test_login.user or str(test_login.user.id) != str(user_id):return render_template(request,"auth/change_password.html",{"error": "Mật khẩu hiện tại không chính xác.", "success": None},status_code=status.HTTP_401_UNAUTHORIZED,)await run_in_threadpool(supabase.auth.update_user,{"password": new_password})return render_template(request,"auth/change_password.html",{"error": None, "success": "Đổi mật khẩu thành công!"},)except Exception as e:logger.error(f"CHANGE PASSWORD ERROR: {e}")return render_template(request,"auth/change_password.html",{"error": "Không thể đổi mật khẩu lúc này. Vui lòng thử lại.", "success": None},status_code=status.HTTP_400_BAD_REQUEST,)@router.get("/forgot-password", response_class=HTMLResponse)async def forgot_password_page(request: Request):return render_template(request, "auth/forgot_password.html", {"message": None, "error": None})2 unmodified lines@router.post("/forgot-password")async def forgot_password(request: Request, email: str = Form(...)):email_clean = email.strip().lower()if not email_clean:return render_template(request,"auth/forgot_password.html",{"message": None, "error": "Vui lòng nhập email."},status_code=status.HTTP_400_BAD_REQUEST,)message = ("Nếu email tồn tại trong hệ thống, hướng dẫn khôi phục ""mật khẩu đã được gửi. Vui lòng kiểm tra hộp thư.")try:base_url = str(request.base_url).rstrip("/")redirect_link = f"{base_url}/auth/update-password"await run_in_threadpool(supabase.auth.reset_password_for_email,email_clean,{"redirect_to": redirect_link})except Exception as e:logger.error(f"FORGOT PASSWORD ERROR: {e}")return render_template(request, "auth/forgot_password.html", {"message": message, "error": None})10 unmodified linesaccess_token: Optional[str] = Form(None),):if new_password != confirm_password:return render_template(request,"auth/update_password.html",{"error": "Xác nhận mật khẩu không khớp.", "success": None},status_code=status.HTTP_400_BAD_REQUEST,)valid, password_error = is_valid_password(new_password)if not valid:return render_template(request,"auth/update_password.html",{"error": password_error, "success": None},status_code=status.HTTP_400_BAD_REQUEST,)try:def _perform_update():if access_token:supabase.auth.set_session(access_token, "")return supabase.auth.update_user({"password": new_password})res = await run_in_threadpool(_perform_update)if not res or not res.user:raise ValueError("Cập nhật thất bại hoặc phiên làm việc đã hết hạn.")return render_template(request,"auth/update_password.html",{"error": None,"success": "Đặt lại mật khẩu thành công! Bạn có thể đăng nhập bằng mật khẩu mới.",},)except Exception as e:logger.error(f"UPDATE PASSWORD ERROR: {e}")return render_template(request,"auth/update_password.html",{"error": "Link khôi phục không hợp lệ hoặc đã hết hạn. Vui lòng yêu cầu lại.","success": None,},status_code=status.HTTP_400_BAD_REQUEST,)1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241255 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122131 unmodified line2152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033 unmodified lines3073083093103113123133143153163173183193203213223233243253262 unmodified lines3293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723732 unmodified lines37637737837938038138238338438538638738838939039139239310 unmodified lines4044054064074084094104114124134144154164174184194204214224234244254264274281 unmodified lineimport uuidfrom pathlib import Pathfrom typing import Optional, Dict, Any, Tuplefrom fastapi import APIRouter, Request, Form, status, HTTPException, Dependsfrom fastapi.responses import HTMLResponse, RedirectResponsefrom fastapi.templating import Jinja2Templatesfrom starlette.concurrency import run_in_threadpoolfrom config import supabase, supabase_adminfrom app.templates_config import templateslogger = logging.getLogger(__name__)router = APIRouter(prefix="/auth", tags=["Auth"])# =========================================================# CẤU HÌNH HẰNG SỐ# =========================================================APP_CODE = "CENTER"SUPER_ADMIN_ROLES = {"super admin", "system admin"}MIN_PASSWORD_LENGTH = 8 # ✅ Nâng từ 6 lên 8BASE_DIR = Path(__file__).resolve().parentTEMPLATES_DIR = (BASE_DIR.parent / "templates"if (BASE_DIR.parent / "templates").exists()else BASE_DIR / "templates")DEVICE_TYPE_DESKTOP = "desktop"DEVICE_TYPE_MOBILE = "mobile"DEFAULT_REDIRECT_URL = "/"# =========================================================# HELPER FUNCTIONS# =========================================================def render_template(request, name, context=None, status_code=200):return templates.TemplateResponse(request=request, name=name, context=context or {}, status_code=status_code)def is_valid_password(password: str) -> Tuple[bool, Optional[str]]:if not password:return False, "Mật khẩu không được để trống."if len(password) < MIN_PASSWORD_LENGTH:return False, f"Mật khẩu phải có ít nhất {MIN_PASSWORD_LENGTH} ký tự."return True, Nonedef detect_device_type(user_agent: str) -> str:ua = (user_agent or "").lower()mobile_keywords = ["android", "iphone", "ipad", "ipod", "mobile", "webos", "blackberry", "windows phone", "tablet"]return DEVICE_TYPE_MOBILE if any(k in ua for k in mobile_keywords) else DEVICE_TYPE_DESKTOPdef _is_auth_error(e: Exception) -> bool:"""Phân biệt lỗi xác thực thật vs lỗi hệ thống/DB."""msg = str(e).lower()auth_keywords = ["invalid login", "invalid credentials", "invalid_credentials","email not confirmed", "user not found", "invalid password","wrong password", "email not found", "user already registered",]return any(k in msg for k in auth_keywords)async def refresh_supabase_token_if_needed(request: Request) -> Optional[str]:"""Kiểm tra và tự động gia hạn Access Token bằng Refresh Token nếu đã hết hạn."""access_token = request.session.get("access_token")refresh_token = request.session.get("refresh_token")if not access_token or not refresh_token:return access_tokendef _check_and_refresh():try:# 1. Thử xác thực access_token hiện tại với Supabaseuser_res = supabase.auth.get_user(access_token)if user_res and user_res.user:return access_tokenexcept Exception:# 2. Nếu access_token hết hạn, thử dùng refresh_token để lấy cặp token mớitry:res = supabase.auth.refresh_session(refresh_token)if res and res.session:# Cập nhật token mới vào session cookierequest.session["access_token"] = res.session.access_tokenrequest.session["refresh_token"] = res.session.refresh_tokenlogger.info("✅ Auto-refreshed Supabase Access Token successfully!")return res.session.access_tokenexcept Exception as refresh_err:logger.error(f"❌ Refresh Token failed/expired: {refresh_err}")return Nonereturn await run_in_threadpool(_check_and_refresh)def extract_user_from_session(request: Request) -> Optional[Dict[str, Any]]:"""Trích xuất và chuẩn hóa thông tin user từ request.session."""session = request.sessionuser_id = session.get("user_id")if not user_id:return None# Trả về Dict thống nhất cho toàn bộ hệ thốngreturn {"auth_id": user_id, # Map user_id sang auth_id để khớp với require_login & verify_active_session"user_id": user_id,"session_token": session.get("session_token"),"user_email": session.get("user_email"),"username": session.get("username"),"ho_ten": session.get("ho_ten"),"role": session.get("role"),"department": session.get("department"), # 👈 Đã được móc nối chính xác với /login"device_type": session.get("device_type"),"access_token": session.get("access_token"),"refresh_token": session.get("refresh_token"),}async def verify_active_session(user_id: str, session_token: str) -> bool:"""Kiểm tra session còn hiệu lực. ✅ Fail-closed: DB lỗi → từ chối."""def _check():res = (supabase_admin.table("user_sessions")5 unmodified lines.execute())return bool(res and res.data)try:return await run_in_threadpool(_check)except Exception as e:logger.error(f"VERIFY SESSION DB ERROR: {e}")return False # ✅ Fail-closed — KHÔNG còn return Trueasync def require_login(request: Request) -> Dict[str, Any]:"""Dependency cho API JSON → trả 401."""user = extract_user_from_session(request)if not user:raise HTTPException(status_code=401, detail="Chưa đăng nhập hoặc phiên đã hết hạn.")# 💡 Kiểm tra & Tự động gia hạn Supabase Access Token ngầmawait refresh_supabase_token_if_needed(request)if not await verify_active_session(user["auth_id"], user["session_token"]):request.session.clear()raise HTTPException(status_code=401, detail="Tài khoản đã được đăng nhập từ thiết bị khác cùng loại.")return user# ✅ Thêm alias cho dễ importget_current_user = require_loginasync def get_current_user_or_redirect(request: Request) -> Optional[Dict[str, Any]]:"""Dependency cho trang HTML → trả None, route tự redirect."""user = extract_user_from_session(request)if not user:return Noneif not await verify_active_session(user["auth_id"], user["session_token"]):request.session.clear()return Nonereturn user# =========================================================# 1. ĐĂNG NHẬP# =========================================================@router.get("/login", response_class=HTMLResponse)async def login_page(request: Request):if request.session.get("user_id"):return RedirectResponse(url=DEFAULT_REDIRECT_URL,status_code=status.HTTP_303_SEE_OTHER,)return render_template(request, "auth/login.html", {"error": None})@router.post("/login")async def login(request: Request, email: str = Form(...), password: str = Form(...)):email_clean = email.strip().lower()if not email_clean or not password:return render_template(request, "auth/login.html", {"error": "Vui lòng nhập đầy đủ email và mật khẩu."}, status_code=400)# BƯỚC 1: Xác thực Supabase — tách riêng để phân biệt lỗitry:response = await run_in_threadpool(supabase.auth.sign_in_with_password,{"email": email_clean, "password": password},)except Exception as e:if _is_auth_error(e):logger.info(f"LOGIN FAILED (sai thông tin): {email_clean} — {e}")return render_template(request, "auth/login.html", {"error": "Email hoặc mật khẩu không chính xác."}, status_code=401)logger.error(f"LOGIN SYSTEM ERROR (Supabase): {e}", exc_info=True)return render_template(request, "auth/login.html", {"error": "Hệ thống tạm thời gián đoạn, vui lòng thử lại sau."}, status_code=503)if not response or not response.user:return render_template(request, "auth/login.html", {"error": "Email hoặc mật khẩu không chính xác."}, status_code=401)auth_id = str(response.user.id)# BƯỚC 2: Lấy profile + đồng bộ session — lỗi ở đây KHÔNG phải sai mật khẩutry:def _fetch_profile():return (supabase_admin.table("quan_tri_vien").select("*")1 unmodified line.limit(1).execute())user_record = await run_in_threadpool(_fetch_profile)username = email_clean.split("@")[0]ho_ten = "Quản trị viên"role = "user"department = "KTSC"if user_record and user_record.data:info = user_record.data[0]username = info.get("username") or usernameho_ten = info.get("ho_ten") or info.get("name") or ho_tenrole = str(info.get("role") or "user").strip().lower() # ✅ Chuẩn hóa lowerdepartment = "ALL" if role in SUPER_ADMIN_ROLES else str(info.get("department") or "KTSC").strip()xff = request.headers.get("x-forwarded-for")client_ip = xff.split(",")[0].strip() if xff else (request.client.host if request.client else "Unknown")user_agent = (request.headers.get("user-agent") or "Unknown")[:255]device_type = detect_device_type(user_agent)new_session_token = str(uuid.uuid4())def _sync_db_session() -> int:old = (supabase_admin.table("user_sessions").select("session_token").eq("user_id", auth_id).eq("app_code", APP_CODE).eq("device_type", device_type).execute())old_count = len(old.data) if old and old.data else 0if old_count:supabase_admin.table("user_sessions").delete() \.eq("user_id", auth_id).eq("app_code", APP_CODE) \.eq("device_type", device_type).execute()logger.info(f"Kick {old_count} session {device_type} cũ của user {auth_id}")supabase_admin.table("user_sessions").insert({"user_id": auth_id, "app_code": APP_CODE,"session_token": new_session_token,"ip_address": client_ip, "user_agent": user_agent,"device_type": device_type,}).execute()return old_countkicked_count = await run_in_threadpool(_sync_db_session)except Exception as e:# Lỗi DB sau khi xác thực thành công → báo hệ thống, KHÔNG báo sai mật khẩulogger.error(f"LOGIN SYSTEM ERROR (profile/session): {e}", exc_info=True)return render_template(request, "auth/login.html", {"error": "Hệ thống tạm thời gián đoạn, vui lòng thử lại sau."}, status_code=503)# BƯỚC 3: Lưu session (Đã bổ sung refresh_token)request.session.clear()request.session.update({"user_id": auth_id,"session_token": new_session_token,"user_email": response.user.email or email_clean,"username": username,"ho_ten": ho_ten,"role": role,"department": department,"device_type": device_type,"access_token": response.session.access_token if response.session else None,"refresh_token": response.session.refresh_token if response.session else None, # 👈 BỔ SUNG DÒNG NÀY})if kicked_count:logger.info(f"User {auth_id} đăng nhập từ {device_type}, {kicked_count} thiết bị cùng loại bị đăng xuất.")# ✅ Đã thêm status_code 303 See Otherreturn RedirectResponse(url=DEFAULT_REDIRECT_URL,status_code=status.HTTP_303_SEE_OTHER)# =========================================================# 2. ĐĂNG XUẤT# =========================================================@router.get("/logout")async def logout(request: Request):user_id = request.session.get("user_id")session_token = request.session.get("session_token")if user_id and session_token:def _remove():return (supabase_admin.table("user_sessions").delete()3 unmodified lines.execute())try:await run_in_threadpool(_remove)except Exception as e:logger.error(f"LOGOUT DB ERROR: {e}")request.session.clear()return RedirectResponse(url="/auth/login", status_code=status.HTTP_303_SEE_OTHER)# =========================================================# 3. ĐỔI MẬT KHẨU — ✅ Kiểm tra phiên bằng Depends# =========================================================@router.get("/change-password", response_class=HTMLResponse)async def change_password_page(request: Request, user=Depends(get_current_user_or_redirect)):if not user:return RedirectResponse(url="/auth/login", status_code=status.HTTP_303_SEE_OTHER)return render_template(request, "auth/change_password.html", {"error": None, "success": None})2 unmodified linesrequest: Request,current_password: str = Form(...),new_password: str = Form(...),user=Depends(get_current_user_or_redirect),):if not user:return RedirectResponse(url="/auth/login", status_code=status.HTTP_303_SEE_OTHER)if not current_password:return render_template(request, "auth/change_password.html", {"error": "Vui lòng nhập mật khẩu hiện tại.", "success": None}, status_code=400)valid, password_error = is_valid_password(new_password)if not valid:return render_template(request, "auth/change_password.html", {"error": password_error, "success": None}, status_code=400)if current_password == new_password:return render_template(request, "auth/change_password.html", {"error": "Mật khẩu mới không được giống mật khẩu hiện tại.", "success": None}, status_code=400)try:test_login = await run_in_threadpool(supabase.auth.sign_in_with_password,{"email": user["email"], "password": current_password},)if not test_login or not test_login.user or str(test_login.user.id) != str(user["auth_id"]):return render_template(request, "auth/change_password.html", {"error": "Mật khẩu hiện tại không chính xác.", "success": None}, status_code=401)await run_in_threadpool(supabase_admin.auth.admin.update_user_by_id,user["auth_id"],{"password": new_password},)return render_template(request, "auth/change_password.html", {"error": None, "success": "Đổi mật khẩu thành công!"})except Exception as e:if _is_auth_error(e):return render_template(request, "auth/change_password.html", {"error": "Mật khẩu hiện tại không chính xác.", "success": None}, status_code=401)logger.error(f"CHANGE PASSWORD SYSTEM ERROR: {e}", exc_info=True)return render_template(request, "auth/change_password.html", {"error": "Hệ thống tạm thời gián đoạn, vui lòng thử lại.", "success": None}, status_code=503)# =========================================================# 4. QUÊN & ĐẶT LẠI MẬT KHẨU# =========================================================@router.get("/forgot-password", response_class=HTMLResponse)async def forgot_password_page(request: Request):return render_template(request, "auth/forgot_password.html", {"message": None, "error": None})2 unmodified lines@router.post("/forgot-password")async def forgot_password(request: Request, email: str = Form(...)):email_clean = email.strip().lower()if not email_clean:return render_template(request, "auth/forgot_password.html", {"message": None, "error": "Vui lòng nhập email."}, status_code=400)message = "Nếu email tồn tại, hướng dẫn khôi phục đã được gửi. Vui lòng kiểm tra hộp thư."try:base_url = str(request.base_url).rstrip("/")await run_in_threadpool(supabase.auth.reset_password_for_email,email_clean,{"redirect_to": f"{base_url}/auth/update-password"},)except Exception as e:logger.error(f"FORGOT PASSWORD ERROR: {e}")return render_template(request, "auth/forgot_password.html", {"message": message, "error": None})10 unmodified linesaccess_token: Optional[str] = Form(None),):if new_password != confirm_password:return render_template(request, "auth/update_password.html", {"error": "Xác nhận mật khẩu không khớp.", "success": None}, status_code=400)valid, password_error = is_valid_password(new_password)if not valid:return render_template(request, "auth/update_password.html", {"error": password_error, "success": None}, status_code=400)token = access_token or request.query_params.get("access_token")if not token:return render_template(request, "auth/update_password.html", {"error": "Thiếu mã xác thực (access_token).", "success": None}, status_code=400)try:user_res = await run_in_threadpool(supabase_admin.auth.get_user, token)if not user_res or not user_res.user:raise ValueError("Token không hợp lệ")await run_in_threadpool(supabase_admin.auth.admin.update_user_by_id,str(user_res.user.id),{"password": new_password},)return render_template(request, "auth/update_password.html", {"error": None, "success": "Đặt lại mật khẩu thành công! Bạn có thể đăng nhập bằng mật khẩu mới."})except Exception as e:logger.error(f"UPDATE PASSWORD ERROR: {e}")return render_template(request, "auth/update_password.html", {"error": "Link khôi phục không hợp lệ hoặc đã hết hạn.", "success": None}, status_code=400)
3 unmodified lines456789105 unmodified lines1617181920218 unmodified lines3031323334353637383940414260 unmodified lines1031041051061071081091 unmodified line111112113114115116117183 unmodified lines30130230330430530630762 unmodified lines37037137237337437537623 unmodified lines40040140240340440540640740840941041141241341441541674 unmodified lines4914924934944954964972 unmodified lines50050150250350450550631 unmodified lines53853954054154254354454554654735 unmodified lines5835845855865875885895905915925938 unmodified lines6026036046056066076082 unmodified lines6116126136146156166173 unmodified lines62162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967055 unmodified lines7267277287297307317327337347353 unmodified lines7397407417427437447453 unmodified lines74975075175275375475575638 unmodified lines79579679779879980080141 unmodified lines84384484584684784884911 unmodified lines86186286386486586686786827 unmodified lines8968978988999009019029039049055 unmodified lines9119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429437 unmodified lines9519529539549559569579589599608 unmodified lines969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410252 unmodified lines102810291030103110321033103410357 unmodified lines1043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312643 unmodified linesimport uuidfrom datetime import datetime, timezone, timedeltafrom pathlib import Pathfrom typing import Optional, Tuple, Dict, Anyfrom zoneinfo import ZoneInfofrom PIL import Image, ImageOps5 unmodified linesfrom app.auth import require_loginfrom config import supabase # Supabase client instancelogger = logging.getLogger(__name__)8 unmodified linesif not TEMPLATES_DIR.exists():logger.error(f"CRITICAL: Không tìm thấy thư mục templates tại: {TEMPLATES_DIR}")templates = Jinja2Templates(directory=str(TEMPLATES_DIR))router = APIRouter(prefix="/cham-cong", tags=["Chấm Công Lắp Đặt"])# ZoneInfo cho Việt NamVN_TZ = ZoneInfo("Asia/Ho_Chi_Minh")# ==========================================# 1. HELPER FUNCTIONS & LOGIC CHẤM CÔNG# ==========================================60 unmodified linesdef process_image(file_bytes: bytes, rotation: int = 0) -> bytes:"""Sửa hướng EXIF tự động, xoay ảnh và tối ưu dung lượng."""try:img = Image.open(io.BytesIO(file_bytes))img = ImageOps.exif_transpose(img)1 unmodified lineif rotation != 0:img = img.rotate(-rotation, expand=True)if img.mode in ("RGBA", "P"):img = img.convert("RGB")buffer = io.BytesIO()183 unmodified linesgia_thuong_luong: float) -> str:"""Tạo ghi chú nội dung tổng hợp (Đã fix lỗi trùng lặp khi Edit)"""clean_base = re.sub(r'\s*\[.*?\]$', '', noi_dung_goc.strip())details = []if is_di_tinh:62 unmodified lines# 2. Kiểm tra quyền xem phiếu (IDOR Protection)user_role = str(current_user.get("role", "")).strip().lower()is_admin = user_role in ["admin", "super admin", "system admin"]item_owner = str(item.get("username") or "")current_username = str(current_user.get("username") or "")23 unmodified linesreturn RedirectResponse(url=REDIRECT_URL, status_code=status.HTTP_303_SEE_OTHER)from typing import Optionalimport loggingfrom fastapi import APIRouter, Request, Dependsfrom fastapi.responses import HTMLResponselogger = logging.getLogger(__name__)# ✅ Khai báo tập hợp role Admin chuẩn chữ thường để tái sử dụngADMIN_ROLES = {"admin", "super admin", "system admin"}@router.get("/form", response_class=HTMLResponse)async def get_form_cham_cong(request: Request,74 unmodified linesso_hd: str,current_user: dict = Depends(require_login)):"""API tra cứu hóa đơn theo số HD để chỉnh sửa"""try:so_hd_clean = re.sub(r'\s+', '', so_hd.strip().upper())if not so_hd_clean:2 unmodified linescontent={"success": False, "message": "❌ Vui lòng nhập số hóa đơn!"})res = supabase.table("cham_cong").select("id, so_hoa_don").ilike("so_hoa_don", f"%{so_hd_clean}%").limit(1).execute()if res.data and len(res.data) > 0:return JSONResponse(status_code=status.HTTP_200_OK, content={"success": True, "data": res.data[0]})31 unmodified linestarget_username: Optional[str] = Form(None),edit_id: Optional[str] = Form(None),existing_image_url: Optional[str] = Form(None),file: Optional[UploadFile] = File(None)):try:# 1. VALIDATION CÁC TRƯỜNG ĐẦU VÀOclean_noi_dung = noi_dung.strip()if not clean_noi_dung or len(clean_noi_dung) < 8:return JSONResponse(35 unmodified linessession_user = current_user.get("username", "system_user")session_fullname = current_user.get("ho_ten") or current_user.get("username", "system_user")user_role = str(current_user.get("role") or "User").strip()# 2. KIỂM TRA QUYỀN CHỈNH SỬAif parsed_edit_id:existing_res = supabase.table("cham_cong").select("username, trang_thai").eq("id", parsed_edit_id).execute()if not existing_res.data:return JSONResponse(status_code=status.HTTP_404_NOT_FOUND,8 unmodified linescontent={"success": False, "message": "❌ Đơn này đã được duyệt, không thể chỉnh sửa!"})is_owner = (existing_record.get("username") == session_user) or (user_role in ("admin", "super admin", "system admin"))if not is_owner:return JSONResponse(status_code=status.HTTP_403_FORBIDDEN,2 unmodified lines# 3. XÁC ĐỊNH NGƯỜI ĐƯỢC CHẤM CÔNGif target_username and target_username.strip():if user_role in ("admin", "super admin", "system admin"):target_user = target_username.strip()try:emp_res = supabase.table("quan_tri_vien").select("ho_ten").eq("username", target_user).limit(1).execute()3 unmodified lineselse:target_user = session_userho_ten_target = session_fullnameelse:target_user = session_userho_ten_target = session_fullname# 4. KIỂM TRA TRÙNG SỐ HÓA ĐƠNhop_le, final_hd = check_duplicate_invoice(so_hoa_don, parsed_edit_id)if not hop_le:return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,content={"success": False, "message": f"❌ Số hóa đơn {final_hd} đã tồn tại!"})# 5. XỬ LÝ ẢNH CHỨNG TỪfinal_image_url = existing_image_urlif file and file.filename:if not file.content_type.startswith("image/"):return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,content={"success": False, "message": "❌ Định dạng tệp đính kèm không hợp lệ! Chỉ chấp nhận file ảnh."})file_bytes = await file.read()if len(file_bytes) > 15 * 1024 * 1024:return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,content={"success": False, "message": "❌ Dung lượng ảnh quá lớn (vượt quá 15MB)!"})processed_bytes = process_image(file_bytes, image_rotation)cloud_url = upload_image_to_supabase(processed_bytes, file.filename)if cloud_url:final_image_url = cloud_urlelse:return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,content={"success": False, "message": "❌ Lỗi upload ảnh lên Cloud Storage!"})if not final_image_url:return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,content={"success": False, "message": "❌ Yêu cầu ảnh đính kèm chứng từ!"})# 6. CHUẨN HÓA THÔNG TIN ĐẦU VÀOactual_so_nguoi_di_cung = so_nguoi_di_cung if is_hotro_khac else 0actual_so_ngay_an = so_ngay_an if is_di_tinh else 055 unmodified lines# 10. LƯU VÀO DB SUPABASEif parsed_edit_id:supabase.table("cham_cong").update(data_payload).eq("id", parsed_edit_id).execute()msg = f"✏️ Đã cập nhật hóa đơn {final_hd}!"else:supabase.table("cham_cong").insert(data_payload).execute()msg = f"🎉 Đã gửi phiếu {final_hd} chờ duyệt!"return JSONResponse(status_code=status.HTTP_200_OK, content={"success": True, "message": msg})3 unmodified linesstatus_code=status.HTTP_500_INTERNAL_SERVER_ERROR,content={"success": False, "message": f"❌ Lỗi hệ thống: {str(e)}"})@router.post("/api/duyet/{item_id}")async def duyet_phieu(request: Request,3 unmodified lines):"""Phê duyệt / Từ chối phiếu (Chỉ dành cho Admin)"""try:user_role = str(current_user.get("role") or "User").strip()if user_role not in ("admin", "super admin", "system admin"):return JSONResponse(status_code=status.HTTP_403_FORBIDDEN,content={"success": False, "message": "❌ Từ chối truy cập: Bạn không có quyền quản trị!"}38 unmodified lines"""Xóa phiếu chấm công (Admin xóa mọi phiếu, User chỉ xóa phiếu của chính mình khi chưa duyệt)"""try:session_user = current_user.get("username", "")user_role = str(current_user.get("role") or "User").strip()existing_res = supabase.table("cham_cong").select("username, trang_thai").eq("id", item_id).execute()if not existing_res.data:41 unmodified lines):"""Trang quản trị giao diện điều chỉnh định mức chấm công cho Admin"""user_role = str(current_user.get("role") or "User").strip()if user_role not in ("admin", "super admin", "system admin"):return HTMLResponse(content="<h3>❌ Bạn không có quyền truy cập trang này!</h3>", status_code=403)cfg = get_config_cham_cong()11 unmodified lines):"""API lưu toàn bộ thông số định mức mới vào Supabase (Gom Batch Upsert tối ưu hiệu năng)"""try:user_role = str(current_user.get("role") or "User").strip()if user_role not in ("admin", "super admin", "system admin"):return JSONResponse(status_code=status.HTTP_403_FORBIDDEN,content={"success": False, "message": "❌ Bạn không có quyền thực hiện thao tác này!"}27 unmodified linescontent={"success": False, "message": f"❌ Lỗi hệ thống: {str(e)}"})@router.get("", response_class=HTMLResponse)@router.get("/", response_class=HTMLResponse)@router.get("/list", response_class=HTMLResponse)async def view_danh_sach_cham_cong(request: Request,5 unmodified linesktv: Optional[str] = Query(None),limit: int = Query(100)):"""Giao diện danh sách đơn phân quyền theo User / Admin chuẩn 100% Schema DB"""try:# 1. ĐỌC DỮ LIỆU USER AN TOÀN (HỖ TRỢ CẢ DICT LẪN OBJECT)if isinstance(current_user, dict):raw_role = current_user.get("role") or "User"current_username = current_user.get("username") or ""else:raw_role = getattr(current_user, "role", "User")current_username = getattr(current_user, "username", "")# user_role_clean dùng để kiểm tra logic Pythonuser_role_clean = str(raw_role).strip().lower()is_admin = user_role_clean in ADMIN_ROLESnow = datetime.now()current_year = now.yearcurrent_month = now.monthselected_month = current_month if thang is None else thangselected_year = current_year if nam is None else nam# 2. Query dữ liệu từ Supabasequery = supabase.table("cham_cong").select("*")# 3. PHÂN QUYỀNif not is_admin:query = query.eq("username", current_username)# 4. LỌC THEO TRẠNG THÁIif status_filter and status_filter in ["Chờ duyệt", "Đã duyệt", "Từ chối"]:7 unmodified linesif selected_year > 0:if selected_month > 0:start_date = f"{selected_year}-{selected_month:02d}-01T00:00:00"if selected_month == 12:end_date = f"{selected_year + 1}-01-01T00:00:00"else:end_date = f"{selected_year}-{selected_month + 1:02d}-01T00:00:00"query = query.gte("thoi_gian", start_date).lt("thoi_gian", end_date)else:query = query.gte("thoi_gian", f"{selected_year}-01-01T00:00:00").lt("thoi_gian", f"{selected_year + 1}-01-01T00:00:00")8 unmodified linesf"so_hoa_don.ilike.%{clean_search}%")# 8. TRUY VẤN VÀ SẮP XẾP GẦN NHẤTres = query.order("id", desc=True).limit(limit).execute()danh_sach = res.data or []for idx, item in enumerate(danh_sach):try:danh_sach[idx] = parse_datetime_field(item)except Exception as parse_err:logger.warning(f"Lỗi parse datetime cho ID {item.get('id')}: {parse_err}")# ✅ 9. LẤY DANH SÁCH KTV CHO BỘ LỌC (DẠNG TUPLE 2 PHẦN TỬ CHUẨN JINJA2)danh_sach_ktv = []if is_admin:try:cc_res = supabase.table("cham_cong").select("username").execute()if cc_res.data:# Trích xuất username an toàn bất kể Dict hay Objectraw_usernames = []for item in cc_res.data:u = item.get("username") if isinstance(item, dict) else getattr(item, "username", None)if u:raw_usernames.append(u)attended_usernames = sorted(list(set(raw_usernames)))if attended_usernames:emp_res = (supabase.table("quan_tri_vien").select("username, ho_ten").in_("username", attended_usernames).execute())name_map = {}if emp_res.data:for emp in emp_res.data:u_val = emp.get("username") if isinstance(emp, dict) else getattr(emp, "username", None)h_val = emp.get("ho_ten") if isinstance(emp, dict) else getattr(emp, "ho_ten", None)if u_val:name_map[u_val] = h_val or u_val# ✅ Trả về Tuple 2 phần tử: (username, display_name)for u in attended_usernames:display_name = name_map.get(u, u)danh_sach_ktv.append((u, display_name))except Exception as ktv_err:logger.error(f"Lỗi tải danh sách KTV: {ktv_err}")error_message = request.session.pop("error_message", None)# ✅ 10. RENDER TEMPLATE (TRUYỀN RAW_ROLE GỐC ĐỂ KHÔNG LỖI IF/ELSE Ở JINJA2)return templates.TemplateResponse(request=request,name="installation/danh_sach_cham_cong.html",2 unmodified lines"danh_sach": danh_sach,"danh_sach_don": danh_sach,"current_user": current_user,"user_role": raw_role, # ✅ Giữ nguyên chữ hoa (Admin) cho Jinja2 Template"is_admin": is_admin, # ✅ Truyền thêm cờ boolean tiện lợi"current_username": current_username,"danh_sach_ktv": danh_sach_ktv,"selected_month": selected_month,7 unmodified lines})except Exception as e:logger.error(f"Lỗi tải danh sách chấm công: {str(e)}")return HTMLResponse(content=f"<h3>Lỗi hệ thống: {str(e)}</h3>", status_code=500)# ==========================================# BÁO CÁO TỔNG QUÁT SỐ LƯỢNG ĐƠN LẮP ĐẶT# ==========================================@router.get("/bao-cao-lap-dat", response_class=HTMLResponse)async def bao_cao_lap_dat(request: Request,start_date: Optional[str] = Query(None),end_date: Optional[str] = Query(None),username: Optional[str] = Query(None),user_payload: dict = Depends(require_login)):try:# ==========================================# 1. XỬ LÝ NGÀY MẶC ĐỊNH# ==========================================today = datetime.now(ZoneInfo("Asia/Ho_Chi_Minh")).date()if not end_date:end_date = today.strftime("%Y-%m-%d")if not start_date:start_date = (today - timedelta(days=30)).strftime("%Y-%m-%d")# ==========================================# 2. TRUY VẤN DỮ LIỆU CHẤM CÔNG# ==========================================query = (supabase.table("cham_cong").select("*").gte("thoi_gian",f"{start_date}T00:00:00").lte("thoi_gian",f"{end_date}T23:59:59"))if username:query = query.eq("username", username)res = query.execute()records = res.data or []# ==========================================# 3. KHỞI TẠO THỐNG KÊ# ==========================================staff_summary: Dict[str, Dict[str, Any]] = {}daily_trend: Dict[str, int] = {}total_orders = len(records)total_payout = 0.0total_km = 0.0# ==========================================# 4. HÀM CHUYỂN SỐ AN TOÀN# ==========================================def to_float(value):if value is None or value == "":return 0.0try:return float(value)except (TypeError, ValueError):return 0.0# ==========================================# 5. GOM NHÓM DỮ LIỆU# ==========================================for item in records:# Tên nhân viênstaff_name = (item.get("ten")or item.get("ho_ten")or item.get("username")or "Chưa rõ")# Ngàythoi_gian = item.get("thoi_gian")if thoi_gian:date_str = str(thoi_gian)[:10]else:date_str = "N/A"# Tiền và kmmoney = to_float(item.get("thanh_tien"))km = to_float(item.get("quang_duong"))# Tổng toàn bộtotal_payout += moneytotal_km += km# ======================================# Gom theo nhân viên# ======================================if staff_name not in staff_summary:staff_summary[staff_name] = {"count": 0,"total_money": 0.0,"total_km": 0.0}staff_summary[staff_name]["count"] += 1staff_summary[staff_name]["total_money"] += moneystaff_summary[staff_name]["total_km"] += km# ======================================# Gom theo ngày# ======================================daily_trend[date_str] = (daily_trend.get(date_str, 0) + 1)# ==========================================# 6. DANH SÁCH NHÂN VIÊN# ==========================================sorted_staff_list = []for name, info in sorted(staff_summary.items(),key=lambda x: x[1]["count"],reverse=True):sorted_staff_list.append({"name": name,"count": info["count"],"total_money": info["total_money"],"total_km": info["total_km"]})# ==========================================# 7. DỮ LIỆU BIỂU ĐỒ NHÂN VIÊN# ==========================================chart_staff_names = [item["name"]for item in sorted_staff_list]chart_staff_counts = [item["count"]for item in sorted_staff_list]# ==========================================# 8. DỮ LIỆU BIỂU ĐỒ THEO NGÀY# ==========================================sorted_dates = sorted(daily_trend.keys())chart_dates = sorted_dateschart_date_counts = [daily_trend[d]for d in sorted_dates]# ==========================================# 9. DANH SÁCH USER CHO DROPDOWN# ==========================================users_res = (supabase.table("quan_tri_vien").select("username, ho_ten").execute())all_users = users_res.data or []# ==========================================# 10. RENDER TEMPLATE# ==========================================return templates.TemplateResponse(request=request,name="admin/admin_report_cham_cong.html",context={"start_date": start_date,"end_date": end_date,"selected_user": username,"all_users": all_users,"total_orders": total_orders,"total_payout": total_payout,"total_km": total_km,"staff_list": sorted_staff_list,"chart_data": {"staffNames": chart_staff_names,"staffCounts": chart_staff_counts,"dates": chart_dates,"dateCounts": chart_date_counts,},},)except Exception as e:logger.error(f"Lỗi truy vấn báo cáo chấm công: {str(e)}",exc_info=True)return HTMLResponse(content=(f"Đã xảy ra lỗi khi tải báo cáo: {str(e)}"),status_code=500)3 unmodified lines456789105 unmodified lines161718192021222324258 unmodified lines343536373839404142434445464748495051525354555657585960616260 unmodified lines1231241251261271281291 unmodified line131132133134135136137183 unmodified lines32132232332432532632762 unmodified lines39039139239339439539623 unmodified lines42042142242342442574 unmodified lines5005015025035045055062 unmodified lines50951051151251351451551651751851952052131 unmodified lines55355455555655755855956056156256356456556656756835 unmodified lines6046056066076086096106116126136146156166176188 unmodified lines6276286296306316326332 unmodified lines6366376386396406416423 unmodified lines64664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371455 unmodified lines7707717727737747757767777787793 unmodified lines7837847857867877883 unmodified lines79279379479579679779879938 unmodified lines83883984084184284384441 unmodified lines88688788888989089189211 unmodified lines90490590690790890991091127 unmodified lines9399409419429439445 unmodified lines9509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989997 unmodified lines10071008100910101011101210138 unmodified lines102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010712 unmodified lines107410751076107710781079108010817 unmodified lines108910901091109210933 unmodified linesimport uuidfrom datetime import datetime, timezone, timedeltafrom pathlib import Pathfrom typing import Optional, Tuple, Dict, Any, Listfrom zoneinfo import ZoneInfofrom PIL import Image, ImageOps5 unmodified linesfrom app.auth import require_loginfrom config import supabase # Supabase client instancefrom app.templates_config import templatesfrom app.permissions import can_access, ROLE_LEVELSfrom config import supabase_adminfrom starlette.concurrency import run_in_threadpoollogger = logging.getLogger(__name__)8 unmodified linesif not TEMPLATES_DIR.exists():logger.error(f"CRITICAL: Không tìm thấy thư mục templates tại: {TEMPLATES_DIR}")router = APIRouter(prefix="/cham-cong", tags=["Chấm Công Lắp Đặt"])# ZoneInfo cho Việt NamVN_TZ = ZoneInfo("Asia/Ho_Chi_Minh")# ✅ Khai báo tập hợp role Admin chuẩn chữ thường để tái sử dụngADMIN_ROLES = {"admin", "super admin", "system admin"}def extract_user_info(user_obj: Any) -> Tuple[str, str, str, bool]:"""Helper trích xuất username, ho_ten, role chuẩn hóa và cờ is_admin an toàn."""if isinstance(user_obj, dict):username = str(user_obj.get("username") or "")ho_ten = str(user_obj.get("ho_ten") or user_obj.get("username") or "")raw_role = str(user_obj.get("role") or "user")else:username = str(getattr(user_obj, "username", ""))ho_ten = str(getattr(user_obj, "ho_ten", username))raw_role = str(getattr(user_obj, "role", "user"))clean_role = raw_role.strip().lower()is_admin = clean_role in ADMIN_ROLESreturn username, ho_ten, raw_role, is_admin# ==========================================# 1. HELPER FUNCTIONS & LOGIC CHẤM CÔNG# ==========================================60 unmodified linesdef process_image(file_bytes: bytes, rotation: int = 0) -> bytes:"""Sửa hướng EXIF tự động, xoay ảnh và chuyển đổi chế độ RGB chuẩn JPEG."""try:img = Image.open(io.BytesIO(file_bytes))img = ImageOps.exif_transpose(img)1 unmodified lineif rotation != 0:img = img.rotate(-rotation, expand=True)if img.mode != "RGB":img = img.convert("RGB")buffer = io.BytesIO()183 unmodified linesgia_thuong_luong: float) -> str:"""Tạo ghi chú nội dung tổng hợp (Đã fix lỗi trùng lặp khi Edit)"""clean_base = re.sub(r'(\s*\[.*?\])+$', '', noi_dung_goc.strip())details = []if is_di_tinh:62 unmodified lines# 2. Kiểm tra quyền xem phiếu (IDOR Protection)user_role = str(current_user.get("role", "")).strip().lower()is_admin = user_role in ADMIN_ROLESitem_owner = str(item.get("username") or "")current_username = str(current_user.get("username") or "")23 unmodified linesreturn RedirectResponse(url=REDIRECT_URL, status_code=status.HTTP_303_SEE_OTHER)@router.get("/form", response_class=HTMLResponse)async def get_form_cham_cong(request: Request,74 unmodified linesso_hd: str,current_user: dict = Depends(require_login)):"""API tra cứu hóa đơn theo số HD để chỉnh sửa (Đã fix lỗi crash & rò rỉ quyền)."""try:so_hd_clean = re.sub(r'\s+', '', so_hd.strip().upper())if not so_hd_clean:2 unmodified linescontent={"success": False, "message": "❌ Vui lòng nhập số hóa đơn!"})c_username, _, _, is_admin = extract_user_info(current_user)query = supabase.table("cham_cong").select("id, so_hoa_don").ilike("so_hoa_don", f"%{so_hd_clean}%")if not is_admin:query = query.eq("username", c_username)res = query.limit(1).execute()if res.data and len(res.data) > 0:return JSONResponse(status_code=status.HTTP_200_OK, content={"success": True, "data": res.data[0]})31 unmodified linestarget_username: Optional[str] = Form(None),edit_id: Optional[str] = Form(None),existing_image_url: Optional[str] = Form(None),files: Optional[List[UploadFile]] = File(None) # 🟢 ĐÃ NÂNG CẤP THÀNH DANH SÁCH NHIỀU FILE):try:# 1. VALIDATION CÁC TRƯỜNG ĐẦU VÀOif not so_hoa_don or not so_hoa_don.strip():return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,content={"success": False, "message": "❌ Vui lòng nhập số hóa đơn!"})clean_noi_dung = noi_dung.strip()if not clean_noi_dung or len(clean_noi_dung) < 8:return JSONResponse(35 unmodified linessession_user = current_user.get("username", "system_user")session_fullname = current_user.get("ho_ten") or current_user.get("username", "system_user")# Chuẩn hóa role về chữ thường để so sánh chính xác với ADMIN_ROLESuser_role = str(current_user.get("role") or "user").strip().lower()is_admin = user_role in ADMIN_ROLES# 2. KIỂM TRA QUYỀN CHỈNH SỬAexisting_record = Noneif parsed_edit_id:existing_res = supabase.table("cham_cong").select("username, ten, hinh_anh, trang_thai").eq("id", parsed_edit_id).execute()if not existing_res.data:return JSONResponse(status_code=status.HTTP_404_NOT_FOUND,8 unmodified linescontent={"success": False, "message": "❌ Đơn này đã được duyệt, không thể chỉnh sửa!"})is_owner = (existing_record.get("username") == session_user) or is_adminif not is_owner:return JSONResponse(status_code=status.HTTP_403_FORBIDDEN,2 unmodified lines# 3. XÁC ĐỊNH NGƯỜI ĐƯỢC CHẤM CÔNGif target_username and target_username.strip():if is_admin:target_user = target_username.strip()try:emp_res = supabase.table("quan_tri_vien").select("ho_ten").eq("username", target_user).limit(1).execute()3 unmodified lineselse:target_user = session_userho_ten_target = session_fullnameelif parsed_edit_id and existing_record:target_user = existing_record.get("username")ho_ten_target = existing_record.get("ten") or target_userelse:target_user = session_userho_ten_target = session_fullname# 4. KIỂM TRA TRÙNG SỐ HÓA ĐƠNhop_le, final_hd = check_duplicate_invoice(so_hoa_don.strip(), parsed_edit_id)if not hop_le:return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,content={"success": False, "message": f"❌ Số hóa đơn {final_hd} đã tồn tại!"})# 5. XỬ LÝ NHIỀU ẢNH CHỨNG TỪ (NÂNG CẤP XỬ LÝ BẮT FILE HÀNG LOẠT)url_list = []# Giữ lại danh sách ảnh cũ (nếu có khi sửa đơn)if existing_image_url and existing_image_url.strip():url_list = [u.strip() for u in existing_image_url.split(",") if u.strip()]# Xử lý toàn bộ danh sách tệp mới tải lênif files:for file_item in files:if file_item and file_item.filename:# Kiểm tra định dạng ảnhif not file_item.content_type.startswith("image/"):return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,content={"success": False, "message": f"❌ Tệp '{file_item.filename}' không đúng định dạng ảnh!"})# Đọc và kiểm tra dung lượngfile_bytes = await file_item.read()if len(file_bytes) > 15 * 1024 * 1024:return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,content={"success": False, "message": f"❌ Tệp '{file_item.filename}' vượt quá dung lượng 15MB!"})# Xoay ảnh (nếu cần) & Upload lên Storageprocessed_bytes = process_image(file_bytes, image_rotation)cloud_url = upload_image_to_supabase(processed_bytes, file_item.filename)if cloud_url:url_list.append(cloud_url)else:return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,content={"success": False, "message": f"❌ Lỗi upload tệp '{file_item.filename}' lên Storage!"})# Kiểm tra bắt buộc phải có ít nhất 1 ảnh chứng từif not url_list:return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,content={"success": False, "message": "❌ Vui lòng đính kèm ít nhất 1 ảnh hóa đơn chứng từ!"})# Chuỗi URL cuối cùng lưu CSDL (phân cách bởi dấu phẩy)final_image_url = ",".join(url_list)# 6. CHUẨN HÓA THÔNG TIN ĐẦU VÀOactual_so_nguoi_di_cung = so_nguoi_di_cung if is_hotro_khac else 0actual_so_ngay_an = so_ngay_an if is_di_tinh else 055 unmodified lines# 10. LƯU VÀO DB SUPABASEif parsed_edit_id:supabase.table("cham_cong").update(data_payload).eq("id", parsed_edit_id).execute()msg = f"✏️ Đã cập nhật hóa đơn {final_hd} ({len(url_list)} ảnh)!"else:supabase.table("cham_cong").insert(data_payload).execute()msg = f"🎉 Đã gửi phiếu {final_hd} chờ duyệt ({len(url_list)} ảnh)!"return JSONResponse(status_code=status.HTTP_200_OK, content={"success": True, "message": msg})3 unmodified linesstatus_code=status.HTTP_500_INTERNAL_SERVER_ERROR,content={"success": False, "message": f"❌ Lỗi hệ thống: {str(e)}"})@router.post("/api/duyet/{item_id}")async def duyet_phieu(request: Request,3 unmodified lines):"""Phê duyệt / Từ chối phiếu (Chỉ dành cho Admin)"""try:user_role = str(current_user.get("role") or "User").strip().lower()if user_role not in ADMIN_ROLES:return JSONResponse(status_code=status.HTTP_403_FORBIDDEN,content={"success": False, "message": "❌ Từ chối truy cập: Bạn không có quyền quản trị!"}38 unmodified lines"""Xóa phiếu chấm công (Admin xóa mọi phiếu, User chỉ xóa phiếu của chính mình khi chưa duyệt)"""try:session_user = current_user.get("username", "")user_role = str(current_user.get("role") or "User").strip().lower()existing_res = supabase.table("cham_cong").select("username, trang_thai").eq("id", item_id).execute()if not existing_res.data:41 unmodified lines):"""Trang quản trị giao diện điều chỉnh định mức chấm công cho Admin"""user_role = str(current_user.get("role") or "User").strip()if user_role not in ADMIN_ROLES:return HTMLResponse(content="<h3>❌ Bạn không có quyền truy cập trang này!</h3>", status_code=403)cfg = get_config_cham_cong()11 unmodified lines):"""API lưu toàn bộ thông số định mức mới vào Supabase (Gom Batch Upsert tối ưu hiệu năng)"""try:user_role = str(current_user.get("role") or "User").strip().lower()if user_role not in ADMIN_ROLES:return JSONResponse(status_code=status.HTTP_403_FORBIDDEN,content={"success": False, "message": "❌ Bạn không có quyền thực hiện thao tác này!"}27 unmodified linescontent={"success": False, "message": f"❌ Lỗi hệ thống: {str(e)}"})@router.get("/list", response_class=HTMLResponse)async def view_danh_sach_cham_cong(request: Request,5 unmodified linesktv: Optional[str] = Query(None),limit: int = Query(100)):"""Giao diện danh sách chấm công phân quyền theo Role & Cô lập dữ liệu theo Phòng ban."""# 1. KIỂM TRA QUYỀN TRUY CẬP TRANG (DYNAMIC RBAC)if not can_access('danh_sach_cham_cong', current_user):return HTMLResponse("<h2>⚠️ Bạn không có quyền truy cập trang Bảng Chấm Công!</h2>", status_code=403)try:# 2. ĐỌC THÔNG TIN USER AN TOÀN (ROLE & DEPARTMENT)if isinstance(current_user, dict):raw_role = current_user.get("role") or "User"current_username = current_user.get("username") or ""current_dept = str(current_user.get("department") or "KT").strip().upper()else:raw_role = getattr(current_user, "role", "User")current_username = getattr(current_user, "username", "")current_dept = str(getattr(current_user, "department", "KT")).strip().upper()user_role_clean = str(raw_role).strip().lower()user_level = ROLE_LEVELS.get(user_role_clean, 1)# Quyền Admin (Cấp >= 2) & Phạm vi xem toàn bộ công ty (System/Super Admin hoặc Department ALL)is_admin = user_level >= 2has_full_scope = (user_role_clean in ["system admin", "super admin"]) or (current_dept in ["ALL", "KT"])now = datetime.now()selected_month = now.month if thang is None else thangselected_year = now.year if nam is None else nam# 3. PHÂN QUYỀN VÀ CÔ LẬP DỮ LIỆU (DEPARTMENT SCOPE)# Bắt đầu dựng Queryquery = supabase_admin.table("cham_cong").select("*")if not is_admin:# User thường: Chỉ xem chấm công của chính mìnhquery = query.eq("username", current_username)elif not has_full_scope:# Admin phòng ban: Chỉ xem danh sách nhân viên thuộc phòng ban của mìnhdept_users_res = await run_in_threadpool(lambda: supabase_admin.table("quan_tri_vien").select("username").eq("department", current_dept).execute())dept_usernames = [u["username"] for u in (dept_users_res.data or []) if u.get("username")]query = query.in_("username", dept_usernames if dept_usernames else ["__NONE__"])# 4. LỌC THEO TRẠNG THÁIif status_filter and status_filter in ["Chờ duyệt", "Đã duyệt", "Từ chối"]:7 unmodified linesif selected_year > 0:if selected_month > 0:start_date = f"{selected_year}-{selected_month:02d}-01T00:00:00"end_date = f"{selected_year + 1}-01-01T00:00:00" if selected_month == 12 else f"{selected_year}-{selected_month + 1:02d}-01T00:00:00"query = query.gte("thoi_gian", start_date).lt("thoi_gian", end_date)else:query = query.gte("thoi_gian", f"{selected_year}-01-01T00:00:00").lt("thoi_gian", f"{selected_year + 1}-01-01T00:00:00")8 unmodified linesf"so_hoa_don.ilike.%{clean_search}%")# 8. THỰC THI TRUY VẤN BẤT ĐỒNG BỘ (TRÁNH BLOCK EVENT LOOP)res = await run_in_threadpool(lambda: query.order("id", desc=True).limit(limit).execute())danh_sach = res.data or []# Chuẩn hóa DateTime & Hình Ảnhfor item in danh_sach:try:parse_datetime_field(item)except Exception as parse_err:logger.warning(f"Lỗi parse datetime ID {item.get('id')}: {parse_err}")img_path = item.get("hinh_anh") or item.get("image_url") or ""if not img_path or str(img_path).strip().lower() in ["none", "null", "undefined", ""]:item["hinh_anh_valid"] = Noneelse:item["hinh_anh_valid"] = str(img_path).strip()# 9. LẤY DANH SÁCH KTV CHO BỘ LỌC (CÔ LẬP THEO PHÒNG BAN)danh_sach_ktv = []if is_admin:try:ktv_map = {}# Tìm danh sách nhân viên thuộc phạm vi quản lýemp_query = supabase_admin.table("quan_tri_vien").select("username, ho_ten")if not has_full_scope:emp_query = emp_query.eq("department", current_dept)emp_res = await run_in_threadpool(lambda: emp_query.execute())for emp in (emp_res.data or []):u_val = emp.get("username")h_val = emp.get("ho_ten")if u_val:ktv_map[u_val] = h_val or u_valdanh_sach_ktv = sorted([(u, name) for u, name in ktv_map.items()],key=lambda x: str(x[1]).lower())except Exception as ktv_err:logger.error(f"Lỗi tải danh sách KTV: {ktv_err}")error_message = request.session.pop("error_message", None)# 10. RENDER TEMPLATEreturn templates.TemplateResponse(request=request,name="installation/danh_sach_cham_cong.html",2 unmodified lines"danh_sach": danh_sach,"danh_sach_don": danh_sach,"current_user": current_user,"user_role": raw_role,"is_admin": is_admin,"current_username": current_username,"danh_sach_ktv": danh_sach_ktv,"selected_month": selected_month,7 unmodified lines})except Exception as e:logger.error(f"Lỗi tải danh sách chấm công: {str(e)}", exc_info=True)return HTMLResponse(content=f"<h3>Lỗi hệ thống: {str(e)}</h3>", status_code=500)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601614 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921 unmodified lines2312322332342352362372382395 unmodified lines2452462472482492502515 unmodified lines2572582592602612622632642652662672682692702712721 unmodified line2742752762772782792802812822831 unmodified line2852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983 unmodified lines4024034044054064074084094104113 unmodified lines41541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544610 unmodified lines45745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149215 unmodified lines5085095105115125135148 unmodified lines5235245255265275285295305315325335345351 unmodified line5375385395405415425435445457 unmodified lines5535545555565575585592 unmodified lines562563564565566567568import loggingimport refrom typing import Optional, Dict, Any, Listimport uuidfrom fastapi import APIRouter, Request, Query, HTTPException, Depends, status, Path as FastAPIPathfrom fastapi.responses import HTMLResponse, RedirectResponsefrom pydantic import BaseModel, Field, HttpUrl, field_validatorfrom config import supabasefrom app.templates_config import templatesfrom app.auth import require_login, get_current_user_or_redirect# ==========================================# CẤU HÌNH LOGGING & HẰNG SỐ# ==========================================logger = logging.getLogger("uvicorn.error")DEFAULT_PAGE_SIZE = 20MAX_PAGE_SIZE = 100MAX_SERIAL_LENGTH = 100MIN_SERIAL_LENGTH = 1MAX_BATCH_CODE_LENGTH = 50MAX_SCAN_SOURCE_LENGTH = 30MAX_CREATED_BY_NAME_LENGTH = 150SERIAL_ALLOWED_PATTERN = re.compile(r"^[A-Za-z0-9\-\_\.\/\+\#\:\s]+$")VALID_STATUSES = ("pending", "verified", "rejected", "completed")VALID_SCAN_SOURCES = ("scanner", "camera", "manual", "import")router = APIRouter(prefix="/inventory", tags=["Quản Lý Kho & Seri Máy In"])api_router = APIRouter(prefix="/api/inventory", tags=["API Kiểm Kê Seri Máy In"])# ==========================================# HÀM CHUẨN HÓA & TRÍCH XUẤT USER# ==========================================def normalize_serial_value(v: str) -> str:normalized = " ".join(v.strip().split()).upper()if not normalized:raise ValueError("Số seri không được để trống")if len(normalized) > MAX_SERIAL_LENGTH:raise ValueError(f"Số seri tối đa {MAX_SERIAL_LENGTH} ký tự")if not SERIAL_ALLOWED_PATTERN.match(normalized):raise ValueError("Số seri chứa ký tự không hợp lệ")return normalizeddef normalize_batch_code(v: Optional[str]) -> Optional[str]:if not v:return Nonecleaned = " ".join(v.strip().split())return cleaned[:MAX_BATCH_CODE_LENGTH] if cleaned else Nonedef normalize_scan_source(v: Optional[str]) -> str:if not v:return "scanner"cleaned = v.strip().lower()[:MAX_SCAN_SOURCE_LENGTH]return cleaned if cleaned in VALID_SCAN_SOURCES else "scanner"def validate_uuid(val: Any) -> bool:if not val:return Falsetry:uuid.UUID(str(val))return Trueexcept ValueError:return Falsedef extract_user_id(current_user: Any) -> Optional[str]:uid = current_user.get("id") if isinstance(current_user, dict) else getattr(current_user, "id", None)if uid and validate_uuid(uid):return str(uid)return Nonedef extract_user_name(current_user: Any) -> Optional[str]:fields = ("full_name", "ho_ten", "name", "username", "email")for key in fields:val = current_user.get(key) if isinstance(current_user, dict) else getattr(current_user, key, None)if val and str(val).strip():return str(val).strip()[:MAX_CREATED_BY_NAME_LENGTH]return Nonedef is_admin_user(current_user: Any) -> bool:if isinstance(current_user, dict):role = current_user.get("role", "") or current_user.get("user_role", "")is_admin_flag = current_user.get("is_admin", False)else:role = getattr(current_user, "role", "") or getattr(current_user, "user_role", "")is_admin_flag = getattr(current_user, "is_admin", False)return bool(is_admin_flag) or str(role).lower() in ("admin", "administrator", "manager", "quanly", "super admin", "system admin")# ==========================================# PYDANTIC SCHEMAS (KHỚP SCHEMA DB)# ==========================================class SerialScanRequest(BaseModel):serial_number: str = Field(..., min_length=MIN_SERIAL_LENGTH, max_length=MAX_SERIAL_LENGTH)printer_id: int = Field(..., gt=0)image_url: Optional[HttpUrl] = Nonebatch_code: Optional[str] = Field(None, max_length=MAX_BATCH_CODE_LENGTH)note: Optional[str] = Field(None, max_length=1000)scan_source: Optional[str] = Field("scanner", max_length=MAX_SCAN_SOURCE_LENGTH)@field_validator("serial_number")@classmethoddef validate_serial(cls, v: str) -> str:return normalize_serial_value(v)@field_validator("batch_code")@classmethoddef validate_batch(cls, v: Optional[str]) -> Optional[str]:return normalize_batch_code(v)@field_validator("scan_source")@classmethoddef validate_source(cls, v: Optional[str]) -> str:return normalize_scan_source(v)class BatchSerialItem(BaseModel):serial_number: str = Field(..., min_length=MIN_SERIAL_LENGTH, max_length=MAX_SERIAL_LENGTH)printer_id: int = Field(..., gt=0)image_url: Optional[HttpUrl] = Nonenote: Optional[str] = Field(None, max_length=1000)scan_source: Optional[str] = Field("scanner", max_length=MAX_SCAN_SOURCE_LENGTH)@field_validator("serial_number")@classmethoddef validate_item_serial(cls, v: str) -> str:return normalize_serial_value(v)@field_validator("scan_source")@classmethoddef validate_item_source(cls, v: Optional[str]) -> str:return normalize_scan_source(v)class BatchSerialScanRequest(BaseModel):batch_code: Optional[str] = Field(None, max_length=MAX_BATCH_CODE_LENGTH)items: List[BatchSerialItem] = Field(..., min_length=1, max_length=1000)@field_validator("batch_code")@classmethoddef validate_batch(cls, v: Optional[str]) -> Optional[str]:return normalize_batch_code(v)class StatusUpdateRequest(BaseModel):status: strnote: Optional[str] = Field(None, max_length=1000)@field_validator("status")@classmethod4 unmodified linesreturn normalizedclass BatchStatusRequest(BaseModel):ids: List[str] = Field(..., min_length=1, max_length=5000)status: strnote: Optional[str] = Field(None, max_length=1000)@field_validator("status")@classmethoddef validate_batch_status(cls, v: str) -> str:normalized = v.strip().lower()if normalized not in ("verified", "rejected", "pending", "completed"):raise ValueError("Trạng thái batch không hợp lệ.")return normalizedclass BatchDeleteRequest(BaseModel):ids: List[str] = Field(..., min_length=1, max_length=5000)# ==========================================# 1. HTML ROUTERS# ==========================================@router.get("/scan", response_class=HTMLResponse)def get_scan_page(request: Request, user: dict = Depends(get_current_user_or_redirect)):return templates.TemplateResponse(request=request,name="scan_inventory.html",context={"user": user, "page_title": "Barcode To Sheet · Kiểm Kê Seri"})@router.get("/admin/review", response_class=HTMLResponse)def get_admin_review_page(request: Request, current_user: dict = Depends(get_current_user_or_redirect)):if not is_admin_user(current_user):return RedirectResponse(url="/", status_code=303)return templates.TemplateResponse(request=request,name="admin/admin_inventory_review.html",context={"current_user": current_user})21 unmodified lines"status": "success","data": response.data or [],"pagination": {"page": page,"page_size": page_size,"total": total,"total_pages": (total + page_size - 1) // page_size if page_size else 1}}5 unmodified lines@api_router.post("/scan-serial", status_code=status.HTTP_201_CREATED)def create_serial_record(payload: SerialScanRequest, current_user: dict = Depends(require_login)):user_id = extract_user_id(current_user)user_name = extract_user_name(current_user)serial = payload.serial_numbertry:5 unmodified linesif not printer.data:raise HTTPException(status_code=400, detail="Model máy in không tồn tại!")data_to_insert: Dict[str, Any] = {"serial_number": serial,"printer_id": payload.printer_id,"image_url": str(payload.image_url) if payload.image_url else None,"created_by": user_id,"created_by_name": user_name,"status": "pending","batch_code": payload.batch_code,"note": payload.note.strip() if (payload.note and payload.note.strip()) else None,"scan_source": payload.scan_source}response = supabase.table("inventory_serials").insert(data_to_insert).execute()1 unmodified lineraise HTTPException(status_code=400, detail="Không thể lưu dữ liệu.")return {"status": "success","message": f"Đã lưu thành công Seri: {serial}","data": response.data[0],"printer_info": printer.data[0]}except HTTPException:raise1 unmodified lineerror_msg = str(e)if "duplicate key" in error_msg or "23505" in error_msg:raise HTTPException(status_code=409, detail=f"Mã Seri '{serial}' đã tồn tại trong hệ thống!")logger.exception("Lỗi lưu serial đơn lẻ: %s", error_msg)raise HTTPException(status_code=500, detail="Lỗi hệ thống khi lưu dữ liệu.")@api_router.post("/scan-serial/batch", status_code=status.HTTP_200_OK)def create_serial_records_batch(payload: BatchSerialScanRequest, current_user: dict = Depends(require_login)):"""Đồng bộ hàng loạt 1 phiếu (batch_code) lên public.inventory_serials."""user_id = extract_user_id(current_user)user_name = extract_user_name(current_user)unique_items: Dict[str, BatchSerialItem] = {}duplicate_in_payload: List[str] = []for item in payload.items:if item.serial_number in unique_items:duplicate_in_payload.append(item.serial_number)else:unique_items[item.serial_number] = itemserials = list(unique_items.keys())printer_ids = list({item.printer_id for item in unique_items.values()})try:printers_res = supabase.table("list_printer").select("id").in_("id", printer_ids).execute()valid_printer_ids = {row["id"] for row in (printers_res.data or [])}existing_res = supabase.table("inventory_serials").select("serial_number").in_("serial_number", serials).execute()existing_serials = {row["serial_number"] for row in (existing_res.data or [])}rows_to_insert: List[Dict[str, Any]] = []results: List[Dict[str, Any]] = []for dup in duplicate_in_payload:results.append({"serial_number": dup, "status": "duplicate", "reason": "Trùng lặp trong phiếu"})for serial, item in unique_items.items():if serial in existing_serials:results.append({"serial_number": serial, "status": "duplicate", "reason": "Đã tồn tại trên hệ thống"})continueif item.printer_id not in valid_printer_ids:results.append({"serial_number": serial, "status": "error", "reason": f"Model ID #{item.printer_id} không hợp lệ"})continuerows_to_insert.append({"serial_number": serial,"printer_id": item.printer_id,"image_url": str(item.image_url) if item.image_url else None,"created_by": user_id,"created_by_name": user_name,"status": "pending","batch_code": payload.batch_code,"note": item.note.strip() if (item.note and item.note.strip()) else None,"scan_source": item.scan_source})saved_map: Dict[str, Any] = {}if rows_to_insert:insert_res = supabase.table("inventory_serials").insert(rows_to_insert).execute()for r in (insert_res.data or []):saved_map[r["serial_number"]] = r.get("id")for row in rows_to_insert:sn = row["serial_number"]if sn in saved_map:results.append({"serial_number": sn, "status": "saved", "id": saved_map[sn]})else:results.append({"serial_number": sn, "status": "error", "reason": "Không thể ghi vào DB"})saved_count = sum(1 for r in results if r["status"] == "saved")dup_count = sum(1 for r in results if r["status"] == "duplicate")err_count = sum(1 for r in results if r["status"] == "error")return {"status": "success","batch_code": payload.batch_code,"summary": {"total": len(payload.items),"saved": saved_count,"duplicate": dup_count,"error": err_count},"results": results}except Exception as e:logger.exception("Lỗi đồng bộ batch serial: %s", str(e))raise HTTPException(status_code=500, detail="Lỗi hệ thống khi đồng bộ phiếu quét.")@api_router.get("/history", status_code=status.HTTP_200_OK)def get_scan_history(page: int = Query(1, ge=1),page_size: int = Query(DEFAULT_PAGE_SIZE, ge=1, le=MAX_PAGE_SIZE),status_filter: Optional[str] = Query(None),serial_search: Optional[str] = Query(None, max_length=100),batch_code: Optional[str] = Query(None, max_length=MAX_BATCH_CODE_LENGTH),current_user: dict = Depends(require_login)):user_id = extract_user_id(current_user)admin_mode = is_admin_user(current_user)if not admin_mode and not user_id:raise HTTPException(status_code=401, detail="Không xác định được người dùng.")try:query = supabase.table("inventory_serials").select("id, serial_number, printer_id, image_url, status, batch_code, ""created_by, created_by_name, note, scan_source, created_at, updated_at, ""list_printer(brand_name, model_code)",count="exact")if not admin_mode:query = query.eq("created_by", user_id)3 unmodified linesif status_clean in VALID_STATUSES:query = query.eq("status", status_clean)if batch_code and batch_code.strip():escaped_batch = batch_code.strip().replace("%", "\\%").replace("_", "\\_")query = query.ilike("batch_code", f"%{escaped_batch}%")if serial_search and serial_search.strip():escaped = serial_search.strip().replace("%", "\\%").replace("_", "\\_")query = query.ilike("serial_number", f"%{escaped}%")3 unmodified linestotal = response.count if response.count is not None else len(response.data or [])return {"status": "success","data": response.data or [],"is_admin": admin_mode,"pagination": {"page": page,"page_size": page_size,"total": total,"total_pages": (total + page_size - 1) // page_size if page_size else 1}}except Exception:logger.exception("Lỗi tải lịch sử kiểm kê")raise HTTPException(status_code=500, detail="Lỗi hệ thống khi lấy lịch sử.")@api_router.get("/records/{record_id}", status_code=status.HTTP_200_OK)def get_serial_record_detail(record_id: str = FastAPIPath(...), current_user: dict = Depends(require_login)):if not validate_uuid(record_id):raise HTTPException(status_code=400, detail="ID bản ghi không hợp lệ (Phải là UUID).")user_id = extract_user_id(current_user)try:response = supabase.table("inventory_serials").select("id, serial_number, printer_id, image_url, status, batch_code, ""created_by, created_by_name, note, scan_source, created_at, updated_at, ""list_printer(brand_name, model_code)").eq("id", record_id).limit(1).execute()if not response.data:10 unmodified linesraise HTTPException(status_code=500, detail="Lỗi hệ thống.")@api_router.patch("/records/{record_id}/status", status_code=status.HTTP_200_OK)def update_record_status(record_id: str, payload: StatusUpdateRequest, current_user: dict = Depends(require_login)):if not is_admin_user(current_user):raise HTTPException(status_code=403, detail="Yêu cầu quyền quản trị.")if not validate_uuid(record_id):raise HTTPException(status_code=400, detail="ID bản ghi không hợp lệ.")try:exist = supabase.table("inventory_serials").select("id").eq("id", record_id).limit(1).execute()if not exist.data:raise HTTPException(status_code=404, detail="Không tìm thấy bản ghi.")update_data: Dict[str, Any] = {"status": payload.status}if payload.note is not None:update_data["note"] = payload.note.strip() or Noneresponse = supabase.table("inventory_serials").update(update_data).eq("id", record_id).execute()return {"status": "success", "message": "Đã cập nhật trạng thái", "data": response.data[0] if response.data else None}except HTTPException:raiseexcept Exception:raise HTTPException(status_code=500, detail="Lỗi hệ thống.")@api_router.delete("/records/{record_id}", status_code=status.HTTP_200_OK)def delete_record(record_id: str, current_user: dict = Depends(require_login)):if not is_admin_user(current_user):raise HTTPException(status_code=403, detail="Yêu cầu quyền quản trị.")if not validate_uuid(record_id):raise HTTPException(status_code=400, detail="ID bản ghi không hợp lệ.")try:exist = supabase.table("inventory_serials").select("serial_number").eq("id", record_id).limit(1).execute()15 unmodified linestry:query = supabase.table("inventory_serials").select("id, status", count="exact")if not admin_mode and user_id:query = query.eq("created_by", user_id)response = query.execute()8 unmodified linesreturn {"status": "success", "data": {"total": total, "by_status": counts, "is_admin": admin_mode}}except Exception:raise HTTPException(status_code=500, detail="Lỗi hệ thống khi lấy thống kê.")@api_router.patch("/records/batch-status", status_code=status.HTTP_200_OK)def batch_update_status(payload: BatchStatusRequest, current_user: dict = Depends(require_login)):if not is_admin_user(current_user):raise HTTPException(status_code=403, detail="Yêu cầu quyền quản trị.")invalid_ids = [uid for uid in payload.ids if not validate_uuid(uid)]if invalid_ids:raise HTTPException(status_code=400, detail=f"Có {len(invalid_ids)} ID không hợp lệ (không phải UUID).")1 unmodified linetry:update_data: Dict[str, Any] = {"status": payload.status}if payload.note is not None:update_data["note"] = payload.note.strip() or Noneresponse = supabase.table("inventory_serials").update(update_data).in_("id", payload.ids).execute()updated_count = len(response.data or [])return {"status": "success",7 unmodified lines@api_router.post("/records/batch-delete", status_code=status.HTTP_200_OK)def batch_delete_records(payload: BatchDeleteRequest, current_user: dict = Depends(require_login)):if not is_admin_user(current_user):raise HTTPException(status_code=403, detail="Yêu cầu quyền quản trị.")2 unmodified linesraise HTTPException(status_code=400, detail=f"Có {len(invalid_ids)} ID không hợp lệ.")try:existing = supabase.table("inventory_serials").select("id, serial_number").in_("id", payload.ids).execute()existing_ids = [r["id"] for r in (existing.data or [])]missing = len(payload.ids) - len(existing_ids)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768694 unmodified lines747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811921 unmodified lines1411421431441451461475 unmodified lines1531541551561571581591601615 unmodified lines1671681691701711721731741751761771781 unmodified line1801811821831841851861871 unmodified line1891901911921931941951961971981992002012022032042052062072082092102112122132143 unmodified lines2182192202212222233 unmodified lines22722822923023123223323423523623723823924024124224324424524624724824925025125210 unmodified lines26326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930015 unmodified lines3163173183193203213228 unmodified lines3313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853861 unmodified line3883893903913923933943953963973983994007 unmodified lines4084094104114124134144154164174182 unmodified lines421422423424425426427428429430431import loggingimport refrom pathlib import Pathfrom typing import Optional, Dict, Any,Listfrom fastapi import APIRouter, Request, Query, HTTPException, Depends, status, Path as FastAPIPathfrom fastapi.responses import HTMLResponse, JSONResponsefrom fastapi.templating import Jinja2Templatesfrom pydantic import BaseModel, Field, HttpUrl, field_validatorimport uuid # <-- Đã thêm thư viện UUID# Imports đồng bộ với hệ thống hiện tạifrom config import supabasefrom app.templates_config import templatesfrom app.auth import require_login, get_current_user_or_redirect# ==========================================# CẤU HÌNH LOGGING & TEMPLATES# ==========================================logger = logging.getLogger("uvicorn.error")BASE_DIR = Path(__file__).resolve().parentTEMPLATES_DIR = (BASE_DIR.parent / "templates"if (BASE_DIR.parent / "templates").exists()else BASE_DIR / "templates")# ==========================================# HẰNG SỐ & THAM SỐ CẤU HÌNH# ==========================================DEFAULT_PAGE_SIZE = 20MAX_PAGE_SIZE = 100MAX_SERIAL_LENGTH = 100MIN_SERIAL_LENGTH = 1SERIAL_ALLOWED_PATTERN = re.compile(r"^[A-Za-z0-9\-\_\.\/\+\#\:\s]+$")# Các trạng thái hợp lệ đã được đồng bộ với DB mớiVALID_STATUSES = ("pending", "verified", "rejected", "completed")router = APIRouter(prefix="/inventory", tags=["Quản Lý Kho & Seri Máy In"])api_router = APIRouter(prefix="/api/inventory", tags=["API Kiểm Kê Seri Máy In"])# ==========================================# PYDANTIC SCHEMAS# ==========================================class SerialScanRequest(BaseModel):serial_number: str = Field(..., min_length=MIN_SERIAL_LENGTH, max_length=MAX_SERIAL_LENGTH)printer_id: int = Field(..., gt=0)image_url: Optional[HttpUrl] = None@field_validator("serial_number")@classmethoddef validate_and_normalize_serial(cls, v: str) -> str:normalized = " ".join(v.strip().split()).upper()if not normalized:raise ValueError("Số seri không được để trống")if not SERIAL_ALLOWED_PATTERN.match(normalized):raise ValueError("Số seri chứa ký tự không hợp lệ")return normalizedclass StatusUpdateRequest(BaseModel):status: strnote: Optional[str] = Field(None, max_length=500)@field_validator("status")@classmethod4 unmodified linesreturn normalized# ==========================================# HÀM TIỆN ÍCH (ĐÃ FIX LỖI ÉP KIỂU UUID)# ==========================================def extract_user_id(current_user: Any) -> Optional[str]:"""Trích xuất user_id (UUID) một cách an toàn."""if isinstance(current_user, dict):uid = current_user.get("id")else:uid = getattr(current_user, "id", None)if uid:return str(uid) # Supabase auth.users.id là UUID kiểu chuỗi (String)return Nonedef is_admin_user(current_user: Any) -> bool:if isinstance(current_user, dict):role = current_user.get("role", "") or current_user.get("user_role", "")is_admin_flag = current_user.get("is_admin", False)else:role = getattr(current_user, "role", "") or getattr(current_user, "user_role", "")is_admin_flag = getattr(current_user, "is_admin", False)return bool(is_admin_flag) or str(role).lower() in ("admin", "administrator", "manager", "quanly", "super admin", "system admin")def validate_uuid(val: str):"""Kiểm tra xem chuỗi có phải là UUID hợp lệ không."""try:uuid.UUID(str(val))return Trueexcept ValueError:return False# ==========================================# 1. HTML ROUTER# ==========================================@router.get("/scan", response_class=HTMLResponse)def get_scan_page(request: Request, user: dict = Depends(get_current_user_or_redirect)):return templates.TemplateResponse(request=request, name="scan_inventory.html",context={"user": user, "page_title": "Quét Mã & Kiểm Kê Seri Máy In"})21 unmodified lines"status": "success","data": response.data or [],"pagination": {"page": page, "page_size": page_size, "total": total,"total_pages": (total + page_size - 1) // page_size if page_size else 1}}5 unmodified lines@api_router.post("/scan-serial", status_code=status.HTTP_201_CREATED)def create_serial_record(payload: SerialScanRequest, current_user: dict = Depends(require_login)):user_id = extract_user_id(current_user)if not user_id:raise HTTPException(status_code=401, detail="Không xác định được thông tin người dùng.")serial = payload.serial_numbertry:5 unmodified linesif not printer.data:raise HTTPException(status_code=400, detail="Model máy in không tồn tại!")data_to_insert = {"serial_number": serial,"printer_id": payload.printer_id,"image_url": str(payload.image_url) if payload.image_url else None,"created_by": user_id,"status": "pending"}response = supabase.table("inventory_serials").insert(data_to_insert).execute()1 unmodified lineraise HTTPException(status_code=400, detail="Không thể lưu dữ liệu.")return {"status": "success", "message": f"Đã lưu thành công Seri: {serial}","data": response.data[0], "printer_info": printer.data[0]}except HTTPException:raise1 unmodified lineerror_msg = str(e)if "duplicate key" in error_msg or "23505" in error_msg:raise HTTPException(status_code=409, detail=f"Mã Seri '{serial}' đã tồn tại trong hệ thống!")raise HTTPException(status_code=500, detail="Lỗi hệ thống khi lưu dữ liệu.")@api_router.get("/history", status_code=status.HTTP_200_OK)def get_scan_history(page: int = Query(1, ge=1),page_size: int = Query(DEFAULT_PAGE_SIZE, ge=1, le=MAX_PAGE_SIZE),status_filter: Optional[str] = Query(None),serial_search: Optional[str] = Query(None, max_length=100),current_user: dict = Depends(require_login)):user_id = extract_user_id(current_user)if not user_id:raise HTTPException(status_code=401, detail="Không xác định được người dùng.")admin_mode = is_admin_user(current_user)try:query = supabase.table("inventory_serials").select("id, serial_number, image_url, status, created_at, created_by, list_printer(brand_name, model_code)", count="exact")if not admin_mode:query = query.eq("created_by", user_id)3 unmodified linesif status_clean in VALID_STATUSES:query = query.eq("status", status_clean)if serial_search and serial_search.strip():escaped = serial_search.strip().replace("%", "\\%").replace("_", "\\_")query = query.ilike("serial_number", f"%{escaped}%")3 unmodified linestotal = response.count if response.count is not None else len(response.data or [])return {"status": "success", "data": response.data or [], "is_admin": admin_mode,"pagination": {"page": page, "page_size": page_size, "total": total,"total_pages": (total + page_size - 1) // page_size if page_size else 1}}except Exception:raise HTTPException(status_code=500, detail="Lỗi hệ thống khi lấy lịch sử.")# ĐÃ SỬA: record_id đổi từ int -> str để hỗ trợ kiểu UUID của DB@api_router.get("/records/{record_id}", status_code=status.HTTP_200_OK)def get_serial_record_detail(record_id: str = FastAPIPath(...), current_user: dict = Depends(require_login)):if not validate_uuid(record_id):raise HTTPException(status_code=400, detail="ID bản ghi không hợp lệ (Phải là UUID).")user_id = extract_user_id(current_user)try:response = supabase.table("inventory_serials").select("id, serial_number, image_url, status, note, created_at, created_by, list_printer(brand_name, model_code)").eq("id", record_id).limit(1).execute()if not response.data:10 unmodified linesraise HTTPException(status_code=500, detail="Lỗi hệ thống.")# ĐÃ SỬA: record_id từ int -> str@api_router.patch("/records/{record_id}/status", status_code=status.HTTP_200_OK)def update_record_status(record_id: str, payload: StatusUpdateRequest, current_user: dict = Depends(require_login)):if not is_admin_user(current_user):raise HTTPException(status_code=403, detail="Yêu cầu quyền quản trị.")if not validate_uuid(record_id):raise HTTPException(status_code=400, detail="ID bản ghi không hợp lệ.")try:exist = supabase.table("inventory_serials").select("id").eq("id", record_id).limit(1).execute()if not exist.data:raise HTTPException(status_code=404, detail="Không tìm thấy bản ghi.")update_data = {"status": payload.status}if payload.note is not None:update_data["note"] = payload.note.strip()response = supabase.table("inventory_serials").update(update_data).eq("id", record_id).execute()return {"status": "success", "message": f"Đã cập nhật trạng thái", "data": response.data[0] if response.data else None}except HTTPException:raiseexcept Exception:raise HTTPException(status_code=500, detail="Lỗi hệ thống.")# ĐÃ SỬA: record_id từ int -> str@api_router.delete("/records/{record_id}", status_code=status.HTTP_200_OK)def delete_record(record_id: str, current_user: dict = Depends(require_login)):if not is_admin_user(current_user):raise HTTPException(status_code=403, detail="Yêu cầu quyền quản trị.")if not validate_uuid(record_id):raise HTTPException(status_code=400, detail="ID bản ghi không hợp lệ.")try:exist = supabase.table("inventory_serials").select("serial_number").eq("id", record_id).limit(1).execute()15 unmodified linestry:query = supabase.table("inventory_serials").select("id, status", count="exact")if not admin_mode:query = query.eq("created_by", user_id)response = query.execute()8 unmodified linesreturn {"status": "success", "data": {"total": total, "by_status": counts, "is_admin": admin_mode}}except Exception:raise HTTPException(status_code=500, detail="Lỗi hệ thống khi lấy thống kê.")@router.get("/admin/review", response_class=HTMLResponse)def get_admin_review_page(request: Request,current_user: dict = Depends(get_current_user_or_redirect)):"""Render giao diện Dashboard Duyệt kiểm kê cho Admin"""if not is_admin_user(current_user):from fastapi.responses import RedirectResponsereturn RedirectResponse(url="/", status_code=303)return templates.TemplateResponse(request=request,name="admin/admin_inventory_review.html", # Cập nhật đường dẫn thư mục ở đâycontext={"current_user": current_user,})# ==========================================# 3. API BATCH (THEO LÔ) — ĐÃ SỬA HOÀN CHỈNH# ==========================================class BatchStatusRequest(BaseModel):ids: List[str] = Field(..., min_length=1, max_length=5000, description="Danh sách ID cần cập nhật")status: str = Field(..., description="Trạng thái mới")note: Optional[str] = Field(None, max_length=500)@field_validator("status")@classmethoddef validate_batch_status(cls, v: str) -> str:normalized = v.strip().lower()if normalized not in ("verified", "rejected", "pending"):raise ValueError("Trạng thái batch chỉ cho phép: verified, rejected, pending")return normalizedclass BatchDeleteRequest(BaseModel):ids: List[str] = Field(..., min_length=1, max_length=5000, description="Danh sách ID cần xóa")@api_router.patch("/records/batch-status", status_code=status.HTTP_200_OK)def batch_update_status(payload: BatchStatusRequest,current_user: dict = Depends(require_login)):"""Cập nhật trạng thái hàng loạt theo lô (chỉ admin)."""if not is_admin_user(current_user):raise HTTPException(status_code=403, detail="Yêu cầu quyền quản trị.")# Validate tất cả ID là UUIDinvalid_ids = [uid for uid in payload.ids if not validate_uuid(uid)]if invalid_ids:raise HTTPException(status_code=400, detail=f"Có {len(invalid_ids)} ID không hợp lệ (không phải UUID).")1 unmodified linetry:update_data: Dict[str, Any] = {"status": payload.status}if payload.note is not None:update_data["note"] = payload.note.strip()response = supabase.table("inventory_serials") \.update(update_data) \.in_("id", payload.ids) \.execute()updated_count = len(response.data or [])return {"status": "success",7 unmodified lines@api_router.post("/records/batch-delete", status_code=status.HTTP_200_OK)def batch_delete_records(payload: BatchDeleteRequest,current_user: dict = Depends(require_login)):"""Xóa hàng loạt theo lô (chỉ admin). Dùng POST thay vì DELETE để tránh bị bỏ body."""if not is_admin_user(current_user):raise HTTPException(status_code=403, detail="Yêu cầu quyền quản trị.")2 unmodified linesraise HTTPException(status_code=400, detail=f"Có {len(invalid_ids)} ID không hợp lệ.")try:# Lấy danh sách serial để trả về (log)existing = supabase.table("inventory_serials") \.select("id, serial_number") \.in_("id", payload.ids) \.execute()existing_ids = [r["id"] for r in (existing.data or [])]missing = len(payload.ids) - len(existing_ids)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124import ioimport qrcodeimport requestsfrom functools import lru_cachefrom pypdf import PdfReader, PdfWriterfrom reportlab.pdfgen import canvasfrom reportlab.lib.pagesizes import A4from reportlab.lib.utils import ImageReader
# Đường dẫn phôi PDF mẫu trên Supabase StoragePDF_TEMPLATE_URL = "https://ejbillnpxxiubbiyyaxn.supabase.co/storage/v1/object/public/assets/Phieu_Bao_Hanh.pdf"
@lru_cache(maxsize=1)def get_pdf_template_bytes() -> bytes: """ Tải và lưu tạm (cache) phôi PDF mẫu từ Supabase Storage trong RAM. Chỉ thực hiện tải 1 lần duy nhất khi ứng dụng khởi động hoặc trong lần gọi đầu tiên. """ try: response = requests.get(PDF_TEMPLATE_URL, timeout=10) response.raise_for_status() return response.content except Exception as e: print(f"❌ Lỗi khi tải phôi PDF mẫu từ Supabase: {e}") raise e
def generate_qr_code_bytes(data_str: str) -> bytes: """Tạo ảnh mã QR Code dạng PNG bytes""" qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=8, border=2, ) qr.add_data(data_str) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") img_byte_arr = io.BytesIO() img.save(img_byte_arr, format='PNG') return img_byte_arr.getvalue()
def create_warranty_pdf(data: dict) -> tuple[bytes, bytes]: """ Hàm chính nhận thông tin phiếu bảo hành và xuất file PDF cùng ảnh QR Code. Dữ liệu `data` đầu vào kỳ vọng: { 'customer_name': 'Nguyễn Văn A', 'phone_number': '0901234567', 'purchase_date': '15/03/2026', 'model': 'Canon ix6770', 'serial': 'AGWH12345', 'warranty': 'Cơ máy: 12 tháng hoặc 10.000 trang\nĐầu phun: 12 tháng' } Trả về: (pdf_bytes, qr_png_bytes) """ serial = data.get("serial", "") or "NoSerial" # 1. Tạo QR Code liên kết đến trang tra cứu bảo hành lookup_url = f"https://center-hub.onrender.com/warranty/lookup?q={serial}" qr_png_bytes = generate_qr_code_bytes(lookup_url)
# 2. Đọc phôi PDF từ Supabase Storage (qua RAM) template_bytes = get_pdf_template_bytes() template_reader = PdfReader(io.BytesIO(template_bytes)) writer = PdfWriter()
# 3. Tạo layer đè văn bản bằng ReportLab packet = io.BytesIO() can = canvas.Canvas(packet, pagesize=A4) # Tùy chỉnh Font chữ (Căn chỉnh tọa độ x, y theo khung mẫu của phôi) can.setFont("Helvetica-Bold", 10) x_start = 140 # Vị trí lề trái nội dung # Vẽ các dòng thông tin khách hàng & thiết bị can.drawString(x_start, 680, str(data.get("customer_name", ""))) can.drawString(x_start, 655, str(data.get("phone_number", ""))) can.drawString(x_start, 630, str(data.get("model", ""))) can.drawString(x_start, 605, str(serial)) can.drawString(x_start, 580, str(data.get("purchase_date", "")))
# Vẽ thông tin chính sách bảo hành (xử lý xuống dòng) warranty_text = str(data.get("warranty", "")) y_pos = 555 for line in warranty_text.split('\n'): if line.strip(): can.drawString(x_start, y_pos, line.strip()) y_pos -= 16
# (Tùy chọn) Chèn trực tiếp góc mã QR vào phôi PDF try: qr_img = ImageReader(io.BytesIO(qr_png_bytes)) can.drawImage(qr_img, x=430, y=580, width=90, height=90) except Exception as e: print(f"⚠️ Không thể vẽ QR lên PDF: {e}")
can.save()
# 4. Gộp layer dữ liệu mới vừa tạo vào trang 1 của phôi PDF packet.seek(0) overlay_pdf = PdfReader(packet) page_1 = template_reader.pages[0] if len(overlay_pdf.pages) > 0: page_1.merge_page(overlay_pdf.pages[0]) writer.add_page(page_1)
# Giữ nguyên các trang còn lại của phôi nếu phôi có nhiều trang for i in range(1, len(template_reader.pages)): writer.add_page(template_reader.pages[i])
# 5. Xuất kết quả PDF dạng bytes pdf_output_stream = io.BytesIO() writer.write(pdf_output_stream) pdf_bytes = pdf_output_stream.getvalue()
return pdf_bytes, qr_png_bytes123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177import loggingimport timefrom typing import Any, Dict, Optional, Setfrom config import supabase_admin
logger = logging.getLogger(__name__)
# Cấu hình cấp bậc RoleROLE_LEVELS: Dict[str, int] = { "user": 1, "admin": 2, "super admin": 3, "system admin": 4}
# Bộ nhớ đệm RAMPERMISSIONS_CACHE: Dict[str, Any] = {}IS_CACHE_LOADED: bool = FalseLAST_CACHE_UPDATE: float = 0CACHE_TTL_SECONDS: int = 300 # 5 phút TTL
def load_permissions_cache(force: bool = False) -> None: """Nạp ma trận phân quyền từ CSDL vào RAM Cache.""" global PERMISSIONS_CACHE, IS_CACHE_LOADED, LAST_CACHE_UPDATE now = time.time() if IS_CACHE_LOADED and not force and (now - LAST_CACHE_UPDATE < CACHE_TTL_SECONDS): return
try: res = supabase_admin.table("page_permissions").select("page_key, allowed_roles, allowed_departments").execute() new_cache = {} if res.data: for item in res.data: page_key = str(item.get("page_key") or "").strip() if not page_key: continue roles = {str(r).strip().lower() for r in (item.get("allowed_roles") or [])} depts = {str(d).strip().upper() for d in (item.get("allowed_departments") or ["ALL"])} # 💡 Lưu dạng Dictionary chứa cả Roles và Departments new_cache[page_key] = { "roles": roles, "departments": depts }
PERMISSIONS_CACHE = new_cache IS_CACHE_LOADED = True LAST_CACHE_UPDATE = now logger.info(f"✅ Đã tải {len(PERMISSIONS_CACHE)} trang phân quyền vào Cache RAM.") except Exception as e: logger.error(f"❌ Lỗi nạp permissions cache: {e}")
def can_access(page_key: str, user: Optional[dict]) -> bool: """Kiểm tra quyền truy cập trang qua Cache RAM (RBAC + Data Scope).""" if not user or not isinstance(user, dict): return False
page_key_clean = str(page_key or "").strip() user_role = str(user.get("role") or "").strip().lower() user_dept = str(user.get("department") or "KTSC").strip().upper() user_level = ROLE_LEVELS.get(user_role, 1)
# 1. System Admin luôn có toàn quyền if user_role == "system admin" or user_level >= ROLE_LEVELS["system admin"]: return True
# 2. Nạp Cache nếu chưa tải if not IS_CACHE_LOADED: load_permissions_cache()
perm = PERMISSIONS_CACHE.get(page_key_clean) if not perm: return False
# 💡 XỬ LÝ AN TOÀN KHI PERM LÀ SET (CACHE CỦ) HOẶC DICT (CACHE MỚI) if isinstance(perm, set): allowed_roles = perm allowed_depts = {"ALL"} elif isinstance(perm, dict): allowed_roles = perm.get("roles", set()) allowed_depts = perm.get("departments", {"ALL"}) else: return False
# 3. Kiểm tra Phạm vi Phòng Ban (Department Scope) if user_role != "super admin" and "ALL" not in allowed_depts: if user_dept not in allowed_depts: return False
# 4. Kiểm tra Cấp bậc Vai trò (Role Level) if user_role in allowed_roles: return True
allowed_levels = [ROLE_LEVELS.get(r, 1) for r in allowed_roles if r in ROLE_LEVELS] if allowed_levels and user_level >= min(allowed_levels): return True
return False
def parse_int(val, default_val: int = 0) -> int: """Parse giá trị sang int an toàn, trả về default_val nếu lỗi hoặc rỗng.""" try: if val is None or str(val).strip() == "": return default_val return int(val) except (ValueError, TypeError): return default_val
def get_staff_department_map() -> dict: """Lấy danh sách ánh xạ từ tên nhân viên/username sang phòng ban từ bảng quan_tri_vien.""" try: res = supabase_admin.table("quan_tri_vien").select("ho_ten, username, department").execute() mapping = {} if res.data: for row in res.data: dept = str(row.get("department") or "").strip().lower() ho_ten = str(row.get("ho_ten") or "").strip().lower() username = str(row.get("username") or "").strip().lower() if ho_ten: mapping[ho_ten] = dept if username: mapping[username] = dept return mapping except Exception as e: logger.error(f"❌ Lỗi lấy mapping phòng ban nhân viên: {e}") return {}
def can_modify_warranty_record(user: dict, record: dict) -> bool: """ Kiểm tra quyền Sửa/Xóa phiếu bảo hành: - Super Admin / System Admin: Toàn quyền. - Tác giả tạo phiếu: Được phép. - Người cùng phòng ban với tác giả: Được phép (Tra cứu tự ��ộng qua bảng quan_tri_vien). """ if not user or not record: return False
role = str(user.get("role") or "").strip().lower() if role in ["super admin", "system admin"]: return True
# 1. Kiểm tra chính chủ (Tác giả) current_user_display = str( user.get("ho_ten") or user.get("display_name") or user.get("username") or user.get("email") or "" ).strip().lower() creator = str(record.get("created_by") or record.get("staff_name") or "").strip().lower() if current_user_display and creator and current_user_display == creator: return True
# 2. Kiểm tra cùng phòng ban (Tra cứu tự động từ bảng quan_tri_vien dựa vào staff_name) user_dept = str(user.get("department") or "").strip().lower() if not user_dept: # Nếu user hiện tại không có department sẵn trong session, thử lấy từ metadata hoặc quan_tri_vien meta = user.get("user_metadata", {}) user_dept = str(meta.get("department") or "").strip().lower()
if user_dept: # Lấy bảng ánh xạ nhân viên -> phòng ban staff_dept_map = get_staff_department_map() # Phòng ban của người tạo phiếu chính là phòng ban tra được từ staff_name của record record_dept = staff_dept_map.get(creator, "") if record_dept and user_dept == record_dept: return True
return False1234567891011121314151617181920212223243 unmodified lines28293031323334353637383 unmodified lines424344454647484950515253545556575 unmodified lines6364656667686970717273747576772 unmodified lines808182838485865 unmodified lines92939495969798991001011021031041051061071081091101111121131147 unmodified lines1221231241251261271281291301311321331345 unmodified lines1401411421431441451464 unmodified lines1511521531541551561578 unmodified lines16616716816917017117217317415 unmodified lines1901911921931941951965 unmodified lines2022032042052062072086 unmodified lines21521621721821922022110 unmodified lines23223323423523623723826 unmodified lines2652662672682692702714 unmodified lines27627727827928028128213 unmodified lines2962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253 unmodified lines3293303313323333343354 unmodified lines3403413423433443453462 unmodified lines3493503513523533543553563573583599 unmodified lines3693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054061 unmodified line40840941041141241341441541641741841914 unmodified lines434435436437import calendarimport ioimport loggingfrom datetime import datetimefrom typing import Optional, List, Dict, Anyfrom urllib.parse import quoteimport pandas as pdfrom fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom fastapi.responses import HTMLResponse, JSONResponse, StreamingResponsefrom fastapi.templating import Jinja2Templatesfrom app.auth import require_loginfrom config import supabaselogger = logging.getLogger(__name__)# Cấu hình Templates & Routertemplates = Jinja2Templates(directory="templates")router = APIRouter(prefix="/admin/report", tags=["Báo cáo & Thống kê"])ALLOWED_ADMIN_ROLES = {"admin", "super admin", "system admin"}NUMERIC_COLS = ["quang_duong", "combo", "device_cost", "distance_cost",3 unmodified lines# =========================================================# HELPER: THỜI GIAN & LỌC D DỮ LIỆU# =========================================================def _parse_month_range(month_str: str) -> tuple[str, str]:"""Parse chuỗi tháng (MM/YYYY hoặc YYYY) thành mốc thời gian ISO start/end."""try:clean_str = str(month_str).strip()if "/" in clean_str:3 unmodified linesend_d = sel_dt.date().replace(day=last_day)else:year = int(clean_str)start_d = datetime(year, 1, 1).date()end_d = datetime(year, 12, 31).date()except Exception:now = datetime.now()start_d = now.date().replace(day=1)last_day = calendar.monthrange(now.year, now.month)[1]end_d = now.date().replace(day=last_day)start_ts = f"{start_d.strftime('%Y-%m-%d')}T00:00:00"end_ts = f"{end_d.strftime('%Y-%m-%d')}T23:59:59"return start_ts, end_ts5 unmodified linesselected_tt: str = "Tất cả",search: str = "") -> pd.DataFrame:"""Query dữ liệu từ Supabase theo chuẩn Schema và chuyển đổi sang Pandas DataFrame."""start_ts, end_ts = _parse_month_range(month)# 1. Query Databasequery = (supabase.table("cham_cong").select("*").gte("thoi_gian", start_ts).lte("thoi_gian", end_ts))# Phân quyền & Lọc theo Nhân viên2 unmodified lineselif selected_nv and selected_nv != "Tất cả":query = query.or_(f"username.eq.{selected_nv},ten.eq.{selected_nv}")# Lọc Trạng tháiif selected_tt and selected_tt != "Tất cả":query = query.eq("trang_thai", selected_tt)5 unmodified linesdf = pd.DataFrame(data)# 2. Chuẩn hóa Cột dữ liệu & Chuỗi hiển thịdf["Tên"] = df["ten"].fillna(df["username"]).fillna("N/A")if "thoi_gian" in df.columns:df["Thời Gian"] = pd.to_datetime(df["thoi_gian"], utc=True).dt.tz_convert("Asia/Ho_Chi_Minh")df["Thời Gian Str"] = df["Thời Gian"].dt.strftime("%d/%m/%Y %H:%M")else:df["Thời Gian Str"] = ""# Ép kiểu dữ liệu số hàng loạt (Vectorized)for col in NUMERIC_COLS:if col in df.columns:df[col] = pd.to_numeric(df[col], errors="coerce").fillna(0.0)else:df[col] = 0.0# Chuẩn hóa văn bảnstring_cols = {"so_hoa_don": "","noi_dung": "",7 unmodified lineselse:df[col] = default_val# 3. Lọc Từ khóa Tìm kiếm (Search)if search and search.strip():search_lower = search.lower().strip()mask = (df["so_hoa_don"].astype(str).str.lower().str.contains(search_lower) |df["noi_dung"].astype(str).str.lower().str.contains(search_lower) |df["Tên"].astype(str).str.lower().str.contains(search_lower))df = df[mask]5 unmodified lines# =========================================================def _build_excel_report(df_display: pd.DataFrame, month: str) -> io.BytesIO:"""Khởi tạo Workbook Excel định dạng chuẩn bao gồm bảng chi tiết và tổng hợp."""df_export = df_display.sort_values("Thời Gian").copy() if "Thời Gian" in df_display.columns else df_display.copy()df_export["STT"] = range(1, len(df_export) + 1)df_export["Ngày"] = df_export["Thời Gian"].dt.strftime("%d/%m/%Y") if "Thời Gian" in df_export.columns else ""4 unmodified lineswb = writer.bookws = wb.add_worksheet("BaoCaoChiTiet")# Định dạng Stylesfmt_title = wb.add_format({"bold": True, "font_size": 14, "font_name": "Segoe UI", "align": "center", "valign": "vcenter", "bg_color": "#1F4E79", "font_color": "white", "border": 1})fmt_header = wb.add_format({"bold": True, "font_size": 10, "font_name": "Segoe UI", "align": "center", "valign": "vcenter", "bg_color": "#2F5597", "font_color": "white", "border": 1, "text_wrap": True})fmt_center = wb.add_format({"border": 1, "align": "center", "valign": "vcenter", "font_name": "Segoe UI"})8 unmodified linesfmt_sum_header = wb.add_format({"bold": True, "font_size": 10, "font_name": "Segoe UI", "align": "center", "valign": "vcenter", "bg_color": "#E2EFDA", "border": 1, "text_wrap": True})fmt_sum_total = wb.add_format({"bold": True, "font_size": 10, "font_name": "Segoe UI", "align": "left", "valign": "vcenter", "bg_color": "#D9EAD3", "border": 1})fmt_sum_money_total = wb.add_format({"bold": True, "font_size": 10, "font_name": "Segoe UI", "align": "right", "valign": "vcenter", "num_format": "#,##0", "bg_color": "#D9EAD3", "border": 1})# 1. Render Bảng Chi Tiết (Cột A -> P)headers = ["STT", "Ngày", "Số HĐ", "Nhân viên", "Nội dung / Địa chỉ", "Số máy", "Quãng đường","Tiền máy", "Tiền KM", "Thợ phụ", "Đi tỉnh", "Ngoài giờ", "Phụ phí", "Thành tiền", "Ghi chú", "Trạng thái"15 unmodified linesws.write(curr, 5, row["combo"], fmt_center)ws.write(curr, 6, row["Quãng đường Str"], fmt_center)# Tiền tệws.write(curr, 7, row["device_cost"], fmt_money)ws.write(curr, 8, row["distance_cost"], fmt_money)ws.write(curr, 9, row["tho_phu_cost"], fmt_money)5 unmodified linesws.write(curr, 14, row["ghi_chu_duyet"], fmt_left)ws.write(curr, 15, row["trang_thai"], fmt_center)# Dòng Tổng Cộng Bảng Chínhtotal_row = start_row + len(df_export)excel_start_line = start_row + 1excel_end_line = total_row6 unmodified linesws.write(total_row, 14, "", fmt_total_lbl)ws.write(total_row, 15, "", fmt_total_lbl)# 2. Khung Chính Sách (Cột R -> X)policy_text = ("1. ĐƠN GIÁ CÔNG LẮP ĐẶT THEO KHOẢNG CÁCH (NỘI THÀNH):\n"" • Dưới 20km : 30.000 đ/máy\n"10 unmodified linesws.merge_range("R1:X1", "📌 CHÍNH SÁCH PHỤ CẤP LẮP ĐẶT & BẢO HÀNH", fmt_policy_title)ws.merge_range("R2:X10", policy_text, fmt_policy_box)# 3. Bảng Tổng Hợp Theo Nhân Viên (Cột R -> X)df_approved = df_export[df_export["trang_thai"] == "Đã duyệt"]if df_approved.empty:df_approved = df_export26 unmodified linesws.write(r_idx, 23, s_row["tong_tien"], fmt_money)r_idx += 1# Dòng Tổng Cộng Bảng Nhân Viênws.write(r_idx, 17, "TỔNG CỘNG", fmt_sum_total)ws.write(r_idx, 18, summary_df["tong_don"].sum(), fmt_sum_total)ws.write(r_idx, 19, summary_df["tien_may"].sum(), fmt_sum_money_total)4 unmodified linesws.write(r_idx, 22, tong_phu_cap, fmt_sum_money_total)ws.write(r_idx, 23, summary_df["tong_tien"].sum(), fmt_sum_money_total)# 4. Cấu hình Độ Rộng Cộtcol_widths = [5, 12, 12, 18, 32, 8, 12, 12, 12, 12, 12, 12, 12, 15, 25, 12]for idx, width in enumerate(col_widths):ws.set_column(idx, idx, width)13 unmodified lines# =========================================================@router.get("", response_class=HTMLResponse)def report_page(request: Request, current_user: dict = Depends(require_login)):"""Render giao diện HTML trang báo cáo."""return templates.TemplateResponse("admin/admin_report.html",{"request": request, "current_user": current_user, "admin": current_user})@router.get("/api/data")def get_report_api_data(month: str = Query(...),selected_nv: Optional[str] = Query("Tất cả"),selected_tt: Optional[str] = Query("Tất cả"),search: Optional[str] = Query(""),current_user: dict = Depends(require_login),):"""API lấy dữ liệu bảng, chỉ số KPIs & biểu đồ.Đã chuyển sang hàm đồng bộ ('def') để tối ưu ThreadPool cho Pandas."""user_role = current_user.get("role", "User")username = current_user.get("username", "")df_filtered = get_filtered_report_data(month, user_role, username, selected_nv, selected_tt, search or "")if df_filtered.empty:return JSONResponse({3 unmodified lines"items": []})# 1. Tính toán KPIs bằng Pandas Masktotal_orders = len(df_filtered)is_approved = df_filtered["trang_thai"] == "Đã duyệt"is_pending = df_filtered["trang_thai"] == "Chờ duyệt"4 unmodified linesrev_sum = float(df_approved["thanh_tien"].sum()) if not df_approved.empty else 0.0pending_sum = float(df_filtered[is_pending]["thanh_tien"].sum()) if not df_filtered[is_pending].empty else 0.0# 2. Biểu đồ Doanh thu (Chỉ dành cho Admin)chart_data = []if user_role in ALLOWED_ADMIN_ROLES and not df_approved.empty:chart_grouped = (2 unmodified lines)chart_data = chart_grouped.to_dict(orient="records")# 3. Chuẩn hóa nhanh danh sách bản ghi (Vectorized JSON Mapping)df_items = df_filtered.copy()df_items.insert(0, "stt", range(1, len(df_items) + 1))df_items.rename(columns={"Tên": "ten", "Thời Gian Str": "thoi_gian_str"}, inplace=True)items = df_items.to_dict(orient="records")return {9 unmodified lines}@router.get("/api/employees")def get_employee_list(month: str = Query(...),current_user: dict = Depends(require_login)):"""API nạp danh sách nhân viên cho Dropdown lọc (Truy vấn tối ưu gọn nhẹ)."""user_role = current_user.get("role", "User")if user_role not in ALLOWED_ADMIN_ROLES:return {"employees": []}start_ts, end_ts = _parse_month_range(month)# Truy vấn tối giản chỉ lấy 2 cột ten và usernameres = (supabase.table("cham_cong").select("ten, username").gte("thoi_gian", start_ts).lte("thoi_gian", end_ts).execute())data = res.data or []if not data:return {"employees": ["Tất cả"]}# Trích xuất danh sách tên duy nhấtnames = {item.get("ten") or item.get("username") for item in data if item.get("ten") or item.get("username")}return {"employees": ["Tất cả"] + sorted(list(names))}@router.get("/export-excel")def export_report_excel(month: Optional[str] = Query(None),selected_nv: Optional[str] = Query("Tất cả"),selected_tt: Optional[str] = Query("Tất cả"),1 unmodified linecurrent_user: dict = Depends(require_login),):"""Endpoint xuất file Excel báo cáo chi tiết."""target_month = month or datetime.now().strftime("%m/%Y")user_role = current_user.get("role", "User")username = current_user.get("username", "")df_display = get_filtered_report_data(target_month, user_role, username, selected_nv, selected_tt, search or "")if df_display.empty:raise HTTPException(status_code=400, detail="Không tìm thấy dữ liệu phù hợp để xuất Excel")14 unmodified lines"Pragma": "no-cache","Expires": "0"})1234567891011121314151617181920212223242526273 unmodified lines31323334353637383940413 unmodified lines454647484950515253545556575859605 unmodified lines666768697071727374757677787980812 unmodified lines8485868788895 unmodified lines95969798991001011021031041051061071081091101111121131141157 unmodified lines1231241251261271281291301311321331341355 unmodified lines1411421431441451461474 unmodified lines1521531541551561578 unmodified lines16616716816917017117217315 unmodified lines1891901911921931945 unmodified lines2002012022032042056 unmodified lines21221321421521621710 unmodified lines22822923023123223326 unmodified lines2602612622632642654 unmodified lines27027127227327427513 unmodified lines2892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243 unmodified lines3283293303313323334 unmodified lines3383393403413423432 unmodified lines3463473483493503513523533543553563573583593603619 unmodified lines3713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224231 unmodified line42542642742842943043143243343443543643743843944014 unmodified lines455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604import calendarimport ioimport loggingfrom datetime import date, datetime, timedeltafrom typing import Any, Dict, List, Optionalfrom urllib.parse import quotefrom zoneinfo import ZoneInfoimport numpy as npimport pandas as pdfrom fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom fastapi.responses import HTMLResponse, JSONResponse, StreamingResponsefrom starlette.concurrency import run_in_threadpoolfrom app.auth import require_loginfrom app.permissions import can_accessfrom app.templates_config import templatesfrom config import supabase_adminlogger = logging.getLogger(__name__)router = APIRouter(prefix="/admin/report", tags=["Báo cáo & Thống kê"])VN_TZ = ZoneInfo("Asia/Ho_Chi_Minh")ALLOWED_ADMIN_ROLES = {"admin", "super admin", "system admin"}NUMERIC_COLS = ["quang_duong", "combo", "device_cost", "distance_cost",3 unmodified lines# =========================================================# HELPER: THỜI GIAN & LỌC DỮ LIỆU# =========================================================def _parse_month_range(month_str: str) -> tuple[str, str]:"""Parse chuỗi tháng (MM/YYYY hoặc YYYY) thành mốc thời gian ISO start/end chuẩn múi giờ +07:00."""try:clean_str = str(month_str).strip()if "/" in clean_str:3 unmodified linesend_d = sel_dt.date().replace(day=last_day)else:year = int(clean_str)start_d = date(year, 1, 1)end_d = date(year, 12, 31)except Exception:now = datetime.now(VN_TZ)start_d = now.date().replace(day=1)last_day = calendar.monthrange(now.year, now.month)[1]end_d = now.date().replace(day=last_day)start_ts = f"{start_d.strftime('%Y-%m-%d')}T00:00:00+07:00"end_ts = f"{end_d.strftime('%Y-%m-%d')}T23:59:59+07:00"return start_ts, end_ts5 unmodified linesselected_tt: str = "Tất cả",search: str = "") -> pd.DataFrame:"""Query dữ liệu từ Supabase và chuyển đổi sang Pandas DataFrame."""start_ts, end_ts = _parse_month_range(month)# 1. Query Database qua supabase_admin & tăng limit lên 5000query = (supabase_admin.table("cham_cong").select("*").gte("thoi_gian", start_ts).lte("thoi_gian", end_ts).limit(5000))# Phân quyền & Lọc theo Nhân viên2 unmodified lineselif selected_nv and selected_nv != "Tất cả":query = query.or_(f"username.eq.{selected_nv},ten.eq.{selected_nv}")if selected_tt and selected_tt != "Tất cả":query = query.eq("trang_thai", selected_tt)5 unmodified linesdf = pd.DataFrame(data)# 2. Chuẩn hóa Cột dữ liệudf["Tên"] = df["ten"].fillna(df["username"]).fillna("N/A")if "thoi_gian" in df.columns:df["Thời Gian"] = pd.to_datetime(df["thoi_gian"], utc=True, errors="coerce").dt.tz_convert("Asia/Ho_Chi_Minh")df["Thời Gian Str"] = df["Thời Gian"].dt.strftime("%d/%m/%Y %H:%M").fillna("")else:df["Thời Gian Str"] = ""for col in NUMERIC_COLS:if col in df.columns:df[col] = pd.to_numeric(df[col], errors="coerce").fillna(0.0)else:df[col] = 0.0string_cols = {"so_hoa_don": "","noi_dung": "",7 unmodified lineselse:df[col] = default_val# 3. Lọc Tìm kiếmif search and search.strip():search_lower = search.lower().strip()mask = (df["so_hoa_don"].astype(str).str.lower().str.contains(search_lower, regex=False) |df["noi_dung"].astype(str).str.lower().str.contains(search_lower, regex=False) |df["Tên"].astype(str).str.lower().str.contains(search_lower, regex=False))df = df[mask]5 unmodified lines# =========================================================def _build_excel_report(df_display: pd.DataFrame, month: str) -> io.BytesIO:"""Khởi tạo Workbook Excel định dạng chuẩn."""df_export = df_display.sort_values("Thời Gian").copy() if "Thời Gian" in df_display.columns else df_display.copy()df_export["STT"] = range(1, len(df_export) + 1)df_export["Ngày"] = df_export["Thời Gian"].dt.strftime("%d/%m/%Y") if "Thời Gian" in df_export.columns else ""4 unmodified lineswb = writer.bookws = wb.add_worksheet("BaoCaoChiTiet")fmt_title = wb.add_format({"bold": True, "font_size": 14, "font_name": "Segoe UI", "align": "center", "valign": "vcenter", "bg_color": "#1F4E79", "font_color": "white", "border": 1})fmt_header = wb.add_format({"bold": True, "font_size": 10, "font_name": "Segoe UI", "align": "center", "valign": "vcenter", "bg_color": "#2F5597", "font_color": "white", "border": 1, "text_wrap": True})fmt_center = wb.add_format({"border": 1, "align": "center", "valign": "vcenter", "font_name": "Segoe UI"})8 unmodified linesfmt_sum_header = wb.add_format({"bold": True, "font_size": 10, "font_name": "Segoe UI", "align": "center", "valign": "vcenter", "bg_color": "#E2EFDA", "border": 1, "text_wrap": True})fmt_sum_total = wb.add_format({"bold": True, "font_size": 10, "font_name": "Segoe UI", "align": "left", "valign": "vcenter", "bg_color": "#D9EAD3", "border": 1})fmt_sum_money_total = wb.add_format({"bold": True, "font_size": 10, "font_name": "Segoe UI", "align": "right", "valign": "vcenter", "num_format": "#,##0", "bg_color": "#D9EAD3", "font_name": "Segoe UI"})headers = ["STT", "Ngày", "Số HĐ", "Nhân viên", "Nội dung / Địa chỉ", "Số máy", "Quãng đường","Tiền máy", "Tiền KM", "Thợ phụ", "Đi tỉnh", "Ngoài giờ", "Phụ phí", "Thành tiền", "Ghi chú", "Trạng thái"15 unmodified linesws.write(curr, 5, row["combo"], fmt_center)ws.write(curr, 6, row["Quãng đường Str"], fmt_center)ws.write(curr, 7, row["device_cost"], fmt_money)ws.write(curr, 8, row["distance_cost"], fmt_money)ws.write(curr, 9, row["tho_phu_cost"], fmt_money)5 unmodified linesws.write(curr, 14, row["ghi_chu_duyet"], fmt_left)ws.write(curr, 15, row["trang_thai"], fmt_center)total_row = start_row + len(df_export)excel_start_line = start_row + 1excel_end_line = total_row6 unmodified linesws.write(total_row, 14, "", fmt_total_lbl)ws.write(total_row, 15, "", fmt_total_lbl)policy_text = ("1. ĐƠN GIÁ CÔNG LẮP ĐẶT THEO KHOẢNG CÁCH (NỘI THÀNH):\n"" • Dưới 20km : 30.000 đ/máy\n"10 unmodified linesws.merge_range("R1:X1", "📌 CHÍNH SÁCH PHỤ CẤP LẮP ĐẶT & BẢO HÀNH", fmt_policy_title)ws.merge_range("R2:X10", policy_text, fmt_policy_box)df_approved = df_export[df_export["trang_thai"] == "Đã duyệt"]if df_approved.empty:df_approved = df_export26 unmodified linesws.write(r_idx, 23, s_row["tong_tien"], fmt_money)r_idx += 1ws.write(r_idx, 17, "TỔNG CỘNG", fmt_sum_total)ws.write(r_idx, 18, summary_df["tong_don"].sum(), fmt_sum_total)ws.write(r_idx, 19, summary_df["tien_may"].sum(), fmt_sum_money_total)4 unmodified linesws.write(r_idx, 22, tong_phu_cap, fmt_sum_money_total)ws.write(r_idx, 23, summary_df["tong_tien"].sum(), fmt_sum_money_total)col_widths = [5, 12, 12, 18, 32, 8, 12, 12, 12, 12, 12, 12, 12, 15, 25, 12]for idx, width in enumerate(col_widths):ws.set_column(idx, idx, width)13 unmodified lines# =========================================================@router.get("", response_class=HTMLResponse)async def report_page(request: Request, current_user: dict = Depends(require_login)):"""Render giao diện HTML trang báo cáo."""if not can_access('report_cham_cong', current_user):return HTMLResponse("<h2>⚠️ Bạn không có quyền truy cập Báo cáo Chấm công!</h2>", status_code=403)return templates.TemplateResponse(request=request,name="admin/admin_report.html",context={"request": request, "current_user": current_user, "admin": current_user})@router.get("/api/data")async def get_report_api_data(month: str = Query(...),selected_nv: Optional[str] = Query("Tất cả"),selected_tt: Optional[str] = Query("Tất cả"),search: Optional[str] = Query(""),current_user: dict = Depends(require_login),):"""API lấy dữ liệu bảng, chỉ số KPIs & biểu đồ."""if not can_access('report_cham_cong', current_user):return JSONResponse(status_code=403, content={"success": False, "message": "Không có quyền truy cập dữ liệu báo cáo"})user_role = current_user.get("role", "User")username = current_user.get("username", "")df_filtered = await run_in_threadpool(get_filtered_report_data, month, user_role, username, selected_nv, selected_tt, search or "")if df_filtered.empty:return JSONResponse({3 unmodified lines"items": []})total_orders = len(df_filtered)is_approved = df_filtered["trang_thai"] == "Đã duyệt"is_pending = df_filtered["trang_thai"] == "Chờ duyệt"4 unmodified linesrev_sum = float(df_approved["thanh_tien"].sum()) if not df_approved.empty else 0.0pending_sum = float(df_filtered[is_pending]["thanh_tien"].sum()) if not df_filtered[is_pending].empty else 0.0chart_data = []if user_role in ALLOWED_ADMIN_ROLES and not df_approved.empty:chart_grouped = (2 unmodified lines)chart_data = chart_grouped.to_dict(orient="records")df_items = df_filtered.copy()df_items.insert(0, "stt", range(1, len(df_items) + 1))df_items.rename(columns={"Tên": "ten", "Thời Gian Str": "thoi_gian_str"}, inplace=True)if "Thời Gian" in df_items.columns:df_items.drop(columns=["Thời Gian"], inplace=True)df_items = df_items.replace({np.nan: None, np.inf: None, -np.inf: None})df_items = df_items.where(pd.notnull(df_items), None)items = df_items.to_dict(orient="records")return {9 unmodified lines}@router.get("/employees")async def get_employee_list(month: str = Query(...),current_user: dict = Depends(require_login)):"""API nạp danh sách nhân viên cho Dropdown lọc."""user_role = current_user.get("role", "User")if user_role not in ALLOWED_ADMIN_ROLES:return {"employees": []}start_ts, end_ts = _parse_month_range(month)def _fetch_employees():cc_res = (supabase_admin.table("cham_cong").select("ten, username").gte("thoi_gian", start_ts).lte("thoi_gian", end_ts).limit(5000).execute())cc_data = cc_res.data or []names = {item.get("ten") or item.get("username") for item in cc_data if item.get("ten") or item.get("username")}ktld_res = (supabase_admin.table("quan_tri_vien").select("ho_ten, username").eq("department", "KTLD").execute())ktld_data = ktld_res.data or []for item in ktld_data:name = item.get("ho_ten") or item.get("username")if name:names.add(name)return namesnames = await run_in_threadpool(_fetch_employees)if not names:return {"employees": ["Tất cả"]}return {"employees": ["Tất cả"] + sorted(list(names))}@router.get("/export-excel")async def export_report_excel(month: Optional[str] = Query(None),selected_nv: Optional[str] = Query("Tất cả"),selected_tt: Optional[str] = Query("Tất cả"),1 unmodified linecurrent_user: dict = Depends(require_login),):"""Endpoint xuất file Excel báo cáo chi tiết."""if not can_access('report_cham_cong', current_user):raise HTTPException(status_code=403, detail="⛔ Bạn không có quyền xuất file Excel!")target_month = month or datetime.now(VN_TZ).strftime("%m/%Y")user_role = current_user.get("role", "User")username = current_user.get("username", "")df_display = await run_in_threadpool(get_filtered_report_data, target_month, user_role, username, selected_nv, selected_tt, search or "")if df_display.empty:raise HTTPException(status_code=400, detail="Không tìm thấy dữ liệu phù hợp để xuất Excel")14 unmodified lines"Pragma": "no-cache","Expires": "0"})# ==========================================# BÁO CÁO TỔNG QUÁT SỐ LƯỢNG ĐƠN LẮP ĐẶT# ==========================================@router.get("/bao-cao-lap-dat", response_class=HTMLResponse)async def bao_cao_lap_dat(request: Request,start_date: Optional[str] = Query(None),end_date: Optional[str] = Query(None),username: Optional[str] = Query(None),user_payload: dict = Depends(require_login)):"""Trang Báo cáo Tổng quát Số lượng Đơn Lắp đặt & Phụ cấp."""if not can_access('report_cham_cong', user_payload):return HTMLResponse("<h2>⚠️ Bạn không có quyền truy cập Báo cáo Lắp đặt!</h2>", status_code=403)try:user_role = str(user_payload.get("role") or "user").strip().lower()if user_role not in ALLOWED_ADMIN_ROLES:username = user_payload.get("username")today = datetime.now(VN_TZ).date()if not end_date:end_date = today.strftime("%Y-%m-%d")if not start_date:start_date = (today - timedelta(days=30)).strftime("%Y-%m-%d")# 🟢 ĐÃ KHẮC PHỤC: Chuẩn hóa múi giờ +07:00 tránh lệch 7 tiếng UTCstart_ts = f"{start_date}T00:00:00+07:00"end_ts = f"{end_date}T23:59:59+07:00"def _fetch_lap_dat_data():query = (supabase_admin.table("cham_cong").select("*").gte("thoi_gian", start_ts).lte("thoi_gian", end_ts).limit(5000) # 🟢 ĐÃ KHẮC PHỤC: Thêm limit 5000 tránh bị xén ở mốc 1000)if username:query = query.eq("username", username)res_cc = query.execute()users_res = (supabase_admin.table("quan_tri_vien").select("username, ho_ten").execute())return res_cc.data or [], users_res.data or []# 🟢 ĐÃ KHẮC PHỤC: Chạy bất đồng bộ tránh làm nghẽn Event Loop FastAPIrecords, all_users = await run_in_threadpool(_fetch_lap_dat_data)staff_summary: Dict[str, Dict[str, Any]] = {}daily_trend: Dict[str, int] = {}total_orders = len(records)total_payout = 0.0total_km = 0.0def to_float(value):if value is None or value == "":return 0.0try:return float(value)except (TypeError, ValueError):return 0.0for item in records:staff_name = (item.get("ten")or item.get("ho_ten")or item.get("username")or "Chưa rõ")thoi_gian = item.get("thoi_gian")date_str = str(thoi_gian)[:10] if thoi_gian else "N/A"money = to_float(item.get("thanh_tien"))km = to_float(item.get("quang_duong"))total_payout += moneytotal_km += kmif staff_name not in staff_summary:staff_summary[staff_name] = {"count": 0,"total_money": 0.0,"total_km": 0.0}staff_summary[staff_name]["count"] += 1staff_summary[staff_name]["total_money"] += moneystaff_summary[staff_name]["total_km"] += kmdaily_trend[date_str] = daily_trend.get(date_str, 0) + 1sorted_staff_list = []for name, info in sorted(staff_summary.items(), key=lambda x: x[1]["count"], reverse=True):sorted_staff_list.append({"name": name,"count": info["count"],"total_money": info["total_money"],"total_km": info["total_km"]})chart_staff_names = [item["name"] for item in sorted_staff_list]chart_staff_counts = [item["count"] for item in sorted_staff_list]sorted_dates = sorted(daily_trend.keys())chart_dates = sorted_dateschart_date_counts = [daily_trend[d] for d in sorted_dates]return templates.TemplateResponse(request=request,name="admin/admin_report_cham_cong.html",context={"start_date": start_date,"end_date": end_date,"selected_user": username,"current_user": user_payload,"all_users": all_users,"total_orders": total_orders,"total_payout": total_payout,"total_km": total_km,"staff_list": sorted_staff_list,"chart_data": {"staffNames": chart_staff_names,"staffCounts": chart_staff_counts,"dates": chart_dates,"dateCounts": chart_date_counts,},},)except Exception as e:logger.error(f"Lỗi truy vấn báo cáo chấm công: {str(e)}", exc_info=True)return HTMLResponse(content=f"Đã xảy ra lỗi khi tải báo cáo: {str(e)}", status_code=500)
12342 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758592 unmodified lines6263646566676869707172737475767778import loggingfrom datetime import datetime, timezone, timedeltafrom typing import Dict, Any, Optional2 unmodified linesfrom fastapi.templating import Jinja2Templatesfrom config import supabaselogger = logging.getLogger(__name__)router = APIRouter()templates = Jinja2Templates(directory="app/templates")# Múi giờ Việt Nam (UTC+7)VIETNAM_TZ = timezone(timedelta(hours=7))def format_vn_time(value: Optional[str]) -> str:"""Chuyển đổi chuỗi ISO UTC sang giờ Việt Nam (DD/MM/YYYY HH:MM)."""if not value:return ""try:# Chuẩn hóa chuỗi UTC từ Supabaseclean_value = str(value).replace("Z", "+00:00")dt = datetime.fromisoformat(clean_value)# Chuyển sang múi giờ Việt Namdt_vn = dt.astimezone(VIETNAM_TZ)return dt_vn.strftime("%d/%m/%Y %H:%M")except Exception:return str(value)# Đăng ký filter với Jinja2 templatestemplates.env.filters["vn_time"] = format_vn_timedef get_current_user_from_session(request: Request) -> Optional[Dict[str, Any]]:"""Dependency kiểm tra session người dùng."""user_id = request.session.get('user_id')if not user_id:return Nonereturn {"is_authenticated": True,"id": user_id,"name": request.session.get('ho_ten', 'Quản trị viên'),"role": request.session.get('role', 'User')}@router.get("/")def index(request: Request,current_user: Optional[Dict[str, Any]] = Depends(get_current_user_from_session)):"""Trang chủ Dashboard: Hiển thị 5 phiếu bảo hành và 5 lượt chấm công mới nhất."""# 1. Điều hướng nếu chưa đăng nhậpif not current_user:return RedirectResponse(url="/auth/login", status_code=303)2 unmodified linestry:if supabase:# Lấy 5 phiếu bảo hành MỚI NHẤT (Bỏ lọc .gte để tránh bị rỗng khi đầu tháng chưa có dữ liệu)res_warranty = (supabase.table('warranty_records').select('id, serial_number, customer_name, model_name, created_at, category').order('created_at', desc=True).limit(5).execute())warranties = res_warranty.data or []# Lấy 5 đơn chấm công MỚI NHẤT (Sắp xếp theo thoi_gian thay vì id)res_cham_cong = (supabase.table('cham_cong').select('id, ten, thoi_gian, so_hoa_don, thanh_tien, trang_thai')123452 unmodified lines8910111213141516171819202122232425262728293031323334353637383940414243444546474849505152532 unmodified lines5657585960616263646566676869707172import loggingfrom pathlib import Pathfrom datetime import datetime, timezone, timedeltafrom typing import Dict, Any, Optional2 unmodified linesfrom fastapi.templating import Jinja2Templatesfrom config import supabasefrom app.templates_config import templatesfrom app.auth import get_current_user_or_redirectlogger = logging.getLogger(__name__)router = APIRouter()# === XỬ LÝ ĐƯỜNG DẪN TEMPLATES LINH HOẠT ===BASE_DIR = Path(__file__).resolve().parentTEMPLATES_DIR = (BASE_DIR.parent / "templates"if (BASE_DIR.parent / "templates").exists()else BASE_DIR / "templates")# === KHAI BÁO MÚI GIỜ & FILTER JINJA2 ===VIETNAM_TZ = timezone(timedelta(hours=7))def format_vn_time(value: Optional[str]) -> str:if not value:return ""try:clean_value = str(value).replace("Z", "+00:00")dt = datetime.fromisoformat(clean_value)dt_vn = dt.astimezone(VIETNAM_TZ)return dt_vn.strftime("%d/%m/%Y %H:%M")except Exception:return str(value)templates.env.filters["vn_time"] = format_vn_time# ==========================================# === 🏠 TRANG CHỦ DASHBOARD ===# ==========================================@router.get("/")def index(request: Request,current_user: Optional[Dict[str, Any]] = Depends(get_current_user_or_redirect)):if not current_user:return RedirectResponse(url="/auth/login", status_code=303)2 unmodified linestry:if supabase:# Truy vấn 1: Lấy 5 bảo hành mới nhất (Đã bổ sung brand_name và ink_type)res_warranty = (supabase.table('warranty_records').select('id, serial_number, customer_name, brand_name, model_name, ink_type, created_at, category').order('created_at', desc=True).limit(5).execute())warranties = res_warranty.data or []# Truy vấn 2: Lấy 5 chấm công / lắp đặt mới nhấtres_cham_cong = (supabase.table('cham_cong').select('id, ten, thoi_gian, so_hoa_don, thanh_tien, trang_thai')
123456789101112# app/templates_config.pyfrom fastapi.templating import Jinja2Templatesfrom config import SUPABASE_URL, SUPABASE_KEYfrom app.permissions import can_access
# Khởi tạo Jinja2Templates duy nhất cho toàn ứng dụngtemplates = Jinja2Templates(directory="app/templates")
# Đăng ký các biến & hàm global dùng chungtemplates.env.globals["SUPABASE_URL"] = SUPABASE_URLtemplates.env.globals["SUPABASE_KEY"] = SUPABASE_KEYtemplates.env.globals["can_access"] = can_access9 unmodified lines101112139 unmodified linesreturn response, Noneexcept Exception as e:# Trả về lỗi nếu sai mật khẩu hoặc tài khoản không tồn tạireturn None, str(e)9 unmodified lines101112131415161718192021222324252627289 unmodified linesreturn response, Noneexcept Exception as e:# Trả về lỗi nếu sai mật khẩu hoặc tài khoản không tồn tạireturn None, str(e)def apply_department_scope(query, user: dict):"""Tự động áp đặt phạm vi dữ liệu dựa trên Phòng ban của User:- System Admin / Super Admin hoặc Department == 'ALL': Xem toàn bộ dữ liệu.- Admin / User của phòng ban khác (KTSC, KD, KT...): Chỉ xem/sửa dữ liệu phòng ban mình."""user_role = str(user.get("role") or "").strip().lower()user_dept = str(user.get("department") or "KTSC").strip().upper()# 1. Quản trị cấp cao hoặc tài khoản ALL được toàn quyền xem dữ liệu các phòng banif user_role in ["system admin", "super admin"] or user_dept == "ALL":return query# 2. Ngược lại, ép buộc truy vấn CSDL chỉ trả về dữ liệu thuộc phòng ban của User đóreturn query.eq("department", user_dept)
app/__init__.py+6-6
app/auth.py+222-307
app/cham_cong.py+167-338
app/inventory.py+146-283
app/pdf_warranty.pyAdded+124
app/permissions.pyAdded+177
app/report.py+235-68
app/routes.py+19-25
app/templates_config.pyAdded+12
app/utils.py+16-1