Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Common setting format #146

Merged
merged 2 commits into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions cmdb-api/api/lib/common_setting/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@


class OperatorType(BaseEnum):
EQUAL = 1 # 等于
NOT_EQUAL = 2 # 不等于
IN = 3 # 包含
NOT_IN = 4 # 不包含
GREATER_THAN = 5 # 大于
LESS_THAN = 6 # 小于
IS_EMPTY = 7 # 为空
IS_NOT_EMPTY = 8 # 不为空
EQUAL = 1
NOT_EQUAL = 2
IN = 3
NOT_IN = 4
GREATER_THAN = 5
LESS_THAN = 6
IS_EMPTY = 7
IS_NOT_EMPTY = 8
18 changes: 8 additions & 10 deletions cmdb-api/api/lib/common_setting/department.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from wtforms import StringField
from wtforms import validators

from api.extensions import db
from api.lib.common_setting.resp_format import ErrFormat
from api.lib.perm.acl.role import RoleCRUD
from api.models.common_setting import Department, Employee
Expand Down Expand Up @@ -44,7 +45,6 @@ def get_all_employee_list(block=0, to_dict=True):
'email',
'mobile',
'direct_supervisor_id',
'annual_leave',
'block',
'department_id',
]
Expand Down Expand Up @@ -94,11 +94,9 @@ def get_tree_departments(self):

for top_d in top_departments:
department_id = top_d['department_id']
# 检查 department_id 是否作为其他部门的 parent
sub_deps = self.get_department_by_parent_id(department_id)
employees = []
if self.append_employee:
# 要包含员工
employees = self.get_employees_by_d_id(department_id)

top_d['employees'] = employees
Expand Down Expand Up @@ -127,7 +125,6 @@ def parse_sub_department(self, deps, top_d):
sub_deps = self.get_department_by_parent_id(d['department_id'])
employees = []
if self.append_employee:
# 要包含员工
employees = self.get_employees_by_d_id(d['department_id'])

d['employees'] = employees
Expand Down Expand Up @@ -184,7 +181,6 @@ def add(**kwargs):
def check_department_parent_id_allow(d_id, department_parent_id):
if department_parent_id == 0:
return
# 检查 department_parent_id 是否在许可范围内
allow_p_d_id_list = DepartmentCRUD.get_allow_parent_d_id_by(d_id)
target = list(
filter(lambda d: d['department_id'] == department_parent_id, allow_p_d_id_list))
Expand Down Expand Up @@ -263,9 +259,6 @@ def delete(_id):

@staticmethod
def get_allow_parent_d_id_by(department_id):
"""
获取可以成为 department_id 的 department_parent_id 的 list
"""
tree_list = DepartmentCRUD.get_department_tree_list()

allow_d_id_list = []
Expand Down Expand Up @@ -307,7 +300,6 @@ def get_department_tree_list():
if len(all_deps) == 0:
return []

# 一级部门
top_deps = list(filter(lambda d: d['department_parent_id'] == -1, all_deps))
if len(top_deps) == 0:
return []
Expand All @@ -321,7 +313,6 @@ def get_department_tree_list():
top_d['department_name'],
identifier_root
)
# 检查 department_id 是否作为其他部门的 parent
sub_ds = list(filter(lambda d: d['department_parent_id'] == identifier_root, all_deps))
if len(sub_ds) == 0:
tree_list.append(tree)
Expand Down Expand Up @@ -350,6 +341,13 @@ def parse_sub_department_node(sub_ds, all_ds, tree, parent_id):
DepartmentCRUD.parse_sub_department_node(
next_sub_ds, all_ds, tree, d['department_id'])

@staticmethod
def get_department_by_query(query, to_dict=True):
results = query.all()
if not results:
return []
return results if not to_dict else [r.to_dict() for r in results]

