zhaoqingang
2024-12-18 91062dda27e06bf29eaa78eff47ba505ad19b7a2
机构接口优化
7个文件已修改
190 ■■■■ 已修改文件
app/api/chat.py 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/api/organization.py 22 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/config/const.py 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/models/organization_model.py 12 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/service/organization.py 63 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/service/user.py 73 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/task/fetch_agent.py 8 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/api/chat.py
@@ -235,7 +235,7 @@
                if not question:
                    await websocket.send_json({"message": "Invalid request", "type": "error"})
                    continue
                logger.error(agent.type)
                # logger.error(agent.type)
                if chat_type == "questionTalk":
                    try:
app/api/organization.py
@@ -1,11 +1,11 @@
from fastapi import APIRouter, Depends
from app.api import Response, pwd_context, get_current_user
from app.models import DeptList, DeptInfo, DeptParent
from app.models import DeptList, DeptInfo, DeptParent, DeptStatus
from app.models.base_model import get_db
from app.models.user import PageParameter, UserStatus, UserInfo, LoginData
from app.models.user_model import UserModel
from app.service.organization import get_organization_list, create_dept, edit_dept_data, edit_dept_parent, \
    get_organization_info, delete_organization_info
    get_organization_info, delete_organization_info, edit_organization_status
dept_router = APIRouter()
@@ -54,15 +54,17 @@
@dept_router.delete("/{deptId}", response_model=Response)
async def delete_dept(deptId, current_user: UserModel = Depends(get_current_user), db=Depends(get_db)):
    is_edit = await delete_organization_info(db, deptId)
    if not is_edit:
        return Response(code=500, msg="dept delete failure", data={})
    msg = await delete_organization_info(db, deptId)
    if msg:
        return Response(code=400, msg=f"{msg}", data={})
    return Response(code=200, msg="dept delete successfully", data={})
@dept_router.delete("/{deptId}", response_model=Response)
async def delete_dept(deptId, current_user: UserModel = Depends(get_current_user), db=Depends(get_db)):
    is_edit = await delete_organization_info(db, deptId)
    if not is_edit:
        return Response(code=500, msg="dept delete failure", data={})
@dept_router.put("/status", response_model=Response)
async def edit_status_api(dept: DeptStatus, current_user: UserModel = Depends(get_current_user), db=Depends(get_db)):
    if dept.status not in ["0", '1']:
        return Response(code=400, msg="未知状态!", data={})
    msg = await edit_organization_status(db, dept.deptId, dept.status)
    if msg:
        return Response(code=400, msg=f"{msg}", data={})
    return Response(code=200, msg="dept delete successfully", data={})
app/config/const.py
@@ -22,4 +22,12 @@
USER_STATSU_ON = "1"
USER_STATSU_OFF = "0"
Dialog_STATSU_DELETE = "2"
Dialog_STATSU_DELETE = "2"
DEPT_STATUS_DELETE = "2"
DEPT_STATUS_ON = "1"
DEPT_STATUS_OFF = "0"
ROLE_STATUS_DELETE = "2"
ROLE_STATUS_ON = "1"
ROLE_STATUS_OFF = "0"
app/models/organization_model.py
@@ -5,6 +5,7 @@
from sqlalchemy import Column, Integer, String, Table, ForeignKey, DateTime
from sqlalchemy.orm import relationship, backref
from app.config.const import DEPT_STATUS_DELETE
from app.models.base_model import Base
# organization_group_table = Table('organization_group', Base.metadata,
@@ -29,7 +30,7 @@
    leader = Column(String(255))
    phone = Column(String(32))
    email = Column(String(64))
    status = Column(String(10), nullable=False, default="0")
    status = Column(String(10), nullable=False, default="1")
    # groups = relationship('GroupModel',
    #                             secondary=organization_group_table,
@@ -65,7 +66,7 @@
            'roles': [self.role_json(role) for role in self.roles],
            # 'groups': [self.group_json(group) for group in self.groups],
            'children': [
                org.to_json() for org in self.children
                org.to_json() for org in self.children if org.status != DEPT_STATUS_DELETE
            ]
        }
