feat: ship OA drafts/badges, role dual-track, and test-env deploy tooling.

Add approval instance drafts with menu badges, dual-track user/role read model and role bound names, form-designer outline docs, and bare-metal test deploy scripts. Ignore local test-server credential file.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zlwuandCursor committed 2026-08-06 13:58:47 +08:00
1 parent 7af53fc344
commit de22678c87
56 files changed
+11861 -6082

No files matched your search

+18 -24
View File
@@ -26,8 +26,11 @@ from app.crud import menu as menu_svc
from app.crud import role as role_svc
from app.crud import user as user_svc
from app.crud.collection_protocol import _lookup_attachment_by_url
from app.models.models import BizAttachment, SysDept, SysRole, SysUser, SysUserRole
from app.services.web_auth_roles import _map_role_name_to_web
from app.models.models import BizAttachment, SysDept, SysRole, SysUser
from app.services.web_auth_roles import (
_map_role_name_to_web,
list_user_ids_with_effective_role_name,
)
router = APIRouter(prefix="/web/admin", tags=["运营端管理"])
@@ -77,7 +80,7 @@ async def list_users_for_select(
):
"""返回用户下拉选项(label=昵称,value=用户ID),供流程设计器审批人选择使用。
可选 roleName:按 sys_role.role_name 精确过滤拥有该角色的用户。
可选 roleName:按有效角色(直接绑定 ∪ 职位继承)精确过滤。
"""
tenant_no = _user.get("tenant_no", "")
q = db.query(SysUser).filter(SysUser.del_flag == 0, SysUser.status == "1")
@@ -85,18 +88,12 @@ async def list_users_for_select(
q = q.filter(SysUser.tenant_no == tenant_no)
rn = (roleName or "").strip()
if rn:
q = (
q.join(SysUserRole, SysUserRole.user_id == SysUser.id)
.join(SysRole, SysRole.id == SysUserRole.role_id)
.filter(
SysUserRole.del_flag == 0,
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.role_name == rn,
)
matched_ids = list_user_ids_with_effective_role_name(
db, tenant_no=tenant_no or settings.DEFAULT_TENANT_NO, role_name=rn
)
if tenant_no:
q = q.filter(SysUserRole.tenant_no == tenant_no, SysRole.tenant_no == tenant_no)
if not matched_ids:
return success_response([])
q = q.filter(SysUser.id.in_(matched_ids))
rows = q.order_by(SysUser.create_time.desc()).distinct().all()
out = [{"label": (r.nick_name or r.user_no or ""), "value": r.id} for r in rows]
return success_response(out)
@@ -317,17 +314,14 @@ async def list_users(
query = query.filter(SysUser.status == status)
rn = (roleName or "").strip()
if rn:
query = (
query.join(SysUserRole, SysUserRole.user_id == SysUser.id)
.join(SysRole, SysRole.id == SysUserRole.role_id)
.filter(
SysUserRole.del_flag == 0,
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.role_name == rn,
)
matched_ids = list_user_ids_with_effective_role_name(
db, tenant_no=tenant_no, role_name=rn
)
query = query.filter(SysUserRole.tenant_no == tenant_no, SysRole.tenant_no == tenant_no)
if not matched_ids:
return success_response(
{"list": [], "total": 0, "page": page, "pageSize": pageSize, "totalPages": 0}
)
query = query.filter(SysUser.id.in_(matched_ids))
query = apply_data_scope(query, SysUser, user, db, tenant_no)
total = query.distinct().count()
items = (
+272
View File
@@ -1,4 +1,5 @@
"""OA 审批管理接口(钉钉交互)"""
from datetime import datetime
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, Query
@@ -8,7 +9,9 @@ from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.menu_guard import require_admin_or_super_admin
from app.core.response import error_response, success_response
from app.core.utils import parse_datetime
from app.crud import oa_approval as oa_crud
from app.crud import oa_instance_draft as oid_crud
from app.crud import oa_receive_account as ora_crud
from app.models.models import SysUser
from app.services.oa_receive_account import normalize_account_fields
@@ -164,6 +167,258 @@ async def delete_receive_account(
return success_response(None, message="删除成功")
# ---------------------------------------------------------------------------
# 发起审批草稿箱(oa_instance_draft)
# ---------------------------------------------------------------------------
class OaInstanceDraftBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
app_id: str = Field(..., alias="appId")
form_data: Optional[Dict[str, Any]] = Field(None, alias="formData")
title: Optional[str] = None
initiator_dept_id: Optional[str] = Field(None, alias="initiatorDeptId")
initiator_select_by_node: Optional[Dict[str, List[str]]] = Field(
None, alias="initiatorSelectByNode"
)
class OaInstanceDraftUpdateBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
form_data: Optional[Dict[str, Any]] = Field(None, alias="formData")
title: Optional[str] = None
initiator_dept_id: Optional[str] = Field(None, alias="initiatorDeptId")
initiator_select_by_node: Optional[Dict[str, List[str]]] = Field(
None, alias="initiatorSelectByNode"
)
class OaInstanceDraftBatchDeleteBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
ids: List[str] = Field(default_factory=list)
class OaInstanceDraftSubmitBody(BaseModel):
model_config = ConfigDict(populate_by_name=True)
form_data: Optional[Dict[str, Any]] = Field(None, alias="formData")
title: Optional[str] = None
initiator_dept_id: Optional[str] = Field(None, alias="initiatorDeptId")
initiator_select_by_node: Optional[Dict[str, List[str]]] = Field(
None, alias="initiatorSelectByNode"
)
def _parse_draft_range_end(raw: Optional[str]) -> Optional[datetime]:
"""截止日期:仅日期时扩到当天 23:59:59。"""
if not raw or not str(raw).strip():
return None
s = str(raw).strip()
dt = parse_datetime(s)
if dt is None and len(s) == 10:
try:
dt = datetime.strptime(s, "%Y-%m-%d")
except ValueError:
return None
if dt is None:
return None
if len(s) <= 10:
return dt.replace(hour=23, minute=59, second=59)
return dt
def _parse_draft_range_start(raw: Optional[str]) -> Optional[datetime]:
if not raw or not str(raw).strip():
return None
s = str(raw).strip()
dt = parse_datetime(s)
if dt is None and len(s) == 10:
try:
return datetime.strptime(s, "%Y-%m-%d")
except ValueError:
return None
return dt
@router.get("/drafts/count")
async def oa_instance_draft_count(
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
tenant_no = _get_tenant_no(db, user)
n = oid_crud.count_drafts(
db,
tenant_no=tenant_no,
owner_user_id=user.get("user_id") or "",
)
return success_response({"count": int(n)})
@router.get("/drafts")
async def list_oa_instance_drafts(
page: int = Query(1, ge=1),
pageSize: int = Query(20, ge=1, le=100),
keyword: Optional[str] = None,
groupId: Optional[str] = None,
updateTimeFrom: Optional[str] = None,
updateTimeTo: Optional[str] = None,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
tenant_no = _get_tenant_no(db, user)
items, total = oid_crud.list_drafts(
db,
tenant_no=tenant_no,
owner_user_id=user.get("user_id") or "",
keyword=keyword,
group_id=groupId,
update_time_from=_parse_draft_range_start(updateTimeFrom),
update_time_to=_parse_draft_range_end(updateTimeTo),
page=page,
page_size=pageSize,
)
return success_response({"list": items, "total": total})
@router.post("/drafts")
async def create_oa_instance_draft(
body: OaInstanceDraftBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
data = oid_crud.create_draft(
db,
tenant_no=tenant_no,
owner_user_id=user.get("user_id") or "",
app_id=body.app_id,
form_data=body.form_data,
initiator_select_by_node=body.initiator_select_by_node,
initiator_dept_id=body.initiator_dept_id,
title=body.title,
create_dept_id=user.get("dept_id") or "",
)
return success_response(data, message="已存入草稿箱")
except ValueError as e:
return error_response(400, str(e))
@router.post("/drafts/batch-delete")
async def batch_delete_oa_instance_drafts(
body: OaInstanceDraftBatchDeleteBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
n = oid_crud.batch_soft_delete_drafts(
db,
body.ids,
tenant_no=tenant_no,
owner_user_id=user.get("user_id") or "",
)
return success_response({"deleted": n}, message="删除成功")
except oid_crud.DraftAccessError as e:
return error_response(403, str(e))
except ValueError as e:
return error_response(400, str(e))
@router.get("/drafts/{draft_id}")
async def get_oa_instance_draft(
draft_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
data = oid_crud.get_draft_detail(
db,
draft_id,
tenant_no=tenant_no,
owner_user_id=user.get("user_id") or "",
)
return success_response(data)
except oid_crud.DraftAccessError as e:
return error_response(404, str(e))
@router.put("/drafts/{draft_id}")
async def update_oa_instance_draft(
draft_id: str,
body: OaInstanceDraftUpdateBody,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
data = oid_crud.update_draft(
db,
draft_id,
tenant_no=tenant_no,
owner_user_id=user.get("user_id") or "",
form_data=body.form_data,
initiator_select_by_node=body.initiator_select_by_node,
initiator_dept_id=body.initiator_dept_id,
title=body.title,
)
return success_response(data, message="草稿已保存")
except oid_crud.DraftAccessError as e:
return error_response(404, str(e))
except ValueError as e:
return error_response(400, str(e))
@router.delete("/drafts/{draft_id}")
async def delete_oa_instance_draft(
draft_id: str,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = _get_tenant_no(db, user)
oid_crud.soft_delete_draft(
db,
draft_id,
tenant_no=tenant_no,
owner_user_id=user.get("user_id") or "",
)
return success_response(None, message="删除成功")
except oid_crud.DraftAccessError as e:
return error_response(404, str(e))
@router.post("/drafts/{draft_id}/submit")
async def submit_oa_instance_draft(
draft_id: str,
body: Optional[OaInstanceDraftSubmitBody] = None,
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.services.oa_engine import OaEngineError
payload = body or OaInstanceDraftSubmitBody()
try:
tenant_no = _get_tenant_no(db, user)
data = oid_crud.submit_draft(
db,
draft_id,
tenant_no=tenant_no,
owner_user_id=user.get("user_id") or "",
form_data=payload.form_data,
initiator_select_by_node=payload.initiator_select_by_node,
initiator_dept_id=payload.initiator_dept_id,
title=payload.title,
)
return success_response(data, message="发起成功")
except oid_crud.DraftAccessError as e:
return error_response(404, str(e))
except OaEngineError as e:
return error_response(400, str(e))
except ValueError as e:
return error_response(400, str(e))
# ---------------------------------------------------------------------------
# 分组
# ---------------------------------------------------------------------------
@@ -700,6 +955,23 @@ async def get_related_summaries(
return success_response({"list": items})
@router.get("/tasks/pending/count")
async def oa_pending_task_count(
user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
from app.services.oa_engine import OaEngineError, count_pending_tasks
try:
tenant_no = _get_tenant_no(db, user)
n = count_pending_tasks(
db, tenant_no=tenant_no, user_id=user.get("user_id") or ""
)
return success_response({"count": int(n)})
except OaEngineError as e:
return error_response(400, str(e))
@router.get("/tasks/cc/unread-count")
async def oa_cc_unread_count(
user: dict = Depends(require_admin_or_super_admin),
+368
View File
@@ -0,0 +1,368 @@
"""OA 发起审批草稿 CRUD(oa_instance_draft)"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.crud import oa_approval as oa_crud
from app.models.models import OaApp, OaAppGroup, OaAppVersion, OaInstanceDraft
def _loads(raw: Any, default: Any) -> Any:
if raw is None or raw == "":
return default
if isinstance(raw, (dict, list)):
return raw
try:
return json.loads(raw)
except (TypeError, ValueError, json.JSONDecodeError):
return default
def _dumps(obj: Any) -> Optional[str]:
if obj is None:
return None
return json.dumps(obj, ensure_ascii=False)
def row_to_dict(
d: OaInstanceDraft,
*,
app_name: str = "",
version_no: Optional[int] = None,
group_id: str = "",
group_name: str = "",
include_payload: bool = False,
) -> Dict[str, Any]:
out: Dict[str, Any] = {
"id": d.id,
"appId": d.app_id,
"appVersionId": d.app_version_id,
"appName": app_name or "",
"versionNo": version_no,
"groupId": group_id or "",
"groupName": group_name or "",
"title": d.title or "",
"ownerUserId": d.owner_user_id,
"initiatorDeptId": d.initiator_dept_id or "",
"status": "draft",
"createTime": d.create_time.strftime("%Y-%m-%d %H:%M:%S") if d.create_time else "",
"updateTime": d.update_time.strftime("%Y-%m-%d %H:%M:%S") if d.update_time else "",
}
if include_payload:
out["formData"] = _loads(d.form_data_json, {}) or {}
out["initiatorSelectByNode"] = _loads(d.initiator_select_json, {}) or {}
return out
class DraftAccessError(ValueError):
"""草稿不存在或无权访问"""
def get_owned_draft(
db: Session,
draft_id: str,
*,
tenant_no: str,
owner_user_id: str,
) -> OaInstanceDraft:
row = (
db.query(OaInstanceDraft)
.filter(
OaInstanceDraft.id == draft_id,
OaInstanceDraft.tenant_no == tenant_no,
OaInstanceDraft.owner_user_id == owner_user_id,
OaInstanceDraft.del_flag == 0,
)
.first()
)
if not row:
raise DraftAccessError("草稿不存在或无权访问")
return row
def _enrich(db: Session, d: OaInstanceDraft, *, include_payload: bool = False) -> Dict[str, Any]:
app = (
db.query(OaApp)
.filter(OaApp.id == d.app_id, OaApp.tenant_no == d.tenant_no, OaApp.del_flag == 0)
.first()
)
ver = (
db.query(OaAppVersion)
.filter(OaAppVersion.id == d.app_version_id, OaAppVersion.del_flag == 0)
.first()
)
group_name = ""
group_id = ""
if app and app.group_id:
group_id = app.group_id
g = (
db.query(OaAppGroup)
.filter(OaAppGroup.id == app.group_id, OaAppGroup.del_flag == 0)
.first()
)
if g:
group_name = g.group_name or ""
return row_to_dict(
d,
app_name=(app.app_name if app else "") or "",
version_no=ver.version_no if ver else None,
group_id=group_id,
group_name=group_name,
include_payload=include_payload,
)
def count_drafts(db: Session, *, tenant_no: str, owner_user_id: str) -> int:
return (
db.query(OaInstanceDraft)
.filter(
OaInstanceDraft.tenant_no == tenant_no,
OaInstanceDraft.owner_user_id == owner_user_id,
OaInstanceDraft.del_flag == 0,
)
.count()
)
def list_drafts(
db: Session,
*,
tenant_no: str,
owner_user_id: str,
keyword: Optional[str] = None,
group_id: Optional[str] = None,
update_time_from: Optional[datetime] = None,
update_time_to: Optional[datetime] = None,
page: int = 1,
page_size: int = 20,
) -> Tuple[List[Dict[str, Any]], int]:
q = (
db.query(OaInstanceDraft, OaApp, OaAppVersion, OaAppGroup)
.outerjoin(
OaApp,
(OaApp.id == OaInstanceDraft.app_id)
& (OaApp.tenant_no == OaInstanceDraft.tenant_no)
& (OaApp.del_flag == 0),
)
.outerjoin(
OaAppVersion,
(OaAppVersion.id == OaInstanceDraft.app_version_id) & (OaAppVersion.del_flag == 0),
)
.outerjoin(
OaAppGroup,
(OaAppGroup.id == OaApp.group_id) & (OaAppGroup.del_flag == 0),
)
.filter(
OaInstanceDraft.tenant_no == tenant_no,
OaInstanceDraft.owner_user_id == owner_user_id,
OaInstanceDraft.del_flag == 0,
)
)
kw = (keyword or "").strip()
if kw:
like = f"%{kw}%"
q = q.filter(or_(OaApp.app_name.like(like), OaInstanceDraft.title.like(like)))
gid = (group_id or "").strip()
if gid:
q = q.filter(OaApp.group_id == gid)
if update_time_from is not None:
q = q.filter(OaInstanceDraft.update_time >= update_time_from)
if update_time_to is not None:
q = q.filter(OaInstanceDraft.update_time <= update_time_to)
total = q.order_by(None).with_entities(func.count(OaInstanceDraft.id)).scalar() or 0
page = max(1, page)
page_size = min(max(1, page_size), 100)
rows = (
q.order_by(OaInstanceDraft.update_time.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
items: List[Dict[str, Any]] = []
for d, app, ver, group in rows:
items.append(
row_to_dict(
d,
app_name=(app.app_name if app else "") or "",
version_no=ver.version_no if ver else None,
group_id=(app.group_id if app else "") or "",
group_name=(group.group_name if group else "") or "",
)
)
return items, int(total)
def get_draft_detail(
db: Session,
draft_id: str,
*,
tenant_no: str,
owner_user_id: str,
) -> Dict[str, Any]:
d = get_owned_draft(db, draft_id, tenant_no=tenant_no, owner_user_id=owner_user_id)
return _enrich(db, d, include_payload=True)
def create_draft(
db: Session,
*,
tenant_no: str,
owner_user_id: str,
app_id: str,
form_data: Optional[Dict[str, Any]] = None,
initiator_select_by_node: Optional[Dict[str, Any]] = None,
initiator_dept_id: Optional[str] = None,
title: Optional[str] = None,
create_dept_id: str = "",
) -> Dict[str, Any]:
app = oa_crud.get_app(db, app_id, tenant_no)
if not app or app.status != "1":
raise ValueError("应用不存在或已停用")
ver = oa_crud._find_latest_published(db, app_id, tenant_no)
if not ver:
raise ValueError("应用尚未发布,无法暂存草稿")
now = datetime.now()
row = OaInstanceDraft(
id=generate_uuid(),
app_id=app_id,
app_version_id=ver.id,
title=(title or app.app_name or "")[:200] or None,
form_data_json=_dumps(form_data or {}),
initiator_select_json=_dumps(initiator_select_by_node or {}),
initiator_dept_id=(initiator_dept_id or "").strip() or None,
owner_user_id=owner_user_id,
tenant_no=tenant_no,
create_by=owner_user_id,
create_dept_id=create_dept_id or "",
create_time=now,
update_by=owner_user_id,
update_time=now,
del_flag=0,
)
db.add(row)
db.commit()
db.refresh(row)
return _enrich(db, row, include_payload=True)
def update_draft(
db: Session,
draft_id: str,
*,
tenant_no: str,
owner_user_id: str,
form_data: Optional[Dict[str, Any]] = None,
initiator_select_by_node: Optional[Dict[str, Any]] = None,
initiator_dept_id: Optional[str] = None,
title: Optional[str] = None,
) -> Dict[str, Any]:
d = get_owned_draft(db, draft_id, tenant_no=tenant_no, owner_user_id=owner_user_id)
ver = oa_crud._find_latest_published(db, d.app_id, tenant_no)
if ver:
d.app_version_id = ver.id
if form_data is not None:
d.form_data_json = _dumps(form_data)
if initiator_select_by_node is not None:
d.initiator_select_json = _dumps(initiator_select_by_node)
if initiator_dept_id is not None:
d.initiator_dept_id = (initiator_dept_id or "").strip() or None
if title is not None:
d.title = (title or "")[:200] or None
d.update_by = owner_user_id
d.update_time = datetime.now()
db.commit()
db.refresh(d)
return _enrich(db, d, include_payload=True)
def soft_delete_draft(
db: Session,
draft_id: str,
*,
tenant_no: str,
owner_user_id: str,
) -> None:
d = get_owned_draft(db, draft_id, tenant_no=tenant_no, owner_user_id=owner_user_id)
d.del_flag = 1
d.update_by = owner_user_id
d.update_time = datetime.now()
db.commit()
def batch_soft_delete_drafts(
db: Session,
ids: List[str],
*,
tenant_no: str,
owner_user_id: str,
) -> int:
cleaned = [str(x).strip() for x in (ids or []) if str(x).strip()]
if not cleaned:
raise ValueError("请选择要删除的草稿")
rows = (
db.query(OaInstanceDraft)
.filter(
OaInstanceDraft.id.in_(cleaned),
OaInstanceDraft.tenant_no == tenant_no,
OaInstanceDraft.owner_user_id == owner_user_id,
OaInstanceDraft.del_flag == 0,
)
.all()
)
if len(rows) != len(set(cleaned)):
raise DraftAccessError("草稿不存在或无权访问")
now = datetime.now()
for d in rows:
d.del_flag = 1
d.update_by = owner_user_id
d.update_time = now
db.commit()
return len(rows)
def submit_draft(
db: Session,
draft_id: str,
*,
tenant_no: str,
owner_user_id: str,
form_data: Optional[Dict[str, Any]] = None,
initiator_select_by_node: Optional[Dict[str, Any]] = None,
initiator_dept_id: Optional[str] = None,
title: Optional[str] = None,
) -> Dict[str, Any]:
"""提交草稿:走 start_instance,成功后软删草稿。"""
from app.services.oa_engine import start_instance
d = get_owned_draft(db, draft_id, tenant_no=tenant_no, owner_user_id=owner_user_id)
payload_form = form_data if form_data is not None else (_loads(d.form_data_json, {}) or {})
payload_select = (
initiator_select_by_node
if initiator_select_by_node is not None
else (_loads(d.initiator_select_json, {}) or {})
)
dept = initiator_dept_id if initiator_dept_id is not None else d.initiator_dept_id
use_title = title if title is not None else d.title
data = start_instance(
db,
tenant_no=tenant_no,
app_id=d.app_id,
initiator_user_id=owner_user_id,
initiator_dept_id=dept,
form_data=payload_form if isinstance(payload_form, dict) else {},
title=use_title,
initiator_select_by_node=payload_select if isinstance(payload_select, dict) else {},
)
d.del_flag = 1
d.update_by = owner_user_id
d.update_time = datetime.now()
db.commit()
return data
@@ -8,7 +8,8 @@ from sqlalchemy.orm import Session
from app.core.db_collation import eq_unicode
from app.core.utils import generate_uuid
from app.models.models import BizProductionTaskStep, BizProductionTaskStepAssignee, SysRole, SysUser, SysUserRole
from app.models.models import BizProductionTaskStep, BizProductionTaskStepAssignee, SysUser
from app.services.web_auth_roles import list_user_ids_with_effective_role_name
PRODUCTION_STEP_ASSIGNEE_ROLE = "实验专员"
@@ -35,30 +36,17 @@ def _active_users_in_tenant(
def _active_users_with_role_in_tenant(
db: Session, user_ids: List[str], tenant_no: str, role_name: str
) -> Set[str]:
"""校验候选用户是否拥有指定角色(直接绑定 ∪ 职位继承)。"""
ids = [x.strip() for x in user_ids if (x or "").strip()]
rn = (role_name or "").strip()
if not ids or not rn:
return set()
rows = (
db.query(SysUser.id)
.join(SysUserRole, SysUserRole.user_id == SysUser.id)
.join(SysRole, SysRole.id == SysUserRole.role_id)
.filter(
SysUser.id.in_(ids),
SysUser.tenant_no == tenant_no,
SysUser.del_flag == 0,
SysUser.status == "1",
SysUserRole.del_flag == 0,
SysUserRole.tenant_no == tenant_no,
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.tenant_no == tenant_no,
SysRole.role_name == rn,
)
.distinct()
.all()
return list_user_ids_with_effective_role_name(
db,
tenant_no=tenant_no,
role_name=rn,
candidate_user_ids=ids,
)
return {r[0] for r in rows}
def validate_assignee_user_ids(
+170 -4
View File
@@ -5,11 +5,20 @@ import math
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import and_, func, or_
from sqlalchemy import and_, func
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.models.models import SysRole, SysRoleMenu, SysRoleDataScopeDetail
from app.models.models import (
SysPost,
SysPostRole,
SysRole,
SysRoleDataScopeDetail,
SysRoleMenu,
SysUser,
SysUserPost,
SysUserRole,
)
# ---------------------------------------------------------------------------
@@ -17,7 +26,151 @@ from app.models.models import SysRole, SysRoleMenu, SysRoleDataScopeDetail
# ---------------------------------------------------------------------------
def _row_to_dict(r: SysRole) -> Dict[str, Any]:
def _user_display_name(nick_name: Optional[str], user_no: Optional[str]) -> str:
n = (nick_name or "").strip()
if n:
return n
return (user_no or "").strip()
def _append_unique(out: Dict[str, List[str]], key: str, value: str) -> None:
if not key or not value:
return
bucket = out.setdefault(key, [])
if value not in bucket:
bucket.append(value)
def _bound_user_names_by_role_ids(
db: Session, role_ids: List[str], tenant_no: str
) -> Dict[str, List[str]]:
"""批量查询有效拥有角色的用户显示名(直接绑定 ∪ 启用职位继承)。"""
out: Dict[str, List[str]] = {}
ids = [rid for rid in (role_ids or []) if rid]
tenant = (tenant_no or "").strip()
if not ids or not tenant:
return out
direct_rows = (
db.query(SysUserRole.role_id, SysUser.nick_name, SysUser.user_no)
.join(
SysUser,
and_(SysUser.id == SysUserRole.user_id, SysUser.del_flag == 0),
)
.join(
SysRole,
and_(
SysRole.id == SysUserRole.role_id,
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.tenant_no == tenant,
),
)
.filter(
and_(
SysUserRole.role_id.in_(ids),
SysUserRole.tenant_no == tenant,
SysUserRole.del_flag == 0,
)
)
.order_by(SysUser.nick_name.asc(), SysUser.user_no.asc())
.all()
)
for role_id, nick_name, user_no in direct_rows:
_append_unique(out, role_id, _user_display_name(nick_name, user_no))
post_rows = (
db.query(SysPostRole.role_id, SysUser.nick_name, SysUser.user_no)
.join(
SysPost,
and_(
SysPost.id == SysPostRole.post_id,
SysPost.del_flag == 0,
SysPost.status == "1",
SysPost.tenant_no == tenant,
),
)
.join(
SysUserPost,
and_(
SysUserPost.post_id == SysPost.id,
SysUserPost.del_flag == 0,
SysUserPost.tenant_no == tenant,
),
)
.join(
SysUser,
and_(SysUser.id == SysUserPost.user_id, SysUser.del_flag == 0),
)
.join(
SysRole,
and_(
SysRole.id == SysPostRole.role_id,
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.tenant_no == tenant,
),
)
.filter(
and_(
SysPostRole.role_id.in_(ids),
SysPostRole.tenant_no == tenant,
SysPostRole.del_flag == 0,
)
)
.order_by(SysUser.nick_name.asc(), SysUser.user_no.asc())
.all()
)
for role_id, nick_name, user_no in post_rows:
_append_unique(out, role_id, _user_display_name(nick_name, user_no))
return out
def _bound_post_names_by_role_ids(
db: Session, role_ids: List[str], tenant_no: str
) -> Dict[str, List[str]]:
"""批量查询角色关联的启用职位名称。"""
out: Dict[str, List[str]] = {}
ids = [rid for rid in (role_ids or []) if rid]
tenant = (tenant_no or "").strip()
if not ids or not tenant:
return out
rows = (
db.query(SysPostRole.role_id, SysPost.post_name)
.join(
SysPost,
and_(
SysPost.id == SysPostRole.post_id,
SysPost.del_flag == 0,
SysPost.status == "1",
SysPost.tenant_no == tenant,
),
)
.filter(
and_(
SysPostRole.role_id.in_(ids),
SysPostRole.tenant_no == tenant,
SysPostRole.del_flag == 0,
)
)
.order_by(SysPost.post_name.asc())
.all()
)
for role_id, post_name in rows:
name = (post_name or "").strip()
_append_unique(out, role_id, name)
return out
def _row_to_dict(
r: SysRole,
*,
bound_user_names: Optional[List[str]] = None,
bound_post_names: Optional[List[str]] = None,
) -> Dict[str, Any]:
return {
"id": r.id,
"roleName": r.role_name,
@@ -26,6 +179,8 @@ def _row_to_dict(r: SysRole) -> Dict[str, Any]:
"tenantNo": r.tenant_no or "",
"orderNum": r.order_num if r.order_num is not None else 0,
"remark": r.remark or "",
"boundUserNames": list(bound_user_names or []),
"boundPostNames": list(bound_post_names or []),
"createTime": r.create_time.strftime("%Y-%m-%d %H:%M:%S") if r.create_time else "",
"updateTime": r.update_time.strftime("%Y-%m-%d %H:%M:%S") if r.update_time else "",
}
@@ -74,7 +229,18 @@ def list_roles(
.limit(page_size)
.all()
)
return [_row_to_dict(x) for x in rows], int(total)
role_ids = [x.id for x in rows]
tenant = tenant_no or ""
user_name_map = _bound_user_names_by_role_ids(db, role_ids, tenant)
post_name_map = _bound_post_names_by_role_ids(db, role_ids, tenant)
return [
_row_to_dict(
x,
bound_user_names=user_name_map.get(x.id, []),
bound_post_names=post_name_map.get(x.id, []),
)
for x in rows
], int(total)
def get_role(db: Session, role_id: str) -> Optional[SysRole]:
+24
View File
@@ -849,6 +849,30 @@ class OaReceiveAccount(Base):
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class OaInstanceDraft(Base):
"""OA发起审批草稿 oa_instance_draft(非模板设计草稿)"""
__tablename__ = "oa_instance_draft"
id = Column(String(64), primary_key=True, comment="主键ID")
app_id = Column(String(64), nullable=False, comment="应用ID")
app_version_id = Column(String(64), nullable=False, comment="暂存时锁定的已发布版本ID")
title = Column(String(200), nullable=True, comment="标题")
form_data_json = Column(Text, nullable=True, comment="表单数据 JSON")
initiator_select_json = Column(Text, nullable=True, comment="发起人自选 JSON")
initiator_dept_id = Column(String(64), nullable=True, comment="发起人部门")
owner_user_id = Column(String(64), nullable=False, comment="草稿所属人")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
order_num = Column(Integer, nullable=True, comment="排序号")
remark = Column(String(512), nullable=True, comment="备注")
create_by = Column(String(64), nullable=True, comment="创建人id")
create_dept_id = Column(String(64), nullable=False, default="", comment="创建人部门ID")
create_time = Column(DateTime, nullable=False, default=datetime.now, comment="创建时间")
update_by = Column(String(64), nullable=True, comment="更新人id")
update_time = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment="更新时间")
del_flag = Column(SmallInteger, nullable=False, default=0, comment="删除标记")
class OaInstance(Base):
"""OA审批实例 oa_instance"""
+14
View File
@@ -1975,6 +1975,20 @@ def count_cc_unread(db: Session, *, tenant_no: str, user_id: str) -> int:
)
def count_pending_tasks(db: Session, *, tenant_no: str, user_id: str) -> int:
return (
db.query(OaTask)
.filter(
OaTask.tenant_no == tenant_no,
OaTask.del_flag == 0,
OaTask.assignee_user_id == user_id,
OaTask.task_type == "approval",
OaTask.status == "pending",
)
.count()
)
def mark_cc_task_read(
db: Session, *, tenant_no: str, user_id: str, task_id: str
) -> Dict[str, Any]:
+216 -20
View File
@@ -4,7 +4,7 @@
"""
from __future__ import annotations
from typing import List, Set
from typing import List, Optional, Set, Collection
from sqlalchemy import and_
from sqlalchemy.orm import Session
@@ -39,13 +39,23 @@ def _map_role_name_to_web(role_name: str) -> str:
return "admin"
def get_effective_role_ids(db: Session, user_id: str) -> List[str]:
"""用户有效角色 ID:直接绑定 ∪ 启用职位关联的启用角色(去重保序)。"""
def _dedupe_role_id_rows(rows) -> List[str]:
out: List[str] = []
seen: Set[str] = set()
for row in rows:
rid = str(row[0]).strip() if row and row[0] else ""
if rid and rid not in seen:
seen.add(rid)
out.append(rid)
return out
def get_direct_enabled_role_ids(db: Session, user_id: str) -> List[str]:
"""用户直接绑定且启用的角色 ID(sys_user_role → sys_role)。"""
if not user_id:
return []
tenant = settings.DEFAULT_TENANT_NO
direct_rows = (
rows = (
db.query(SysRole.id)
.join(SysUserRole, SysUserRole.role_id == SysRole.id)
.filter(
@@ -59,8 +69,15 @@ def get_effective_role_ids(db: Session, user_id: str) -> List[str]:
.order_by(SysRole.create_time.desc())
.all()
)
return _dedupe_role_id_rows(rows)
post_rows = (
def get_post_inherited_role_ids(db: Session, user_id: str) -> List[str]:
"""经启用职位继承的启用角色 ID(sys_user_post → sys_post → sys_post_role → sys_role)。"""
if not user_id:
return []
tenant = settings.DEFAULT_TENANT_NO
rows = (
db.query(SysRole.id)
.join(SysPostRole, SysPostRole.role_id == SysRole.id)
.join(
@@ -91,35 +108,214 @@ def get_effective_role_ids(db: Session, user_id: str) -> List[str]:
.order_by(SysRole.create_time.desc())
.all()
)
return _dedupe_role_id_rows(rows)
def get_effective_role_ids(db: Session, user_id: str) -> List[str]:
"""用户有效角色 ID:直接绑定 ∪ 启用职位关联的启用角色(去重保序)。"""
if not user_id:
return []
out: List[str] = []
seen: Set[str] = set()
for row in list(direct_rows) + list(post_rows):
rid = str(row[0]).strip() if row and row[0] else ""
if rid and rid not in seen:
for rid in get_direct_enabled_role_ids(db, user_id) + get_post_inherited_role_ids(
db, user_id
):
if rid not in seen:
seen.add(rid)
out.append(rid)
return out
def _active_role_name_rows(db: Session, user_id: str) -> list:
"""查询用户当前有效的 sys_role.role_name 列表(含职位继承)。"""
role_ids = get_effective_role_ids(db, user_id)
if not role_ids:
return []
tenant = settings.DEFAULT_TENANT_NO
rows = (
db.query(SysRole.role_name)
def _normalize_candidate_user_ids(
candidate_user_ids: Optional[Collection[str]],
) -> Optional[List[str]]:
if candidate_user_ids is None:
return None
return list(dict.fromkeys([str(u).strip() for u in candidate_user_ids if u and str(u).strip()]))
def list_user_ids_with_effective_role_name(
db: Session,
*,
tenant_no: str,
role_name: str,
candidate_user_ids: Optional[Collection[str]] = None,
) -> Set[str]:
"""拥有指定角色名的用户 ID(直接绑定 ∪ 职位继承)。"""
tenant = (tenant_no or "").strip()
rn = (role_name or "").strip()
if not tenant or not rn:
return set()
candidates = _normalize_candidate_user_ids(candidate_user_ids)
if candidates is not None and not candidates:
return set()
direct_q = (
db.query(SysUserRole.user_id)
.join(SysRole, SysRole.id == SysUserRole.role_id)
.filter(
SysRole.id.in_(role_ids),
SysUserRole.del_flag == 0,
SysUserRole.tenant_no == tenant,
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.tenant_no == tenant,
SysRole.role_name == rn,
)
)
post_q = (
db.query(SysUserPost.user_id)
.join(
SysPost,
and_(
SysPost.id == SysUserPost.post_id,
SysPost.del_flag == 0,
SysPost.status == "1",
SysPost.tenant_no == tenant,
),
)
.join(
SysPostRole,
and_(
SysPostRole.post_id == SysPost.id,
SysPostRole.del_flag == 0,
SysPostRole.tenant_no == tenant,
),
)
.join(
SysRole,
and_(
SysRole.id == SysPostRole.role_id,
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.tenant_no == tenant,
SysRole.role_name == rn,
),
)
.filter(SysUserPost.del_flag == 0, SysUserPost.tenant_no == tenant)
)
if candidates is not None:
direct_q = direct_q.filter(SysUserRole.user_id.in_(candidates))
post_q = post_q.filter(SysUserPost.user_id.in_(candidates))
out: Set[str] = set()
for row in direct_q.all():
uid = str(row[0]).strip() if row and row[0] else ""
if uid:
out.add(uid)
for row in post_q.all():
uid = str(row[0]).strip() if row and row[0] else ""
if uid:
out.add(uid)
return out
def list_user_ids_with_any_effective_role_ids(
db: Session,
*,
tenant_no: str,
role_ids: List[str],
candidate_user_ids: Optional[Collection[str]] = None,
) -> List[str]:
"""拥有任一指定角色 ID 的用户 ID 列表(直接绑定 ∪ 职位继承,去重)。"""
tenant = (tenant_no or "").strip()
rids = list(dict.fromkeys([str(r).strip() for r in (role_ids or []) if r and str(r).strip()]))
if not tenant or not rids:
return []
candidates = _normalize_candidate_user_ids(candidate_user_ids)
if candidates is not None and not candidates:
return []
direct_q = (
db.query(SysUserRole.user_id)
.join(SysRole, SysRole.id == SysUserRole.role_id)
.filter(
SysUserRole.del_flag == 0,
SysUserRole.tenant_no == tenant,
SysUserRole.role_id.in_(rids),
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.tenant_no == tenant,
)
)
post_q = (
db.query(SysUserPost.user_id)
.join(
SysPost,
and_(
SysPost.id == SysUserPost.post_id,
SysPost.del_flag == 0,
SysPost.status == "1",
SysPost.tenant_no == tenant,
),
)
.join(
SysPostRole,
and_(
SysPostRole.post_id == SysPost.id,
SysPostRole.del_flag == 0,
SysPostRole.tenant_no == tenant,
SysPostRole.role_id.in_(rids),
),
)
.join(
SysRole,
and_(
SysRole.id == SysPostRole.role_id,
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.tenant_no == tenant,
),
)
.filter(SysUserPost.del_flag == 0, SysUserPost.tenant_no == tenant)
)
if candidates is not None:
direct_q = direct_q.filter(SysUserRole.user_id.in_(candidates))
post_q = post_q.filter(SysUserPost.user_id.in_(candidates))
out: List[str] = []
seen: Set[str] = set()
for row in list(direct_q.all()) + list(post_q.all()):
uid = str(row[0]).strip() if row and row[0] else ""
if uid and uid not in seen:
seen.add(uid)
out.append(uid)
return out
def get_role_names_by_ids(db: Session, role_ids: List[str]) -> List[str]:
"""按给定角色 ID 返回启用角色名称(保序、去重)。"""
ordered = list(dict.fromkeys([str(r).strip() for r in (role_ids or []) if r]))
if not ordered:
return []
tenant = settings.DEFAULT_TENANT_NO
rows = (
db.query(SysRole.id, SysRole.role_name)
.filter(
SysRole.id.in_(ordered),
SysRole.del_flag == 0,
SysRole.status == "1",
SysRole.tenant_no == tenant,
)
.order_by(SysRole.create_time.desc())
.all()
)
return [str(r[0]).strip() for r in rows if r and r[0]]
name_by_id = {
str(rid).strip(): str(name).strip()
for rid, name in rows
if rid and name
}
out: List[str] = []
seen: Set[str] = set()
for rid in ordered:
name = name_by_id.get(rid)
if name and name not in seen:
seen.add(name)
out.append(name)
return out
def _active_role_name_rows(db: Session, user_id: str) -> list:
"""查询用户当前有效的 sys_role.role_name 列表(含职位继承)。"""
return get_role_names_by_ids(db, get_effective_role_ids(db, user_id))
def user_has_active_roles(db: Session, user_id: str) -> bool:
+8 -3
View File
@@ -13,12 +13,12 @@ from sqlalchemy.orm import Session
from app.crud import workflow as wf_crud
from app.models.models import (
SysUser,
SysUserRole,
WfNode,
WfProcessInstance,
WfTask,
WfTransition,
)
from app.services.web_auth_roles import list_user_ids_with_any_effective_role_ids
from app.services.workflow_callback import trigger_callback
logger = logging.getLogger("sqxp.workflow_engine")
@@ -250,11 +250,16 @@ class WorkflowEngine:
role_ids = config.get("roleIds", [])
if not role_ids:
return []
user_ids = list_user_ids_with_any_effective_role_ids(
self.db, tenant_no=tenant_no, role_ids=role_ids
)
if not user_ids:
return []
rows = (
self.db.query(SysUser.id)
.join(SysUserRole, SysUserRole.user_id == SysUser.id)
.filter(
SysUserRole.role_id.in_(role_ids),
SysUser.id.in_(user_ids),
SysUser.tenant_no == tenant_no,
SysUser.del_flag == 0,
SysUser.status == "1",
)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+85 -100
View File
@@ -1,11 +1,11 @@
# Graph Report - app (2026-08-06)
## Corpus Check
- Large corpus: 242 files · ~296,606 words. Semantic extraction will be expensive (many Claude tokens). Consider running on a subfolder, or use --no-semantic to run AST-only.
- Large corpus: 242 files · ~296,735 words. Semantic extraction will be expensive (many Claude tokens). Consider running on a subfolder, or use --no-semantic to run AST-only.
## Summary
- 5114 nodes · 27947 edges · 42 communities detected
- Extraction: 32% EXTRACTED · 68% INFERRED · 0% AMBIGUOUS · INFERRED: 19091 edges (avg confidence: 0.6)
- 5118 nodes · 27963 edges · 39 communities detected
- Extraction: 32% EXTRACTED · 68% INFERRED · 0% AMBIGUOUS · INFERRED: 19101 edges (avg confidence: 0.6)
- Token cost: 0 input · 0 output
## Community Hubs (Navigation)
@@ -42,19 +42,16 @@
- [[_COMMUNITY_Community 30|Community 30]]
- [[_COMMUNITY_Community 31|Community 31]]
- [[_COMMUNITY_Community 32|Community 32]]
- [[_COMMUNITY_Community 33|Community 33]]
- [[_COMMUNITY_Community 34|Community 34]]
- [[_COMMUNITY_Community 35|Community 35]]
- [[_COMMUNITY_Community 36|Community 36]]
- [[_COMMUNITY_Community 37|Community 37]]
- [[_COMMUNITY_Community 38|Community 38]]
- [[_COMMUNITY_Community 39|Community 39]]
- [[_COMMUNITY_Community 40|Community 40]]
- [[_COMMUNITY_Community 41|Community 41]]
- [[_COMMUNITY_Community 42|Community 42]]
- [[_COMMUNITY_Community 43|Community 43]]
## God Nodes (most connected - your core abstractions)
1. `success_response()` - 730 edges
2. `error_response()` - 604 edges
1. `success_response()` - 732 edges
2. `error_response()` - 605 edges
3. `SysUser` - 591 edges
4. `BizQcTaskResult` - 345 edges
5. `BizProductionMaterial` - 329 edges
@@ -80,216 +77,204 @@
### Community 0 - "Community 0"
Cohesion: 0.01
Nodes (917): attachment_download_url(), create_dept(), create_dict_data(), create_dict_type(), create_express_company(), create_item_unit(), create_menu(), create_post() (+909 more)
Nodes (966): create_dept(), create_dict_data(), create_dict_type(), create_express_company(), create_item_unit(), create_menu(), create_post(), create_role_management() (+958 more)
### Community 1 - "Community 1"
Cohesion: 0.01
Nodes (738): generate_uuid(), create_cell_sample_type(), get_cell_sample_type(), list_cell_sample_types(), 细胞样本类型 CRUD(biz_cell_sample_type), _row_to_dict(), soft_delete_cell_sample_type(), type_code_exists() (+730 more)
Nodes (736): get_role_menus(), generate_uuid(), create_cell_sample_type(), get_cell_sample_type(), list_cell_sample_types(), 细胞样本类型 CRUD(biz_cell_sample_type), _row_to_dict(), soft_delete_cell_sample_type() (+728 more)
### Community 2 - "Community 2"
Cohesion: 0.01
Nodes (679): AttachmentDownloadUrlBody, DeptCreateBody, DeptUpdateBody, DictDataCreateBody, DictDataUpdateBody, DictTypeCreateBody, DictTypeUpdateBody, ExpressCompanyCreateBody (+671 more)
Nodes (626): attachment_download_url(), AttachmentDownloadUrlBody, DeptCreateBody, DeptUpdateBody, dict_data_options(), DictDataCreateBody, DictDataUpdateBody, DictTypeCreateBody (+618 more)
### Community 3 - "Community 3"
Cohesion: 0.05
Nodes (603): 细胞存储 — 采集协议单 / 审核 / 财务确认 / 分期预警 API, 持久化协议子资源。 缴费(含明细校验)须在样本之前:明细校验失败时不得已占用样本编码。 各子表 CRUD 内部仍可能分段 commit,创建接, 与列表接口一致:按租户 + 角色数据权限判断是否可访问该协议单。, If mother info exists but no customerId, create a customer record and link it., Base, 细胞产品 CRUD(biz_cell_product), 解析任务样本投入物,返回祖先链单段(样本终止节点)。, 将 get_product_chain 结果展平为上游→下游节点列表(含 current,不含 descendants)。 (+595 more)
Cohesion: 0.06
Nodes (500): 保险公司及险种价格管理 API(保险公司 + 开票信息 + 险种价格), Base, 按输注计划 ID 批量索引缴费记录(列表页展示用,不做关联 enrich), 输注计划创建时自动调用,生成 dfj 缴费记录, 关联查询申请单、患者、输注计划信息,附加到 dict, 将 BizMaterialUsage 行转换为字典(用于我的领用记录)。, 当前登录人的手动出库领用记录:领用人字段存昵称或用户 ID(与生产/质检一致)。, 获取当前用户的物料领用记录(手动出库记录) 筛选条件: - tenant_no = 当前用户租户 - source_type = 'm (+492 more)
### Community 4 - "Community 4"
Cohesion: 0.02
Nodes (282): _normalize_date_bound(), complete_protocol_invoice_request(), create_collection_protocol(), delete_collection_protocol(), _draft_fields_from_body(), _ensure_customer_for_mother(), get_collection_protocol_detail(), _get_current_user_id() (+274 more)
Cohesion: 0.01
Nodes (342): _normalize_date_bound(), list_ethnics_for_select(), apply_data_scope(), format_date(), optional_date(), parse_date(), 将字符串 / date / datetime 转为 date 或 None, ApiRequestLogCRUD (+334 more)
### Community 5 - "Community 5"
Cohesion: 0.01
Nodes (247): list_collection_regions(), list_ethnics_for_select(), get_designer_data(), apply_data_scope(), _get_child_dept_ids(), get_user_dept_id(), _resolve_user_role_scopes(), ApiRequestLogCRUD (+239 more)
Cohesion: 0.02
Nodes (267): _body_to_payload(), _get_current_user_id(), get_production_reception_by_sample_code(), get_production_reception_detail(), _get_tenant_no(), post_production_reception(), put_production_reception(), _resolve_reception_id() (+259 more)
### Community 6 - "Community 6"
Cohesion: 0.02
Nodes (189): 截止日期:仅日期时扩到当天 23:59:59。, 发起前预览审批链(条件齐后解析最终路径与审批人)。, 兼容旧 GET:无 formData,含条件分支时多为待确定占位。, _app_to_dict(), _copied_app_name(), copy_app(), create_app(), _create_version() (+181 more)
Nodes (139): get_designer_data(), _error_json(), lifespan(), 数据库异常:返回 JSON 并保留 CORS 头,避免浏览器只报跨域错误, 未捕获异常:统一 JSON 500,确保跨域场景下仍有 Access-Control-Allow-Origin, sqlalchemy_exception_handler(), unhandled_exception_handler(), BaseHTTPMiddleware (+131 more)
### Community 7 - "Community 7"
Cohesion: 0.02
Nodes (182): eq_unicode(), like_unicode(), MySQL 字符串比较/模糊匹配时统一排序规则,避免 Illegal mix of collations。, 跨表字符串等值比较(JOIN / WHERE)时统一为 utf8mb4_unicode_ci。, 将列显式设为 utf8mb4_unicode_ci。, unicode_ci(), build_void_type_label_map(), format_protocol_status_label() (+174 more)
Nodes (185): 截止日期:仅日期时扩到当天 23:59:59。, 发起前预览审批链(条件齐后解析最终路径与审批人)。, 兼容旧 GET:无 formData,含条件分支时多为待确定占位。, _app_to_dict(), _copied_app_name(), copy_app(), create_app(), _create_version() (+177 more)
### Community 8 - "Community 8"
Cohesion: 0.03
Nodes (155): map_payments_by_schedule_ids(), _fmt_dt(), get_handover_by_schedule(), get_outbound_handover(), get_outbound_handover_view(), _handover_row_to_dict(), _handover_view_dict(), _parse_handover_time() (+147 more)
Cohesion: 0.02
Nodes (191): api_save_application(), get_protocol_nos_used_in_protocols(), _fmt_dt(), get_handover_by_schedule(), get_outbound_handover(), get_outbound_handover_view(), _handover_row_to_dict(), _handover_view_dict() (+183 more)
### Community 9 - "Community 9"
Cohesion: 0.02
Nodes (96): _error_json(), lifespan(), 数据库异常:返回 JSON 并保留 CORS 头,避免浏览器只报跨域错误, 未捕获异常:统一 JSON 500,确保跨域场景下仍有 Access-Control-Allow-Origin, sqlalchemy_exception_handler(), unhandled_exception_handler(), BaseHTTPMiddleware, ApiCryptoError (+88 more)
Cohesion: 0.08
Nodes (189): CellSampleTypeCreateBody, CellSampleTypeUpdateBody, CollectionRegionCreateBody, CollectionRegionUpdateBody, CustomerCreateBody, CustomerUpdateBody, HospitalCreateBody, HospitalUpdateBody (+181 more)
### Community 10 - "Community 10"
Cohesion: 0.05
Nodes (112): AccessLogCreateBody, AccessLogUpdateBody, CleanRoomCreateBody, CleanRoomUpdateBody, ExhibitionAppointmentCreateBody, ExhibitionAppointmentUpdateBody, OccupancyCreateBody, 运营支撑 API(洁净室、进出记录、仓储设施、储位、展厅预约) (+104 more)
Cohesion: 0.03
Nodes (141): get_next_cell_product_code(), _ancestor_link_from_cell_product_input(), _ancestor_sample_chain_link(), _apply_cell_product_status_change(), _build_ancestor_chain(), _build_descendant_chain(), _build_facility_path_label(), build_split_product_codes() (+133 more)
### Community 11 - "Community 11"
Cohesion: 0.03
Nodes (90): _jwt_user_payload(), Web 端登录用 RSA 公钥(PKCS#1 v1.5,与 JSEncrypt 一致), Web 端登录:账号为 sys_user.user_no,密码为 sys_user.password(bcrypt)。, refresh_token(), web_login(), web_login_rsa_public_key(), create_access_token(), create_refresh_token() (+82 more)
Cohesion: 0.05
Nodes (108): AccessLogCreateBody, AccessLogUpdateBody, CleanRoomCreateBody, CleanRoomUpdateBody, ExhibitionAppointmentCreateBody, ExhibitionAppointmentUpdateBody, OccupancyCreateBody, 运营支撑 API(洁净室、进出记录、仓储设施、储位、展厅预约) (+100 more)
### Community 12 - "Community 12"
Cohesion: 0.06
Nodes (75): _body_to_payload(), _get_current_user_id(), get_production_reception_by_sample_code(), get_production_reception_detail(), _get_tenant_no(), post_production_reception(), put_production_reception(), _resolve_reception_id() (+67 more)
Cohesion: 0.04
Nodes (91): get_user_by_id(), _jwt_user_payload(), Web 端登录用 RSA 公钥(PKCS#1 v1.5,与 JSEncrypt 一致), Web 端登录:账号为 sys_user.user_no,密码为 sys_user.password(bcrypt)。, refresh_token(), web_login(), web_login_rsa_public_key(), create_access_token() (+83 more)
### Community 13 - "Community 13"
Cohesion: 0.05
Nodes (77): api_save_application(), auto_generate_schedules(), complete_application(), create_application(), create_basic_experiment_sale_schedules(), create_infusion_plan(), create_schedule(), _create_schedule_products() (+69 more)
Cohesion: 0.45
Nodes (71): BatchStockInBody, BatchStockInItem, BatchStockOutBody, BatchStockOutItem, ConsumableCreateBody, ConsumablePackCreateBody, ConsumablePackUpdateBody, ConsumableUpdateBody (+63 more)
### Community 14 - "Community 14"
Cohesion: 0.05
Nodes (76): _ancestor_link_from_cell_product_input(), _ancestor_sample_chain_link(), _apply_cell_product_status_change(), _build_ancestor_chain(), _build_descendant_chain(), _build_facility_path_label(), build_split_product_codes(), create_cell_product() (+68 more)
### Community 15 - "Community 15"
Cohesion: 0.12
Nodes (11): get_wechat_pay_client(), get_wechat_pay_v2(), 微信支付工具模块 支持微信支付 V3 API 文档参考: https://pay.weixin.qq.com/docs/v3/apis/index.ht, 统一下单接口 (V3) Args: out_trade_no: 商户订单号 total, 申请退款 Args: out_trade_no: 商户订单号 total_amount, 小程序调起支付的二次签名参数(与公众号 JSAPI 规则一致), 统一下单 (V2 API) Args: out_trade_no: 商户订单号 tot, 生成签名 V3 (SHA256 with RSA) (+3 more)
### Community 16 - "Community 16"
Cohesion: 0.16
Nodes (22): _code_exists(), create_material(), _dec(), _fmt_dt(), get_material(), get_material_entity(), get_my_usages(), _is_enabled_status() (+14 more)
### Community 17 - "Community 17"
### Community 15 - "Community 15"
Cohesion: 0.21
Nodes (19): _consumable_row_to_dict(), create_process(), _create_sub_consumable(), _create_sub_data_collection(), _create_sub_output(), _create_sub_reagent(), _data_collection_row_to_dict(), get_process() (+11 more)
### Community 18 - "Community 18"
Cohesion: 0.21
Nodes (16): _field_label(), _is_non_empty_str(), _is_required(), _is_valid_receive_account_item(), normalize_account_fields(), _pick(), _pick_order_num(), _pick_str() (+8 more)
### Community 16 - "Community 16"
Cohesion: 0.2
Nodes (19): _code_exists(), create_material(), _dec(), _fmt_dt(), get_material(), get_material_entity(), get_my_usages(), _is_enabled_status() (+11 more)
### Community 19 - "Community 19"
### Community 17 - "Community 17"
Cohesion: 0.27
Nodes (12): create_equipment(), _dec(), equipment_code_exists(), equipment_is_referenced(), get_equipment(), list_equipments(), _norm_status(), _parse_date() (+4 more)
### Community 20 - "Community 20"
Cohesion: 0.24
Nodes (9): 微信消息通知服务 支持微信小程序模板消息推送 使用方式: from app.core.wechat_message import Wech, 发送模板消息 Args: openid: 用户openid templ, send_delivery_notice(), send_delivery_warning(), send_order_status(), send_payment_success(), send_refund_result(), send_urge_notification() (+1 more)
### Community 21 - "Community 21"
Cohesion: 0.23
Nodes (12): Config, ProductBase, ProductCategoryBase, ProductCategoryCreate, ProductCategoryResponse, ProductCreate, ProductResponse, ProductUnitBase (+4 more)
### Community 22 - "Community 22"
### Community 18 - "Community 18"
Cohesion: 0.27
Nodes (12): _field_label(), _is_empty(), _is_required(), _parse_money(), OA 表单设计器:金额控件 form_data 校验, 校验 form_data 中金额控件的值格式,返回中文错误列表(空表示通过)。, 解析金额值。成功返回 (number, None);失败返回 (None, error_key)。, _rule_props() (+4 more)
### Community 23 - "Community 23"
### Community 19 - "Community 19"
Cohesion: 0.24
Nodes (11): deduct_for_step(), _display_remark(), list_stock_logs(), _parse_receiver_purpose_from_remark(), 试剂变动记录 CRUD(biz_reagent_stock_log), 撤销步骤此前 step_save 扣减,便于重新填报。, 扣减试剂库存并生成变动记录。调用方控制事务,本函数不 commit。, _resolve_receiver_purpose() (+3 more)
### Community 20 - "Community 20"
Cohesion: 0.24
Nodes (11): deduct_for_step(), _display_remark(), list_stock_logs(), _parse_receiver_purpose_from_remark(), 耗材变动记录 CRUD(biz_consumable_stock_log), 撤销步骤此前 step_save 扣减,便于重新填报。, 扣减耗材库存并生成变动记录。调用方控制事务,本函数不 commit。, _resolve_receiver_purpose() (+3 more)
### Community 24 - "Community 24"
### Community 21 - "Community 21"
Cohesion: 0.31
Nodes (10): create_account(), _filtered_query(), get_account(), list_accounts(), list_options(), OA 收款账户 CRUD(oa_receive_account), row_to_dict(), soft_delete_account() (+2 more)
### Community 25 - "Community 25"
### Community 22 - "Community 22"
Cohesion: 0.31
Nodes (10): _build_tree(), _cascade_soft_delete(), _collect_with_ancestors(), get_dept(), list_depts(), list_depts_tree(), 保留匹配节点及其全部上级,供关键词检索后仍能正确组树。, _row_to_dict() (+2 more)
### Community 26 - "Community 26"
Cohesion: 0.38
Nodes (9): create_env_detect_item(), get_env_detect_item(), item_code_exists(), list_active_env_detect_items(), list_env_detect_items(), _order_query(), _row_to_dict(), soft_delete_env_detect_item() (+1 more)
### Community 23 - "Community 23"
Cohesion: 0.33
Nodes (8): _build_tree(), _cascade_soft_delete(), get_menu(), list_menus(), list_menus_tree(), _row_to_dict(), soft_delete_menu(), update_menu()
### Community 27 - "Community 27"
### Community 24 - "Community 24"
Cohesion: 0.29
Nodes (2): BaseModel, SoftDeleteModel
### Community 28 - "Community 28"
### Community 25 - "Community 25"
Cohesion: 0.38
Nodes (6): derive_legacy_status_from_three(), derive_three_status_from_legacy(), 阶段A兼容:从旧 status 推导三字段。 约束:旧 status 本身混合了支付/配送/订单生命周期,因此只能尽力推断; 若业务侧已有更精确, 阶段A兼容:从三字段反推旧 status(用于旧前端/旧筛选参数兼容)。, ThreeStatus, _to_decimal()
### Community 29 - "Community 29"
### Community 26 - "Community 26"
Cohesion: 0.5
Nodes (3): BaseSettings, Config, Settings
### Community 30 - "Community 30"
### Community 27 - "Community 27"
Cohesion: 0.5
Nodes (2): _auto_fill_create_dept_id(), ORM before_insert 钩子:当 create_dept_id 为空时,自动从请求上下文填充当前用户部门 ID
### Community 31 - "Community 31"
### Community 28 - "Community 28"
Cohesion: 0.67
Nodes (2): get_menu_list(), 运营端菜单接口(与 web-admin 前端静态路由 sqxp.ts 对齐,5 个一级菜单分组)
### Community 32 - "Community 32"
### Community 29 - "Community 29"
Cohesion: 0.67
Nodes (1): 转正套件:入职日 + 试用期月数 → 建议转正日(YYYY-MM-DD)。
### Community 33 - "Community 33"
### Community 30 - "Community 30"
Cohesion: 1.0
Nodes (1): 质检物料金额查看授权:专用角色与菜单权限常量。
### Community 34 - "Community 34"
### Community 31 - "Community 31"
Cohesion: 1.0
Nodes (1): 请求级别的用户上下文变量 通过 contextvars 在请求处理链路中传递当前用户信息, 供 SQLAlchemy 事件监听器等底层机制使用,避免逐层手动传
### Community 35 - "Community 35"
### Community 32 - "Community 32"
Cohesion: 1.0
Nodes (1): API 路由包(骨架:公共鉴权 + 静态菜单 + 运营端占位)
### Community 38 - "Community 38"
### Community 35 - "Community 35"
Cohesion: 1.0
Nodes (1): 发送订单状态通知 Args: openid: 用户openid ord
### Community 39 - "Community 39"
### Community 36 - "Community 36"
Cohesion: 1.0
Nodes (1): 发送支付成功通知 Args: openid: 用户openid ord
### Community 40 - "Community 40"
### Community 37 - "Community 37"
Cohesion: 1.0
Nodes (1): 发送配送通知 Args: openid: 配送员openid task
### Community 41 - "Community 41"
### Community 38 - "Community 38"
Cohesion: 1.0
Nodes (1): 发送配送时效预警 Args: openid: 配送员openid ta
### Community 42 - "Community 42"
### Community 39 - "Community 39"
Cohesion: 1.0
Nodes (1): 发送退款结果通知 Args: openid: 用户openid ord
### Community 43 - "Community 43"
### Community 40 - "Community 40"
Cohesion: 1.0
Nodes (1): 发送催单通知给配送员 Args: deliver_openid: 配送员openid
## Knowledge Gaps
- **163 isolated node(s):** `刷新会话 TTL(refreshToken 续期;已登录用户每次 API 校验通过后滑动续期)`, `写入 refreshToken(用于 one-time 使用/吊销)`, `根据 token 获取当前用户(包含 Redis 会话校验;会话滑动续期)`, `登录凭据 RSA 解密(与前端 JSEncrypt PKCS#1 v1.5 兼容)。`, `加载 RSA 密钥对:优先环境变量,否则使用内置固定默认密钥。` (+158 more)
These have ≤1 connection - possible missing edges or undocumented components.
- **Thin community `Community 27`** (8 nodes): `BaseModel`, `.to_dict()`, `get_active()`, `base.py`, `SoftDeleteModel`, `.restore()`, `.soft_delete()`, `__tablename__()`
- **Thin community `Community 24`** (8 nodes): `BaseModel`, `.to_dict()`, `get_active()`, `base.py`, `SoftDeleteModel`, `.restore()`, `.soft_delete()`, `__tablename__()`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 30`** (4 nodes): `_auto_fill_create_dept_id()`, `get_db()`, `database.py`, `ORM before_insert 钩子:当 create_dept_id 为空时,自动从请求上下文填充当前用户部门 ID`
- **Thin community `Community 27`** (4 nodes): `_auto_fill_create_dept_id()`, `get_db()`, `database.py`, `ORM before_insert 钩子:当 create_dept_id 为空时,自动从请求上下文填充当前用户部门 ID`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 31`** (3 nodes): `get_menu_list()`, `menu.py`, `运营端菜单接口(与 web-admin 前端静态路由 sqxp.ts 对齐,5 个一级菜单分组)`
- **Thin community `Community 28`** (3 nodes): `get_menu_list()`, `menu.py`, `运营端菜单接口(与 web-admin 前端静态路由 sqxp.ts 对齐,5 个一级菜单分组)`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 32`** (3 nodes): `add_months_ymd()`, `oa_confirmation_date.py`, `转正套件:入职日 + 试用期月数 → 建议转正日(YYYY-MM-DD)。`
- **Thin community `Community 29`** (3 nodes): `add_months_ymd()`, `oa_confirmation_date.py`, `转正套件:入职日 + 试用期月数 → 建议转正日(YYYY-MM-DD)。`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 33`** (2 nodes): `qc_material_amount_auth_constants.py`, `质检物料金额查看授权:专用角色与菜单权限常量。`
- **Thin community `Community 30`** (2 nodes): `qc_material_amount_auth_constants.py`, `质检物料金额查看授权:专用角色与菜单权限常量。`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 34`** (2 nodes): `context.py`, `请求级别的用户上下文变量 通过 contextvars 在请求处理链路中传递当前用户信息, 供 SQLAlchemy 事件监听器等底层机制使用,避免逐层手动传`
- **Thin community `Community 31`** (2 nodes): `context.py`, `请求级别的用户上下文变量 通过 contextvars 在请求处理链路中传递当前用户信息, 供 SQLAlchemy 事件监听器等底层机制使用,避免逐层手动传`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 35`** (2 nodes): `__init__.py`, `API 路由包(骨架:公共鉴权 + 静态菜单 + 运营端占位)`
- **Thin community `Community 32`** (2 nodes): `__init__.py`, `API 路由包(骨架:公共鉴权 + 静态菜单 + 运营端占位)`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 38`** (1 nodes): `发送订单状态通知 Args: openid: 用户openid ord`
- **Thin community `Community 35`** (1 nodes): `发送订单状态通知 Args: openid: 用户openid ord`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 39`** (1 nodes): `发送支付成功通知 Args: openid: 用户openid ord`
- **Thin community `Community 36`** (1 nodes): `发送支付成功通知 Args: openid: 用户openid ord`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 40`** (1 nodes): `发送配送通知 Args: openid: 配送员openid task`
- **Thin community `Community 37`** (1 nodes): `发送配送通知 Args: openid: 配送员openid task`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 41`** (1 nodes): `发送配送时效预警 Args: openid: 配送员openid ta`
- **Thin community `Community 38`** (1 nodes): `发送配送时效预警 Args: openid: 配送员openid ta`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 42`** (1 nodes): `发送退款结果通知 Args: openid: 用户openid ord`
- **Thin community `Community 39`** (1 nodes): `发送退款结果通知 Args: openid: 用户openid ord`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
- **Thin community `Community 43`** (1 nodes): `发送催单通知给配送员 Args: deliver_openid: 配送员openid`
- **Thin community `Community 40`** (1 nodes): `发送催单通知给配送员 Args: deliver_openid: 配送员openid`
Too small to be a meaningful cluster - may be noise or needs more connections extracted.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `SysUser` connect `Community 2` to `Community 0`, `Community 1`, `Community 3`, `Community 4`, `Community 5`, `Community 6`, `Community 8`, `Community 9`, `Community 10`, `Community 11`, `Community 16`, `Community 23`?**
_High betweenness centrality (0.113) - this node is a cross-community bridge._
- **Why does `generate_uuid()` connect `Community 1` to `Community 0`, `Community 4`, `Community 5`, `Community 6`, `Community 7`, `Community 8`, `Community 9`, `Community 10`, `Community 11`, `Community 12`, `Community 13`, `Community 14`, `Community 16`, `Community 17`, `Community 19`, `Community 23`, `Community 24`, `Community 26`?**
- **Why does `SysUser` connect `Community 2` to `Community 0`, `Community 1`, `Community 3`, `Community 4`, `Community 6`, `Community 7`, `Community 8`, `Community 9`, `Community 10`, `Community 11`, `Community 12`, `Community 13`, `Community 19`, `Community 20`?**
_High betweenness centrality (0.112) - this node is a cross-community bridge._
- **Why does `success_response()` connect `Community 0` to `Community 1`, `Community 2`, `Community 4`, `Community 5`, `Community 6`, `Community 8`, `Community 10`, `Community 12`, `Community 28`?**
_High betweenness centrality (0.048) - this node is a cross-community bridge._
- **Why does `success_response()` connect `Community 0` to `Community 2`, `Community 4`, `Community 5`, `Community 11`, `Community 12`, `Community 13`, `Community 31`?**
_High betweenness centrality (0.038) - this node is a cross-community bridge._
- **Are the 858 inferred relationships involving `str` (e.g. with `unhandled_exception_handler()` and `get_current_user_by_token()`) actually correct?**
_`str` has 858 INFERRED edges - model-reasoned connections that need verification._
- **Are the 729 inferred relationships involving `success_response()` (e.g. with `list_storage_release_reviews()` and `get_storage_release_review_detail()`) actually correct?**
_`success_response()` has 729 INFERRED edges - model-reasoned connections that need verification._
- **Are the 603 inferred relationships involving `error_response()` (e.g. with `_json_error_response()` and `list_storage_release_reviews()`) actually correct?**
_`error_response()` has 603 INFERRED edges - model-reasoned connections that need verification._
- **Why does `generate_uuid()` connect `Community 1` to `Community 0`, `Community 2`, `Community 4`, `Community 5`, `Community 6`, `Community 7`, `Community 8`, `Community 9`, `Community 10`, `Community 11`, `Community 12`, `Community 15`, `Community 16`, `Community 17`, `Community 19`, `Community 20`, `Community 21`?**
_High betweenness centrality (0.048) - this node is a cross-community bridge._
- **Are the 859 inferred relationships involving `str` (e.g. with `unhandled_exception_handler()` and `get_current_user_by_token()`) actually correct?**
_`str` has 859 INFERRED edges - model-reasoned connections that need verification._
- **Are the 731 inferred relationships involving `success_response()` (e.g. with `list_storage_release_reviews()` and `get_storage_release_review_detail()`) actually correct?**
_`success_response()` has 731 INFERRED edges - model-reasoned connections that need verification._
- **Are the 604 inferred relationships involving `error_response()` (e.g. with `_json_error_response()` and `list_storage_release_reviews()`) actually correct?**
_`error_response()` has 604 INFERRED edges - model-reasoned connections that need verification._
- **Are the 589 inferred relationships involving `SysUser` (e.g. with `数据权限过滤(V0.3:基于角色 data_scope 的查询级行级过滤) data_scope 值: 1 = 全部数据 2 = 本部门数据 3` and `从 SysUser 读取用户的 dept_id。`) actually correct?**
_`SysUser` has 589 INFERRED edges - model-reasoned connections that need verification._
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,423 @@
#!/usr/bin/env python3
"""将「用户-角色」迁移为「用户-职位 + 职位-角色」,并清理直接绑定。
步骤(与产品约定一致):
1. 软删除清空 sys_post / sys_user_post / sys_post_role(指定租户)
2. 按 sys_role(未删除)逐条创建职位:post_name=角色名,post_code=名称拼音首字母缩写;
并为职位绑定该角色(sys_post_role 一对一)
3. 按 sys_user_role 为用户绑定对应职位(sys_user_post)
4. 软删除清空 sys_user_role(指定租户)
用法(在 backend 目录):
# 务必指向测试库,勿连生产
export ENV_FILE=./.env.test # 或确认 .env 已是测试库
source venv/bin/activate
pip install pypinyin # 若尚未安装
# 只预览,不写库
python scripts/migrate_user_role_to_post.py --dry-run
# 真正执行(需同时传 --execute 与库名确认)
python scripts/migrate_user_role_to_post.py --execute --confirm-database zkxw-sc
注意:
- 菜单/数据权限运行时已走有效角色并集,迁移后可由职位继承。
- 仍有少量代码只查 sys_user_role(如「实验专员」步骤负责人校验、
质检金额授权列表、工作流按角色选人)。若业务依赖这些入口,需另改代码或
保留对应直接绑定(可用 --preserve-role-ids)。
"""
from __future__ import annotations
import argparse
import os
import re
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple
from urllib.parse import urlparse
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
try:
from pypinyin import Style, lazy_pinyin
except ImportError as exc: # pragma: no cover
raise SystemExit(
"缺少依赖 pypinyin。请先执行: pip install pypinyin\n" + str(exc)
) from exc
from sqlalchemy import and_
from app.core.config import settings
from app.core.database import SessionLocal
from app.core.utils import generate_uuid
from app.models.models import SysPost, SysPostRole, SysRole, SysUserPost, SysUserRole
# 质检物料金额查看:授权管理模块仍读写 sys_user_role;默认迁移后一并清理,
# 若需保留其直接绑定,执行时加:
# --preserve-role-ids ROLE000000000000000000000000000011
DEFAULT_PRESERVE_ROLE_IDS: Tuple[str, ...] = ()
def _mask_database_url(url: str) -> str:
try:
u = urlparse(url)
user = u.username or ""
host = u.hostname or ""
port = f":{u.port}" if u.port else ""
db = (u.path or "").lstrip("/")
return f"{u.scheme}://{user}:***@{host}{port}/{db}"
except Exception:
return "***"
def _database_name(url: str) -> str:
try:
return (urlparse(url).path or "").lstrip("/").split("?")[0]
except Exception:
return ""
def role_name_to_post_code(role_name: str, used: Set[str]) -> str:
"""职位编码 = 角色名拼音首字母缩写(大写),冲突则追加序号。"""
name = (role_name or "").strip() or "POST"
letters = "".join(lazy_pinyin(name, style=Style.FIRST_LETTER))
base = re.sub(r"[^A-Za-z0-9]", "", letters).upper()
if not base:
base = "POST"
# 编码不宜过长
base = base[:48]
code = base
n = 2
while code in used:
suffix = f"-{n}"
code = (base[: 48 - len(suffix)] + suffix).upper()
n += 1
used.add(code)
return code
def soft_clear_posts(db, tenant_no: str, now: datetime, dry_run: bool) -> Dict[str, int]:
counts = {}
for model, key in (
(SysPostRole, "sys_post_role"),
(SysUserPost, "sys_user_post"),
(SysPost, "sys_post"),
):
q = db.query(model).filter(model.tenant_no == tenant_no, model.del_flag == 0)
n = q.count()
counts[key] = n
if not dry_run and n:
q.update(
{"del_flag": 1, "update_time": now},
synchronize_session=False,
)
return counts
def load_roles(db, tenant_no: str) -> List[SysRole]:
return (
db.query(SysRole)
.filter(SysRole.tenant_no == tenant_no, SysRole.del_flag == 0)
.order_by(SysRole.order_num.asc(), SysRole.create_time.asc())
.all()
)
def create_posts_for_roles(
db,
roles: List[SysRole],
tenant_no: str,
operator_id: Optional[str],
now: datetime,
dry_run: bool,
) -> Dict[str, str]:
"""返回 role_id -> post_id。"""
used_codes: Set[str] = set()
role_to_post: Dict[str, str] = {}
for idx, role in enumerate(roles, start=1):
post_id = generate_uuid()
code = role_name_to_post_code(role.role_name, used_codes)
status = (role.status or "1").strip() or "1"
print(
f" [{idx}/{len(roles)}] 角色「{role.role_name}」({role.id}) "
f"→ 职位 {code} / {role.role_name}"
)
role_to_post[role.id] = post_id
if dry_run:
continue
db.add(
SysPost(
id=post_id,
post_name=role.role_name,
post_code=code,
status=status,
tenant_no=tenant_no,
order_num=role.order_num if role.order_num is not None else idx,
remark=f"由角色迁移生成,role_id={role.id}",
create_by=operator_id,
create_dept_id="",
create_time=now,
update_by=operator_id,
update_time=now,
del_flag=0,
)
)
db.add(
SysPostRole(
id=generate_uuid(),
post_id=post_id,
role_id=role.id,
tenant_no=tenant_no,
order_num=0,
remark="角色一对一迁移",
create_by=operator_id,
create_dept_id="",
create_time=now,
update_by=operator_id,
update_time=now,
del_flag=0,
)
)
return role_to_post
def migrate_user_posts(
db,
tenant_no: str,
role_to_post: Dict[str, str],
operator_id: Optional[str],
now: datetime,
dry_run: bool,
) -> Tuple[int, int]:
"""按用户-角色生成用户-职位。返回 (将写入条数, 跳过条数)。"""
rows = (
db.query(SysUserRole)
.filter(SysUserRole.tenant_no == tenant_no, SysUserRole.del_flag == 0)
.all()
)
# 同一用户同一职位只绑一次
seen: Set[Tuple[str, str]] = set()
written = 0
skipped = 0
for ur in rows:
post_id = role_to_post.get(ur.role_id)
if not post_id:
skipped += 1
continue
key = (ur.user_id, post_id)
if key in seen:
skipped += 1
continue
seen.add(key)
written += 1
if dry_run:
continue
db.add(
SysUserPost(
id=generate_uuid(),
user_id=ur.user_id,
post_id=post_id,
tenant_no=tenant_no,
order_num=ur.order_num if ur.order_num is not None else 0,
remark=f"由用户角色迁移,role_id={ur.role_id}",
create_by=operator_id,
create_dept_id="",
create_time=now,
update_by=operator_id,
update_time=now,
del_flag=0,
)
)
return written, skipped
def clear_user_roles(
db,
tenant_no: str,
preserve_role_ids: Set[str],
now: datetime,
dry_run: bool,
) -> Tuple[int, int]:
q = db.query(SysUserRole).filter(
SysUserRole.tenant_no == tenant_no, SysUserRole.del_flag == 0
)
if preserve_role_ids:
q = q.filter(~SysUserRole.role_id.in_(list(preserve_role_ids)))
n = q.count()
preserved = 0
if preserve_role_ids:
preserved = (
db.query(SysUserRole)
.filter(
SysUserRole.tenant_no == tenant_no,
SysUserRole.del_flag == 0,
SysUserRole.role_id.in_(list(preserve_role_ids)),
)
.count()
)
if not dry_run and n:
q.update({"del_flag": 1, "update_time": now}, synchronize_session=False)
return n, preserved
def run(
*,
tenant_no: str,
dry_run: bool,
execute: bool,
confirm_database: Optional[str],
operator_id: Optional[str],
preserve_role_ids: Set[str],
) -> None:
db_url = settings.DATABASE_URL
db_name = _database_name(db_url)
print("=== 用户角色 → 职位 迁移 ===")
print(f"ENV_FILE : {os.getenv('ENV_FILE', '(default backend/.env)')}")
print(f"DATABASE_URL : {_mask_database_url(db_url)}")
print(f"database : {db_name}")
print(f"tenant_no : {tenant_no}")
print(f"mode : {'DRY-RUN' if dry_run or not execute else 'EXECUTE'}")
if preserve_role_ids:
print(f"preserve UR : {', '.join(sorted(preserve_role_ids))}")
print()
if execute and not dry_run:
if not confirm_database:
raise SystemExit(
"执行写库必须传 --confirm-database <库名>,"
f"当前检测到库名为「{db_name}」。"
)
if confirm_database != db_name:
raise SystemExit(
f"--confirm-database={confirm_database!r} 与当前连接库名 "
f"{db_name!r} 不一致,已中止。"
)
db = SessionLocal()
now = datetime.now()
try:
roles = load_roles(db, tenant_no)
user_role_count = (
db.query(SysUserRole)
.filter(SysUserRole.tenant_no == tenant_no, SysUserRole.del_flag == 0)
.count()
)
print(f"当前有效角色数 : {len(roles)}")
print(f"当前用户-角色绑定数: {user_role_count}")
print()
print("步骤1:清空职位相关表(软删除)…")
cleared = soft_clear_posts(db, tenant_no, now, dry_run=dry_run or not execute)
for k, v in cleared.items():
print(f" {k}: {v}")
print("步骤2:按角色创建职位并绑定角色…")
role_to_post = create_posts_for_roles(
db,
roles,
tenant_no,
operator_id,
now,
dry_run=dry_run or not execute,
)
print("步骤3:按用户-角色生成用户-职位…")
written, skipped = migrate_user_posts(
db,
tenant_no,
role_to_post,
operator_id,
now,
dry_run=dry_run or not execute,
)
print(f" 将写入用户-职位: {written},跳过: {skipped}")
print("步骤4:清理用户-角色直接绑定(软删除)…")
cleared_ur, preserved_ur = clear_user_roles(
db,
tenant_no,
preserve_role_ids,
now,
dry_run=dry_run or not execute,
)
print(f" 将清理用户-角色: {cleared_ur},保留: {preserved_ur}")
if dry_run or not execute:
db.rollback()
print()
print("DRY-RUN 完成,未写入数据库。确认无误后执行:")
print(
f" ENV_FILE=... python scripts/migrate_user_role_to_post.py "
f"--execute --confirm-database {db_name}"
)
else:
db.commit()
print()
print("迁移已提交。")
print(
"请在测试环境登录验证:菜单权限、数据权限、职位管理、用户查看中的有效角色。"
)
except Exception:
db.rollback()
raise
finally:
db.close()
def main() -> None:
parser = argparse.ArgumentParser(
description="将用户-角色迁移为用户-职位(测试库专用)"
)
parser.add_argument("--tenant-no", default="zkxw", help="租户编号,默认 zkxw")
parser.add_argument(
"--dry-run",
action="store_true",
help="仅预览(默认若不带 --execute 也等同预览)",
)
parser.add_argument(
"--execute",
action="store_true",
help="真正写库(必须同时传 --confirm-database)",
)
parser.add_argument(
"--confirm-database",
default=None,
help="当前连接的数据库名(与 DATABASE_URL 路径段一致)",
)
parser.add_argument(
"--operator-id",
default=None,
help="create_by / update_by,可选",
)
parser.add_argument(
"--preserve-role-ids",
default="",
help="清理 sys_user_role 时保留的角色 ID,逗号分隔",
)
args = parser.parse_args()
preserve = set(DEFAULT_PRESERVE_ROLE_IDS)
for part in (args.preserve_role_ids or "").split(","):
pid = part.strip()
if pid:
preserve.add(pid)
# 未显式 --execute 时一律 dry-run
dry_run = bool(args.dry_run) or not bool(args.execute)
run(
tenant_no=args.tenant_no,
dry_run=dry_run,
execute=bool(args.execute),
confirm_database=args.confirm_database,
operator_id=args.operator_id,
preserve_role_ids=preserve,
)
if __name__ == "__main__":
main()
@@ -0,0 +1,31 @@
"""按有效角色查用户:空入参行为(不依赖 DB)。"""
from app.services.web_auth_roles import (
list_user_ids_with_any_effective_role_ids,
list_user_ids_with_effective_role_name,
)
class _DummySession:
def query(self, *args, **kwargs): # pragma: no cover
raise AssertionError("空入参不应访问数据库")
def test_list_by_role_name_empty_inputs():
db = _DummySession()
assert list_user_ids_with_effective_role_name(db, tenant_no="", role_name="实验专员") == set()
assert list_user_ids_with_effective_role_name(db, tenant_no="zkxw", role_name="") == set()
assert list_user_ids_with_effective_role_name(
db, tenant_no="zkxw", role_name="实验专员", candidate_user_ids=[]
) == set()
def test_list_by_role_ids_empty_inputs():
db = _DummySession()
assert list_user_ids_with_any_effective_role_ids(db, tenant_no="zkxw", role_ids=[]) == []
assert list_user_ids_with_any_effective_role_ids(db, tenant_no="", role_ids=["r1"]) == []
assert (
list_user_ids_with_any_effective_role_ids(
db, tenant_no="zkxw", role_ids=["r1"], candidate_user_ids=[]
)
== []
)
+54
View File
@@ -0,0 +1,54 @@
"""OA 发起审批草稿序列化与访问错误"""
import unittest
from datetime import datetime
from types import SimpleNamespace
from app.crud.oa_instance_draft import DraftAccessError, row_to_dict
class TestOaInstanceDraftRowToDict(unittest.TestCase):
def _row(self, **kwargs):
base = dict(
id="d1",
app_id="a1",
app_version_id="v1",
title="请假",
form_data_json='{"days":1}',
initiator_select_json='{"n1":["u1"]}',
initiator_dept_id="dept1",
owner_user_id="u-owner",
create_time=datetime(2026, 8, 6, 10, 0, 0),
update_time=datetime(2026, 8, 6, 11, 0, 0),
)
base.update(kwargs)
return SimpleNamespace(**base)
def test_list_shape_without_payload(self):
d = row_to_dict(
self._row(),
app_name="请假申请",
version_no=3,
group_id="g1",
group_name="人事",
)
self.assertEqual(d["id"], "d1")
self.assertEqual(d["appId"], "a1")
self.assertEqual(d["appName"], "请假申请")
self.assertEqual(d["versionNo"], 3)
self.assertEqual(d["status"], "draft")
self.assertEqual(d["updateTime"], "2026-08-06 11:00:00")
self.assertNotIn("formData", d)
def test_detail_includes_payload(self):
d = row_to_dict(self._row(), include_payload=True)
self.assertEqual(d["formData"], {"days": 1})
self.assertEqual(d["initiatorSelectByNode"], {"n1": ["u1"]})
self.assertEqual(d["initiatorDeptId"], "dept1")
def test_access_error_message(self):
err = DraftAccessError("草稿不存在或无权访问")
self.assertEqual(str(err), "草稿不存在或无权访问")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,38 @@
"""OA 菜单角标:待办数 / 草稿数"""
import unittest
from unittest.mock import MagicMock, patch
from app.crud import oa_instance_draft as oid_crud
from app.services import oa_engine as eng
class TestCountPendingTasks(unittest.TestCase):
def test_filters_approval_pending_for_user(self):
db = MagicMock()
q = db.query.return_value
filtered = q.filter.return_value
filtered.count.return_value = 3
n = eng.count_pending_tasks(db, tenant_no="t1", user_id="u1")
self.assertEqual(n, 3)
db.query.assert_called_once()
q.filter.assert_called_once()
filtered.count.assert_called_once()
class TestCountDrafts(unittest.TestCase):
def test_filters_owner_and_tenant(self):
db = MagicMock()
q = db.query.return_value
filtered = q.filter.return_value
filtered.count.return_value = 5
n = oid_crud.count_drafts(db, tenant_no="t1", owner_user_id="u1")
self.assertEqual(n, 5)
db.query.assert_called_once()
q.filter.assert_called_once()
filtered.count.assert_called_once()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,35 @@
"""角色列表 boundUserNames / boundPostNames enrichment。"""
import inspect
from app.crud import role as role_crud
class _DummySession:
def query(self, *args, **kwargs): # pragma: no cover
raise AssertionError("空入参不应访问数据库")
def test_bound_user_names_by_role_ids_empty():
db = _DummySession()
assert role_crud._bound_user_names_by_role_ids(db, [], "zkxw") == {}
assert role_crud._bound_user_names_by_role_ids(db, ["r1"], "") == {}
def test_bound_post_names_by_role_ids_empty():
db = _DummySession()
assert role_crud._bound_post_names_by_role_ids(db, [], "zkxw") == {}
assert role_crud._bound_post_names_by_role_ids(db, ["r1"], "") == {}
def test_user_display_name_prefers_nick():
assert role_crud._user_display_name("张三", "zhangsan") == "张三"
assert role_crud._user_display_name("", "zhangsan") == "zhangsan"
assert role_crud._user_display_name(" ", "u1") == "u1"
assert role_crud._user_display_name(None, None) == ""
def test_list_roles_enriches_bound_names():
source = inspect.getsource(role_crud.list_roles)
assert "_bound_user_names_by_role_ids" in source
assert "_bound_post_names_by_role_ids" in source
assert "boundUserNames" in inspect.getsource(role_crud._row_to_dict) or "bound_user_names" in source