121 lines
5.1 KiB
Python
Executable File
121 lines
5.1 KiB
Python
Executable File
from __future__ import annotations
|
||
|
||
import uuid
|
||
|
||
from fastapi import Depends, FastAPI
|
||
from fastapi.exceptions import RequestValidationError
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import FileResponse, JSONResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
|
||
from . import audit, config, finance, security
|
||
from .db import Base, SessionLocal, engine
|
||
from .routers import ai, auth, board, custom, export, focus, projects, rbac, staff, weekly
|
||
from .schema_patch import drop_stale_columns, ensure_columns
|
||
|
||
Base.metadata.create_all(bind=engine)
|
||
_patch = ensure_columns(engine, Base.metadata)
|
||
if _patch:
|
||
print(f"[ok] 已补齐数据库字段:{', '.join(_patch)}")
|
||
_dropped = drop_stale_columns(engine)
|
||
if _dropped:
|
||
print(f"[ok] 已清理历史死列:{', '.join(_dropped)}")
|
||
|
||
# 内置角色与管理员(一次性旧库迁移 migrate_legacy_rbac 已于 2026-11 下线:
|
||
# 它只服务 2026-10-01 之前的库;那种库请先升级到含迁移的版本再上当前版本)
|
||
with SessionLocal() as _db:
|
||
for _note in security.ensure_seed(_db):
|
||
print(f"[ok] {_note}")
|
||
security.purge_expired_sessions(_db)
|
||
audit.prune(_db)
|
||
# 定开财务口径回填(验收年份 / 由项目状态推导阶段),幂等
|
||
for _note in finance.backfill(_db):
|
||
print(f"[ok] {_note}")
|
||
|
||
# 每次进程启动换一个值;热加载重启后前端据此自动刷新
|
||
BOOT_ID = uuid.uuid4().hex
|
||
|
||
app = FastAPI(title="DMS管理平台", version="1.0.0")
|
||
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"],
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
# 所有 /api 接口先过 RBAC 总闸(登录 + 菜单权限),登录接口自身除外
|
||
api = FastAPI(title="DMS管理平台 API", dependencies=[Depends(security.guard)])
|
||
|
||
|
||
@api.exception_handler(RequestValidationError)
|
||
async def validation_error_cn(request, exc):
|
||
"""Pydantic/查询参数校验失败默认返回英文 detail,前端会原样 toast 出「Field required」。
|
||
统一换成中文,界面不再中英夹杂。"""
|
||
bits = []
|
||
for e in exc.errors():
|
||
field = str(e.get("loc", ("?",))[-1])
|
||
kind = "不能为空" if str(e.get("type", "")).endswith("missing") else "格式不正确"
|
||
bits.append(f"「{field}」{kind}")
|
||
return JSONResponse(status_code=422, content={"detail": "提交的数据有误:" + ";".join(bits)})
|
||
|
||
|
||
@api.exception_handler(Exception)
|
||
async def server_error_cn(request, exc):
|
||
"""未捕获异常的默认响应是纯文本 'Internal Server Error',同样会被前端 toast 出来。"""
|
||
return JSONResponse(status_code=500, content={"detail": "服务器内部错误,请稍后重试"})
|
||
api.middleware("http")(audit.audit_middleware_factory())
|
||
api.include_router(board.router, prefix="", tags=["board"])
|
||
api.include_router(projects.router, prefix="", tags=["projects"])
|
||
api.include_router(ai.router, prefix="", tags=["ai"])
|
||
api.include_router(custom.router, prefix="", tags=["custom"])
|
||
api.include_router(export.router, prefix="", tags=["export"])
|
||
api.include_router(staff.router, prefix="", tags=["staff"])
|
||
api.include_router(weekly.router, prefix="", tags=["weekly"])
|
||
api.include_router(focus.router, prefix="", tags=["focus"])
|
||
api.include_router(auth.router, prefix="", tags=["auth"])
|
||
api.include_router(rbac.router, prefix="", tags=["rbac"])
|
||
app.mount("/api", api)
|
||
|
||
# 前端是 Vite 构建产物(web/src → web/dist,栈见 nex.config.yaml:React + TS + AntD + Tailwind v4)。
|
||
# 没构建时退回 web/legacy(改造前的零构建版),本地与容器里都不会白屏。
|
||
# 构建资源以 /static/ 为 base(见 web/vite.config.ts),所以静态目录整个挂到 /static。
|
||
WEB_DIR = config.BASE_DIR / "web"
|
||
DIST_DIR = WEB_DIR / "dist"
|
||
STATIC_DIR = DIST_DIR if (DIST_DIR / "index.html").is_file() else WEB_DIR / "legacy"
|
||
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
||
|
||
|
||
# index.html 不能启发式缓存(它指向的产物文件名带哈希,只有 index.html 会变),
|
||
# no-cache 不做新鲜度缓存、只带 ETag 回源校验(未变更时返回 304)。
|
||
@app.middleware("http")
|
||
async def no_cache_frontend(request, call_next):
|
||
response = await call_next(request)
|
||
if request.url.path == "/" or request.url.path.startswith("/static/"): # 产物文件名带哈希,index.html 才是不缓存的关键
|
||
response.headers["Cache-Control"] = "no-cache"
|
||
return response
|
||
|
||
|
||
@app.get("/health")
|
||
def health():
|
||
return {
|
||
"ok": True,
|
||
"db": config.DATABASE_URL.split("://")[0],
|
||
"dev": config.DEV,
|
||
"boot": BOOT_ID,
|
||
}
|
||
|
||
|
||
@app.get("/")
|
||
def index():
|
||
return FileResponse(str(STATIC_DIR / "index.html"))
|
||
|
||
|
||
@app.get("/{path:path}")
|
||
def spa(path: str):
|
||
"""单页应用深链:/custom、/settings/… 这类路径没有实体文件,一律交回 index.html 由前端路由。
|
||
带扩展名的请求(.js/.css/.svg…)已经由各 mount 接走,落到这里就是 404,不要假装修上了。"""
|
||
if "." in path.rsplit("/", 1)[-1]:
|
||
return JSONResponse({"detail": "没有这个资源"}, status_code=404)
|
||
return FileResponse(str(STATIC_DIR / "index.html"))
|