@@ -168,7 +169,7 @@
    orderNum: int
    address: Optional[str] = ""
    parentId: Optional[str] = ""
    status: str
    status:  Optional[str] = ""
    roles: Optional[list] = []
    groups: Optional[list] = []
@@ -177,3 +178,8 @@
    deptId: str
    parentId: str
    orderNum: int
class DeptStatus(BaseModel):
    deptId: str
    status: str
app/service/organization.py
@@ -1,6 +1,7 @@
import uuid
from Log import logger
from app.config.const import DEPT_STATUS_DELETE, DEPT_STATUS_ON, DEPT_STATUS_OFF
from app.models import OrganizationModel
from app.models.role_model import RoleModel
@@ -40,7 +41,7 @@
        dept_model.address = address
        dept_model.phone = phone
        dept_model.leader = leader
        dept_model.status = status
        # dept_model.status = status
        dept_model.seq = order_num
        # if parent_id:
        #     dept_model.parent = db.get(OrganizationModel, parent_id)
@@ -75,15 +76,67 @@
async def get_organization_info(db, dept_id: str):
    dept = db.query(OrganizationModel).filter(OrganizationModel.id.__eq__(dept_id)).first()
    return {"total": 0, "data":  dept.to_json()}
    return {"total": 0, "data":  dept.to_dict()}
async def delete_organization_info(db, dept_id: str):
    delete_list = []
    dept_list = []
    next_dept_list = []
    base_dept = db.query(OrganizationModel).filter(OrganizationModel.id.__eq__(dept_id)).first()
    dept_list.append(base_dept)
    while dept_list:
        for dept in dept_list:
            delete_list.append(dept.id)
            if dept.roles:
                return "部门:{}已配置角色,不允许删除!".format(dept.name)
            for child_dept in dept.children:
                next_dept_list.append(child_dept)
        dept_list = next_dept_list
        next_dept_list = []
    try:
        db.query(OrganizationModel).filter(OrganizationModel.id.__eq__(dept_id)).delete()
        db.query(OrganizationModel).filter(OrganizationModel.id.in_(delete_list)).update({"status": DEPT_STATUS_DELETE})
        db.commit()
    except Exception as e:
        logger.error(e)
        db.rollback()
        return False
    return True
        return '服务异常 !'
    return ""
async def edit_organization_status(db, dept_id: str, status:str):
    delete_list = []
    dept_list = []
    next_dept_list = []
    base_dept = db.query(OrganizationModel).filter(OrganizationModel.id.__eq__(dept_id)).first()
    if status == DEPT_STATUS_ON:
        try:
            base_dept.status=status
            db.commit()
        except Exception as e:
            logger.error(e)
            db.rollback()
            return '服务异常 !'
    else:
        dept_list.append(base_dept)
        while dept_list:
            for dept in dept_list:
                delete_list.append(dept.id)
                if dept.roles:
                    return "部门:{}已配置角色,不允许!".format(dept.name)
                for child_dept in dept.children:
                    next_dept_list.append(child_dept)
            dept_list = next_dept_list
            next_dept_list = []
        try:
            db.query(OrganizationModel).filter(OrganizationModel.id.in_(delete_list)).update({"status": DEPT_STATUS_OFF})
            db.commit()
        except Exception as e:
            logger.error(e)
            db.rollback()
            return '服务异常 !'
    return ""
app/service/user.py
@@ -4,8 +4,9 @@
from app.api import pwd_context
from app.api.dialog import dialog_list
from app.config.config import settings
from app.config.const import RAGFLOW, BISHENG, DIFY, USER_STATSU_DELETE
from app.models import RoleModel, GroupModel, AgentType, role_resource_table, DialogModel, OrganizationModel
from app.config.const import RAGFLOW, BISHENG, DIFY, USER_STATSU_DELETE, ROLE_STATUS_ON, DEPT_STATUS_ON
from app.models import RoleModel, GroupModel, AgentType, role_resource_table, DialogModel, OrganizationModel, \
    ResourceModel
