diff --git a/app/audit.py b/app/audit.py index cfdb10e..dfa76da 100644 --- a/app/audit.py +++ b/app/audit.py @@ -15,8 +15,6 @@ from sqlalchemy.orm import Session from .db import SessionLocal from .models import AuditLog, now -# 命中这些路径前缀的 GET 也要留痕(登录相关) -TRACKED_GETS = () # 方法 → 动作 METHOD_ACTION = {"POST": "create", "PUT": "update", "PATCH": "update", "DELETE": "delete"} # 特殊动作:路径以这些结尾时按语义记,不套 method 默认值 @@ -42,7 +40,7 @@ def action_for(path: str, method: str) -> str | None: return SPECIAL_ACTION[clean] if method in METHOD_ACTION: return METHOD_ACTION[method] - if clean.endswith("/revoke") or clean.endswith("/purge"): + if clean.endswith("/revoke"): return "revoke" return None diff --git a/app/constants.py b/app/constants.py index f864191..a154a00 100644 --- a/app/constants.py +++ b/app/constants.py @@ -15,8 +15,6 @@ STATUSES = [ STATUS_MAP = {code: (name, color) for code, name, color in STATUSES} STATUS_CODES = [c for c, _, _ in STATUSES] -NEGATIVE_STATUS = ("at_risk", "blocked", "paused") - # 项目优先级 PRIORITIES = [ ("p0", "P0 最高", "#dc2626"), @@ -24,7 +22,6 @@ PRIORITIES = [ ("p2", "P2 中", "#2563eb"), ("p3", "P3 低", "#6b7280"), ] -PRIORITY_MAP = {code: (name, color) for code, name, color in PRIORITIES} # 台账类别(来自《项目明细表》) LEDGER_CATEGORIES = [ @@ -91,8 +88,6 @@ CUSTOM_STAGES = [ ] CUSTOM_STAGE_MAP = {c: (n, col, r) for c, n, col, r in CUSTOM_STAGES} CUSTOM_STAGE_CODES = [c for c, _, _, _ in CUSTOM_STAGES] -# 阶段先后顺序(用于看板列排序与阶段流转判断) -CUSTOM_STAGE_ORDER = {c: i for i, (c, _, _, _) in enumerate(CUSTOM_STAGES)} def custom_revenue_ratio(stage: str, progress: float | None, manual_ratio=None, @@ -404,22 +399,10 @@ CUSTOM_ANNUAL_TARGETS_DEFAULT = {1: 35.0, 2: 225.0, 3: 160.0, 4: 260.0} # 「在途」阶段:还没走完 入库→签单→交付→验收 这条主线(已计收 / 暂停 / 已关闭不算在途) CUSTOM_INFLIGHT_STAGES = {"lead", "signed", "developing", "delivered", "accepted"} -# 环节顺序索引,用于判断项目当前卡在哪一环 -CUSTOM_STEP_ORDER = {key: i for i, (key, _, _, _, _) in enumerate(CUSTOM_PIPELINE)} - # 环节停滞天数超过该值视为「卡住」,需要在看板上提示 CUSTOM_STEP_AGING_DAYS = 45 -def custom_current_step(dates: dict[str, str | None]) -> int: - """按已完成的环节日期,返回项目当前所处的环节下标(-1 表示连入库都没有)。""" - step = -1 - for i, (_key, _name, field, _stage, _color) in enumerate(CUSTOM_PIPELINE): - if (dates.get(field) or "").strip(): - step = i - return step - - # -------------------------------------------------------------------------- # 人力资源库 # -------------------------------------------------------------------------- diff --git a/app/main.py b/app/main.py index cfc588d..7662019 100644 --- a/app/main.py +++ b/app/main.py @@ -18,9 +18,8 @@ _patch = ensure_columns(engine, Base.metadata) if _patch: print(f"[ok] 已补齐数据库字段:{', '.join(_patch)}") -# 权限模型升级(旧库的 roles.menus / users.role_id → role_menus / user_roles)+ 内置角色与管理员 -for _note in security.migrate_legacy_rbac(engine): - print(f"[ok] {_note}") +# 内置角色与管理员(一次性旧库迁移 migrate_legacy_rbac 已于 2026-11 下线: +# 它只服务 2026-10-01 之前的库;那种库请先升级到含迁移的版本再上当前版本) with SessionLocal() as _db: for _note in security.ensure_seed(_db): print(f"[ok] {_note}") diff --git a/app/schemas.py b/app/schemas.py index 3850c79..bfac7fd 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -40,21 +40,6 @@ class CategoryIn(BaseModel): color: str = "#2563eb" -class PeriodIn(BaseModel): - label: str - kind: str = "week" - year: int - month: int - week: int = 0 - start_date: str | None = None - end_date: str | None = None - - -class TaskIn(BaseModel): - project_id: int - name: str - - class UpdateIn(BaseModel): project_id: int task_id: int | None = None @@ -106,10 +91,6 @@ class AICommitIn(BaseModel): model: str | None = None -class SettingsIn(BaseModel): - values: dict[str, str] - - class FocusIn(BaseModel): """每周重点工作(单条录入)。 diff --git a/app/security.py b/app/security.py index 326c385..df4c329 100644 --- a/app/security.py +++ b/app/security.py @@ -15,20 +15,16 @@ from __future__ import annotations import hashlib import hmac -import json import secrets from datetime import datetime, timedelta from fastapi import Depends, HTTPException, Request -from sqlalchemy import inspect, text from sqlalchemy.orm import Session from . import config from .constants import ( LEVEL_LABELS, - LEVEL_RANK, LEVELS, - MENUS, MENU_KEYS, MENU_LABELS, merge_levels, @@ -40,10 +36,10 @@ SESSION_COOKIE = "unis_session" PBKDF2_ROUNDS = 120_000 __all__ = [ - "MENUS", "MENU_KEYS", "MENU_LABELS", "LEVELS", "LEVEL_LABELS", - "SESSION_COOKIE", "normalize_menus", "menus_json", "hash_password", "verify_password", + "MENU_KEYS", "MENU_LABELS", "LEVELS", "LEVEL_LABELS", + "SESSION_COOKIE", "normalize_menus", "hash_password", "verify_password", "start_session", "revoke_all", "user_from_token", "current_user", "guard", - "resolve_rule", "ensure_seed", "migrate_legacy_rbac", "level_of", + "resolve_rule", "ensure_seed", ] # 接口路径首段 -> 菜单。没列出来的(/meta 等)只要求登录,不看菜单。 @@ -81,16 +77,6 @@ def normalize_menus(raw) -> dict: return out -def menus_json(menus: dict) -> str: - return json.dumps(normalize_menus(menus), ensure_ascii=False, sort_keys=True) - - -def level_of(user: User | None, menu: str) -> str: - if user is None: - return "" - return user.menus.get(menu, "") - - # ------------------------------------------------------------------ 密码 def hash_password(password: str) -> tuple[str, str]: salt = secrets.token_hex(16) @@ -153,56 +139,6 @@ def user_from_token(db: Session, token: str | None) -> User | None: return user -# ------------------------------------------------------------------ 旧库升级 -def migrate_legacy_rbac(engine) -> list[str]: - """把旧版的 roles.menus(JSON) / users.role_id 迁到 role_menus / user_roles。 - - 幂等:目标表里已经有数据就跳过。老库升级后第一次启动自动完成。 - """ - notes: list[str] = [] - insp = inspect(engine) - tables = set(insp.get_table_names()) - if "roles" not in tables or "users" not in tables: - return notes - with engine.begin() as conn: - cols = {c["name"] for c in insp.get_columns("roles")} - if "menus" in cols and "role_menus" in tables: - filled = conn.execute(text("SELECT COUNT(*) FROM role_menus")).scalar() or 0 - if not filled: - rows = conn.execute(text("SELECT id, menus FROM roles")).all() - moved = 0 - for rid, raw in rows: - if not raw: - continue - try: - data = json.loads(raw) - except ValueError: - continue - for menu, level in normalize_menus(data).items(): - conn.execute( - text("INSERT INTO role_menus(role_id, menu, level, created_at) " - "VALUES(:r,:m,:l,:c)"), - {"r": rid, "m": menu, "l": level, "c": now()}, - ) - moved += 1 - if moved: - notes.append(f"角色菜单授权已迁到 role_menus({moved} 条)") - if "role_id" in {c["name"] for c in insp.get_columns("users")} and "user_roles" in tables: - filled = conn.execute(text("SELECT COUNT(*) FROM user_roles")).scalar() or 0 - if not filled: - rows = conn.execute( - text("SELECT id, role_id FROM users WHERE role_id IS NOT NULL") - ).all() - for uid, rid in rows: - conn.execute( - text("INSERT INTO user_roles(user_id, role_id, created_at) VALUES(:u,:r,:c)"), - {"u": uid, "r": rid, "c": now()}, - ) - if rows: - notes.append(f"用户角色已迁到 user_roles({len(rows)} 条)") - return notes - - # ------------------------------------------------------------------ 内置数据 BUILTIN_ROLES = [ ("管理员", "全部菜单可编辑,含设置与权限管理", {k: "rw" for k in MENU_KEYS}, True), @@ -307,12 +243,3 @@ def current_user(request: Request, db: Session = Depends(get_db)) -> User: raise HTTPException(status_code=401, detail="请先登录") request.state.user = user return user - - -def require_level(menu: str, level: str = "rw"): - """给个别高危接口用的显式授权依赖(除菜单写权限外还要求指定菜单可编辑)。""" - def dep(user: User = Depends(current_user)) -> User: - if LEVEL_RANK.get(user.menus.get(menu, ""), 0) < LEVEL_RANK.get(level, 0): - raise HTTPException(status_code=403, detail=f"需要「{MENU_LABELS.get(menu, menu)}」的可编辑权限") - return user - return dep