unis_hrms/app/api/v1/common.py

242 lines
9.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""公共能力:文件上传下载、数据字典、聚合下拉选项、健康检查."""
from __future__ import annotations
import uuid
from datetime import datetime
from pathlib import Path
from typing import Annotated
from fastapi import APIRouter, Depends, File, Form, Query, UploadFile
from fastapi.responses import FileResponse
from pydantic import BaseModel, ConfigDict
from sqlalchemy import select
from ..helpers import label_map
from ...core.config import settings
from ...core.deps import (
AuthCtx,
Session,
apply_employee_scope,
can_see_employee,
ensure,
require_perm,
)
from ...core.errors import AppError
from ...models.benefits import InsurancePlan, LeaveType
from ...models.org import Department, DictItem, DictType, JobLevel, Position
from ...models.payroll import SalaryItem
from ...models.rbac import Attachment
from ...models.benefits import BenefitItem
router = APIRouter(prefix="/common", tags=["公共"])
SAFE_EXT = {
".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg",
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
".txt", ".csv", ".zip", ".rar", ".7z",
}
class AttachmentRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
stored_name: str
content_type: str | None = None
size: int = 0
biz_type: str | None = None
biz_id: int | None = None
employee_id: int | None = None
uploaded_by: int | None = None
created_at: datetime | None = None
def _safe_name(name: str) -> str:
name = (name or "file").replace("\\", "/").split("/")[-1].strip()
return name[:180] or "file"
@router.get("/health", summary="健康检查")
async def health() -> dict:
return {"status": "ok", "app": settings.app_name, "version": settings.version,
"database": "sqlite" if settings.is_sqlite else "mysql"}
# ---------------------------------------------------------------- 文件管理 ----
@router.post("/upload", response_model=AttachmentRead, summary="上传附件")
async def upload_file(
session: Session,
auth: AuthCtx,
file: Annotated[UploadFile, File()],
biz_type: Annotated[str | None, Form()] = None,
biz_id: Annotated[int | None, Form()] = None,
employee_id: Annotated[int | None, Form()] = None,
):
data = await file.read()
limit = settings.max_upload_mb * 1024 * 1024
if not data:
raise AppError("上传文件为空", "empty_file")
if len(data) > limit:
raise AppError(f"文件超过 {settings.max_upload_mb}MB 限制", "file_too_large")
original = _safe_name(file.filename or "file")
ext = Path(original).suffix.lower()
if ext and ext not in SAFE_EXT:
raise AppError(f"不支持的文件类型 {ext}", "unsupported_type")
stored = f"{uuid.uuid4().hex}{ext}"
day_dir = Path(settings.upload_dir)
day_dir.mkdir(parents=True, exist_ok=True)
(day_dir / stored).write_bytes(data)
record = Attachment(
name=original, stored_name=stored, path=str(day_dir / stored),
content_type=file.content_type, size=len(data), biz_type=biz_type,
biz_id=biz_id, employee_id=employee_id, uploaded_by=auth.user.id,
)
session.add(record)
await session.commit()
await session.refresh(record)
return record
@router.get("/files", response_model=list[AttachmentRead], summary="附件列表")
async def list_files(
session: Session,
auth: Annotated[AuthCtx, Depends(require_perm("employee:attachment:read"))],
biz_type: str | None = Query(None),
biz_id: int | None = Query(None),
employee_id: int | None = Query(None),
):
stmt = select(Attachment).order_by(Attachment.id.desc())
if biz_type:
stmt = stmt.where(Attachment.biz_type == biz_type)
if biz_id:
stmt = stmt.where(Attachment.biz_id == biz_id)
if employee_id:
stmt = stmt.where(Attachment.employee_id == employee_id)
stmt = await apply_employee_scope(session, stmt, auth, Attachment.employee_id)
return list((await session.execute(stmt.limit(300))).scalars().all())
@router.get("/files/{item_id}", summary="下载附件")
async def download_file(item_id: int, session: Session, auth: AuthCtx):
record = await session.get(Attachment, item_id)
ensure(record is not None, "附件不存在", "not_found")
if record.employee_id and not await can_see_employee(session, auth, record.employee_id):
raise AppError("没有权限下载该附件", "forbidden", 403)
path = Path(record.path)
if not path.exists():
path = Path(settings.upload_dir) / record.stored_name
if not path.exists():
raise AppError("文件已丢失,请重新上传", "file_missing")
inline = (record.content_type or "").startswith("image/")
return FileResponse(str(path), filename=record.name,
media_type=record.content_type,
content_disposition_type="inline" if inline else "attachment")
@router.delete("/files/{item_id}", summary="删除附件")
async def delete_file(
item_id: int, session: Session,
auth: Annotated[AuthCtx, Depends(require_perm("employee:attachment:delete"))],
):
record = await session.get(Attachment, item_id)
ensure(record is not None, "附件不存在", "not_found")
if record.employee_id and not await can_see_employee(session, auth, record.employee_id):
raise AppError("没有权限删除该附件", "forbidden", 403)
path = Path(record.path)
if path.exists():
try:
path.unlink()
except OSError:
pass
await session.delete(record)
await session.commit()
return {"message": "已删除"}
# ---------------------------------------------------------------- 数据字典 ----
@router.get("/dict/{type_code}", summary="按类型读取字典项")
async def dict_items(type_code: str, session: Session, auth: AuthCtx):
rows = list((await session.execute(
select(DictItem).where(DictItem.type_code == type_code, DictItem.is_active.is_(True))
.order_by(DictItem.sort, DictItem.id))).scalars().all())
return [{"label": r.label, "value": r.value, "extra": r.extra, "sort": r.sort} for r in rows]
@router.get("/dict", summary="全部字典类型")
async def dict_types(session: Session, auth: AuthCtx):
rows = list((await session.execute(
select(DictType).order_by(DictType.id))).scalars().all())
return [{"code": r.code, "name": r.name, "builtin": r.builtin} for r in rows]
# ------------------------------------------------------------ 聚合下拉选项 ----
async def _model_options(session, model, label_attr: str = "name",
only_active: bool = False) -> list[dict]:
"""聚合下拉选项。
停用的资源**照样返回**并带上 ``extra.is_active``:历史数据(如员工所属部门)
仍要能解析出名称,但前端会把它标成不可选,避免新记录继续挂到停用资源上。
"""
stmt = select(model)
if only_active and hasattr(model, "is_active"):
stmt = stmt.where(model.is_active.is_(True))
rows = list((await session.execute(stmt.order_by(getattr(model, "id")))).scalars().all())
out: list[dict] = []
for r in rows:
item = {"id": r.id, "label": getattr(r, label_attr)}
if hasattr(r, "is_active"):
item["extra"] = {"is_active": bool(r.is_active)}
out.append(item)
return out
@router.get("/options", summary="聚合下拉选项")
async def options(
session: Session, auth: AuthCtx,
groups: str = Query("department,position,joblevel,dict",
description="逗号分隔:department/position/joblevel/plan/item/"
"leavetype/benefit/insurance/dict/status"),
):
wanted = {g.strip() for g in groups.split(",") if g.strip()}
out: dict[str, list] = {}
if "department" in wanted:
out["department"] = await _model_options(session, Department)
if "position" in wanted:
out["position"] = await _model_options(session, Position)
if "joblevel" in wanted:
out["joblevel"] = await _model_options(session, JobLevel)
if "item" in wanted:
out["item"] = await _model_options(session, SalaryItem, label_attr="name")
if "leavetype" in wanted:
out["leavetype"] = await _model_options(session, LeaveType)
if "benefit" in wanted:
out["benefit"] = await _model_options(session, BenefitItem)
if "insurance" in wanted:
out["insurance"] = await _model_options(session, InsurancePlan)
if "dict" in wanted:
rows = list((await session.execute(
select(DictItem).where(DictItem.is_active.is_(True))
.order_by(DictItem.type_code, DictItem.sort, DictItem.id))).scalars().all())
grouped: dict[str, list] = {}
for r in rows:
grouped.setdefault(r.type_code, []).append(
{"label": r.label, "value": r.value, "extra": r.extra})
out["dict"] = grouped
if "status" in wanted:
from .employee import STATUS_LABELS
out["status"] = [{"value": k, "label": v} for k, v in STATUS_LABELS.items()]
return out
@router.get("/summary-labels", summary="名称映射(部门/职位/职级)")
async def summary_labels(session: Session, auth: AuthCtx):
return {
"department": await label_map(session, Department),
"position": await label_map(session, Position),
"joblevel": await label_map(session, JobLevel),
}