from app.models.menu_model import WebMenuModel, MenuCapacityModel
from app.models.user_model import UserModel, UserAppModel
from Log import logger
@@ -168,6 +169,8 @@
    user = db.query(UserModel).filter(UserModel.id==user_id,UserModel.status !=USER_STATSU_DELETE).first()
    await role_resource(role_set, roles, permissions, user.roles)
    for ogt in user.organizations:
        if ogt.status != DEPT_STATUS_ON:
            continue
        dept.append(ogt.to_json())
        if ogt.roles:
            await role_resource(role_set, roles, permissions, user.roles)
@@ -185,11 +188,11 @@
async def role_resource(role_set, role_list, permissions, roles):
    for role in roles:
        if role.id not in role_set:
        if role.id not in role_set and role.status == ROLE_STATUS_ON:
            role_set.add(role.id)
            role_list.append(role.to_dict())
            for r in role.resources:
                if r.resource_type_id == "1":
                if r.resource_type_id == "1" and r.status==DEPT_STATUS_ON:
                    permissions.add(r.perms)
@@ -199,33 +202,43 @@
    dept_set = set()
    user = db.query(UserModel).filter_by(id=user_id).first()
    parent_id = ""
    async def role_resource(role_set, permissions, roles):
        nonlocal parent_id
        for role in roles:
            if role.id not in role_set:
                role_set.add(role.id)
                for r in role.resources:
                    if r.resource_type_id != "1":
                        if not r.resource_id:
                            parent_id = r.id
                            continue
                        permissions[r.id] = r.to_router_dict()
    await role_resource(role_set, permissions, user.roles)
    for ogt in user.organizations:
        if ogt.roles:
            await role_resource(role_set, permissions, user.roles)
        parent_ogt = ogt.parent
        while parent_ogt:
            if parent_ogt.id not in dept_set:
                await role_resource(role_set, permissions, parent_ogt.roles)
                dept_set.add(parent_ogt.id)
                parent_ogt = parent_ogt.parent
            else:
                break
    tmp_dit = {}
    if user.permission == "admin":
        dept_list = db.query(ResourceModel).filter(ResourceModel.status==DEPT_STATUS_ON, ResourceModel.resource_type_id != "1").all()
        for dept in dept_list:
            if not dept.resource_id:
                parent_id = dept.id
                continue
            permissions[dept.id] = dept.to_router_dict()
    else:
        async def role_resource(role_set, permissions, roles):
            nonlocal parent_id
            for role in roles:
                if role.id not in role_set and role.status == ROLE_STATUS_ON:
                    role_set.add(role.id)
                    for r in role.resources:
                        if r.resource_type_id != "1" and r.status==DEPT_STATUS_ON:
                            if not r.resource_id:
                                parent_id = r.id
                                continue
                            permissions[r.id] = r.to_router_dict()
        await role_resource(role_set, permissions, user.roles)
        for ogt in user.organizations:
            if ogt.status != DEPT_STATUS_ON:
                continue
            if ogt.roles:
                await role_resource(role_set, permissions, user.roles)
            parent_ogt = ogt.parent
            while parent_ogt:
                if parent_ogt.id not in dept_set:
                    await role_resource(role_set, permissions, parent_ogt.roles)
                    dept_set.add(parent_ogt.id)
                    parent_ogt = parent_ogt.parent
                else:
                    break
    for permission in permissions.values():
        tmp_dit[permission["parentId"]] = tmp_dit.get(permission["parentId"], []) + [permission]
app/task/fetch_agent.py
@@ -318,9 +318,9 @@
                dify_data = get_data_from_dify_v2([])
                if dify_data:
                    update_ids_in_local_v2(dify_data, "4")
        print("Agents synchronized successfully")
        print("v2 Agents synchronized successfully")
    except Exception as e:
        print(f"Failed to sync agents: {str(e)}")
        print(f"v2 Failed to sync agents: {str(e)}")
def update_ids_in_local_knowledge(data, klg_type):
    type_dict = {"1": RAGFLOW, "2": BISHENG, "4": DIFY}
@@ -380,9 +380,9 @@
            # elif app["id"] == DIFY:
            #     dify_data = get_data_from_dify_v2([])
            #     update_ids_in_local_v2(dify_data, "4")
        print("Agents synchronized successfully")
        print("sync knowledge successfully")
    except Exception as e:
        print(f"Failed to sync agents: {str(e)}")
        print(f"Failed to sync knowledge: {str(e)}")
if __name__ == "__main__":