@staticmethod
def get_departments_and_ids(department_parent_id, block):
query = Department.query.filter(
Expand Down
81 changes: 30 additions & 51 deletions cmdb-api/api/lib/common_setting/employee.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@
from api.lib.common_setting.resp_format import ErrFormat
from api.models.common_setting import Employee, Department

acl_user_columns = [
'email',
'mobile',
'nickname',
'username',
'password',
'block',
'avatar',
]
employee_pop_columns = ['password']
can_not_edit_columns = ['email']


def edit_acl_user(uid, **kwargs):
user_data = {column: kwargs.get(
Expand Down Expand Up @@ -68,9 +80,6 @@ def get_employee_by_id(_id):

@staticmethod
def get_employee_by_uid_with_create(_uid):
"""
根据 uid 获取员工信息,不存在则创建
"""
try:
return EmployeeCRUD.get_employee_by_uid(_uid).to_dict()
except Exception as e:
Expand Down Expand Up @@ -100,7 +109,6 @@ def check_acl_user_and_create(user_info):
acl_uid=user_info['uid'],
)
return existed.to_dict()
# 创建员工
if not user_info.get('nickname', None):
user_info['nickname'] = user_info['name']

Expand Down Expand Up @@ -143,9 +151,6 @@ def update(_id, **kwargs):

if len(e_list) > 0:
from api.tasks.common_setting import edit_employee_department_in_acl
# fixme: comment next line
# edit_employee_department_in_acl(e_list, new_department_id, current_user.uid)

edit_employee_department_in_acl.apply_async(
args=(e_list, new_department_id, current_user.uid),
queue=COMMON_SETTING_QUEUE
Expand Down Expand Up @@ -218,8 +223,6 @@ def get_export_employee_list(block_status):
else:
employees = Employee.get_by(to_dict=False)

keep_cols = EmployeeCRUD.get_current_user_view_columns()

all_departments = Department.get_by(to_dict=False)
d_id_map = {d.department_id: d.department_name for d in all_departments}
e_id_map = {e.employee_id: e.nickname for e in employees}
Expand Down Expand Up @@ -249,8 +252,7 @@ def get_export_employee_list(block_status):
data['department_name'] = department_name
data['nickname_direct_supervisor'] = nickname_direct_supervisor

tmp = {export_columns_map[k]: data[k] for k in export_columns_map.keys() if
k in keep_cols or k in sub_columns}
tmp = {export_columns_map[k]: data[k] for k in export_columns_map.keys()}

data_list.append(tmp)

Expand Down Expand Up @@ -355,7 +357,6 @@ def edit_employee_block_column(_id, is_acl=False, **kwargs):
existed = EmployeeCRUD.get_employee_by_id(_id)
value = get_block_value(kwargs.get('block'))
if value is True:
# 判断该用户是否为 部门负责人,或者员工的直接上级
check_department_director_id_or_direct_supervisor_id(_id)

if is_acl:
Expand Down Expand Up @@ -449,7 +450,7 @@ def parse_condition_list_to_query(condition_list):
@staticmethod
def get_expr_by_condition(column, operator, value, relation):
"""
根据conditions返回expr: (and_list, or_list)
get expr: (and_list, or_list)
"""
attr = EmployeeCRUD.get_attr_by_column(column)
# 根据operator生成条件表达式
Expand Down Expand Up @@ -483,7 +484,6 @@ def get_expr_by_condition(column, operator, value, relation):
else:
abort(400, ErrFormat.not_support_operator.format(operator))

# 根据relation生成复合条件
if relation == "&":
return expr, []
elif relation == "|":
Expand All @@ -493,7 +493,6 @@ def get_expr_by_condition(column, operator, value, relation):

@staticmethod
def check_condition(column, operator, value, relation):
# 对于condition中column为空的,报错
if column is None or operator is None or relation is None:
return abort(400, ErrFormat.conditions_field_missing)

Expand Down Expand Up @@ -642,19 +641,6 @@ def get_user_map(key='uid', acl=None):
return data


acl_user_columns = [
'email',
'mobile',
'nickname',
'username',
'password',
'block',
'avatar',
]
employee_pop_columns = ['password']
can_not_edit_columns = ['email']


def format_params(params):
for k in ['_key', '_secret']:
params.pop(k, None)
Expand All @@ -664,19 +650,22 @@ def format_params(params):
class CreateEmployee(object):
def __init__(self):
self.acl = ACLManager()
self.useremail_map = {}
self.all_acl_users = self.acl.get_all_users()

def check_acl_user(self, user_data):
target_email = list(filter(lambda x: x['email'] == user_data['email'], self.all_acl_users))
if target_email:
return target_email[0]

def check_acl_user(self, email):
user_info = self.useremail_map.get(email, None)
if user_info:
return user_info
return None
target_username = list(filter(lambda x: x['username'] == user_data['username'], self.all_acl_users))
if target_username:
return target_username[0]

def add_acl_user(self, **kwargs):
user_data = {column: kwargs.get(
column, '') for column in acl_user_columns if kwargs.get(column, '')}
try:
existed = self.check_acl_user(user_data['email'])
existed = self.check_acl_user(user_data)
if not existed:
return self.acl.create_user(user_data)
return existed
Expand All @@ -685,8 +674,6 @@ def add_acl_user(self, **kwargs):

def create_single(self, **kwargs):
EmployeeCRUD.check_email_unique(kwargs['email'])
self.useremail_map = self.useremail_map if self.useremail_map else get_user_map(
'email', self.acl)
user = self.add_acl_user(**kwargs)
kwargs['acl_uid'] = user['uid']
kwargs['last_login'] = user['last_login']
Expand All @@ -699,8 +686,6 @@ def create_single(self, **kwargs):
)

def create_single_with_import(self, **kwargs):
self.useremail_map = self.useremail_map if self.useremail_map else get_user_map(
'email', self.acl)
user = self.add_acl_user(**kwargs)
kwargs['acl_uid'] = user['uid']
kwargs['last_login'] = user['last_login']
Expand Down Expand Up @@ -743,9 +728,6 @@ def get_end_department_id(self, department_name_list, department_name_map):
return end_d_id

def format_department_id(self, employee):
"""
部门名称转化为ID,不存在则创建
"""
department_name_map = {}
try:
department_name = employee.get('department_name', '')
Expand All @@ -762,16 +744,13 @@ def format_department_id(self, employee):

def batch_create(self, employee_list):
err_list = []
self.useremail_map = get_user_map('email', self.acl)

for employee in employee_list:
try:
# 获取username
username = employee.get('username', None)
if username is None:
employee['username'] = employee['email']

# 校验通过后获取department_id
employee = self.format_department_id(employee)
err = employee.get('err', None)
if err:
Expand All @@ -783,7 +762,7 @@ def batch_create(self, employee_list):
raise Exception(
','.join(['{}: {}'.format(filed, ','.join(msg)) for filed, msg in form.errors.items()]))

data = self.create_single_with_import(**form.data)
self.create_single_with_import(**form.data)
except Exception as e:
err_list.append({
'email': employee.get('email', ''),
Expand All @@ -797,12 +776,12 @@ def batch_create(self, employee_list):

class EmployeeAddForm(Form):
username = StringField(validators=[
validators.DataRequired(message="username不能为空"),
validators.DataRequired(message=ErrFormat.username_is_required),
validators.Length(max=255),
])
email = StringField(validators=[
validators.DataRequired(message="邮箱不能为空"),
validators.Email(message="邮箱格式不正确"),
validators.DataRequired(message=ErrFormat.email_is_required),
validators.Email(message=ErrFormat.email_format_error),
validators.Length(max=255),
])
password = StringField(validators=[
Expand All @@ -811,7 +790,7 @@ class EmployeeAddForm(Form):
position_name = StringField(validators=[])

nickname = StringField(validators=[
validators.DataRequired(message="用户名不能为空"),
validators.DataRequired(message=ErrFormat.nickname_is_required),
validators.Length(max=255),
])
sex = StringField(validators=[])
Expand All @@ -822,7 +801,7 @@ class EmployeeAddForm(Form):

class EmployeeUpdateByUidForm(Form):
nickname = StringField(validators=[
validators.DataRequired(message="用户名不能为空"),
validators.DataRequired(message=ErrFormat.nickname_is_required),
validators.Length(max=255),
])
avatar = StringField(validators=[])
Expand Down
5 changes: 5 additions & 0 deletions cmdb-api/api/lib/common_setting/resp_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,8 @@ class ErrFormat(CommonErrFormat):
acl_add_user_to_role_failed = "ACL 添加用户到角色失败: {}"
acl_import_user_failed = "ACL 导入用户[{}]失败: {}"

nickname_is_required = "用户名不能为空"
username_is_required = "username不能为空"
email_is_required = "邮箱不能为空"
email_format_error = "邮箱格式错误"

Loading
Loading