Compare commits

..

59 Commits

Author SHA1 Message Date
pycook
ab8ccf7d1b ui: lint 2024-01-12 18:21:47 +08:00
wang-liang0615
ae1f0f6b4f lint regexSelect (#382) 2024-01-12 18:09:03 +08:00
wang-liang0615
ff47e0ade6 feat:citype regex check & pref:edit is_list (#380) 2024-01-12 17:09:44 +08:00
pycook
0dd272fb04 feat(api): password supports regular check 2024-01-12 16:56:10 +08:00
pycook
6bc5c1516d feat(api): Attributes support regular check (#379)
feat(api): Attributes support regular check
2024-01-12 13:05:37 +08:00
wang-liang0615
4a4b9e6ef0 feat(cmdb-ui):preference citype order (#378) 2024-01-12 11:14:53 +08:00
pycook
6e3f9478b3 Dev api 240111 (#377)
* feat(api): My subscription supports CIType sorting

* feat(api): db change
2024-01-11 18:01:37 +08:00
pycook
691051c254 perf(api): /api/v0.1/ci/adc/statistics
perf(api): /api/v0.1/ci/adc/statistics
2024-01-11 10:10:01 +08:00
pycook
8f066e95a6 fix(api): grant by attr (#373) 2024-01-10 16:52:27 +08:00
pycook
75bca39bf6 fix(api): commands add-user 2024-01-10 11:56:39 +08:00
pycook
3360e4d0fe feat(db): set variable sql_mode
feat(db): set variable sql_mode
2024-01-10 10:28:15 +08:00
wang-liang0615
521fcd0ba2 fix(ui):some fix (#370)
* pref(ui):some bugfix & some style

* fix(ui):some fix
2024-01-10 09:46:02 +08:00
wang-liang0615
fc113425cb pref(ui):some bugfix & some style (#369) 2024-01-09 14:48:13 +08:00
pycook
81a76a9632 fix(api): cmdb-init-acl commands (#368) 2024-01-09 10:04:53 +08:00
wang-liang0615
9ec105ca37 fix(ui):logout (#365) 2024-01-04 16:12:20 +08:00
wang-liang0615
1e1c92a3ef refactor(ui):extract pager components (#364) 2024-01-04 13:41:07 +08:00
pycook
0b3cad8215 feat: update docker-compose 2024-01-04 10:26:47 +08:00
pycook
ed41a72900 release: v2.3.10 2024-01-03 19:23:42 +08:00
wang-liang0615
27854d4e0a fix(acl-ui):operation history (#363) 2024-01-03 17:41:42 +08:00
wang-liang0615
0372459f9d fix(ui) (#362) 2024-01-03 17:09:25 +08:00
simontigers
f56378e2b5 fix(api): common edit department return (#359)
fix(api): common edit department return (#359)
2024-01-03 16:42:14 +08:00
wang-liang0615
00b276d5e7 format(ui) (#361) 2024-01-03 16:35:50 +08:00
wang-liang0615
3faefbe8d3 feat(ui):i18n (#360)
* feat(ui):i18n

* i18n

* feat(ui):i18n
2024-01-03 16:03:15 +08:00
simontigers
4261f6fb57 fix(api): common department allow parent (#358)
* fix(api): common department edit method

* fix(api): common department edit method

* fix(api): common department allow parent
2024-01-03 15:19:08 +08:00
wang-liang0615
c98199e98e feat(ui):i18n (#357)
* feat(ui):i18n

* i18n
2024-01-03 14:58:47 +08:00
simontigers
82ea1ddc79 fix(api): common department edit method (#356)
* fix(api): common department edit method

* fix(api): common department edit method
2024-01-03 14:31:54 +08:00
simontigers
995e581315 fix(api): common department edit method (#355) 2024-01-03 14:26:40 +08:00
pycook
ec8f626b8f docs: update install (#354) 2024-01-03 13:58:35 +08:00
wang-liang0615
ec884c92e1 feat(ui):i18n (#352) 2024-01-03 13:29:38 +08:00
simontigers
9ee2776bdd fix(api): common i18n wide (#351)
* fix(api): common_i18n wide

* fix(api): department i18n
2024-01-03 13:26:58 +08:00
simontigers
7186bdac9c fix(api): common_i18n wide (#350) 2024-01-03 12:29:49 +08:00
wang-liang0615
0a9964375a feat(ui):add packages (#349) 2024-01-03 09:42:32 +08:00
wang-liang0615
bff45d00b6 i18n (#348) 2024-01-02 18:04:53 +08:00
wang-liang0615
e429ad59ff feat(ui):i18n (#347)
* feat(acl-ui):i18n

* feat(base-ui):i18n

* feat(cmdb-ui):i18n
2024-01-02 17:53:07 +08:00
pycook
ace160ae19 Dev api 231229 (#345)
* fix(api): predefined value for float

* feat(api): update public clouds config

* feat(api): commands add-user support is_admin
2023-12-29 13:44:23 +08:00
wang-liang0615
7036fe023c style(ui):global.less (#344) 2023-12-28 11:00:00 +08:00
wang-liang0615
341f5dba53 fix(cmdb-ui):model relation table (#343) 2023-12-27 13:24:01 +08:00
wang-liang0615
5883c1616e feat:Batch import and download templates support predefined values (#342) 2023-12-27 13:18:05 +08:00
simontigers
bee0a3a3e5 feat(api): common i18n (#340) 2023-12-26 10:06:15 +08:00
pycook
7a79a8bbf7 feat(api): i18n
feat(api): i18n
2023-12-25 21:51:44 +08:00
pycook
100a889cb8 fix(api): CI revoke permission (#337) 2023-12-25 12:15:20 +08:00
kdyq007
b093569453 [更新] 修复 LDAP 登录失败的问题 (#336)
Co-authored-by: sherlock <sherlock@gmail.com>
2023-12-25 09:36:31 +08:00
pycook
3919dfdfbb release: 2.3.9 2023-12-23 12:51:09 +08:00
pycook
ef85ba2542 feat(api): update cmdb-init-acl commands (#335) 2023-12-23 12:44:01 +08:00
pycook
3d5c2ec5bc Merge branch 'master' of github.com:veops/cmdb 2023-12-23 12:31:52 +08:00
pycook
c143d6ae5b fix(api): role grant 2023-12-23 12:30:52 +08:00
simontigers
10b273ee81 feat(api): add update_last_login_by_uid (#333) 2023-12-22 18:43:20 +08:00
wang-liang0615
855cb91b31 feat(cmdb-ui):ci type import&export,pref(cmdb-ui):download ci xlsx name, pref(cmdb-ui):ci detail history merge row method (#331)
* pref(cmdb-ui):download ci xlsx name

* pref(cmdb-ui):ci detail history merge row method

* feat(cmdb-ui):ci type import&export
2023-12-22 15:42:20 +08:00
pycook
ffae57642c fix(api): ci relation search
fix(api): ci relation search
2023-12-22 15:35:02 +08:00
simontigers
9ed1108c20 feat(api): add get_file_binary_str and save (#329) 2023-12-22 15:33:05 +08:00
simontigers
72b2f8b6de fix(api): refresh rid after create and import employee (#328) 2023-12-22 15:24:48 +08:00
pycook
20f3e917fe pref(api): import and export of CIType templates
pref(api): import and export of CIType templates
2023-12-22 14:32:03 +08:00
pycook
c430515377 fix(api): add CI (#326) 2023-12-22 11:19:16 +08:00
simontigers
a6e2aca281 fix(api): svg upload (#321) 2023-12-21 18:58:35 +08:00
wang-liang0615
18313b7bd1 fix(acl_ui):permission (#325) 2023-12-21 17:22:49 +08:00
wang-liang0615
dbc44a8ad6 fix(ui):common double menu (#324) 2023-12-21 14:59:39 +08:00
wang-liang0615
f143e30cf5 feat(ui):批量导入模型根据create权限过滤&&模型配置页面权限 (#323) 2023-12-21 14:23:38 +08:00
wang-liang0615
4beece5a6e fix:open triggerForm from attributeCard (#322) 2023-12-21 14:18:00 +08:00
pycook
920295d955 feat: Fixed db volume name 2023-12-21 10:26:51 +08:00
247 changed files with 25508 additions and 22734 deletions

3
.gitignore vendored
View File

@@ -43,7 +43,8 @@ cmdb-api/api/uploaded_files
cmdb-api/migrations/versions cmdb-api/migrations/versions
# Translations # Translations
*.mo #*.mo
messages.pot
# Mr Developer # Mr Developer
.mr.developer.cfg .mr.developer.cfg

View File

@@ -5,8 +5,8 @@ name = "pypi"
[packages] [packages]
# Flask # Flask
Flask = "==2.3.2" Flask = "==2.2.5"
Werkzeug = ">=2.3.6" Werkzeug = "==2.2.3"
click = ">=5.0" click = ">=5.0"
# Api # Api
Flask-RESTful = "==0.3.10" Flask-RESTful = "==0.3.10"
@@ -27,6 +27,8 @@ Flask-Cors = ">=3.0.8"
ldap3 = "==2.9.1" ldap3 = "==2.9.1"
pycryptodome = "==3.12.0" pycryptodome = "==3.12.0"
cryptography = ">=41.0.2" cryptography = ">=41.0.2"
# i18n
flask-babel = "==4.0.0"
# Caching # Caching
Flask-Caching = ">=1.0.0" Flask-Caching = ">=1.0.0"
# Environment variable parsing # Environment variable parsing

View File

@@ -12,12 +12,14 @@ from pathlib import Path
from flask import Flask from flask import Flask
from flask import jsonify from flask import jsonify
from flask import make_response from flask import make_response
from flask import request
from flask.blueprints import Blueprint from flask.blueprints import Blueprint
from flask.cli import click from flask.cli import click
from flask.json.provider import DefaultJSONProvider from flask.json.provider import DefaultJSONProvider
from flask_babel.speaklater import LazyString
import api.views.entry import api.views.entry
from api.extensions import (bcrypt, cache, celery, cors, db, es, login_manager, migrate, rd) from api.extensions import (bcrypt, babel, cache, celery, cors, db, es, login_manager, migrate, rd)
from api.extensions import inner_secrets from api.extensions import inner_secrets
from api.lib.perm.authentication.cas import CAS from api.lib.perm.authentication.cas import CAS
from api.lib.perm.authentication.oauth2 import OAuth2 from api.lib.perm.authentication.oauth2 import OAuth2
@@ -72,7 +74,7 @@ class ReverseProxy(object):
class MyJSONEncoder(DefaultJSONProvider): class MyJSONEncoder(DefaultJSONProvider):
def default(self, o): def default(self, o):
if isinstance(o, (decimal.Decimal, datetime.date, datetime.time)): if isinstance(o, (decimal.Decimal, datetime.date, datetime.time, LazyString)):
return str(o) return str(o)
if isinstance(o, datetime.datetime): if isinstance(o, datetime.datetime):
@@ -117,7 +119,13 @@ def configure_upload_dir(app):
def register_extensions(app): def register_extensions(app):
"""Register Flask extensions.""" """Register Flask extensions."""
def get_locale():
accept_languages = app.config.get('ACCEPT_LANGUAGES', ['en', 'zh'])
return request.accept_languages.best_match(accept_languages)
bcrypt.init_app(app) bcrypt.init_app(app)
babel.init_app(app, locale_selector=get_locale)
cache.init_app(app) cache.init_app(app)
db.init_app(app) db.init_app(app)
cors.init_app(app) cors.init_app(app)

View File

@@ -35,8 +35,22 @@ def add_user():
""" """
from api.models.acl import App
from api.lib.perm.acl.cache import AppCache
from api.lib.perm.acl.cache import RoleCache
from api.lib.perm.acl.role import RoleCRUD
from api.lib.perm.acl.role import RoleRelationCRUD
username = click.prompt('Enter username', confirmation_prompt=False) username = click.prompt('Enter username', confirmation_prompt=False)
password = click.prompt('Enter password', hide_input=True, confirmation_prompt=True) password = click.prompt('Enter password', hide_input=True, confirmation_prompt=True)
email = click.prompt('Enter email ', confirmation_prompt=False) email = click.prompt('Enter email ', confirmation_prompt=False)
is_admin = click.prompt('Admin (Y/N) ', confirmation_prompt=False, type=bool, default=False)
UserCRUD.add(username=username, password=password, email=email) UserCRUD.add(username=username, password=password, email=email)
if is_admin:
app = AppCache.get('acl') or App.create(name='acl')
acl_admin = RoleCache.get_by_name(app.id, 'acl_admin') or RoleCRUD.add_role('acl_admin', app.id, True)
rid = RoleCache.get_by_name(None, username).id
RoleRelationCRUD.add(acl_admin, acl_admin.id, [rid], app.id)

View File

@@ -1,13 +1,13 @@
# -*- coding:utf-8 -*- # -*- coding:utf-8 -*-
import click
import copy import copy
import datetime import datetime
import json import json
import time
import click
import requests import requests
import time
import uuid
from flask import current_app from flask import current_app
from flask.cli import with_appcontext from flask.cli import with_appcontext
from flask_login import login_user from flask_login import login_user
@@ -114,10 +114,20 @@ def cmdb_init_acl():
_app = AppCache.get('cmdb') or App.create(name='cmdb') _app = AppCache.get('cmdb') or App.create(name='cmdb')
app_id = _app.id app_id = _app.id
current_app.test_request_context().push()
# 1. add resource type # 1. add resource type
for resource_type in ResourceTypeEnum.all(): for resource_type in ResourceTypeEnum.all():
try: try:
ResourceTypeCRUD.add(app_id, resource_type, '', PermEnum.all()) perms = PermEnum.all()
if resource_type in (ResourceTypeEnum.CI_FILTER, ResourceTypeEnum.PAGE):
perms = [PermEnum.READ]
elif resource_type == ResourceTypeEnum.CI_TYPE_RELATION:
perms = [PermEnum.ADD, PermEnum.DELETE, PermEnum.GRANT]
elif resource_type == ResourceTypeEnum.RELATION_VIEW:
perms = [PermEnum.READ, PermEnum.UPDATE, PermEnum.DELETE, PermEnum.GRANT]
ResourceTypeCRUD.add(app_id, resource_type, '', perms)
except AbortException: except AbortException:
pass pass
@@ -168,12 +178,25 @@ def cmdb_counter():
from api.lib.cmdb.cache import CMDBCounterCache from api.lib.cmdb.cache import CMDBCounterCache
current_app.test_request_context().push() current_app.test_request_context().push()
if not UserCache.get('worker'):
from api.lib.perm.acl.user import UserCRUD
UserCRUD.add(username='worker', password=uuid.uuid4().hex, email='worker@xxx.com')
login_user(UserCache.get('worker')) login_user(UserCache.get('worker'))
i = 0
while True: while True:
try: try:
db.session.remove() db.session.remove()
CMDBCounterCache.reset() CMDBCounterCache.reset()
if i % 5 == 0:
CMDBCounterCache.flush_adc_counter()
i = 0
i += 1
except: except:
import traceback import traceback
print(traceback.format_exc()) print(traceback.format_exc())

View File

@@ -5,9 +5,7 @@ from glob import glob
from subprocess import call from subprocess import call
import click import click
from flask import current_app
from flask.cli import with_appcontext from flask.cli import with_appcontext
from werkzeug.exceptions import MethodNotAllowed, NotFound
from api.extensions import db from api.extensions import db
@@ -90,3 +88,50 @@ def db_setup():
"""create tables """create tables
""" """
db.create_all() db.create_all()
db.session.execute("set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,"
"ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'")
db.session.commit()
try:
db.session.execute("set global tidb_enable_noop_functions='ON'")
db.session.commit()
except:
pass
@click.group()
def translate():
"""Translation and localization commands."""
@translate.command()
@click.argument('lang')
def init(lang):
"""Initialize a new language."""
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('extract command failed')
if os.system(
'pybabel init -i messages.pot -d api/translations -l ' + lang):
raise RuntimeError('init command failed')
os.remove('messages.pot')
@translate.command()
def update():
"""Update all languages."""
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('extract command failed')
if os.system('pybabel update -i messages.pot -d api/translations'):
raise RuntimeError('update command failed')
os.remove('messages.pot')
@translate.command()
def compile():
"""Compile all languages."""
if os.system('pybabel compile -d api/translations'):
raise RuntimeError('compile command failed')

View File

@@ -2,6 +2,7 @@
from celery import Celery from celery import Celery
from flask_babel import Babel
from flask_bcrypt import Bcrypt from flask_bcrypt import Bcrypt
from flask_caching import Cache from flask_caching import Cache
from flask_cors import CORS from flask_cors import CORS
@@ -14,6 +15,7 @@ from api.lib.utils import ESHandler
from api.lib.utils import RedisHandler from api.lib.utils import RedisHandler
bcrypt = Bcrypt() bcrypt = Bcrypt()
babel = Babel()
login_manager = LoginManager() login_manager = LoginManager()
db = SQLAlchemy(session_options={"autoflush": False}) db = SQLAlchemy(session_options={"autoflush": False})
migrate = Migrate() migrate = Migrate()

View File

@@ -189,7 +189,8 @@ class AttributeManager(object):
return attr return attr
def get_attribute(self, key, choice_web_hook_parse=True, choice_other_parse=True): def get_attribute(self, key, choice_web_hook_parse=True, choice_other_parse=True):
attr = AttributeCache.get(key).to_dict() attr = AttributeCache.get(key) or dict()
attr = attr and attr.to_dict()
if attr.get("is_choice"): if attr.get("is_choice"):
attr["choice_value"] = self.get_choice_values( attr["choice_value"] = self.get_choice_values(
attr["id"], attr["id"],

File diff suppressed because it is too large Load Diff

View File

@@ -1,427 +1,344 @@
[ [
{ {
"name": "amiLaunchIndex", "name": "amiLaunchIndex",
"type": "整数", "type": "Integer",
"desc": "The AMI launch index, which can be used to find this instance in the launch group.", "desc": "The AMI launch index, which can be used to find this instance in the launch group.",
"example": "0" "example": ""
}, },
{ {
"name": "architecture", "name": "architecture",
"type": "文本", "type": "String",
"desc": "The architecture of the image.", "desc": "The architecture of the image.",
"example": "x86_64" "example": "i386"
}, },
{ {
"name": "blockDeviceMapping", "name": "blockDeviceMapping",
"type": "json", "type": "Array of InstanceBlockDeviceMapping objects",
"desc": "Any block device mapping entries for the instance.", "desc": "Any block device mapping entries for the instance.",
"example": { "example": ""
"item": { },
"deviceName": "/dev/xvda", {
"ebs": { "name": "bootMode",
"volumeId": "vol-1234567890abcdef0", "type": "String",
"status": "attached", "desc": "The boot mode that was specified by the AMI. If the value is uefi-preferred, the AMI supports both UEFI and Legacy BIOS. The currentInstanceBootMode parameter is the boot mode that is used to boot the instance at launch or start. For more information, see Boot modes in the Amazon EC2 User Guide.",
"attachTime": "2015-12-22T10:44:09.000Z", "example": "legacy-bios"
"deleteOnTermination": "true" },
} {
} "name": "capacityReservationId",
} "type": "String",
}, "desc": "The ID of the Capacity Reservation.",
{ "example": ""
"name": "bootMode", },
"type": "文本", {
"desc": "The boot mode that was specified by the AMI. If the value is uefi-preferred, the AMI supports both UEFI and Legacy BIOS. The currentInstanceBootMode parameter is the boot mode that is used to boot the instance at launch or start.", "name": "capacityReservationSpecification",
"example": null "type": "CapacityReservationSpecificationResponse object",
}, "desc": "Information about the Capacity Reservation targeting option.",
{ "example": ""
"name": "capacityReservationId", },
"type": "文本", {
"desc": "The ID of the Capacity Reservation.", "name": "clientToken",
"example": null "type": "String",
}, "desc": "The idempotency token you provided when you launched the instance, if applicable.",
{ "example": ""
"name": "capacityReservationSpecification", },
"type": "json", {
"desc": "Information about the Capacity Reservation targeting option.", "name": "cpuOptions",
"example": null "type": "CpuOptions object",
}, "desc": "The CPU options for the instance.",
{ "example": ""
"name": "clientToken", },
"type": "文本", {
"desc": "The idempotency token you provided when you launched the instance, if applicable.", "name": "currentInstanceBootMode",
"example": "xMcwG14507example" "type": "String",
}, "desc": "The boot mode that is used to boot the instance at launch or start. For more information, see Boot modes in the Amazon EC2 User Guide.",
{ "example": "legacy-bios"
"name": "cpuOptions", },
"type": "json", {
"desc": "The CPU options for the instance.", "name": "dnsName",
"example": { "type": "String",
"coreCount": "1", "desc": "[IPv4 only] The public DNS name assigned to the instance. This name is not available until the instance enters the running state. This name is only available if you've enabled DNS hostnames for your VPC.",
"threadsPerCore": "1" "example": ""
} },
}, {
{ "name": "ebsOptimized",
"name": "currentInstanceBootMode", "type": "Boolean",
"type": "文本", "desc": "Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance.",
"desc": "The boot mode that is used to boot the instance at launch or start. For more information, see Boot modes in the Amazon EC2 User Guide.", "example": ""
"example": null },
}, {
{ "name": "elasticGpuAssociationSet",
"name": "dnsName", "type": "Array of ElasticGpuAssociation objects",
"type": "文本", "desc": "The Elastic GPU associated with the instance.",
"desc": "[IPv4 only] The public DNS name assigned to the instance. This name is not available until the instance enters the running state. This name is only available if you've enabled DNS hostnames for your VPC.", "example": ""
"example": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com" },
}, {
{ "name": "elasticInferenceAcceleratorAssociationSet",
"name": "ebsOptimized", "type": "Array of ElasticInferenceAcceleratorAssociation objects",
"type": "Boolean", "desc": "The elastic inference accelerator associated with the instance.",
"desc": "Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance.", "example": ""
"example": "false" },
}, {
{ "name": "enaSupport",
"name": "elasticGpuAssociationSet", "type": "Boolean",
"type": "json", "desc": "Specifies whether enhanced networking with ENA is enabled.",
"desc": "The Elastic GPU associated with the instance.", "example": ""
"example": null },
}, {
{ "name": "enclaveOptions",
"name": "elasticInferenceAcceleratorAssociationSet", "type": "EnclaveOptions object",
"type": "json", "desc": "Indicates whether the instance is enabled for AWS Nitro Enclaves.",
"desc": "The elastic inference accelerator associated with the instance.", "example": ""
"example": null },
}, {
{ "name": "groupSet",
"name": "enaSupport", "type": "Array of GroupIdentifier objects",
"type": "Boolean", "desc": "The security groups for the instance.",
"desc": "Specifies whether enhanced networking with ENA is enabled.", "example": ""
"example": null },
}, {
{ "name": "hibernationOptions",
"name": "enclaveOptions", "type": "HibernationOptions object",
"type": "json", "desc": "Indicates whether the instance is enabled for hibernation.",
"desc": "Indicates whether the instance is enabled for AWS Nitro Enclaves.", "example": ""
"example": null },
}, {
{ "name": "hypervisor",
"name": "groupSet", "type": "String",
"type": "json", "desc": "The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors.",
"desc": "The security groups for the instance.", "example": "ovm"
"example": { },
"item": { {
"groupId": "sg-e4076980", "name": "iamInstanceProfile",
"groupName": "SecurityGroup1" "type": "IamInstanceProfile object",
} "desc": "The IAM instance profile associated with the instance, if applicable.",
} "example": ""
}, },
{ {
"name": "hibernationOptions", "name": "imageId",
"type": "json", "type": "String",
"desc": "Indicates whether the instance is enabled for hibernation.", "desc": "The ID of the AMI used to launch the instance.",
"example": null "example": ""
}, },
{ {
"name": "hypervisor", "name": "instanceId",
"type": "文本", "type": "String",
"desc": "The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors.", "desc": "The ID of the instance.",
"example": "xen" "example": ""
}, },
{ {
"name": "iamInstanceProfile", "name": "instanceLifecycle",
"type": "json", "type": "String",
"desc": "The IAM instance profile associated with the instance, if applicable.", "desc": "Indicates whether this is a Spot Instance or a Scheduled Instance.",
"example": { "example": "spot"
"arn": "arn:aws:iam::123456789012:instance-profile/AdminRole", },
"id": "ABCAJEDNCAA64SSD123AB" {
} "name": "instanceState",
}, "type": "InstanceState object",
{ "desc": "The current state of the instance.",
"name": "imageId", "example": ""
"type": "文本", },
"desc": "The ID of the AMI used to launch the instance.", {
"example": "ami-bff32ccc" "name": "instanceType",
}, "type": "String",
{ "desc": "The instance type.",
"name": "instanceId", "example": "a1.medium"
"type": "文本", },
"desc": "The ID of the instance.", {
"example": "i-1234567890abcdef0" "name": "ipAddress",
}, "type": "String",
{ "desc": "The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable. A Carrier IP address only applies to an instance launched in a subnet associated with a Wavelength Zone.",
"name": "instanceLifecycle", "example": "Required: No"
"type": "文本", },
"desc": "Indicates whether this is a Spot Instance or a Scheduled Instance.", {
"example": null "name": "ipv6Address",
}, "type": "String",
{ "desc": "The IPv6 address assigned to the instance.",
"name": "instanceState", "example": ""
"type": "json", },
"desc": "The current state of the instance.", {
"example": { "name": "kernelId",
"code": "16", "type": "String",
"name": "running" "desc": "The kernel associated with this instance, if applicable.",
} "example": ""
}, },
{ {
"name": "instanceType", "name": "keyName",
"type": "文本", "type": "String",
"desc": "The instance type.", "desc": "The name of the key pair, if this instance was launched with an associated key pair.",
"example": "t2.micro" "example": ""
}, },
{ {
"name": "ipAddress", "name": "launchTime",
"type": "文本", "type": "Timestamp",
"desc": "The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable.", "desc": "The time the instance was launched.",
"example": "54.194.252.215" "example": ""
}, },
{ {
"name": "ipv6Address", "name": "licenseSet",
"type": "文本", "type": "Array of LicenseConfiguration objects",
"desc": "The IPv6 address assigned to the instance.", "desc": "The license configurations for the instance.",
"example": null "example": ""
}, },
{ {
"name": "kernelId", "name": "maintenanceOptions",
"type": "文本", "type": "InstanceMaintenanceOptions object",
"desc": "The kernel associated with this instance, if applicable.", "desc": "Provides information on the recovery and maintenance options of your instance.",
"example": null "example": ""
}, },
{ {
"name": "keyName", "name": "metadataOptions",
"type": "文本", "type": "InstanceMetadataOptionsResponse object",
"desc": "The name of the key pair, if this instance was launched with an associated key pair.", "desc": "The metadata options for the instance.",
"example": "my_keypair" "example": ""
}, },
{ {
"name": "launchTime", "name": "monitoring",
"type": "Time", "type": "Monitoring object",
"desc": "The time the instance was launched.", "desc": "The monitoring for the instance.",
"example": "2018-05-08T16:46:19.000Z" "example": ""
}, },
{ {
"name": "licenseSet", "name": "networkInterfaceSet",
"type": "json", "type": "Array of InstanceNetworkInterface objects",
"desc": "The license configurations for the instance.", "desc": "The network interfaces for the instance.",
"example": null "example": ""
}, },
{ {
"name": "maintenanceOptions", "name": "outpostArn",
"type": "json", "type": "String",
"desc": "Provides information on the recovery and maintenance options of your instance.", "desc": "The Amazon Resource Name (ARN) of the Outpost.",
"example": null "example": ""
}, },
{ {
"name": "metadataOptions", "name": "placement",
"type": "json", "type": "Placement object",
"desc": "The metadata options for the instance.", "desc": "The location where the instance launched, if applicable.",
"example": null "example": ""
}, },
{ {
"name": "monitoring", "name": "platform",
"type": "json", "type": "String",
"desc": "The monitoring for the instance.", "desc": "The platform. This value is windows for Windows instances; otherwise, it is empty.",
"example": { "example": "windows"
"state": "disabled" },
} {
}, "name": "platformDetails",
{ "type": "String",
"name": "networkInterfaceSet", "desc": "The platform details value for the instance. For more information, see AMI billing information fields in the Amazon EC2 User Guide.",
"type": "json", "example": ""
"desc": "The network interfaces for the instance.", },
"example": { {
"item": { "name": "privateDnsName",
"networkInterfaceId": "eni-551ba033", "type": "String",
"subnetId": "subnet-56f5f633", "desc": "[IPv4 only] The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state. The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames if you've enabled DNS resolution and DNS hostnames in your VPC. If you are not using the Amazon-provided DNS server in your VPC, your custom domain name servers must resolve the hostname as appropriate.",
"vpcId": "vpc-11112222", "example": "Required: No"
"description": "Primary network interface", },
"ownerId": "123456789012", {
"status": "in-use", "name": "privateDnsNameOptions",
"macAddress": "02:dd:2c:5e:01:69", "type": "PrivateDnsNameOptionsResponse object",
"privateIpAddress": "192.168.1.88", "desc": "The options for the instance hostname.",
"privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal", "example": ""
"sourceDestCheck": "true", },
"groupSet": { {
"item": { "name": "privateIpAddress",
"groupId": "sg-e4076980", "type": "String",
"groupName": "SecurityGroup1" "desc": "The private IPv4 address assigned to the instance.",
} "example": ""
}, },
"attachment": { {
"attachmentId": "eni-attach-39697adc", "name": "productCodes",
"deviceIndex": "0", "type": "Array of ProductCode objects",
"status": "attached", "desc": "The product codes attached to this instance, if applicable.",
"attachTime": "2018-05-08T16:46:19.000Z", "example": ""
"deleteOnTermination": "true" },
}, {
"association": { "name": "ramdiskId",
"publicIp": "54.194.252.215", "type": "String",
"publicDnsName": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com", "desc": "The RAM disk associated with this instance, if applicable.",
"ipOwnerId": "amazon" "example": ""
}, },
"privateIpAddressesSet": { {
"item": { "name": "reason",
"privateIpAddress": "192.168.1.88", "type": "String",
"privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal", "desc": "The reason for the most recent state transition. This might be an empty string.",
"primary": "true", "example": ""
"association": { },
"publicIp": "54.194.252.215", {
"publicDnsName": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com", "name": "rootDeviceName",
"ipOwnerId": "amazon" "type": "String",
} "desc": "The device name of the root device volume (for example, /dev/sda1).",
} "example": ""
}, },
"ipv6AddressesSet": { {
"item": { "name": "rootDeviceType",
"ipv6Address": "2001:db8:1234:1a2b::123" "type": "String",
} "desc": "The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume.",
} "example": "ebs"
} },
} {
}, "name": "sourceDestCheck",
{ "type": "Boolean",
"name": "outpostArn", "desc": "Indicates whether source/destination checking is enabled.",
"type": "文本", "example": ""
"desc": "The Amazon Resource Name (ARN) of the Outpost.", },
"example": null {
}, "name": "spotInstanceRequestId",
{ "type": "String",
"name": "placement", "desc": "If the request is a Spot Instance request, the ID of the request.",
"type": "json", "example": ""
"desc": "The location where the instance launched, if applicable.", },
"example": { {
"availabilityZone": "eu-west-1c", "name": "sriovNetSupport",
"groupName": null, "type": "String",
"tenancy": "default" "desc": "Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.",
} "example": ""
}, },
{ {
"name": "platform", "name": "stateReason",
"type": "文本", "type": "StateReason object",
"desc": "The value is Windows for Windows instances; otherwise blank.", "desc": "The reason for the most recent state transition.",
"example": null "example": ""
}, },
{ {
"name": "platformDetails", "name": "subnetId",
"type": "文本", "type": "String",
"desc": "The platform details value for the instance. For more information, see AMI billing information fields in the Amazon EC2 User Guide.", "desc": "The ID of the subnet in which the instance is running.",
"example": null "example": ""
}, },
{ {
"name": "privateDnsName", "name": "tagSet",
"type": "文本", "type": "Array of Tag objects",
"desc": "[IPv4 only] The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state.", "desc": "Any tags assigned to the instance.",
"example": "ip-192-168-1-88.eu-west-1.compute.internal" "example": ""
}, },
{ {
"name": "privateDnsNameOptions", "name": "tpmSupport",
"type": "json", "type": "String",
"desc": "The options for the instance hostname.", "desc": "If the instance is configured for NitroTPM support, the value is v2.0. For more information, see NitroTPM in the Amazon EC2 User Guide.",
"example": null "example": ""
}, },
{ {
"name": "privateIpAddress", "name": "usageOperation",
"type": "文本", "type": "String",
"desc": "The private IPv4 address assigned to the instance.", "desc": "The usage operation value for the instance. For more information, see AMI billing information fields in the Amazon EC2 User Guide.",
"example": "192.168.1.88" "example": ""
}, },
{ {
"name": "productCodes", "name": "usageOperationUpdateTime",
"type": "json", "type": "Timestamp",
"desc": "The product codes attached to this instance, if applicable.", "desc": "The time that the usage operation was last updated.",
"example": null "example": ""
}, },
{ {
"name": "ramdiskId", "name": "virtualizationType",
"type": "文本", "type": "String",
"desc": "The RAM disk associated with this instance, if applicable.", "desc": "The virtualization type of the instance.",
"example": null "example": "hvm"
}, },
{ {
"name": "reason", "name": "vpcId",
"type": "文本", "type": "String",
"desc": "The reason for the most recent state transition. This might be an empty string.", "desc": "The ID of the VPC in which the instance is running.",
"example": null "example": ""
}, }
{
"name": "rootDeviceName",
"type": "文本",
"desc": "The device name of the root device volume (for example, /dev/sda1).",
"example": "/dev/xvda"
},
{
"name": "rootDeviceType",
"type": "文本",
"desc": "The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume.",
"example": "ebs"
},
{
"name": "sourceDestCheck",
"type": "Boolean",
"desc": "Indicates whether source/destination checking is enabled.",
"example": "true"
},
{
"name": "spotInstanceRequestId",
"type": "文本",
"desc": "If the request is a Spot Instance request, the ID of the request.",
"example": null
},
{
"name": "sriovNetSupport",
"type": "文本",
"desc": "Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.",
"example": null
},
{
"name": "stateReason",
"type": "json",
"desc": "The reason for the most recent state transition.",
"example": null
},
{
"name": "subnetId",
"type": "文本",
"desc": "The ID of the subnet in which the instance is running.",
"example": "subnet-56f5f633"
},
{
"name": "tagSet",
"type": "json",
"desc": "Any tags assigned to the instance.",
"example": {
"item": {
"key": "Name",
"value": "Server_1"
}
}
},
{
"name": "tpmSupport",
"type": "文本",
"desc": "If the instance is configured for NitroTPM support, the value is v2.0. For more information, see NitroTPM in the Amazon EC2 User Guide.",
"example": null
},
{
"name": "usageOperation",
"type": "文本",
"desc": "The usage operation value for the instance. For more information, see AMI billing information fields in the Amazon EC2 User Guide.",
"example": null
},
{
"name": "usageOperationUpdateTime",
"type": "Time",
"desc": "The time that the usage operation was last updated.",
"example": null
},
{
"name": "virtualizationType",
"type": "文本",
"desc": "The virtualization type of the instance.",
"example": "hvm"
},
{
"name": "vpcId",
"type": "文本",
"desc": "The ID of the VPC in which the instance is running.",
"example": "vpc-11112222"
}
] ]

View File

@@ -1,292 +1,284 @@
[ [
{ {
"name": "status", "name": "status",
"type": "文本", "type": "string",
"example": "ACTIVE", "desc": "弹性云服务器状态。\n\n取值范围:\n\nACTIVE、BUILD、DELETED、ERROR、HARD_REBOOT、MIGRATING、PAUSED、REBOOT、REBUILD、RESIZE、REVERT_RESIZE、SHUTOFF、SHELVED、SHELVED_OFFLOADED、SOFT_DELETED、SUSPENDED、VERIFY_RESIZE\n\n弹性云服务器状态说明请参考[云服务器状态](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u72b6\u6001\u3002\n\n\u53d6\u503c\u8303\u56f4:\n\nACTIVE\u3001BUILD\u3001DELETED\u3001ERROR\u3001HARD_REBOOT\u3001MIGRATING\u3001PAUSED\u3001REBOOT\u3001REBUILD\u3001RESIZE\u3001REVERT_RESIZE\u3001SHUTOFF\u3001SHELVED\u3001SHELVED_OFFLOADED\u3001SOFT_DELETED\u3001SUSPENDED\u3001VERIFY_RESIZE\n\n\u5f39\u6027\u4e91\u670d\u52a1\u5668\u72b6\u6001\u8bf4\u660e\u8bf7\u53c2\u8003[\u4e91\u670d\u52a1\u5668\u72b6\u6001](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)" "example": "ACTIVE"
}, },
{ {
"name": "updated", "name": "updated",
"type": "文本", "type": "string",
"example": "2019-05-22T03:30:52Z", "desc": "弹性云服务器更新时间。\n\n时间格式例如:2019-05-22T03:30:52Z",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u66f4\u65b0\u65f6\u95f4\u3002\n\n\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2019-05-22T03:30:52Z" "example": "2019-05-22T03:30:52Z"
}, },
{ {
"name": "auto_terminate_time", "name": "auto_terminate_time",
"type": "文本", "type": "string",
"example": "2020-01-19T03:30:52Z", "desc": "弹性云服务器定时删除时间。\n\n时间格式例如:2020-01-19T03:30:52Z",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u81ea\u52a8\u91ca\u653e\u65f6\u95f4\u3002\n\n\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2020-01-19T03:30:52Z" "example": "2020-01-19T03:30:52Z"
}, },
{ {
"name": "hostId", "name": "hostId",
"type": "文本", "type": "string",
"example": "c7145889b2e3202cd295ceddb1742ff8941b827b586861fd0acedf64", "desc": "弹性云服务器所在主机的主机ID。",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5728\u4e3b\u673a\u7684\u4e3b\u673aID\u3002" "example": "c7145889b2e3202cd295ceddb1742ff8941b827b586861fd0acedf64"
}, },
{ {
"name": "OS-EXT-SRV-ATTR:host", "name": "OS-EXT-SRV-ATTR:host",
"type": "文本", "type": "string",
"example": "pod01.cn-north-1c", "desc": "弹性云服务器所在主机的主机名称。",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5728\u4e3b\u673a\u7684\u4e3b\u673a\u540d\u79f0\u3002" "example": "pod01.cn-north-1c"
}, },
{ {
"name": "addresses", "name": "addresses",
"type": "json", "type": "object",
"example": null, "desc": "弹性云服务器的网络属性。",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u7f51\u7edc\u5c5e\u6027\u3002" "example": ""
}, },
{ {
"name": "key_name", "name": "key_name",
"type": "文本", "type": "string",
"example": "KeyPair-test", "desc": "弹性云服务器使用的密钥对名称。",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u4f7f\u7528\u7684\u5bc6\u94a5\u5bf9\u540d\u79f0\u3002" "example": "KeyPair-test"
}, },
{ {
"name": "image", "name": "image",
"type": "json", "type": "",
"example": null, "desc": "弹性云服务器镜像信息。",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u955c\u50cf\u4fe1\u606f\u3002" "example": ""
}, },
{ {
"name": "OS-EXT-STS:task_state", "name": "OS-EXT-STS:task_state",
"type": "文本", "type": "string",
"example": "rebooting", "desc": "扩展属性,弹性云服务器当前任务的状态。\n\n取值范围请参考[云服务器状态](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)表3。",
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u5f53\u524d\u4efb\u52a1\u7684\u72b6\u6001\u3002\n\n\u53d6\u503c\u8303\u56f4\u8bf7\u53c2\u8003[\u4e91\u670d\u52a1\u5668\u72b6\u6001](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)\u88683\u3002" "example": "rebooting"
}, },
{ {
"name": "OS-EXT-STS:vm_state", "name": "OS-EXT-STS:vm_state",
"type": "文本", "type": "string",
"example": "active", "desc": "扩展属性,弹性云服务器当前状态。\n\n云服务器状态说明请参考[云服务器状态](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)。",
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u5f53\u524d\u72b6\u6001\u3002\n\n\u4e91\u670d\u52a1\u5668\u72b6\u6001\u8bf4\u660e\u8bf7\u53c2\u8003[\u4e91\u670d\u52a1\u5668\u72b6\u6001](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)\u3002" "example": "active"
}, },
{ {
"name": "OS-EXT-SRV-ATTR:instance_name", "name": "OS-EXT-SRV-ATTR:instance_name",
"type": "文本", "type": "string",
"example": "instance-0048a91b", "desc": "扩展属性,弹性云服务器别名。",
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u522b\u540d\u3002" "example": "instance-0048a91b"
}, },
{ {
"name": "OS-EXT-SRV-ATTR:hypervisor_hostname", "name": "OS-EXT-SRV-ATTR:hypervisor_hostname",
"type": "文本", "type": "string",
"example": "nova022@36", "desc": "扩展属性,弹性云服务器所在虚拟化主机名。",
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5728\u865a\u62df\u5316\u4e3b\u673a\u540d\u3002" "example": "nova022@36"
}, },
{ {
"name": "flavor", "name": "flavor",
"type": "json", "type": "",
"example": null, "desc": "弹性云服务器规格信息。",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u89c4\u683c\u4fe1\u606f\u3002" "example": ""
}, },
{ {
"name": "id", "name": "id",
"type": "文本", "type": "string",
"example": "4f4b3dfa-eb70-47cf-a60a-998a53bd6666", "desc": "弹性云服务器ID,格式为UUID。",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668ID,\u683c\u5f0f\u4e3aUUID\u3002" "example": "4f4b3dfa-eb70-47cf-a60a-998a53bd6666"
}, },
{ {
"name": "security_groups", "name": "security_groups",
"type": "json", "type": "array",
"example": { "desc": "弹性云服务器所属安全组列表。",
"$ref": "#/definitions/ServerSecurityGroup" "example": ""
}, },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5c5e\u5b89\u5168\u7ec4\u5217\u8868\u3002" {
}, "name": "OS-EXT-AZ:availability_zone",
{ "type": "string",
"name": "OS-EXT-AZ:availability_zone", "desc": "扩展属性,弹性云服务器所在可用区名称。",
"type": "文本", "example": "cn-north-1c"
"example": "cn-north-1c", },
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5728\u53ef\u7528\u533a\u540d\u79f0\u3002" {
}, "name": "user_id",
{ "type": "string",
"name": "user_id", "desc": "创建弹性云服务器的用户ID,格式为UUID。",
"type": "文本", "example": "05498fe56b8010d41f7fc01e280b6666"
"example": "05498fe56b8010d41f7fc01e280b6666", },
"desc": "\u521b\u5efa\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u7528\u6237ID,\u683c\u5f0f\u4e3aUUID\u3002" {
}, "name": "name",
{ "type": "string",
"name": "name", "desc": "弹性云服务器名称。",
"type": "文本", "example": "ecs-test-server"
"example": "ecs-test-server", },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u540d\u79f0\u3002" {
}, "name": "created",
{ "type": "string",
"name": "created", "desc": "弹性云服务器创建时间。\n\n时间格式例如:2019-05-22T03:19:19Z",
"type": "文本", "example": "2017-07-15T11:30:52Z"
"example": "2017-07-15T11:30:52Z", },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u521b\u5efa\u65f6\u95f4\u3002\n\n\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2019-05-22T03:19:19Z" {
}, "name": "tenant_id",
{ "type": "string",
"name": "tenant_id", "desc": "弹性云服务器所属租户ID,即项目id,和project_id表示相同的概念,格式为UUID。",
"type": "文本", "example": "743b4c0428d94531b9f2add666646666"
"example": "743b4c0428d94531b9f2add666646666", },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5c5e\u79df\u6237ID,\u5373\u9879\u76eeid,\u548cproject_id\u8868\u793a\u76f8\u540c\u7684\u6982\u5ff5,\u683c\u5f0f\u4e3aUUID\u3002" {
}, "name": "OS-DCF:diskConfig",
{ "type": "string",
"name": "OS-DCF:diskConfig", "desc": "扩展属性, diskConfig的类型。\n\n- MANUAL,镜像空间不会扩展。\n- AUTO,系统盘镜像空间会自动扩展为与flavor大小一致。",
"type": "文本", "example": "AUTO"
"example": "AUTO", },
"desc": "\u6269\u5c55\u5c5e\u6027, diskConfig\u7684\u7c7b\u578b\u3002\n\n- MANUAL,\u955c\u50cf\u7a7a\u95f4\u4e0d\u4f1a\u6269\u5c55\u3002\n- AUTO,\u7cfb\u7edf\u76d8\u955c\u50cf\u7a7a\u95f4\u4f1a\u81ea\u52a8\u6269\u5c55\u4e3a\u4e0eflavor\u5927\u5c0f\u4e00\u81f4\u3002" {
}, "name": "accessIPv4",
{ "type": "string",
"name": "accessIPv4", "desc": "预留属性。",
"type": "文本", "example": ""
"example": null, },
"desc": "\u9884\u7559\u5c5e\u6027\u3002" {
}, "name": "accessIPv6",
{ "type": "string",
"name": "accessIPv6", "desc": "预留属性。",
"type": "文本", "example": ""
"example": null, },
"desc": "\u9884\u7559\u5c5e\u6027\u3002" {
}, "name": "fault",
{ "type": "",
"name": "fault", "desc": "弹性云服务器故障信息。\n\n可选参数,在弹性云服务器状态为ERROR且存在异常的情况下返回。",
"type": "文本", "example": ""
"example": null, },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6545\u969c\u4fe1\u606f\u3002\n\n\u53ef\u9009\u53c2\u6570,\u5728\u5f39\u6027\u4e91\u670d\u52a1\u5668\u72b6\u6001\u4e3aERROR\u4e14\u5b58\u5728\u5f02\u5e38\u7684\u60c5\u51b5\u4e0b\u8fd4\u56de\u3002" {
}, "name": "progress",
{ "type": "integer",
"name": "progress", "desc": "弹性云服务器进度。",
"type": "整数", "example": 0
"example": null, },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u8fdb\u5ea6\u3002" {
}, "name": "OS-EXT-STS:power_state",
{ "type": "integer",
"name": "OS-EXT-STS:power_state", "desc": "扩展属性,弹性云服务器电源状态。",
"type": "整数", "example": 4
"example": 4, },
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7535\u6e90\u72b6\u6001\u3002" {
}, "name": "config_drive",
{ "type": "string",
"name": "config_drive", "desc": "config drive信息。",
"type": "文本", "example": ""
"example": null, },
"desc": "config drive\u4fe1\u606f\u3002" {
}, "name": "metadata",
{ "type": "object",
"name": "metadata", "desc": "弹性云服务器元数据。\n\n> 说明:\n> \n> 元数据包含系统默认添加字段和用户设置的字段。\n\n系统默认添加字段\n\n1. charging_mode\n云服务器的计费类型。\n\n- “0”:按需计费(即postPaid-后付费方式)。\n- “1”:按包年包月计费(即prePaid-预付费方式)。\"2\":竞价实例计费\n\n2. metering.order_id\n按“包年/包月”计费的云服务器对应的订单ID。\n\n3. metering.product_id\n按“包年/包月”计费的云服务器对应的产品ID。\n\n4. vpc_id\n云服务器所属的虚拟私有云ID。\n\n5. EcmResStatus\n云服务器的冻结状态。\n\n- normal:云服务器正常状态(未被冻结)。\n- freeze:云服务器被冻结。\n\n> 当云服务器被冻结或者解冻后,系统默认添加该字段,且该字段必选。\n\n6. metering.image_id\n云服务器操作系统对应的镜像ID\n\n7. metering.imagetype\n镜像类型,目前支持:\n\n- 公共镜像(gold)\n- 私有镜像(private)\n- 共享镜像(shared)\n\n8. metering.resourcespeccode\n云服务器对应的资源规格。\n\n9. image_name\n云服务器操作系统对应的镜像名称。\n\n10. os_bit\n操作系统位数,一般取值为“32”或者“64”。\n\n11. lockCheckEndpoint\n回调URL,用于检查弹性云服务器的加锁是否有效。\n\n- 如果有效,则云服务器保持锁定状态。\n- 如果无效,解除锁定状态,删除失效的锁。\n\n12. lockSource\n弹性云服务器来自哪个服务。订单加锁(ORDER)\n\n13. lockSourceId\n弹性云服务器的加锁来自哪个ID。lockSource为“ORDER”时,lockSourceId为订单ID。\n\n14. lockScene\n弹性云服务器的加锁类型。\n\n- 按需转包周期(TO_PERIOD_LOCK)\n\n15. virtual_env_type\n\n- IOS镜像创建虚拟机,\"virtual_env_type\": \"IsoImage\" 属性;\n- 非IOS镜像创建虚拟机,在19.5.0版本以后创建的虚拟机将不会添加virtual_env_type 属性,而在此之前的版本创建的虚拟机可能会返回\"virtual_env_type\": \"FusionCompute\"属性 。\n\n> virtual_env_type属性不允许用户增加、删除和修改。\n\n16. metering.resourcetype\n云服务器对应的资源类型。\n\n17. os_type\n操作系统类型,取值为:Linux、Windows。\n\n18. cascaded.instance_extrainfo\n系统内部虚拟机扩展信息。\n\n19. __support_agent_list\n云服务器是否支持企业主机安全、主机监控。\n\n- “hss”:企业主机安全\n- “ces”:主机监控\n\n20. agency_name\n委托的名称。\n\n委托是由租户管理员在统一身份认证服务(Identity and Access Management,IAM)上创建的,可以为弹性云服务器提供访问云服务的临时凭证。",
"type": "json", "example": ""
"example": null, },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u5143\u6570\u636e\u3002\n\n> \u8bf4\u660e:\n> \n> \u5143\u6570\u636e\u5305\u542b\u7cfb\u7edf\u9ed8\u8ba4\u6dfb\u52a0\u5b57\u6bb5\u548c\u7528\u6237\u8bbe\u7f6e\u7684\u5b57\u6bb5\u3002\n\n\u7cfb\u7edf\u9ed8\u8ba4\u6dfb\u52a0\u5b57\u6bb5\n\n1. charging_mode\n\u4e91\u670d\u52a1\u5668\u7684\u8ba1\u8d39\u7c7b\u578b\u3002\n\n- \u201c0\u201d:\u6309\u9700\u8ba1\u8d39(\u5373postPaid-\u540e\u4ed8\u8d39\u65b9\u5f0f)\u3002\n- \u201c1\u201d:\u6309\u5305\u5e74\u5305\u6708\u8ba1\u8d39(\u5373prePaid-\u9884\u4ed8\u8d39\u65b9\u5f0f)\u3002\"2\":\u7ade\u4ef7\u5b9e\u4f8b\u8ba1\u8d39\n\n2. metering.order_id\n\u6309\u201c\u5305\u5e74/\u5305\u6708\u201d\u8ba1\u8d39\u7684\u4e91\u670d\u52a1\u5668\u5bf9\u5e94\u7684\u8ba2\u5355ID\u3002\n\n3. metering.product_id\n\u6309\u201c\u5305\u5e74/\u5305\u6708\u201d\u8ba1\u8d39\u7684\u4e91\u670d\u52a1\u5668\u5bf9\u5e94\u7684\u4ea7\u54c1ID\u3002\n\n4. vpc_id\n\u4e91\u670d\u52a1\u5668\u6240\u5c5e\u7684\u865a\u62df\u79c1\u6709\u4e91ID\u3002\n\n5. EcmResStatus\n\u4e91\u670d\u52a1\u5668\u7684\u51bb\u7ed3\u72b6\u6001\u3002\n\n- normal:\u4e91\u670d\u52a1\u5668\u6b63\u5e38\u72b6\u6001(\u672a\u88ab\u51bb\u7ed3)\u3002\n- freeze:\u4e91\u670d\u52a1\u5668\u88ab\u51bb\u7ed3\u3002\n\n> \u5f53\u4e91\u670d\u52a1\u5668\u88ab\u51bb\u7ed3\u6216\u8005\u89e3\u51bb\u540e,\u7cfb\u7edf\u9ed8\u8ba4\u6dfb\u52a0\u8be5\u5b57\u6bb5,\u4e14\u8be5\u5b57\u6bb5\u5fc5\u9009\u3002\n\n6. metering.image_id\n\u4e91\u670d\u52a1\u5668\u64cd\u4f5c\u7cfb\u7edf\u5bf9\u5e94\u7684\u955c\u50cfID\n\n7. metering.imagetype\n\u955c\u50cf\u7c7b\u578b,\u76ee\u524d\u652f\u6301:\n\n- \u516c\u5171\u955c\u50cf(gold)\n- \u79c1\u6709\u955c\u50cf(private)\n- \u5171\u4eab\u955c\u50cf(shared)\n\n8. metering.resourcespeccode\n\u4e91\u670d\u52a1\u5668\u5bf9\u5e94\u7684\u8d44\u6e90\u89c4\u683c\u3002\n\n9. image_name\n\u4e91\u670d\u52a1\u5668\u64cd\u4f5c\u7cfb\u7edf\u5bf9\u5e94\u7684\u955c\u50cf\u540d\u79f0\u3002\n\n10. os_bit\n\u64cd\u4f5c\u7cfb\u7edf\u4f4d\u6570,\u4e00\u822c\u53d6\u503c\u4e3a\u201c32\u201d\u6216\u8005\u201c64\u201d\u3002\n\n11. lockCheckEndpoint\n\u56de\u8c03URL,\u7528\u4e8e\u68c0\u67e5\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u52a0\u9501\u662f\u5426\u6709\u6548\u3002\n\n- \u5982\u679c\u6709\u6548,\u5219\u4e91\u670d\u52a1\u5668\u4fdd\u6301\u9501\u5b9a\u72b6\u6001\u3002\n- \u5982\u679c\u65e0\u6548,\u89e3\u9664\u9501\u5b9a\u72b6\u6001,\u5220\u9664\u5931\u6548\u7684\u9501\u3002\n\n12. lockSource\n\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6765\u81ea\u54ea\u4e2a\u670d\u52a1\u3002\u8ba2\u5355\u52a0\u9501(ORDER)\n\n13. lockSourceId\n\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u52a0\u9501\u6765\u81ea\u54ea\u4e2aID\u3002lockSource\u4e3a\u201cORDER\u201d\u65f6,lockSourceId\u4e3a\u8ba2\u5355ID\u3002\n\n14. lockScene\n\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u52a0\u9501\u7c7b\u578b\u3002\n\n- \u6309\u9700\u8f6c\u5305\u5468\u671f(TO_PERIOD_LOCK)\n\n15. virtual_env_type\n\n- IOS\u955c\u50cf\u521b\u5efa\u865a\u62df\u673a,\"virtual_env_type\": \"IsoImage\" \u5c5e\u6027;\n- \u975eIOS\u955c\u50cf\u521b\u5efa\u865a\u62df\u673a,\u572819.5.0\u7248\u672c\u4ee5\u540e\u521b\u5efa\u7684\u865a\u62df\u673a\u5c06\u4e0d\u4f1a\u6dfb\u52a0virtual_env_type \u5c5e\u6027,\u800c\u5728\u6b64\u4e4b\u524d\u7684\u7248\u672c\u521b\u5efa\u7684\u865a\u62df\u673a\u53ef\u80fd\u4f1a\u8fd4\u56de\"virtual_env_type\": \"FusionCompute\"\u5c5e\u6027 \u3002\n\n> virtual_env_type\u5c5e\u6027\u4e0d\u5141\u8bb8\u7528\u6237\u589e\u52a0\u3001\u5220\u9664\u548c\u4fee\u6539\u3002\n\n16. metering.resourcetype\n\u4e91\u670d\u52a1\u5668\u5bf9\u5e94\u7684\u8d44\u6e90\u7c7b\u578b\u3002\n\n17. os_type\n\u64cd\u4f5c\u7cfb\u7edf\u7c7b\u578b,\u53d6\u503c\u4e3a:Linux\u3001Windows\u3002\n\n18. cascaded.instance_extrainfo\n\u7cfb\u7edf\u5185\u90e8\u865a\u62df\u673a\u6269\u5c55\u4fe1\u606f\u3002\n\n19. __support_agent_list\n\u4e91\u670d\u52a1\u5668\u662f\u5426\u652f\u6301\u4f01\u4e1a\u4e3b\u673a\u5b89\u5168\u3001\u4e3b\u673a\u76d1\u63a7\u3002\n\n- \u201chss\u201d:\u4f01\u4e1a\u4e3b\u673a\u5b89\u5168\n- \u201cces\u201d:\u4e3b\u673a\u76d1\u63a7\n\n20. agency_name\n\u59d4\u6258\u7684\u540d\u79f0\u3002\n\n\u59d4\u6258\u662f\u7531\u79df\u6237\u7ba1\u7406\u5458\u5728\u7edf\u4e00\u8eab\u4efd\u8ba4\u8bc1\u670d\u52a1(Identity and Access Management,IAM)\u4e0a\u521b\u5efa\u7684,\u53ef\u4ee5\u4e3a\u5f39\u6027\u4e91\u670d\u52a1\u5668\u63d0\u4f9b\u8bbf\u95ee\u4e91\u670d\u52a1\u7684\u4e34\u65f6\u51ed\u8bc1\u3002" {
}, "name": "OS-SRV-USG:launched_at",
{ "type": "string",
"name": "OS-SRV-USG:launched_at", "desc": "弹性云服务器启动时间。时间格式例如:2019-05-22T03:23:59.000000",
"type": "文本", "example": "2018-08-15T14:21:22.000000"
"example": "2018-08-15T14:21:22.000000", },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u542f\u52a8\u65f6\u95f4\u3002\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2019-05-22T03:23:59.000000" {
}, "name": "OS-SRV-USG:terminated_at",
{ "type": "string",
"name": "OS-SRV-USG:terminated_at", "desc": "弹性云服务器删除时间。\n\n时间格式例如:2019-05-22T03:23:59.000000",
"type": "文本", "example": "2019-05-22T03:23:59.000000"
"example": "2019-05-22T03:23:59.000000", },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u5220\u9664\u65f6\u95f4\u3002\n\n\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2019-05-22T03:23:59.000000" {
}, "name": "os-extended-volumes:volumes_attached",
{ "type": "array",
"name": "os-extended-volumes:volumes_attached", "desc": "挂载到弹性云服务器上的磁盘。",
"type": "json", "example": ""
"example": { },
"$ref": "#/definitions/ServerExtendVolumeAttachment" {
}, "name": "description",
"desc": "\u6302\u8f7d\u5230\u5f39\u6027\u4e91\u670d\u52a1\u5668\u4e0a\u7684\u78c1\u76d8\u3002" "type": "string",
}, "desc": "弹性云服务器的描述信息。",
{ "example": "ecs description"
"name": "description", },
"type": "文本", {
"example": "ecs description", "name": "host_status",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u63cf\u8ff0\u4fe1\u606f\u3002" "type": "string",
}, "desc": "nova-compute状态。\n\n- UP:服务正常\n- UNKNOWN:状态未知\n- DOWN:服务异常\n- MAINTENANCE:维护状态\n- 空字符串:弹性云服务器无主机信息",
{ "example": "UP"
"name": "host_status", },
"type": "文本", {
"example": "UP", "name": "OS-EXT-SRV-ATTR:hostname",
"desc": "nova-compute\u72b6\u6001\u3002\n\n- UP:\u670d\u52a1\u6b63\u5e38\n- UNKNOWN:\u72b6\u6001\u672a\u77e5\n- DOWN:\u670d\u52a1\u5f02\u5e38\n- MAINTENANCE:\u7ef4\u62a4\u72b6\u6001\n- \u7a7a\u5b57\u7b26\u4e32:\u5f39\u6027\u4e91\u670d\u52a1\u5668\u65e0\u4e3b\u673a\u4fe1\u606f" "type": "string",
}, "desc": "弹性云服务器的主机名。",
{ "example": ""
"name": "OS-EXT-SRV-ATTR:hostname", },
"type": "文本", {
"example": null, "name": "OS-EXT-SRV-ATTR:reservation_id",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u4e3b\u673a\u540d\u3002" "type": "string",
}, "desc": "批量创建场景,弹性云服务器的预留ID。",
{ "example": "r-f06p3js8"
"name": "OS-EXT-SRV-ATTR:reservation_id", },
"type": "文本", {
"example": "r-f06p3js8", "name": "OS-EXT-SRV-ATTR:launch_index",
"desc": "\u6279\u91cf\u521b\u5efa\u573a\u666f,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u9884\u7559ID\u3002" "type": "integer",
}, "desc": "批量创建场景,弹性云服务器的启动顺序。",
{ "example": 0
"name": "OS-EXT-SRV-ATTR:launch_index", },
"type": "整数", {
"example": null, "name": "OS-EXT-SRV-ATTR:kernel_id",
"desc": "\u6279\u91cf\u521b\u5efa\u573a\u666f,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u542f\u52a8\u987a\u5e8f\u3002" "type": "string",
}, "desc": "若使用AMI格式的镜像,则表示kernel image的UUID;否则,留空。",
{ "example": ""
"name": "OS-EXT-SRV-ATTR:kernel_id", },
"type": "文本", {
"example": null, "name": "OS-EXT-SRV-ATTR:ramdisk_id",
"desc": "\u82e5\u4f7f\u7528AMI\u683c\u5f0f\u7684\u955c\u50cf,\u5219\u8868\u793akernel image\u7684UUID;\u5426\u5219,\u7559\u7a7a\u3002" "type": "string",
}, "desc": "若使用AMI格式镜像,则表示ramdisk image的UUID;否则,留空。",
{ "example": ""
"name": "OS-EXT-SRV-ATTR:ramdisk_id", },
"type": "文本", {
"example": null, "name": "OS-EXT-SRV-ATTR:root_device_name",
"desc": "\u82e5\u4f7f\u7528AMI\u683c\u5f0f\u955c\u50cf,\u5219\u8868\u793aramdisk image\u7684UUID;\u5426\u5219,\u7559\u7a7a\u3002" "type": "string",
}, "desc": "弹性云服务器系统盘的设备名称。",
{ "example": "/dev/vda"
"name": "OS-EXT-SRV-ATTR:root_device_name", },
"type": "文本", {
"example": "/dev/vda", "name": "OS-EXT-SRV-ATTR:user_data",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7cfb\u7edf\u76d8\u7684\u8bbe\u5907\u540d\u79f0\u3002" "type": "string",
}, "desc": "创建弹性云服务器时指定的user_data。",
{ "example": "IyEvYmluL2Jhc2gKZWNobyAncm9vdDokNiRjcGRkSjckWm5WZHNiR253Z0l0SGlxUjZxbWtLTlJaeU9lZUtKd3dPbG9XSFdUeGFzWjA1STYwdnJYRTdTUTZGbEpFbWlXZ21WNGNmZ1pac1laN1BkMTBLRndyeC8nIHwgY2hwYXNzd2Q6666"
"name": "OS-EXT-SRV-ATTR:user_data", },
"type": "文本", {
"example": "IyEvYmluL2Jhc2gKZWNobyAncm9vdDokNiRjcGRkSjckWm5WZHNiR253Z0l0SGlxUjZxbWtLTlJaeU9lZUtKd3dPbG9XSFdUeGFzWjA1STYwdnJYRTdTUTZGbEpFbWlXZ21WNGNmZ1pac1laN1BkMTBLRndyeC8nIHwgY2hwYXNzd2Q6666", "name": "locked",
"desc": "\u521b\u5efa\u5f39\u6027\u4e91\u670d\u52a1\u5668\u65f6\u6307\u5b9a\u7684user_data\u3002" "type": "boolean",
}, "desc": "弹性云服务器是否为锁定状态。\n\n- true:锁定\n- false:未锁定",
{ "example": false
"name": "locked", },
"type": "boolean", {
"example": null, "name": "tags",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u662f\u5426\u4e3a\u9501\u5b9a\u72b6\u6001\u3002\n\n- true:\u9501\u5b9a\n- false:\u672a\u9501\u5b9a" "type": "array",
}, "desc": "弹性云服务器标签。",
{ "example": ""
"name": "tags", },
"type": "文本、多值", {
"example": { "name": "os:scheduler_hints",
"type": "文本" "type": "",
}, "desc": "弹性云服务器调度信息",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6807\u7b7e\u3002" "example": ""
}, },
{ {
"name": "os:scheduler_hints", "name": "enterprise_project_id",
"type": "json", "type": "string",
"example": null, "desc": "弹性云服务器所属的企业项目ID。",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u8c03\u5ea6\u4fe1\u606f" "example": "0"
}, },
{ {
"name": "enterprise_project_id", "name": "sys_tags",
"type": "文本", "type": "array",
"example": "0", "desc": "弹性云服务器系统标签。",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5c5e\u7684\u4f01\u4e1a\u9879\u76eeID\u3002" "example": ""
}, },
{ {
"name": "sys_tags", "name": "cpu_options",
"type": "文本、多值", "type": "",
"example": { "desc": "自定义CPU选项。",
"$ref": "#/definitions/ServerSystemTag" "example": ""
}, },
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7cfb\u7edf\u6807\u7b7e\u3002" {
}, "name": "hypervisor",
{ "type": "",
"name": "cpu_options", "desc": "hypervisor信息。",
"type": "json", "example": ""
"example": null, }
"desc": "\u81ea\u5b9a\u4e49CPU\u9009\u9879\u3002"
},
{
"name": "hypervisor",
"type": "文本",
"example": null,
"desc": "hypervisor\u4fe1\u606f\u3002"
}
] ]

View File

@@ -1,297 +1,248 @@
[ [
{ {
"name": "Placement", "name": "Placement",
"type": "json", "type": "Placement",
"desc": "实例所在的位置。", "desc": "实例所在的位置。",
"example": { "example": ""
"HostId": "host-h3m57oik", },
"ProjectId": 1174660, {
"HostIds": [], "name": "InstanceId",
"Zone": "ap-guangzhou-1", "type": "String",
"HostIps": [] "desc": "实例ID。",
} "example": "ins-9bxebleo"
}, },
{ {
"name": "InstanceId", "name": "InstanceType",
"type": "文本", "type": "String",
"desc": "实例ID。", "desc": "实例机型。",
"example": "ins-xlsyru2j" "example": "S1.SMALL1"
}, },
{ {
"name": "InstanceType", "name": "CPU",
"type": "文本", "type": "Integer",
"desc": "实例机型。", "desc": "实例的CPU核数单位。",
"example": "S2.SMALL2" "example": "1"
}, },
{ {
"name": "CPU", "name": "Memory",
"type": "整数", "type": "Integer",
"desc": "实例的CPU核数,单位:。", "desc": "实例内存容量,单位:GB。",
"example": 1 "example": "1"
}, },
{ {
"name": "Memory", "name": "RestrictState",
"type": "整数", "type": "String",
"desc": "实例内存容量单位GB。", "desc": "NORMAL表示正常状态的实例\nEXPIRED表示过期的实例\nPROTECTIVELY_ISOLATED表示被安全隔离的实例。",
"example": 1 "example": "NORMAL"
}, },
{ {
"name": "RestrictState", "name": "InstanceName",
"type": "文本", "type": "String",
"desc": "实例业务状态。取值范围: NORMAL表示正常状态的实例 EXPIRED表示过期的实例 PROTECTIVELY_ISOLATED表示被安全隔离的实例。", "desc": "实例名称。",
"example": "PROTECTIVELY_ISOLATED" "example": "测试实例"
}, },
{ {
"name": "InstanceName", "name": "InstanceChargeType",
"type": "文本", "type": "String",
"desc": "实例名称。", "desc": "PREPAID表示预付费即包年包月\nPOSTPAID_BY_HOUR表示后付费即按量计费\nCDHPAID专用宿主机付费即只对专用宿主机计费不对专用宿主机上的实例计费。\nSPOTPAID表示竞价实例付费。",
"example": "test" "example": "PREPAID"
}, },
{ {
"name": "InstanceChargeType", "name": "SystemDisk",
"type": "文本", "type": "SystemDisk",
"desc": "实例计费模式。取值范围: PREPAID表示预付费即包年包月 POSTPAID_BY_HOUR表示后付费即按量计费 CDHPAID专用宿主机付费即只对专用宿主机计费不对专用宿主机上的实例计费。 SPOTPAID表示竞价实例付费。", "desc": "实例系统盘信息。",
"example": "POSTPAID_BY_HOUR" "example": ""
}, },
{ {
"name": "SystemDisk", "name": "DataDisks",
"type": "json", "type": "Array of DataDisk",
"desc": "实例系统盘信息。", "desc": "实例数据盘信息。",
"example": { "example": ""
"DiskSize": 50, },
"CdcId": null, {
"DiskId": "disk-czsodtl1", "name": "PrivateIpAddresses",
"DiskType": "CLOUD_SSD" "type": "Array of String",
} "desc": "实例主网卡的内网IP列表。",
}, "example": "[\"172.16.32.78\"]"
{ },
"name": "DataDisks", {
"type": "json", "name": "PublicIpAddresses",
"desc": "实例数据盘信息。", "type": "Array of String",
"example": [ "desc": "实例主网卡的公网IP列表。注意此字段可能返回 null表示取不到有效值。",
{ "example": "[\"123.207.11.190\"]"
"DeleteWithInstance": true, },
"Encrypt": true, {
"CdcId": null, "name": "InternetAccessible",
"DiskType": "CLOUD_SSD", "type": "InternetAccessible",
"ThroughputPerformance": 0, "desc": "实例带宽信息。",
"KmsKeyId": null, "example": ""
"DiskSize": 50, },
"SnapshotId": null, {
"DiskId": "disk-bzsodtn1" "name": "VirtualPrivateCloud",
} "type": "VirtualPrivateCloud",
] "desc": "实例所属虚拟私有网络信息。",
}, "example": ""
{ },
"name": "PrivateIpAddresses", {
"type": "文本、多值", "name": "ImageId",
"desc": "实例主网卡的内网IP列表。", "type": "String",
"example": [ "desc": "生产实例所使用的镜像ID。",
"172.16.32.78" "example": "img-9qabwvbn"
] },
}, {
{ "name": "RenewFlag",
"name": "PublicIpAddresses", "type": "String",
"type": "文本、多值", "desc": "NOTIFY_AND_MANUAL_RENEW表示通知即将过期但不自动续费\nNOTIFY_AND_AUTO_RENEW表示通知即将过期而且自动续费\nDISABLE_NOTIFY_AND_MANUAL_RENEW表示不通知即将过期也不自动续费。\n注意后付费模式本项为null",
"desc": "实例主网卡的公网IP列表。 注意:此字段可能返回 null表示取不到有效值。", "example": "NOTIFY_AND_MANUAL_RENEW"
"example": [ },
"123.207.11.190" {
] "name": "CreatedTime",
}, "type": "Timestamp ISO8601",
{ "desc": "创建时间。按照ISO8601标准表示并且使用UTC时间。格式为YYYY-MM-DDThh:mm:ssZ。",
"name": "InternetAccessible", "example": "2020-03-10T02:43:51Z"
"type": "json", },
"desc": "实例带宽信息。", {
"example": { "name": "ExpiredTime",
"PublicIpAssigned": true, "type": "Timestamp ISO8601",
"InternetChargeType": "TRAFFIC_POSTPAID_BY_HOUR", "desc": "到期时间。按照ISO8601标准表示并且使用UTC时间。格式为YYYY-MM-DDThh:mm:ssZ。注意后付费模式本项为null",
"BandwidthPackageId": null, "example": "2020-04-10T02:47:36Z"
"InternetMaxBandwidthOut": 1 },
} {
}, "name": "OsName",
{ "type": "String",
"name": "VirtualPrivateCloud", "desc": "操作系统名称。",
"type": "json", "example": "CentOS 7.6 64bit"
"desc": "实例所属虚拟私有网络信息。", },
"example": { {
"SubnetId": "subnet-mv4sn55k", "name": "SecurityGroupIds",
"AsVpcGateway": false, "type": "Array of String",
"Ipv6AddressCount": 1, "desc": "实例所属安全组。该参数可以通过调用 DescribeSecurityGroups 的返回值中的sgId字段来获取。",
"VpcId": "vpc-m0cnatxj", "example": "[\"sg-p1ezv4wz\"]"
"PrivateIpAddresses": [ },
"172.16.3.59" {
] "name": "LoginSettings",
} "type": "LoginSettings",
}, "desc": "实例登录设置。目前只返回实例所关联的密钥。",
{ "example": ""
"name": "ImageId", },
"type": "文本", {
"desc": "生产实例所使用的镜像ID。", "name": "InstanceState",
"example": "img-8toqc6s3" "type": "String",
}, "desc": "PENDING表示创建中\nLAUNCH_FAILED表示创建失败\nRUNNING表示运行中\nSTOPPED表示关机\nSTARTING表示开机中\nSTOPPING表示关机中\nREBOOTING表示重启中\nSHUTDOWN表示停止待销毁\nTERMINATING表示销毁中。",
{ "example": ""
"name": "RenewFlag", },
"type": "文本", {
"desc": "自动续费标识。取值范围: NOTIFY_AND_MANUAL_RENEW表示通知即将过期但不自动续费 NOTIFY_AND_AUTO_RENEW表示通知即将过期而且自动续费 DISABLE_NOTIFY_AND_MANUAL_RENEW表示不通知即将过期也不自动续费。 注意后付费模式本项为null", "name": "Tags",
"example": "NOTIFY_AND_MANUAL_RENEW" "type": "Array of Tag",
}, "desc": "实例关联的标签列表。",
{ "example": ""
"name": "CreatedTime", },
"type": "json", {
"desc": "创建时间。按照ISO8601标准表示并且使用UTC时间。格式为YYYY-MM-DDThh:mm:ssZ。", "name": "StopChargingMode",
"example": "2020-09-22T00:00:00+00:00" "type": "String",
}, "desc": "KEEP_CHARGING关机继续收费\nSTOP_CHARGING关机停止收费\nNOT_APPLICABLE实例处于非关机状态或者不适用关机停止计费的条件",
{ "example": "NOT_APPLICABLE"
"name": "ExpiredTime", },
"type": "json", {
"desc": "到期时间。按照ISO8601标准表示并且使用UTC时间。格式为YYYY-MM-DDThh:mm:ssZ。注意后付费模式本项为null", "name": "Uuid",
"example": "2020-09-22T00:00:00+00:00" "type": "String",
}, "desc": "实例全局唯一ID",
{ "example": "68b510db-b4c1-4630-a62b-73d0c7c970f9"
"name": "OsName", },
"type": "文本", {
"desc": "操作系统名称。", "name": "LatestOperation",
"example": "CentOS 7.4 64bit" "type": "String",
}, "desc": "实例的最新操作。例StopInstances、ResetInstance。注意此字段可能返回 null表示取不到有效值。",
{ "example": "RenewInstances"
"name": "SecurityGroupIds", },
"type": "文本、多值", {
"desc": "实例所属安全组。该参数可以通过调用 DescribeSecurityGroups 的返回值中的sgId字段来获取。", "name": "LatestOperationState",
"example": [ "type": "String",
"sg-p1ezv4wz" "desc": "SUCCESS表示操作成功\nOPERATING表示操作执行中\nFAILED表示操作失败注意此字段可能返回 null表示取不到有效值。",
] "example": "SUCCESS"
}, },
{ {
"name": "LoginSettings", "name": "LatestOperationRequestId",
"type": "json", "type": "String",
"desc": "实例登录设置。目前只返回实例所关联的密钥。", "desc": "实例最新操作的唯一请求 ID。注意此字段可能返回 null表示取不到有效值。",
"example": { "example": "3554eb5b-1cfa-471a-ae76-dc436c9d43e8"
"Password": "123qwe!@#QWE", },
"KeepImageLogin": "False", {
"KeyIds": [ "name": "DisasterRecoverGroupId",
"skey-b4vakk62" "type": "String",
] "desc": "分散置放群组ID。注意此字段可能返回 null表示取不到有效值。",
} "example": "null"
}, },
{ {
"name": "InstanceState", "name": "IPv6Addresses",
"type": "文本", "type": "Array of String",
"desc": "实例状态。取值范围: PENDING表示创建中 LAUNCH_FAILED表示创建失败 RUNNING表示运行中 STOPPED表示关机 STARTING表示开机中 STOPPING表示关机中 REBOOTING表示重启中 SHUTDOWN表示停止待销毁 TERMINATING表示销毁中。", "desc": "实例的IPv6地址。注意此字段可能返回 null表示取不到有效值。",
"example": "RUNNING" "example": "null"
}, },
{ {
"name": "Tags", "name": "CamRoleName",
"type": "json", "type": "String",
"desc": "实例关联的标签列表。", "desc": "CAM角色名。注意此字段可能返回 null表示取不到有效值。",
"example": [ "example": "null"
{ },
"Value": "test", {
"Key": "test" "name": "HpcClusterId",
} "type": "String",
] "desc": "高性能计算集群ID。注意此字段可能返回 null表示取不到有效值。",
}, "example": "null"
{ },
"name": "StopChargingMode", {
"type": "文本", "name": "RdmaIpAddresses",
"desc": "实例的关机计费模式。 取值范围: KEEP_CHARGING关机继续收费 STOP_CHARGING关机停止收费NOT_APPLICABLE实例处于非关机状态或者不适用关机停止计费的条件", "type": "Array of String",
"example": "NOT_APPLICABLE" "desc": "高性能计算集群IP列表。注意此字段可能返回 null表示取不到有效值。",
}, "example": "null"
{ },
"name": "Uuid", {
"type": "文本", "name": "DedicatedClusterId",
"desc": "实例全局唯一ID", "type": "String",
"example": "e85f1388-0422-410d-8e50-bef540e78c18" "desc": "实例所在的专用集群ID。注意此字段可能返回 null表示取不到有效值。",
}, "example": "cluster-du3jken"
{ },
"name": "LatestOperation", {
"type": "文本", "name": "IsolatedSource",
"desc": "实例的最新操作。例StopInstances、ResetInstance。 注意:此字段可能返回 null表示取不到有效值。", "type": "String",
"example": "ResetInstancesType" "desc": "ARREAR表示欠费隔离\nEXPIRE表示到期隔离\nMANMADE表示主动退还隔离\nNOTISOLATED表示未隔离",
}, "example": ""
{ },
"name": "LatestOperationState", {
"type": "文本", "name": "GPUInfo",
"desc": "实例的最新操作状态。取值范围: SUCCESS表示操作成功 OPERATING表示操作执行中 FAILED表示操作失败 注意:此字段可能返回 null表示取不到有效值。", "type": "GPUInfo",
"example": "SUCCESS" "desc": "GPU信息。如果是gpu类型子机该值会返回GPU信息如果是其他类型子机则不返回。注意此字段可能返回 null表示取不到有效值。",
}, "example": ""
{ },
"name": "LatestOperationRequestId", {
"type": "文本", "name": "LicenseType",
"desc": "实例最新操作的唯一请求 ID。 注意:此字段可能返回 null表示取不到有效值。", "type": "String",
"example": "c7de1287-061d-4ace-8caf-6ad8e5a2f29a" "desc": "实例的操作系统许可类型默认为TencentCloud",
}, "example": "TencentCloud"
{ },
"name": "DisasterRecoverGroupId", {
"type": "文本", "name": "DisableApiTermination",
"desc": "分散置放群组ID。 注意:此字段可能返回 null表示取不到有效值。", "type": "Boolean",
"example": "" "desc": "TRUE表示开启实例保护不允许通过api接口删除实例\nFALSE表示关闭实例保护允许通过api接口删除实例默认取值FALSE。",
}, "example": "false"
{ },
"name": "IPv6Addresses", {
"type": "文本、多值", "name": "DefaultLoginUser",
"desc": "实例的IPv6地址。 注意:此字段可能返回 null表示取不到有效值。", "type": "String",
"example": [ "desc": "默认登录用户。",
"2001:0db8:86a3:08d3:1319:8a2e:0370:7344" "example": "root"
] },
}, {
{ "name": "DefaultLoginPort",
"name": "CamRoleName", "type": "Integer",
"type": "文本", "desc": "默认登录端口。",
"desc": "CAM角色名。 注意:此字段可能返回 null表示取不到有效值。", "example": "22"
"example": "" },
}, {
{ "name": "LatestOperationErrorMsg",
"name": "HpcClusterId", "type": "String",
"type": "文本", "desc": "实例的最新操作错误信息。注意:此字段可能返回 null表示取不到有效值。",
"desc": "高性能计算集群ID。 注意:此字段可能返回 null表示取不到有效值。", "example": "None"
"example": "" }
},
{
"name": "RdmaIpAddresses",
"type": "文本、多值",
"desc": "高性能计算集群IP列表。 注意:此字段可能返回 null表示取不到有效值。",
"example": []
},
{
"name": "IsolatedSource",
"type": "文本",
"desc": "实例隔离类型。取值范围: ARREAR表示欠费隔离 EXPIRE表示到期隔离 MANMADE表示主动退还隔离 NOTISOLATED表示未隔离 注意:此字段可能返回 null表示取不到有效值。",
"example": "NOTISOLATED"
},
{
"name": "GPUInfo",
"type": "json",
"desc": "GPU信息。如果是gpu类型子机该值会返回GPU信息如果是其他类型子机则不返回。 注意:此字段可能返回 null表示取不到有效值。",
"example": null
},
{
"name": "LicenseType",
"type": "文本",
"desc": "实例的操作系统许可类型默认为TencentCloud",
"example": null
},
{
"name": "DisableApiTermination",
"type": "Boolean",
"desc": "实例销毁保护标志表示是否允许通过api接口删除实例。取值范围 TRUE表示开启实例保护不允许通过api接口删除实例 FALSE表示关闭实例保护允许通过api接口删除实例 默认取值FALSE。",
"example": null
},
{
"name": "DefaultLoginUser",
"type": "文本",
"desc": "默认登录用户。",
"example": null
},
{
"name": "DefaultLoginPort",
"type": "整数",
"desc": "默认登录端口。",
"example": null
},
{
"name": "LatestOperationErrorMsg",
"type": "文本",
"desc": "实例的最新操作错误信息。 注意:此字段可能返回 null表示取不到有效值。",
"example": null
}
] ]

View File

@@ -5,10 +5,14 @@ from __future__ import unicode_literals
from flask import current_app from flask import current_app
from api.extensions import cache from api.extensions import cache
from api.extensions import db
from api.lib.cmdb.custom_dashboard import CustomDashboardManager from api.lib.cmdb.custom_dashboard import CustomDashboardManager
from api.models.cmdb import Attribute from api.models.cmdb import Attribute
from api.models.cmdb import CI
from api.models.cmdb import CIType from api.models.cmdb import CIType
from api.models.cmdb import CITypeAttribute from api.models.cmdb import CITypeAttribute
from api.models.cmdb import PreferenceShowAttributes
from api.models.cmdb import PreferenceTreeView
from api.models.cmdb import RelationType from api.models.cmdb import RelationType
@@ -226,7 +230,9 @@ class CITypeAttributeCache(object):
class CMDBCounterCache(object): class CMDBCounterCache(object):
KEY = 'CMDB::Counter' KEY = 'CMDB::Counter::dashboard'
KEY2 = 'CMDB::Counter::adc'
KEY3 = 'CMDB::Counter::sub'
@classmethod @classmethod
def get(cls): def get(cls):
@@ -429,3 +435,47 @@ class CMDBCounterCache(object):
return return
return numfound return numfound
@classmethod
def flush_adc_counter(cls):
res = db.session.query(CI.type_id, CI.is_auto_discovery)
result = dict()
for i in res:
result.setdefault(i.type_id, dict(total=0, auto_discovery=0))
result[i.type_id]['total'] += 1
if i.is_auto_discovery:
result[i.type_id]['auto_discovery'] += 1
cache.set(cls.KEY2, result, timeout=0)
return result
@classmethod
def get_adc_counter(cls):
return cache.get(cls.KEY2) or cls.flush_adc_counter()
@classmethod
def flush_sub_counter(cls):
result = dict(type_id2users=dict())
types = db.session.query(PreferenceShowAttributes.type_id,
PreferenceShowAttributes.uid, PreferenceShowAttributes.created_at).filter(
PreferenceShowAttributes.deleted.is_(False)).group_by(
PreferenceShowAttributes.uid, PreferenceShowAttributes.type_id)
for i in types:
result['type_id2users'].setdefault(i.type_id, []).append(i.uid)
types = PreferenceTreeView.get_by(to_dict=False)
for i in types:
result['type_id2users'].setdefault(i.type_id, [])
if i.uid not in result['type_id2users'][i.type_id]:
result['type_id2users'][i.type_id].append(i.uid)
cache.set(cls.KEY3, result, timeout=0)
return result
@classmethod
def get_sub_counter(cls):
return cache.get(cls.KEY3) or cls.flush_sub_counter()

View File

@@ -5,7 +5,6 @@ import copy
import datetime import datetime
import json import json
import threading import threading
from flask import abort from flask import abort
from flask import current_app from flask import current_app
from flask_login import current_user from flask_login import current_user
@@ -16,6 +15,7 @@ from api.extensions import rd
from api.lib.cmdb.cache import AttributeCache from api.lib.cmdb.cache import AttributeCache
from api.lib.cmdb.cache import CITypeAttributesCache from api.lib.cmdb.cache import CITypeAttributesCache
from api.lib.cmdb.cache import CITypeCache from api.lib.cmdb.cache import CITypeCache
from api.lib.cmdb.cache import CMDBCounterCache
from api.lib.cmdb.ci_type import CITypeAttributeManager from api.lib.cmdb.ci_type import CITypeAttributeManager
from api.lib.cmdb.ci_type import CITypeManager from api.lib.cmdb.ci_type import CITypeManager
from api.lib.cmdb.ci_type import CITypeRelationManager from api.lib.cmdb.ci_type import CITypeRelationManager
@@ -218,15 +218,7 @@ class CIManager(object):
@classmethod @classmethod
def get_ad_statistics(cls): def get_ad_statistics(cls):
res = CI.get_by(to_dict=False) return CMDBCounterCache.get_adc_counter()
result = dict()
for i in res:
result.setdefault(i.type_id, dict(total=0, auto_discovery=0))
result[i.type_id]['total'] += 1
if i.is_auto_discovery:
result[i.type_id]['auto_discovery'] += 1
return result
@staticmethod @staticmethod
def ci_is_exist(unique_key, unique_value, type_id): def ci_is_exist(unique_key, unique_value, type_id):
@@ -368,6 +360,8 @@ class CIManager(object):
if attr.default and attr.default.get('default') == AttributeDefaultValueEnum.UPDATED_AT: if attr.default and attr.default.get('default') == AttributeDefaultValueEnum.UPDATED_AT:
ci_dict[attr.name] = now ci_dict[attr.name] = now
value_manager = AttributeValueManager()
computed_attrs = [] computed_attrs = []
for _, attr in attrs: for _, attr in attrs:
if attr.is_computed: if attr.is_computed:
@@ -378,7 +372,8 @@ class CIManager(object):
elif attr.alias in ci_dict: elif attr.alias in ci_dict:
password_dict[attr.id] = ci_dict.pop(attr.alias) password_dict[attr.id] = ci_dict.pop(attr.alias)
value_manager = AttributeValueManager() if attr.re_check and password_dict.get(attr.id):
value_manager.check_re(attr.re_check, password_dict[attr.id])
if computed_attrs: if computed_attrs:
value_manager.handle_ci_compute_attributes(ci_dict, computed_attrs, ci) value_manager.handle_ci_compute_attributes(ci_dict, computed_attrs, ci)
@@ -395,8 +390,9 @@ class CIManager(object):
k not in ci_type_attrs_alias and _no_attribute_policy == ExistPolicy.REJECT): k not in ci_type_attrs_alias and _no_attribute_policy == ExistPolicy.REJECT):
return abort(400, ErrFormat.attribute_not_found.format(k)) return abort(400, ErrFormat.attribute_not_found.format(k))
if limit_attrs and ci_type_attrs_name.get(k) not in limit_attrs and ( _attr_name = ((ci_type_attrs_name.get(k) and ci_type_attrs_name[k].name) or
ci_type_attrs_alias.get(k) not in limit_attrs): (ci_type_attrs_alias.get(k) and ci_type_attrs_alias[k].name))
if limit_attrs and _attr_name not in limit_attrs:
return abort(403, ErrFormat.ci_filter_perm_attr_no_permission.format(k)) return abort(403, ErrFormat.ci_filter_perm_attr_no_permission.format(k))
ci_dict = {k: v for k, v in ci_dict.items() if k in ci_type_attrs_name or k in ci_type_attrs_alias} ci_dict = {k: v for k, v in ci_dict.items() if k in ci_type_attrs_name or k in ci_type_attrs_alias}
@@ -436,6 +432,8 @@ class CIManager(object):
if attr.default and attr.default.get('default') == AttributeDefaultValueEnum.UPDATED_AT: if attr.default and attr.default.get('default') == AttributeDefaultValueEnum.UPDATED_AT:
ci_dict[attr.name] = now ci_dict[attr.name] = now
value_manager = AttributeValueManager()
password_dict = dict() password_dict = dict()
computed_attrs = list() computed_attrs = list()
for _, attr in attrs: for _, attr in attrs:
@@ -447,7 +445,8 @@ class CIManager(object):
elif attr.alias in ci_dict: elif attr.alias in ci_dict:
password_dict[attr.id] = ci_dict.pop(attr.alias) password_dict[attr.id] = ci_dict.pop(attr.alias)
value_manager = AttributeValueManager() if attr.re_check and password_dict.get(attr.id):
value_manager.check_re(attr.re_check, password_dict[attr.id])
if computed_attrs: if computed_attrs:
value_manager.handle_ci_compute_attributes(ci_dict, computed_attrs, ci) value_manager.handle_ci_compute_attributes(ci_dict, computed_attrs, ci)

View File

@@ -1,12 +1,13 @@
# -*- coding:utf-8 -*- # -*- coding:utf-8 -*-
import copy import copy
import toposort import toposort
from flask import abort from flask import abort
from flask import current_app from flask import current_app
from flask import session
from flask_login import current_user from flask_login import current_user
from toposort import toposort_flatten from toposort import toposort_flatten
from werkzeug.exceptions import BadRequest
from api.extensions import db from api.extensions import db
from api.lib.cmdb.attribute import AttributeManager from api.lib.cmdb.attribute import AttributeManager
@@ -22,6 +23,7 @@ from api.lib.cmdb.const import ResourceTypeEnum
from api.lib.cmdb.const import RoleEnum from api.lib.cmdb.const import RoleEnum
from api.lib.cmdb.const import ValueTypeEnum from api.lib.cmdb.const import ValueTypeEnum
from api.lib.cmdb.history import CITypeHistoryManager from api.lib.cmdb.history import CITypeHistoryManager
from api.lib.cmdb.perms import CIFilterPermsCRUD
from api.lib.cmdb.relation_type import RelationTypeManager from api.lib.cmdb.relation_type import RelationTypeManager
from api.lib.cmdb.resp_format import ErrFormat from api.lib.cmdb.resp_format import ErrFormat
from api.lib.cmdb.value import AttributeValueManager from api.lib.cmdb.value import AttributeValueManager
@@ -43,6 +45,7 @@ from api.models.cmdb import CITypeRelation
from api.models.cmdb import CITypeTrigger from api.models.cmdb import CITypeTrigger
from api.models.cmdb import CITypeUniqueConstraint from api.models.cmdb import CITypeUniqueConstraint
from api.models.cmdb import CustomDashboard from api.models.cmdb import CustomDashboard
from api.models.cmdb import PreferenceCITypeOrder
from api.models.cmdb import PreferenceRelationView from api.models.cmdb import PreferenceRelationView
from api.models.cmdb import PreferenceSearchOption from api.models.cmdb import PreferenceSearchOption
from api.models.cmdb import PreferenceShowAttributes from api.models.cmdb import PreferenceShowAttributes
@@ -72,15 +75,17 @@ class CITypeManager(object):
return CIType.get_by_id(ci_type.id) return CIType.get_by_id(ci_type.id)
@staticmethod @staticmethod
def get_ci_types(type_name=None): def get_ci_types(type_name=None, like=True):
resources = None resources = None
if current_app.config.get('USE_ACL') and not is_app_admin('cmdb'): if current_app.config.get('USE_ACL') and not is_app_admin('cmdb'):
resources = set([i.get('name') for i in ACLManager().get_resources("CIType")]) resources = set([i.get('name') for i in ACLManager().get_resources(ResourceTypeEnum.CI_TYPE)])
ci_types = CIType.get_by() if type_name is None else CIType.get_by_like(name=type_name) ci_types = CIType.get_by() if type_name is None else (
CIType.get_by_like(name=type_name) if like else CIType.get_by(name=type_name))
res = list() res = list()
for type_dict in ci_types: for type_dict in ci_types:
type_dict["unique_key"] = AttributeCache.get(type_dict["unique_id"]).name attr = AttributeCache.get(type_dict["unique_id"])
type_dict["unique_key"] = attr and attr.name
if resources is None or type_dict['name'] in resources: if resources is None or type_dict['name'] in resources:
res.append(type_dict) res.append(type_dict)
@@ -113,6 +118,9 @@ class CITypeManager(object):
@classmethod @classmethod
@kwargs_required("name") @kwargs_required("name")
def add(cls, **kwargs): def add(cls, **kwargs):
if current_app.config.get('USE_ACL') and not is_app_admin('cmdb'):
if ErrFormat.ci_type_config not in {i['name'] for i in ACLManager().get_resources(ResourceTypeEnum.PAGE)}:
return abort(403, ErrFormat.no_permission2)
unique_key = kwargs.pop("unique_key", None) or kwargs.pop("unique_id", None) unique_key = kwargs.pop("unique_key", None) or kwargs.pop("unique_id", None)
unique_key = AttributeCache.get(unique_key) or abort(404, ErrFormat.unique_key_not_define) unique_key = AttributeCache.get(unique_key) or abort(404, ErrFormat.unique_key_not_define)
@@ -131,7 +139,11 @@ class CITypeManager(object):
CITypeCache.clean(ci_type.name) CITypeCache.clean(ci_type.name)
if current_app.config.get("USE_ACL"): if current_app.config.get("USE_ACL"):
ACLManager().add_resource(ci_type.name, ResourceTypeEnum.CI) try:
ACLManager().add_resource(ci_type.name, ResourceTypeEnum.CI)
except BadRequest:
pass
ACLManager().grant_resource_to_role(ci_type.name, ACLManager().grant_resource_to_role(ci_type.name,
RoleEnum.CMDB_READ_ALL, RoleEnum.CMDB_READ_ALL,
ResourceTypeEnum.CI, ResourceTypeEnum.CI,
@@ -211,7 +223,7 @@ class CITypeManager(object):
for table in [PreferenceTreeView, PreferenceShowAttributes, PreferenceSearchOption, CustomDashboard, for table in [PreferenceTreeView, PreferenceShowAttributes, PreferenceSearchOption, CustomDashboard,
CITypeGroupItem, CITypeAttributeGroup, CITypeAttribute, CITypeUniqueConstraint, CITypeTrigger, CITypeGroupItem, CITypeAttributeGroup, CITypeAttribute, CITypeUniqueConstraint, CITypeTrigger,
AutoDiscoveryCIType, CIFilterPerms]: AutoDiscoveryCIType, CIFilterPerms, PreferenceCITypeOrder]:
for item in table.get_by(type_id=type_id, to_dict=False): for item in table.get_by(type_id=type_id, to_dict=False):
item.soft_delete(commit=False) item.soft_delete(commit=False)
@@ -243,7 +255,6 @@ class CITypeGroupManager(object):
else: else:
resources = {i['name']: i['permissions'] for i in resources if PermEnum.READ in i.get("permissions")} resources = {i['name']: i['permissions'] for i in resources if PermEnum.READ in i.get("permissions")}
current_app.logger.info(resources)
groups = sorted(CITypeGroup.get_by(), key=lambda x: x['order'] or 0) groups = sorted(CITypeGroup.get_by(), key=lambda x: x['order'] or 0)
group_types = set() group_types = set()
for group in groups: for group in groups:
@@ -283,7 +294,10 @@ class CITypeGroupManager(object):
""" """
existed = CITypeGroup.get_by_id(gid) or abort( existed = CITypeGroup.get_by_id(gid) or abort(
404, ErrFormat.ci_type_group_not_found.format("id={}".format(gid))) 404, ErrFormat.ci_type_group_not_found.format("id={}".format(gid)))
if name is not None: if name is not None and name != existed.name:
if RoleEnum.CONFIG not in session.get("acl", {}).get("parentRoles", []) and not is_app_admin("cmdb"):
return abort(403, ErrFormat.role_required.format(RoleEnum.CONFIG))
existed.update(name=name) existed.update(name=name)
max_order = max([i.order or 0 for i in CITypeGroupItem.get_by(group_id=gid, to_dict=False)] or [0]) max_order = max([i.order or 0 for i in CITypeGroupItem.get_by(group_id=gid, to_dict=False)] or [0])
@@ -576,6 +590,11 @@ class CITypeRelationManager(object):
ci_type_dict = CITypeCache.get(type_id).to_dict() ci_type_dict = CITypeCache.get(type_id).to_dict()
ci_type_dict["ctr_id"] = relation_inst.id ci_type_dict["ctr_id"] = relation_inst.id
ci_type_dict["attributes"] = CITypeAttributeManager.get_attributes_by_type_id(ci_type_dict["id"]) ci_type_dict["attributes"] = CITypeAttributeManager.get_attributes_by_type_id(ci_type_dict["id"])
attr_filter = CIFilterPermsCRUD.get_attr_filter(type_id)
if attr_filter:
ci_type_dict["attributes"] = [attr for attr in (ci_type_dict["attributes"] or [])
if attr['name'] in attr_filter]
ci_type_dict["relation_type"] = relation_inst.relation_type.name ci_type_dict["relation_type"] = relation_inst.relation_type.name
ci_type_dict["constraint"] = relation_inst.constraint ci_type_dict["constraint"] = relation_inst.constraint
@@ -725,7 +744,7 @@ class CITypeAttributeGroupManager(object):
grouped = list() grouped = list()
attributes = CITypeAttributeManager.get_attributes_by_type_id(type_id) attributes = CITypeAttributeManager.get_attributes_by_type_id(type_id)
id2attr = {i['id']: i for i in attributes} id2attr = {i.get('id'): i for i in attributes}
for group in groups: for group in groups:
items = CITypeAttributeGroupItem.get_by(group_id=group["id"], to_dict=False) items = CITypeAttributeGroupItem.get_by(group_id=group["id"], to_dict=False)
@@ -891,97 +910,58 @@ class CITypeAttributeGroupManager(object):
class CITypeTemplateManager(object): class CITypeTemplateManager(object):
@staticmethod @staticmethod
def __import(cls, data): def __import(cls, data, unique_key='name'):
id2obj_dicts = {i['id']: i for i in data} id2obj_dicts = {i[unique_key]: i for i in data}
existed = cls.get_by(deleted=None, to_dict=False) existed = cls.get_by(to_dict=False)
id2existed = {i.id: i for i in existed} id2existed = {getattr(i, unique_key): i for i in existed}
existed_ids = [i.id for i in existed] existed_ids = [getattr(i, unique_key) for i in existed]
existed_no_delete_ids = [i.id for i in existed if not i.deleted]
id_map = dict()
# add # add
for added_id in set(id2obj_dicts.keys()) - set(existed_ids): for added_id in set(id2obj_dicts.keys()) - set(existed_ids):
_id = id2obj_dicts[added_id].pop('id', None)
id2obj_dicts[added_id].pop('created_at', None)
id2obj_dicts[added_id].pop('updated_at', None)
id2obj_dicts[added_id].pop('uid', None)
if cls == CIType: if cls == CIType:
CITypeManager.add(**id2obj_dicts[added_id]) __id = CITypeManager.add(**id2obj_dicts[added_id])
CITypeCache.clean(__id)
elif cls == CITypeRelation: elif cls == CITypeRelation:
CITypeRelationManager.add(id2obj_dicts[added_id].get('parent_id'), __id = CITypeRelationManager.add(id2obj_dicts[added_id].get('parent_id'),
id2obj_dicts[added_id].get('child_id'), id2obj_dicts[added_id].get('child_id'),
id2obj_dicts[added_id].get('relation_type_id'), id2obj_dicts[added_id].get('relation_type_id'),
id2obj_dicts[added_id].get('constraint'), id2obj_dicts[added_id].get('constraint'),
) )
else: else:
cls.create(flush=True, **id2obj_dicts[added_id]) obj = cls.create(flush=True, **id2obj_dicts[added_id])
if cls == Attribute:
AttributeCache.clean(obj)
__id = obj.id
id_map[_id] = __id
# update # update
for updated_id in set(id2obj_dicts.keys()) & set(existed_ids): for updated_id in set(id2obj_dicts.keys()) & set(existed_ids):
_id = id2obj_dicts[updated_id].pop('id', None)
id2existed[updated_id].update(flush=True, **id2obj_dicts[updated_id])
id_map[_id] = id2existed[updated_id].id
if cls == Attribute:
AttributeCache.clean(id2existed[updated_id])
if cls == CIType: if cls == CIType:
deleted = id2existed[updated_id].deleted CITypeCache.clean(id2existed[updated_id].id)
CITypeManager.update(updated_id, **id2obj_dicts[updated_id])
if deleted and current_app.config.get("USE_ACL"):
type_name = id2obj_dicts[updated_id]['name']
ACLManager().add_resource(type_name, ResourceTypeEnum.CI)
ACLManager().grant_resource_to_role(type_name,
RoleEnum.CMDB_READ_ALL,
ResourceTypeEnum.CI,
permissions=[PermEnum.READ])
ACLManager().grant_resource_to_role(type_name,
current_user.username,
ResourceTypeEnum.CI)
else:
id2existed[updated_id].update(flush=True, **id2obj_dicts[updated_id])
# delete
for deleted_id in set(existed_no_delete_ids) - set(id2obj_dicts.keys()):
if cls == CIType:
id2existed[deleted_id].soft_delete(flush=True)
CITypeCache.clean(deleted_id)
CITypeHistoryManager.add(CITypeOperateType.DELETE, deleted_id, change=id2existed[deleted_id].to_dict())
if current_app.config.get("USE_ACL"):
ACLManager().del_resource(id2existed[deleted_id].name, ResourceTypeEnum.CI)
else:
id2existed[deleted_id].soft_delete(flush=True)
try: try:
db.session.commit() db.session.commit()
except Exception as e: except Exception as e:
db.session.rollback() db.session.rollback()
raise Exception(str(e)) raise Exception(str(e))
def _import_ci_types(self, ci_types): return id_map
for i in ci_types:
i.pop("unique_key", None)
self.__import(CIType, ci_types)
def _import_ci_type_groups(self, ci_type_groups):
_ci_type_groups = copy.deepcopy(ci_type_groups)
for i in _ci_type_groups:
i.pop('ci_types', None)
self.__import(CITypeGroup, _ci_type_groups)
# import group type items
for group in ci_type_groups:
existed = CITypeGroupItem.get_by(group_id=group['id'], to_dict=False)
for i in existed:
i.soft_delete()
for order, ci_type in enumerate(group.get('ci_types') or []):
payload = dict(group_id=group['id'], type_id=ci_type['id'], order=order)
CITypeGroupItem.create(**payload)
def _import_relation_types(self, relation_types):
self.__import(RelationType, relation_types)
def _import_ci_type_relations(self, ci_type_relations):
for i in ci_type_relations:
i.pop('parent', None)
i.pop('child', None)
i.pop('relation_type', None)
self.__import(CITypeRelation, ci_type_relations)
def _import_attributes(self, type2attributes): def _import_attributes(self, type2attributes):
attributes = [attr for type_id in type2attributes for attr in type2attributes[type_id]] attributes = [attr for type_id in type2attributes for attr in type2attributes[type_id]]
@@ -990,122 +970,262 @@ class CITypeTemplateManager(object):
i.pop('default_show', None) i.pop('default_show', None)
i.pop('is_required', None) i.pop('is_required', None)
i.pop('order', None) i.pop('order', None)
i.pop('choice_web_hook', None)
i.pop('choice_other', None)
i.pop('order', None)
choice_value = i.pop('choice_value', None) choice_value = i.pop('choice_value', None)
if not choice_value:
i['is_choice'] = False
attrs.append((i, choice_value)) attrs.append((i, choice_value))
self.__import(Attribute, [i[0] for i in attrs]) attr_id_map = self.__import(Attribute, [i[0] for i in copy.deepcopy(attrs)])
for i, choice_value in attrs: for i, choice_value in attrs:
if choice_value: if choice_value and not i.get('choice_web_hook') and not i.get('choice_other'):
AttributeManager.add_choice_values(i['id'], i['value_type'], choice_value) AttributeManager.add_choice_values(attr_id_map.get(i['id'], i['id']), i['value_type'], choice_value)
return attr_id_map
def _import_ci_types(self, ci_types, attr_id_map):
for i in ci_types:
i.pop("unique_key", None)
i['unique_id'] = attr_id_map.get(i['unique_id'], i['unique_id'])
i['uid'] = current_user.uid
return self.__import(CIType, ci_types)
def _import_ci_type_groups(self, ci_type_groups, type_id_map):
_ci_type_groups = copy.deepcopy(ci_type_groups)
for i in _ci_type_groups:
i.pop('ci_types', None)
group_id_map = self.__import(CITypeGroup, _ci_type_groups)
# import group type items
for group in ci_type_groups:
for order, ci_type in enumerate(group.get('ci_types') or []):
payload = dict(group_id=group_id_map.get(group['id'], group['id']),
type_id=type_id_map.get(ci_type['id'], ci_type['id']),
order=order)
existed = CITypeGroupItem.get_by(group_id=payload['group_id'], type_id=payload['type_id'],
first=True, to_dict=False)
if existed is None:
CITypeGroupItem.create(flush=True, **payload)
else:
existed.update(flush=True, **payload)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
raise Exception(str(e))
def _import_relation_types(self, relation_types):
return self.__import(RelationType, relation_types)
@staticmethod @staticmethod
def _import_type_attributes(type2attributes): def _import_ci_type_relations(ci_type_relations, type_id_map, relation_type_id_map):
# add type attribute for i in ci_type_relations:
i.pop('parent', None)
i.pop('child', None)
i.pop('relation_type', None)
i['parent_id'] = type_id_map.get(i['parent_id'], i['parent_id'])
i['child_id'] = type_id_map.get(i['child_id'], i['child_id'])
i['relation_type_id'] = relation_type_id_map.get(i['relation_type_id'], i['relation_type_id'])
try:
CITypeRelationManager.add(i.get('parent_id'),
i.get('child_id'),
i.get('relation_type_id'),
i.get('constraint'),
)
except BadRequest:
pass
@staticmethod
def _import_type_attributes(type2attributes, type_id_map, attr_id_map):
for type_id in type2attributes:
CITypeAttributesCache.clean(type_id_map.get(int(type_id), type_id))
for type_id in type2attributes: for type_id in type2attributes:
existed = CITypeAttribute.get_by(type_id=type_id, to_dict=False) existed = CITypeAttributesCache.get2(type_id_map.get(int(type_id), type_id))
existed_attr_ids = {i.attr_id: i for i in existed} existed_attr_names = {attr.name: ta for ta, attr in existed}
new_attr_ids = {i['id']: i for i in type2attributes[type_id]}
handled = set()
for attr in type2attributes[type_id]: for attr in type2attributes[type_id]:
payload = dict(type_id=type_id, payload = dict(type_id=type_id_map.get(int(type_id), type_id),
attr_id=attr['id'], attr_id=attr_id_map.get(attr['id'], attr['id']),
default_show=attr['default_show'], default_show=attr['default_show'],
is_required=attr['is_required'], is_required=attr['is_required'],
order=attr['order']) order=attr['order'])
if attr['id'] not in existed_attr_ids: # new if attr['name'] not in handled:
CITypeAttribute.create(flush=True, **payload) if attr['name'] not in existed_attr_names: # new
else: # update CITypeAttribute.create(flush=True, **payload)
existed_attr_ids[attr['id']].update(**payload) else: # update
existed_attr_names[attr['name']].update(flush=True, **payload)
# delete handled.add(attr['name'])
for i in existed:
if i.attr_id not in new_attr_ids: try:
i.soft_delete() db.session.commit()
except Exception as e:
db.session.rollback()
raise Exception(str(e))
for type_id in type2attributes:
CITypeAttributesCache.clean(type_id_map.get(int(type_id), type_id))
@staticmethod @staticmethod
def _import_attribute_group(type2attribute_group): def _import_attribute_group(type2attribute_group, type_id_map, attr_id_map):
for type_id in type2attribute_group: for type_id in type2attribute_group:
existed = CITypeAttributeGroup.get_by(type_id=type_id, to_dict=False)
for i in existed:
i.soft_delete()
for group in type2attribute_group[type_id] or []: for group in type2attribute_group[type_id] or []:
_group = copy.deepcopy(group) _group = copy.deepcopy(group)
_group.pop('attributes', None) _group.pop('attributes', None)
_group.pop('id', None) _group.pop('id', None)
new = CITypeAttributeGroup.create(**_group) existed = CITypeAttributeGroup.get_by(name=_group['name'],
type_id=type_id_map.get(_group['type_id'], _group['type_id']),
first=True, to_dict=False)
if existed is None:
_group['type_id'] = type_id_map.get(_group['type_id'], _group['type_id'])
existed = CITypeAttributeGroupItem.get_by(group_id=new.id, to_dict=False) existed = CITypeAttributeGroup.create(flush=True, **_group)
for i in existed:
i.soft_delete()
for order, attr in enumerate(group['attributes'] or []): for order, attr in enumerate(group['attributes'] or []):
CITypeAttributeGroupItem.create(group_id=new.id, attr_id=attr['id'], order=order) item_existed = CITypeAttributeGroupItem.get_by(group_id=existed.id,
attr_id=attr_id_map.get(attr['id'], attr['id']),
first=True, to_dict=False)
if item_existed is None:
CITypeAttributeGroupItem.create(group_id=existed.id,
attr_id=attr_id_map.get(attr['id'], attr['id']),
order=order)
else:
item_existed.update(flush=True, order=order)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
raise Exception(str(e))
@staticmethod @staticmethod
def _import_auto_discovery_rules(rules): def _import_auto_discovery_rules(rules):
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryRuleCRUD from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryRuleCRUD
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryCITypeCRUD from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryCITypeCRUD
for rule in rules: for rule in rules:
ci_type = CITypeCache.get(rule.pop('type_name', None)) ci_type = CITypeCache.get(rule.pop('type_name', None))
adr = rule.pop('adr', {}) or {}
if ci_type: if ci_type:
rule['type_id'] = ci_type.id rule['type_id'] = ci_type.id
if rule.get('adr_name'): if rule.get('adr_name'):
ad_rule = AutoDiscoveryRuleCRUD.get_by_name(rule.pop("adr_name")) ad_rule = AutoDiscoveryRuleCRUD.get_by_name(rule.pop("adr_name"))
adr.pop('created_at', None)
adr.pop('updated_at', None)
adr.pop('id', None)
if ad_rule: if ad_rule:
rule['adr_id'] = ad_rule.id rule['adr_id'] = ad_rule.id
ad_rule.update(**adr)
elif adr:
ad_rule = AutoDiscoveryRuleCRUD().add(**adr)
rule['adr_id'] = ad_rule.id
else:
continue
rule.pop("id", None) rule.pop("id", None)
rule.pop("created_at", None) rule.pop("created_at", None)
rule.pop("updated_at", None) rule.pop("updated_at", None)
rule['uid'] = current_user.uid rule['uid'] = current_user.uid
try:
AutoDiscoveryCITypeCRUD.add(**rule) existed = False
except Exception as e: for i in AutoDiscoveryCIType.get_by(type_id=ci_type.id, adr_id=rule['adr_id'], to_dict=False):
current_app.logger.warning("import auto discovery rules failed: {}".format(e)) if ((i.extra_option or {}).get('alias') or None) == (
(rule.get('extra_option') or {}).get('alias') or None):
existed = True
AutoDiscoveryCITypeCRUD().update(i.id, **rule)
break
if not existed:
try:
AutoDiscoveryCITypeCRUD().add(**rule)
except Exception as e:
current_app.logger.warning("import auto discovery rules failed: {}".format(e))
@staticmethod
def _import_icons(icons):
from api.lib.common_setting.upload_file import CommonFileCRUD
for icon_name in icons:
if icons[icon_name]:
try:
CommonFileCRUD().save_str_to_file(icon_name, icons[icon_name])
except Exception as e:
current_app.logger.warning("save icon failed: {}".format(e))
def import_template(self, tpt): def import_template(self, tpt):
import time import time
s = time.time() s = time.time()
self._import_attributes(tpt.get('type2attributes') or {}) attr_id_map = self._import_attributes(tpt.get('type2attributes') or {})
current_app.logger.info('import attributes cost: {}'.format(time.time() - s)) current_app.logger.info('import attributes cost: {}'.format(time.time() - s))
s = time.time() s = time.time()
self._import_ci_types(tpt.get('ci_types') or []) ci_type_id_map = self._import_ci_types(tpt.get('ci_types') or [], attr_id_map)
current_app.logger.info('import ci_types cost: {}'.format(time.time() - s)) current_app.logger.info('import ci_types cost: {}'.format(time.time() - s))
s = time.time() s = time.time()
self._import_ci_type_groups(tpt.get('ci_type_groups') or []) self._import_ci_type_groups(tpt.get('ci_type_groups') or [], ci_type_id_map)
current_app.logger.info('import ci_type_groups cost: {}'.format(time.time() - s)) current_app.logger.info('import ci_type_groups cost: {}'.format(time.time() - s))
s = time.time() s = time.time()
self._import_relation_types(tpt.get('relation_types') or []) relation_type_id_map = self._import_relation_types(tpt.get('relation_types') or [])
current_app.logger.info('import relation_types cost: {}'.format(time.time() - s)) current_app.logger.info('import relation_types cost: {}'.format(time.time() - s))
s = time.time() s = time.time()
self._import_ci_type_relations(tpt.get('ci_type_relations') or []) self._import_ci_type_relations(tpt.get('ci_type_relations') or [], ci_type_id_map, relation_type_id_map)
current_app.logger.info('import ci_type_relations cost: {}'.format(time.time() - s)) current_app.logger.info('import ci_type_relations cost: {}'.format(time.time() - s))
s = time.time() s = time.time()
self._import_type_attributes(tpt.get('type2attributes') or {}) self._import_type_attributes(tpt.get('type2attributes') or {}, ci_type_id_map, attr_id_map)
current_app.logger.info('import type2attributes cost: {}'.format(time.time() - s)) current_app.logger.info('import type2attributes cost: {}'.format(time.time() - s))
s = time.time() s = time.time()
self._import_attribute_group(tpt.get('type2attribute_group') or {}) self._import_attribute_group(tpt.get('type2attribute_group') or {}, ci_type_id_map, attr_id_map)
current_app.logger.info('import type2attribute_group cost: {}'.format(time.time() - s)) current_app.logger.info('import type2attribute_group cost: {}'.format(time.time() - s))
s = time.time() s = time.time()
self._import_auto_discovery_rules(tpt.get('ci_type_auto_discovery_rules') or []) self._import_auto_discovery_rules(tpt.get('ci_type_auto_discovery_rules') or [])
current_app.logger.info('import ci_type_auto_discovery_rules cost: {}'.format(time.time() - s)) current_app.logger.info('import ci_type_auto_discovery_rules cost: {}'.format(time.time() - s))
s = time.time()
self._import_icons(tpt.get('icons') or {})
current_app.logger.info('import icons cost: {}'.format(time.time() - s))
@staticmethod @staticmethod
def export_template(): def export_template():
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryCITypeCRUD from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryCITypeCRUD
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryRuleCRUD from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryRuleCRUD
from api.lib.common_setting.upload_file import CommonFileCRUD
tpt = dict(
ci_types=CITypeManager.get_ci_types(),
ci_type_groups=CITypeGroupManager.get(),
relation_types=[i.to_dict() for i in RelationTypeManager.get_all()],
ci_type_relations=CITypeRelationManager.get(),
ci_type_auto_discovery_rules=list(),
type2attributes=dict(),
type2attribute_group=dict(),
icons=dict()
)
def get_icon_value(icon):
try:
return CommonFileCRUD().get_file_binary_str(icon)
except:
return ""
ad_rules = AutoDiscoveryCITypeCRUD.get_all() ad_rules = AutoDiscoveryCITypeCRUD.get_all()
rules = [] rules = []
@@ -1116,23 +1236,91 @@ class CITypeTemplateManager(object):
if r.get('adr_id'): if r.get('adr_id'):
adr = AutoDiscoveryRuleCRUD.get_by_id(r.pop('adr_id')) adr = AutoDiscoveryRuleCRUD.get_by_id(r.pop('adr_id'))
r['adr_name'] = adr and adr.name r['adr_name'] = adr and adr.name
r['adr'] = adr and adr.to_dict() or {}
icon_url = r['adr'].get('option', {}).get('icon', {}).get('url')
if icon_url and icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
rules.append(r) rules.append(r)
tpt = dict( tpt['ci_type_auto_discovery_rules'] = rules
ci_types=CITypeManager.get_ci_types(),
ci_type_groups=CITypeGroupManager.get(),
relation_types=[i.to_dict() for i in RelationTypeManager.get_all()],
ci_type_relations=CITypeRelationManager.get(),
ci_type_auto_discovery_rules=rules,
type2attributes=dict(),
type2attribute_group=dict()
)
for ci_type in tpt['ci_types']: for ci_type in tpt['ci_types']:
if ci_type['icon'] and len(ci_type['icon'].split('$$')) > 3:
icon_url = ci_type['icon'].split('$$')[3]
if icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
tpt['type2attributes'][ci_type['id']] = CITypeAttributeManager.get_attributes_by_type_id( tpt['type2attributes'][ci_type['id']] = CITypeAttributeManager.get_attributes_by_type_id(
ci_type['id'], choice_web_hook_parse=False, choice_other_parse=False) ci_type['id'], choice_web_hook_parse=False, choice_other_parse=False)
for attr in tpt['type2attributes'][ci_type['id']]:
for i in (attr.get('choice_value') or []):
if (i[1] or {}).get('icon', {}).get('url') and len(i[1]['icon']['url'].split('$$')) > 3:
icon_url = i[1]['icon']['url'].split('$$')[3]
if icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
tpt['type2attribute_group'][ci_type['id']] = CITypeAttributeGroupManager.get_by_type_id(ci_type['id'])
return tpt
@staticmethod
def export_template_by_type(type_id):
ci_type = CITypeCache.get(type_id) or abort(404, ErrFormat.ci_type_not_found2.format("id={}".format(type_id)))
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryCITypeCRUD
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryRuleCRUD
from api.lib.common_setting.upload_file import CommonFileCRUD
tpt = dict(
ci_types=CITypeManager.get_ci_types(type_name=ci_type.name, like=False),
ci_type_auto_discovery_rules=list(),
type2attributes=dict(),
type2attribute_group=dict(),
icons=dict()
)
def get_icon_value(icon):
try:
return CommonFileCRUD().get_file_binary_str(icon)
except:
return ""
ad_rules = AutoDiscoveryCITypeCRUD.get_by_type_id(ci_type.id)
rules = []
for r in ad_rules:
r = r.to_dict()
r['type_name'] = ci_type and ci_type.name
if r.get('adr_id'):
adr = AutoDiscoveryRuleCRUD.get_by_id(r.pop('adr_id'))
r['adr_name'] = adr and adr.name
r['adr'] = adr and adr.to_dict() or {}
icon_url = r['adr'].get('option', {}).get('icon', {}).get('url')
if icon_url and icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
rules.append(r)
tpt['ci_type_auto_discovery_rules'] = rules
for ci_type in tpt['ci_types']:
if ci_type['icon'] and len(ci_type['icon'].split('$$')) > 3:
icon_url = ci_type['icon'].split('$$')[3]
if icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
tpt['type2attributes'][ci_type['id']] = CITypeAttributeManager.get_attributes_by_type_id(
ci_type['id'], choice_web_hook_parse=False, choice_other_parse=False)
for attr in tpt['type2attributes'][ci_type['id']]:
for i in (attr.get('choice_value') or []):
if (i[1] or {}).get('icon', {}).get('url') and len(i[1]['icon']['url'].split('$$')) > 3:
icon_url = i[1]['icon']['url'].split('$$')[3]
if icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
tpt['type2attribute_group'][ci_type['id']] = CITypeAttributeGroupManager.get_by_type_id(ci_type['id']) tpt['type2attribute_group'][ci_type['id']] = CITypeAttributeGroupManager.get_by_type_id(ci_type['id'])
return tpt return tpt

View File

@@ -69,6 +69,7 @@ class ResourceTypeEnum(BaseEnum):
CI_TYPE_RELATION = "CITypeRelation" # create/delete/grant CI_TYPE_RELATION = "CITypeRelation" # create/delete/grant
RELATION_VIEW = "RelationView" # read/update/delete/grant RELATION_VIEW = "RelationView" # read/update/delete/grant
CI_FILTER = "CIFilter" # read CI_FILTER = "CIFilter" # read
PAGE = "page" # read
class PermEnum(BaseEnum): class PermEnum(BaseEnum):

View File

@@ -114,6 +114,8 @@ class CIFilterPermsCRUD(DBMixin):
obj.soft_delete() obj.soft_delete()
return obj
else: else:
if not kwargs.get('ci_filter') and not kwargs.get('attr_filter'): if not kwargs.get('ci_filter') and not kwargs.get('attr_filter'):
return return
@@ -143,11 +145,14 @@ class CIFilterPermsCRUD(DBMixin):
first=True, to_dict=False) first=True, to_dict=False)
if obj is not None: if obj is not None:
resource = None
if current_app.config.get('USE_ACL'): if current_app.config.get('USE_ACL'):
ACLManager().del_resource(str(obj.id), ResourceTypeEnum.CI_FILTER) resource = ACLManager().del_resource(str(obj.id), ResourceTypeEnum.CI_FILTER)
obj.soft_delete() obj.soft_delete()
return resource
def has_perm_for_ci(arg_name, resource_type, perm, callback=None, app=None): def has_perm_for_ci(arg_name, resource_type, perm, callback=None, app=None):
def decorator_has_perm(func): def decorator_has_perm(func):

View File

@@ -2,7 +2,6 @@
import copy import copy
import six import six
import toposort import toposort
from flask import abort from flask import abort
@@ -14,6 +13,7 @@ from api.lib.cmdb.attribute import AttributeManager
from api.lib.cmdb.cache import AttributeCache from api.lib.cmdb.cache import AttributeCache
from api.lib.cmdb.cache import CITypeAttributesCache from api.lib.cmdb.cache import CITypeAttributesCache
from api.lib.cmdb.cache import CITypeCache from api.lib.cmdb.cache import CITypeCache
from api.lib.cmdb.cache import CMDBCounterCache
from api.lib.cmdb.const import ConstraintEnum from api.lib.cmdb.const import ConstraintEnum
from api.lib.cmdb.const import PermEnum from api.lib.cmdb.const import PermEnum
from api.lib.cmdb.const import ResourceTypeEnum from api.lib.cmdb.const import ResourceTypeEnum
@@ -24,6 +24,7 @@ from api.lib.exception import AbortException
from api.lib.perm.acl.acl import ACLManager from api.lib.perm.acl.acl import ACLManager
from api.models.cmdb import CITypeAttribute from api.models.cmdb import CITypeAttribute
from api.models.cmdb import CITypeRelation from api.models.cmdb import CITypeRelation
from api.models.cmdb import PreferenceCITypeOrder
from api.models.cmdb import PreferenceRelationView from api.models.cmdb import PreferenceRelationView
from api.models.cmdb import PreferenceSearchOption from api.models.cmdb import PreferenceSearchOption
from api.models.cmdb import PreferenceShowAttributes from api.models.cmdb import PreferenceShowAttributes
@@ -38,13 +39,22 @@ class PreferenceManager(object):
@staticmethod @staticmethod
def get_types(instance=False, tree=False): def get_types(instance=False, tree=False):
ci_type_order = sorted(PreferenceCITypeOrder.get_by(uid=current_user.uid, to_dict=False), key=lambda x: x.order)
types = db.session.query(PreferenceShowAttributes.type_id).filter( types = db.session.query(PreferenceShowAttributes.type_id).filter(
PreferenceShowAttributes.uid == current_user.uid).filter( PreferenceShowAttributes.uid == current_user.uid).filter(
PreferenceShowAttributes.deleted.is_(False)).group_by( PreferenceShowAttributes.deleted.is_(False)).group_by(
PreferenceShowAttributes.type_id).all() if instance else [] PreferenceShowAttributes.type_id).all() if instance else []
types = sorted(types, key=lambda x: {i.type_id: idx for idx, i in enumerate(
ci_type_order) if not i.is_tree}.get(x.type_id, 1))
tree_types = PreferenceTreeView.get_by(uid=current_user.uid, to_dict=False) if tree else [] tree_types = PreferenceTreeView.get_by(uid=current_user.uid, to_dict=False) if tree else []
type_ids = set([i.type_id for i in types + tree_types]) tree_types = sorted(tree_types, key=lambda x: {i.type_id: idx for idx, i in enumerate(
ci_type_order) if i.is_tree}.get(x.type_id, 1))
type_ids = [i.type_id for i in types + tree_types]
if types and tree_types:
type_ids = set(type_ids)
return [CITypeCache.get(type_id).to_dict() for type_id in type_ids] return [CITypeCache.get(type_id).to_dict() for type_id in type_ids]
@@ -59,32 +69,36 @@ class PreferenceManager(object):
:param tree: :param tree:
:return: :return:
""" """
result = dict(self=dict(instance=[], tree=[], type_id2subs_time=dict()), result = dict(self=dict(instance=[], tree=[], type_id2subs_time=dict()))
type_id2users=dict())
result.update(CMDBCounterCache.get_sub_counter())
ci_type_order = sorted(PreferenceCITypeOrder.get_by(uid=current_user.uid, to_dict=False), key=lambda x: x.order)
if instance: if instance:
types = db.session.query(PreferenceShowAttributes.type_id, types = db.session.query(PreferenceShowAttributes.type_id,
PreferenceShowAttributes.uid, PreferenceShowAttributes.created_at).filter( PreferenceShowAttributes.uid, PreferenceShowAttributes.created_at).filter(
PreferenceShowAttributes.deleted.is_(False)).group_by( PreferenceShowAttributes.deleted.is_(False)).filter(
PreferenceShowAttributes.uid == current_user.uid).group_by(
PreferenceShowAttributes.uid, PreferenceShowAttributes.type_id) PreferenceShowAttributes.uid, PreferenceShowAttributes.type_id)
for i in types: for i in types:
if i.uid == current_user.uid: result['self']['instance'].append(i.type_id)
result['self']['instance'].append(i.type_id) if str(i.created_at) > str(result['self']['type_id2subs_time'].get(i.type_id, "")):
if str(i.created_at) > str(result['self']['type_id2subs_time'].get(i.type_id, "")): result['self']['type_id2subs_time'][i.type_id] = i.created_at
result['self']['type_id2subs_time'][i.type_id] = i.created_at
result['type_id2users'].setdefault(i.type_id, []).append(i.uid) instance_order = [i.type_id for i in ci_type_order if not i.is_tree]
if len(instance_order) == len(result['self']['instance']):
result['self']['instance'] = instance_order
if tree: if tree:
types = PreferenceTreeView.get_by(to_dict=False) types = PreferenceTreeView.get_by(uid=current_user.uid, to_dict=False)
for i in types: for i in types:
if i.uid == current_user.uid: result['self']['tree'].append(i.type_id)
result['self']['tree'].append(i.type_id) if str(i.created_at) > str(result['self']['type_id2subs_time'].get(i.type_id, "")):
if str(i.created_at) > str(result['self']['type_id2subs_time'].get(i.type_id, "")): result['self']['type_id2subs_time'][i.type_id] = i.created_at
result['self']['type_id2subs_time'][i.type_id] = i.created_at
result['type_id2users'].setdefault(i.type_id, []) tree_order = [i.type_id for i in ci_type_order if i.is_tree]
if i.uid not in result['type_id2users'][i.type_id]: if len(tree_order) == len(result['self']['tree']):
result['type_id2users'][i.type_id].append(i.uid) result['self']['tree'] = tree_order
return result return result
@@ -151,9 +165,22 @@ class PreferenceManager(object):
if i.attr_id not in attr_dict: if i.attr_id not in attr_dict:
i.soft_delete() i.soft_delete()
if not existed_all and attr_order:
cls.add_ci_type_order_item(type_id, is_tree=False)
elif not PreferenceShowAttributes.get_by(type_id=type_id, uid=current_user.uid, to_dict=False):
cls.delete_ci_type_order_item(type_id, is_tree=False)
@staticmethod @staticmethod
def get_tree_view(): def get_tree_view():
ci_type_order = sorted(PreferenceCITypeOrder.get_by(uid=current_user.uid, is_tree=True, to_dict=False),
key=lambda x: x.order)
res = PreferenceTreeView.get_by(uid=current_user.uid, to_dict=True) res = PreferenceTreeView.get_by(uid=current_user.uid, to_dict=True)
if ci_type_order:
res = sorted(res, key=lambda x: {ii.type_id: idx for idx, ii in enumerate(
ci_type_order)}.get(x['type_id'], 1))
for item in res: for item in res:
if item["levels"]: if item["levels"]:
ci_type = CITypeCache.get(item['type_id']).to_dict() ci_type = CITypeCache.get(item['type_id']).to_dict()
@@ -172,8 +199,8 @@ class PreferenceManager(object):
return res return res
@staticmethod @classmethod
def create_or_update_tree_view(type_id, levels): def create_or_update_tree_view(cls, type_id, levels):
attrs = CITypeAttributesCache.get(type_id) attrs = CITypeAttributesCache.get(type_id)
for idx, i in enumerate(levels): for idx, i in enumerate(levels):
for attr in attrs: for attr in attrs:
@@ -185,9 +212,12 @@ class PreferenceManager(object):
if existed is not None: if existed is not None:
if not levels: if not levels:
existed.soft_delete() existed.soft_delete()
cls.delete_ci_type_order_item(type_id, is_tree=True)
return existed return existed
return existed.update(levels=levels) return existed.update(levels=levels)
elif levels: elif levels:
cls.add_ci_type_order_item(type_id, is_tree=True)
return PreferenceTreeView.create(levels=levels, type_id=type_id, uid=current_user.uid) return PreferenceTreeView.create(levels=levels, type_id=type_id, uid=current_user.uid)
@staticmethod @staticmethod
@@ -356,6 +386,9 @@ class PreferenceManager(object):
for i in PreferenceTreeView.get_by(type_id=type_id, uid=uid, to_dict=False): for i in PreferenceTreeView.get_by(type_id=type_id, uid=uid, to_dict=False):
i.soft_delete() i.soft_delete()
for i in PreferenceCITypeOrder.get_by(type_id=type_id, uid=uid, to_dict=False):
i.soft_delete()
@staticmethod @staticmethod
def can_edit_relation(parent_id, child_id): def can_edit_relation(parent_id, child_id):
views = PreferenceRelationView.get_by(to_dict=False) views = PreferenceRelationView.get_by(to_dict=False)
@@ -381,3 +414,36 @@ class PreferenceManager(object):
return False return False
return True return True
@staticmethod
def add_ci_type_order_item(type_id, is_tree=False):
max_order = PreferenceCITypeOrder.get_by(
uid=current_user.uid, is_tree=is_tree, only_query=True).order_by(PreferenceCITypeOrder.order.desc()).first()
order = (max_order and max_order.order + 1) or 1
PreferenceCITypeOrder.create(type_id=type_id, is_tree=is_tree, uid=current_user.uid, order=order)
@staticmethod
def delete_ci_type_order_item(type_id, is_tree=False):
existed = PreferenceCITypeOrder.get_by(uid=current_user.uid, type_id=type_id, is_tree=is_tree,
first=True, to_dict=False)
existed and existed.soft_delete()
@staticmethod
def upsert_ci_type_order(type_ids, is_tree=False):
for idx, type_id in enumerate(type_ids):
order = idx + 1
existed = PreferenceCITypeOrder.get_by(uid=current_user.uid, type_id=type_id, is_tree=is_tree,
to_dict=False, first=True)
if existed is not None:
existed.update(order=order, flush=True)
else:
PreferenceCITypeOrder.create(uid=current_user.uid, type_id=type_id, is_tree=is_tree, order=order,
flush=True)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
current_app.logger.error("upsert citype order failed: {}".format(e))
return abort(400, ErrFormat.unknown_error)

View File

@@ -1,101 +1,138 @@
# -*- coding:utf-8 -*- # -*- coding:utf-8 -*-
from flask_babel import lazy_gettext as _l
from api.lib.resp_format import CommonErrFormat from api.lib.resp_format import CommonErrFormat
class ErrFormat(CommonErrFormat): class ErrFormat(CommonErrFormat):
invalid_relation_type = "无效的关系类型: {}" ci_type_config = _l("CI Model") # 模型配置
ci_type_not_found = "模型不存在!"
argument_attributes_must_be_list = "参数 attributes 类型必须是列表"
argument_file_not_found = "文件似乎并未上传"
attribute_not_found = "属性 {} 不存在!" invalid_relation_type = _l("Invalid relation type: {}") # 无效的关系类型: {}
attribute_is_unique_id = "该属性是模型的唯一标识,不能被删除!" ci_type_not_found = _l("CIType is not found") # 模型不存在!
attribute_is_ref_by_type = "该属性被模型 {} 引用, 不能删除!"
attribute_value_type_cannot_change = "属性的值类型不允许修改!"
attribute_list_value_cannot_change = "多值不被允许修改!"
attribute_index_cannot_change = "修改索引 非管理员不被允许!"
attribute_index_change_failed = "索引切换失败!"
invalid_choice_values = "预定义值的类型不对!"
attribute_name_duplicate = "重复的属性名 {}"
add_attribute_failed = "创建属性 {} 失败!"
update_attribute_failed = "修改属性 {} 失败!"
cannot_edit_attribute = "您没有权限修改该属性!"
cannot_delete_attribute = "目前只允许 属性创建人、管理员 删除属性!"
attribute_name_cannot_be_builtin = "属性字段名不能是内置字段: id, _id, ci_id, type, _type, ci_type"
attribute_choice_other_invalid = "预定义值: 其他模型请求参数不合法!"
ci_not_found = "CI {} 不存在" # 参数 attributes 类型必须是列表
unique_constraint = "多属性联合唯一校验不通过: {}" argument_attributes_must_be_list = _l("The type of parameter attributes must be a list")
unique_value_not_found = "模型的主键 {} 不存在!" argument_file_not_found = _l("The file doesn't seem to be uploaded") # 文件似乎并未上传
unique_key_required = "主键字段 {} 缺失"
ci_is_already_existed = "CI 已经存在!"
relation_constraint = "关系约束: {}, 校验失败 "
m2m_relation_constraint = "多对多关系 限制: 模型 {} <-> {} 已经存在多对多关系!"
relation_not_found = "CI关系: {} 不存在"
ci_search_Parentheses_invalid = "搜索表达式里小括号前不支持: 或、非"
ci_type_not_found2 = "模型 {} 不存在" attribute_not_found = _l("Attribute {} does not exist!") # 属性 {} 不存在!
ci_type_is_already_existed = "模型 {} 已经存在" attribute_is_unique_id = _l(
unique_key_not_define = "主键未定义或者已被删除" "This attribute is the unique identifier of the model and cannot be deleted!") # 该属性是模型的唯一标识,不能被删除!
only_owner_can_delete = "只有创建人才能删除它!" attribute_is_ref_by_type = _l(
ci_exists_and_cannot_delete_type = "因为CI已经存在不能删除模型" "This attribute is referenced by model {} and cannot be deleted!") # 该属性被模型 {} 引用, 不能删除!
ci_relation_view_exists_and_cannot_delete_type = "因为关系视图 {} 引用了该模型,不能删除模型" attribute_value_type_cannot_change = _l(
ci_type_group_not_found = "模型分组 {} 不存在" "The value type of the attribute is not allowed to be modified!") # 属性的值类型不允许修改!
ci_type_group_exists = "模型分组 {} 已经存在" attribute_list_value_cannot_change = _l("Multiple values are not allowed to be modified!") # 多值不被允许修改!
ci_type_relation_not_found = "模型关系 {} 不存在" # 修改索引 非管理员不被允许!
ci_type_attribute_group_duplicate = "属性分组 {} 已存在" attribute_index_cannot_change = _l("Modifying the index is not allowed for non-administrators!")
ci_type_attribute_group_not_found = "属性分组 {} 不存在" attribute_index_change_failed = _l("Index switching failed!") # 索引切换失败!
ci_type_group_attribute_not_found = "属性组<{0}> - 属性<{1}> 不存在" invalid_choice_values = _l("The predefined value is of the wrong type!") # 预定义值的类型不对!
unique_constraint_duplicate = "唯一约束已经存在!" attribute_name_duplicate = _l("Duplicate attribute name {}") # 重复的属性名 {}
unique_constraint_invalid = "唯一约束的属性不能是 JSON 和 多值" add_attribute_failed = _l("Failed to create attribute {}!") # 创建属性 {} 失败!
ci_type_trigger_duplicate = "重复的触发器" update_attribute_failed = _l("Modify attribute {} failed!") # 修改属性 {} 失败!
ci_type_trigger_not_found = "触发器 {} 不存在" cannot_edit_attribute = _l("You do not have permission to modify this attribute!") # 您没有权限修改该属性!
cannot_delete_attribute = _l(
"Only creators and administrators are allowed to delete attributes!") # 目前只允许 属性创建人、管理员 删除属性!
# 属性字段名不能是内置字段: id, _id, ci_id, type, _type, ci_type
attribute_name_cannot_be_builtin = _l(
"Attribute field names cannot be built-in fields: id, _id, ci_id, type, _type, ci_type")
attribute_choice_other_invalid = _l(
"Predefined value: Other model request parameters are illegal!") # 预定义值: 其他模型请求参数不合法!
record_not_found = "操作记录 {} 不存在" ci_not_found = _l("CI {} does not exist") # CI {} 不存在
cannot_delete_unique = "不能删除唯一标识" unique_constraint = _l("Multiple attribute joint unique verification failed: {}") # 多属性联合唯一校验不通过: {}
cannot_delete_default_order_attr = "不能删除默认排序的属性" unique_value_not_found = _l("The model's primary key {} does not exist!") # 模型的主键 {} 不存在!
unique_key_required = _l("Primary key {} is missing") # 主键字段 {} 缺失
ci_is_already_existed = _l("CI already exists!") # CI 已经存在!
relation_constraint = _l("Relationship constraint: {}, verification failed") # 关系约束: {}, 校验失败
# 多对多关系 限制: 模型 {} <-> {} 已经存在多对多关系!
m2m_relation_constraint = _l(
"Many-to-many relationship constraint: Model {} <-> {} already has a many-to-many relationship!")
preference_relation_view_node_required = "没有选择节点" relation_not_found = _l("CI relationship: {} does not exist") # CI关系: {} 不存在
preference_search_option_not_found = "该搜索选项不存在!"
preference_search_option_exists = "该搜索选项命名重复!"
relation_type_exists = "关系类型 {} 已经存在" # 搜索表达式里小括号前不支持: 或、非
relation_type_not_found = "关系类型 {} 不存在" ci_search_Parentheses_invalid = _l("In search expressions, not supported before parentheses: or, not")
attribute_value_invalid = "无效的属性值: {}" ci_type_not_found2 = _l("Model {} does not exist") # 模型 {} 不存在
attribute_value_invalid2 = "{} 无效的值: {}" ci_type_is_already_existed = _l("Model {} already exists") # 模型 {} 已经存在
not_in_choice_values = "{} 不在预定义值里" unique_key_not_define = _l("The primary key is undefined or has been deleted") # 主键未定义或者已被删除
attribute_value_unique_required = "属性 {} 的值必须是唯一的, 当前值 {} 已存在" only_owner_can_delete = _l("Only the creator can delete it!") # 只有创建人才能删除它!
attribute_value_required = "属性 {} 值必须存在" ci_exists_and_cannot_delete_type = _l(
attribute_value_unknown_error = "新增或者修改属性值未知错误: {}" "The model cannot be deleted because the CI already exists") # 因为CI已经存在不能删除模型
custom_name_duplicate = "订制名重复" # 因为关系视图 {} 引用了该模型,不能删除模型
ci_relation_view_exists_and_cannot_delete_type = _l(
"The model cannot be deleted because the model is referenced by the relational view {}")
ci_type_group_not_found = _l("Model group {} does not exist") # 模型分组 {} 不存在
ci_type_group_exists = _l("Model group {} already exists") # 模型分组 {} 已经存在
ci_type_relation_not_found = _l("Model relationship {} does not exist") # 模型关系 {} 不存在
ci_type_attribute_group_duplicate = _l("Attribute group {} already exists") # 属性分组 {} 已存在
ci_type_attribute_group_not_found = _l("Attribute group {} does not exist") # 属性分组 {} 不存在
# 属性组<{0}> - 属性<{1}> 不存在
ci_type_group_attribute_not_found = _l("Attribute group <{0}> - attribute <{1}> does not exist")
unique_constraint_duplicate = _l("The unique constraint already exists!") # 唯一约束已经存在!
# 唯一约束的属性不能是 JSON 和 多值
unique_constraint_invalid = _l("Uniquely constrained attributes cannot be JSON and multi-valued")
ci_type_trigger_duplicate = _l("Duplicated trigger") # 重复的触发器
ci_type_trigger_not_found = _l("Trigger {} does not exist") # 触发器 {} 不存在
limit_ci_type = "模型数超过限制: {}" record_not_found = _l("Operation record {} does not exist") # 操作记录 {} 不存在
limit_ci = "CI数超过限制: {}" cannot_delete_unique = _l("Unique identifier cannot be deleted") # 不能删除唯一标识
cannot_delete_default_order_attr = _l("Cannot delete default sorted attributes") # 不能删除默认排序的属性
adr_duplicate = "自动发现规则: {} 已经存在!" preference_relation_view_node_required = _l("No node selected") # 没有选择节点
adr_not_found = "自动发现规则: {} 不存在!" preference_search_option_not_found = _l("This search option does not exist!") # 该搜索选项不存在!
adr_referenced = "该自动发现规则被模型引用, 不能删除!" preference_search_option_exists = _l("This search option has a duplicate name!") # 该搜索选项命名重复!
ad_duplicate = "自动发现规则的应用不能重复定义!"
ad_not_found = "您要修改的自动发现: {} 不存在!"
ad_not_unique_key = "属性字段没有包括唯一标识: {}"
adc_not_found = "自动发现的实例不存在!"
adt_not_found = "模型并未关联该自动发现!"
adt_secret_no_permission = "只有创建人才能修改Secret!"
cannot_delete_adt = "该规则已经有自动发现的实例, 不能被删除!"
adr_default_ref_once = "该默认的自动发现规则 已经被模型 {} 引用!"
adr_unique_key_required = "unique_key方法必须返回非空字符串!"
adr_plugin_attributes_list_required = "attributes方法必须返回的是list"
adr_plugin_attributes_list_no_empty = "attributes方法返回的list不能为空!"
adt_target_all_no_permission = "只有管理员才可以定义执行机器为: 所有节点!"
adt_target_expr_no_permission = "执行机器权限检查不通过: {}"
ci_filter_name_cannot_be_empty = "CI过滤授权 必须命名!" relation_type_exists = _l("Relationship type {} already exists") # 关系类型 {} 已经存在
ci_filter_perm_cannot_or_query = "CI过滤授权 暂时不支持 或 查询" relation_type_not_found = _l("Relationship type {} does not exist") # 关系类型 {} 不存在
ci_filter_perm_attr_no_permission = "您没有属性 {} 的操作权限!"
ci_filter_perm_ci_no_permission = "您没有该CI的操作权限!"
password_save_failed = "保存密码失败: {}" attribute_value_invalid = _l("Invalid attribute value: {}") # 无效的属性值: {}
password_load_failed = "获取密码失败: {}" attribute_value_invalid2 = _l("{} Invalid value: {}") # {} 无效的值: {}
not_in_choice_values = _l("{} is not in the predefined values") # {} 不在预定义值里
# 属性 {} 的值必须是唯一的, 当前值 {} 已存在
attribute_value_unique_required = _l("The value of attribute {} must be unique, {} already exists")
attribute_value_required = _l("Attribute {} value must exist") # 属性 {} 值必须存在
# 新增或者修改属性值未知错误: {}
attribute_value_unknown_error = _l("Unknown error when adding or modifying attribute value: {}")
custom_name_duplicate = _l("Duplicate custom name") # 订制名重复
limit_ci_type = _l("Number of models exceeds limit: {}") # 模型数超过限制: {}
limit_ci = _l("The number of CIs exceeds the limit: {}") # CI数超过限制: {}
adr_duplicate = _l("Auto-discovery rule: {} already exists!") # 自动发现规则: {} 已经存在!
adr_not_found = _l("Auto-discovery rule: {} does not exist!") # 自动发现规则: {} 不存在!
# 该自动发现规则被模型引用, 不能删除!
adr_referenced = _l("This auto-discovery rule is referenced by the model and cannot be deleted!")
# 自动发现规则的应用不能重复定义!
ad_duplicate = _l("The application of auto-discovery rules cannot be defined repeatedly!")
ad_not_found = _l("The auto-discovery you want to modify: {} does not exist!") # 您要修改的自动发现: {} 不存在!
ad_not_unique_key = _l("Attribute does not include unique identifier: {}") # 属性字段没有包括唯一标识: {}
adc_not_found = _l("The auto-discovery instance does not exist!") # 自动发现的实例不存在!
adt_not_found = _l("The model is not associated with this auto-discovery!") # 模型并未关联该自动发现!
adt_secret_no_permission = _l("Only the creator can modify the Secret!") # 只有创建人才能修改Secret!
# 该规则已经有自动发现的实例, 不能被删除!
cannot_delete_adt = _l("This rule already has auto-discovery instances and cannot be deleted!")
# 该默认的自动发现规则 已经被模型 {} 引用!
adr_default_ref_once = _l("The default auto-discovery rule is already referenced by model {}!")
# unique_key方法必须返回非空字符串!
adr_unique_key_required = _l("The unique_key method must return a non-empty string!")
adr_plugin_attributes_list_required = _l("The attributes method must return a list") # attributes方法必须返回的是list
# attributes方法返回的list不能为空!
adr_plugin_attributes_list_no_empty = _l("The list returned by the attributes method cannot be empty!")
# 只有管理员才可以定义执行机器为: 所有节点!
adt_target_all_no_permission = _l("Only administrators can define execution targets as: all nodes!")
adt_target_expr_no_permission = _l("Execute targets permission check failed: {}") # 执行机器权限检查不通过: {}
ci_filter_name_cannot_be_empty = _l("CI filter authorization must be named!") # CI过滤授权 必须命名!
ci_filter_perm_cannot_or_query = _l(
"CI filter authorization is currently not supported or query") # CI过滤授权 暂时不支持 或 查询
# 您没有属性 {} 的操作权限!
ci_filter_perm_attr_no_permission = _l("You do not have permission to operate attribute {}!")
ci_filter_perm_ci_no_permission = _l("You do not have permission to operate this CI!") # 您没有该CI的操作权限!
password_save_failed = _l("Failed to save password: {}") # 保存密码失败: {}
password_load_failed = _l("Failed to get password: {}") # 获取密码失败: {}

View File

@@ -28,7 +28,8 @@ class Search(object):
count=None, count=None,
sort=None, sort=None,
reverse=False, reverse=False,
ancestor_ids=None): ancestor_ids=None,
has_m2m=None):
self.orig_query = query self.orig_query = query
self.fl = fl self.fl = fl
self.facet_field = facet_field self.facet_field = facet_field
@@ -45,14 +46,15 @@ class Search(object):
level[0] if isinstance(level, list) and level else level) level[0] if isinstance(level, list) and level else level)
self.ancestor_ids = ancestor_ids self.ancestor_ids = ancestor_ids
self.has_m2m = False self.has_m2m = has_m2m or False
if self.ancestor_ids: if not self.has_m2m:
self.has_m2m = True if self.ancestor_ids:
else: self.has_m2m = True
level = level[0] if isinstance(level, list) and level else level else:
for _l, c in self.level2constraint.items(): level = level[0] if isinstance(level, list) and level else level
if _l < int(level) and c == ConstraintEnum.Many2Many: for _l, c in self.level2constraint.items():
self.has_m2m = True if _l < int(level) and c == ConstraintEnum.Many2Many:
self.has_m2m = True
def _get_ids(self, ids): def _get_ids(self, ids):
if self.level[-1] == 1 and len(ids) == 1: if self.level[-1] == 1 and len(ids) == 1:
@@ -90,12 +92,12 @@ class Search(object):
key = list(set(["{},{}".format(i, j) for idx, i in enumerate(key) for j in _tmp[idx]])) key = list(set(["{},{}".format(i, j) for idx, i in enumerate(key) for j in _tmp[idx]]))
prefix = REDIS_PREFIX_CI_RELATION2 prefix = REDIS_PREFIX_CI_RELATION2
_tmp = list(map(lambda x: json.loads(x).keys() if x else [], rd.get(key, prefix) or []))
ids = [j for i in _tmp for j in i]
if not key: if not key:
return [] return []
_tmp = list(map(lambda x: json.loads(x).keys() if x else [], rd.get(key, prefix) or []))
ids = [j for i in _tmp for j in i]
if level in self.level: if level in self.level:
merge_ids.extend(ids) merge_ids.extend(ids)

View File

@@ -5,10 +5,10 @@ from __future__ import unicode_literals
import copy import copy
import imp import imp
import os
import tempfile
import jinja2 import jinja2
import os
import re
import tempfile
from flask import abort from flask import abort
from flask import current_app from flask import current_app
from jinja2schema import infer from jinja2schema import infer
@@ -94,8 +94,13 @@ class AttributeValueManager(object):
@staticmethod @staticmethod
def _check_is_choice(attr, value_type, value): def _check_is_choice(attr, value_type, value):
choice_values = AttributeManager.get_choice_values(attr.id, value_type, attr.choice_web_hook, attr.choice_other) choice_values = AttributeManager.get_choice_values(attr.id, value_type, attr.choice_web_hook, attr.choice_other)
if str(value) not in list(map(str, [i[0] for i in choice_values])): if value_type == ValueTypeEnum.FLOAT:
return abort(400, ErrFormat.not_in_choice_values.format(value)) if float(value) not in list(map(float, [i[0] for i in choice_values])):
return abort(400, ErrFormat.not_in_choice_values.format(value))
else:
if str(value) not in list(map(str, [i[0] for i in choice_values])):
return abort(400, ErrFormat.not_in_choice_values.format(value))
@staticmethod @staticmethod
def _check_is_unique(value_table, attr, ci_id, type_id, value): def _check_is_unique(value_table, attr, ci_id, type_id, value):
@@ -112,6 +117,11 @@ class AttributeValueManager(object):
if type_attr and type_attr.is_required and not value and value != 0: if type_attr and type_attr.is_required and not value and value != 0:
return abort(400, ErrFormat.attribute_value_required.format(attr.alias)) return abort(400, ErrFormat.attribute_value_required.format(attr.alias))
@staticmethod
def check_re(expr, value):
if not re.compile(expr).match(str(value)):
return abort(400, ErrFormat.attribute_value_invalid.format(value))
def _validate(self, attr, value, value_table, ci=None, type_id=None, ci_id=None, type_attr=None): def _validate(self, attr, value, value_table, ci=None, type_id=None, ci_id=None, type_attr=None):
ci = ci or {} ci = ci or {}
v = self._deserialize_value(attr.value_type, value) v = self._deserialize_value(attr.value_type, value)
@@ -125,6 +135,9 @@ class AttributeValueManager(object):
if v == "" and attr.value_type not in (ValueTypeEnum.TEXT,): if v == "" and attr.value_type not in (ValueTypeEnum.TEXT,):
v = None v = None
if attr.re_check and value:
self.check_re(attr.re_check, value)
return v return v
@staticmethod @staticmethod

View File

@@ -24,7 +24,15 @@ def get_all_department_list(to_dict=True):
*criterion *criterion
).order_by(Department.department_id.asc()) ).order_by(Department.department_id.asc())
results = query.all() results = query.all()
return [r.to_dict() for r in results] if to_dict else results if to_dict:
datas = []
for r in results:
d = r.to_dict()
if r.department_id == 0:
d['department_name'] = ErrFormat.company_wide
datas.append(d)
return datas
return results
def get_all_employee_list(block=0, to_dict=True): def get_all_employee_list(block=0, to_dict=True):
@@ -101,6 +109,7 @@ class DepartmentTree(object):
employees = self.get_employees_by_d_id(department_id) employees = self.get_employees_by_d_id(department_id)
top_d['employees'] = employees top_d['employees'] = employees
top_d['department_name'] = ErrFormat.company_wide
if len(sub_deps) == 0: if len(sub_deps) == 0:
top_d[sub_departments_column_name] = [] top_d[sub_departments_column_name] = []
d_list.append(top_d) d_list.append(top_d)
@@ -246,7 +255,7 @@ class DepartmentCRUD(object):
return abort(400, ErrFormat.acl_update_role_failed.format(str(e))) return abort(400, ErrFormat.acl_update_role_failed.format(str(e)))
try: try:
existed.update(**kwargs) return existed.update(**kwargs)
except Exception as e: except Exception as e:
return abort(400, str(e)) return abort(400, str(e))
@@ -313,6 +322,7 @@ class DepartmentCRUD(object):
tree_list = [] tree_list = []
for top_d in top_deps: for top_d in top_deps:
top_d['department_name'] = ErrFormat.company_wide
tree = Tree() tree = Tree()
identifier_root = top_d['department_id'] identifier_root = top_d['department_id']
tree.create_node( tree.create_node(
@@ -383,6 +393,9 @@ class DepartmentCRUD(object):
d['employee_count'] = len(list(filter(lambda e: e['department_id'] in d_ids, all_employee_list))) d['employee_count'] = len(list(filter(lambda e: e['department_id'] in d_ids, all_employee_list)))
if int(department_parent_id) == -1:
d['department_name'] = ErrFormat.company_wide
return all_departments, department_id_list return all_departments, department_id_list
@staticmethod @staticmethod

View File

@@ -15,10 +15,13 @@ from wtforms import validators
from api.extensions import db from api.extensions import db
from api.lib.common_setting.acl import ACLManager from api.lib.common_setting.acl import ACLManager
from api.lib.common_setting.const import COMMON_SETTING_QUEUE, OperatorType from api.lib.common_setting.const import OperatorType
from api.lib.cmdb.const import CMDB_QUEUE
from api.lib.common_setting.resp_format import ErrFormat from api.lib.common_setting.resp_format import ErrFormat
from api.models.common_setting import Employee, Department from api.models.common_setting import Employee, Department
from api.tasks.common_setting import refresh_employee_acl_info, edit_employee_department_in_acl
acl_user_columns = [ acl_user_columns = [
'email', 'email',
'mobile', 'mobile',
@@ -137,7 +140,9 @@ class EmployeeCRUD(object):
@staticmethod @staticmethod
def add(**kwargs): def add(**kwargs):
try: try:
return CreateEmployee().create_single(**kwargs) res = CreateEmployee().create_single(**kwargs)
refresh_employee_acl_info.apply_async(args=(), queue=CMDB_QUEUE)
return res
except Exception as e: except Exception as e:
abort(400, str(e)) abort(400, str(e))
@@ -164,10 +169,9 @@ class EmployeeCRUD(object):
existed.update(**kwargs) existed.update(**kwargs)
if len(e_list) > 0: if len(e_list) > 0:
from api.tasks.common_setting import edit_employee_department_in_acl
edit_employee_department_in_acl.apply_async( edit_employee_department_in_acl.apply_async(
args=(e_list, new_department_id, current_user.uid), args=(e_list, new_department_id, current_user.uid),
queue=COMMON_SETTING_QUEUE queue=CMDB_QUEUE
) )
return existed return existed
@@ -291,7 +295,9 @@ class EmployeeCRUD(object):
employees = [] employees = []
for r in pagination.items: for r in pagination.items:
d = r.Employee.to_dict() d = r.Employee.to_dict()
d['department_name'] = r.Department.department_name d['department_name'] = r.Department.department_name if r.Department else ''
if r.Employee.department_id == 0:
d['department_name'] = ErrFormat.company_wide
employees.append(d) employees.append(d)
return { return {
@@ -437,7 +443,7 @@ class EmployeeCRUD(object):
employees = [] employees = []
for r in pagination.items: for r in pagination.items:
d = r.Employee.to_dict() d = r.Employee.to_dict()
d['department_name'] = r.Department.department_name d['department_name'] = r.Department.department_name if r.Department else ''
employees.append(d) employees.append(d)
return { return {
@@ -571,6 +577,7 @@ class EmployeeCRUD(object):
@staticmethod @staticmethod
def import_employee(employee_list): def import_employee(employee_list):
res = CreateEmployee().batch_create(employee_list) res = CreateEmployee().batch_create(employee_list)
refresh_employee_acl_info.apply_async(args=(), queue=CMDB_QUEUE)
return res return res
@staticmethod @staticmethod
@@ -687,6 +694,27 @@ class EmployeeCRUD(object):
else: else:
abort(400, ErrFormat.column_name_not_support) abort(400, ErrFormat.column_name_not_support)
@staticmethod
def update_last_login_by_uid(uid, last_login=None):
employee = Employee.get_by(acl_uid=uid, first=True, to_dict=False)
if not employee:
return
if last_login:
try:
last_login = datetime.strptime(last_login, '%Y-%m-%d %H:%M:%S')
except Exception as e:
last_login = datetime.now()
else:
last_login = datetime.now()
try:
employee.update(
last_login=last_login
)
return last_login
except Exception as e:
return
def get_user_map(key='uid', acl=None): def get_user_map(key='uid', acl=None):
""" """

View File

@@ -1,77 +1,82 @@
# -*- coding:utf-8 -*- # -*- coding:utf-8 -*-
from flask_babel import lazy_gettext as _l
from api.lib.resp_format import CommonErrFormat from api.lib.resp_format import CommonErrFormat
class ErrFormat(CommonErrFormat): class ErrFormat(CommonErrFormat):
company_info_is_already_existed = "公司信息已存在!无法创建" company_info_is_already_existed = _l("Company info already existed") # 公司信息已存在!无法创建
no_file_part = "没有文件部分" no_file_part = _l("No file part") # 没有文件部分
file_is_required = "文件是必须的" file_is_required = _l("File is required") # 文件是必须的
file_not_found = "文件不存在" file_not_found = _l("File not found") # 文件不存在
file_type_not_allowed = "文件类型不允许" file_type_not_allowed = _l("File type not allowed") # 文件类型不允许
upload_failed = "上传失败: {}" upload_failed = _l("Upload failed: {}") # 上传失败: {}
direct_supervisor_is_not_self = "直属上级不能是自己" direct_supervisor_is_not_self = _l("Direct supervisor is not self") # 直属上级不能是自己
parent_department_is_not_self = "上级部门不能是自己" parent_department_is_not_self = _l("Parent department is not self") # 上级部门不能是自己
employee_list_is_empty = "员工列表为空" employee_list_is_empty = _l("Employee list is empty") # 员工列表为空
column_name_not_support = "不支持的列名" column_name_not_support = _l("Column name not support") # 不支持的列名
password_is_required = "密码不能为空" password_is_required = _l("Password is required") # 密码是必须的
employee_acl_rid_is_zero = "员工ACL角色ID不能为0" employee_acl_rid_is_zero = _l("Employee acl rid is zero") # 员工ACL角色ID不能为0
generate_excel_failed = "生成excel失败: {}" generate_excel_failed = _l("Generate excel failed: {}") # 生成excel失败: {}
rename_columns_failed = "字段转换为中文失败: {}" rename_columns_failed = _l("Rename columns failed: {}") # 重命名字段失败: {}
cannot_block_this_employee_is_other_direct_supervisor = "该员工是其他员工的直属上级, 不能禁用" cannot_block_this_employee_is_other_direct_supervisor = _l(
cannot_block_this_employee_is_department_manager = "该员工是部门负责人, 不能禁用" "Cannot block this employee is other direct supervisor") # 该员工是其他员工的直属上级, 不能禁用
employee_id_not_found = "员工ID [{}] 不存在" cannot_block_this_employee_is_department_manager = _l(
value_is_required = "值是必须的" "Cannot block this employee is department manager") # 该员工是部门负责人, 不能禁用
email_already_exists = "邮箱 [{}] 已存在" employee_id_not_found = _l("Employee id [{}] not found") # 员工ID [{}] 不存在
query_column_none_keep_value_empty = "查询 {} 空值时请保持value为空" value_is_required = _l("Value is required") # 值是必须的
not_support_operator = "不支持的操作符: {}" email_already_exists = _l("Email already exists") # 邮箱已存在
not_support_relation = "不支持的关系: {}" query_column_none_keep_value_empty = _l("Query {} none keep value empty") # 查询 {} 空值时请保持value为空"
conditions_field_missing = "conditions内元素字段缺失请检查" not_support_operator = _l("Not support operator: {}") # 不支持的操作符: {}
datetime_format_error = "{} 格式错误,应该为:%Y-%m-%d %H:%M:%S" not_support_relation = _l("Not support relation: {}") # 不支持的关系: {}
department_level_relation_error = "部门层级关系不正确" conditions_field_missing = _l("Conditions field missing") # conditions内元素字段缺失请检查
delete_reserved_department_name = "保留部门,无法删除!" datetime_format_error = _l("Datetime format error: {}") # {} 格式错误,应该为:%Y-%m-%d %H:%M:%S
department_id_is_required = "部门ID是必须的" department_level_relation_error = _l("Department level relation error") # 部门层级关系不正确
department_list_is_required = "部门列表是必须的" delete_reserved_department_name = _l("Delete reserved department name") # 保留部门,无法删除!
cannot_to_be_parent_department = "{} 不能设置为上级部门" department_id_is_required = _l("Department id is required") # 部门ID是必须的
department_id_not_found = "部门ID [{}] 不存在" department_list_is_required = _l("Department list is required") # 部门列表是必须的
parent_department_id_must_more_than_zero = "上级部门ID必须大于0" cannot_to_be_parent_department = _l("{} Cannot to be parent department") # 不能设置为上级部门
department_name_already_exists = "部门名称 [{}] 已存在" department_id_not_found = _l("Department id [{}] not found") # 部门ID [{}] 不存在
new_department_is_none = "新部门是空的" parent_department_id_must_more_than_zero = _l("Parent department id must more than zero") # 上级部门ID必须大于0
department_name_already_exists = _l("Department name [{}] already exists") # 部门名称 [{}] 已存在
new_department_is_none = _l("New department is none") # 新部门是空的
acl_edit_user_failed = "ACL 修改用户失败: {}" acl_edit_user_failed = _l("ACL edit user failed: {}") # ACL 修改用户失败: {}
acl_uid_not_found = "ACL 用户UID [{}] 不存在" acl_uid_not_found = _l("ACL uid not found: {}") # ACL 用户UID [{}] 不存在
acl_add_user_failed = "ACL 添加用户失败: {}" acl_add_user_failed = _l("ACL add user failed: {}") # ACL 添加用户失败: {}
acl_add_role_failed = "ACL 添加角色失败: {}" acl_add_role_failed = _l("ACL add role failed: {}") # ACL 添加角色失败: {}
acl_update_role_failed = "ACL 更新角色失败: {}" acl_update_role_failed = _l("ACL update role failed: {}") # ACL 更新角色失败: {}
acl_get_all_users_failed = "ACL 获取所有用户失败: {}" acl_get_all_users_failed = _l("ACL get all users failed: {}") # ACL 获取所有用户失败: {}
acl_remove_user_from_role_failed = "ACL 从角色中移除用户失败: {}" acl_remove_user_from_role_failed = _l("ACL remove user from role failed: {}") # ACL 从角色中移除用户失败: {}
acl_add_user_to_role_failed = "ACL 添加用户到角色失败: {}" acl_add_user_to_role_failed = _l("ACL add user to role failed: {}") # ACL 添加用户到角色失败: {}
acl_import_user_failed = "ACL 导入用户[{}]失败: {}" acl_import_user_failed = _l("ACL import user failed: {}") # ACL 导入用户失败: {}
nickname_is_required = "用户名不能为空" nickname_is_required = _l("Nickname is required") # 昵称不能为空
username_is_required = "username不能为空" username_is_required = _l("Username is required") # 用户名不能为空
email_is_required = "邮箱不能为空" email_is_required = _l("Email is required") # 邮箱不能为空
email_format_error = "邮箱格式错误" email_format_error = _l("Email format error") # 邮箱格式错误
email_send_timeout = "邮件发送超时" email_send_timeout = _l("Email send timeout") # 邮件发送超时
common_data_not_found = "ID {} 找不到记录" common_data_not_found = _l("Common data not found {} ") # ID {} 找不到记录
common_data_already_existed = "{} 已存在" common_data_already_existed = _l("Common data {} already existed") # {} 已存在
notice_platform_existed = "{} 已存在" notice_platform_existed = _l("Notice platform {} existed") # {} 已存在
notice_not_existed = "{} 配置项不存在" notice_not_existed = _l("Notice {} not existed") # {} 配置项不存在
notice_please_config_messenger_first = "请先配置 messenger" notice_please_config_messenger_first = _l("Notice please config messenger first") # 请先配置messenger URL
notice_bind_err_with_empty_mobile = "绑定失败,手机号为空" notice_bind_err_with_empty_mobile = _l("Notice bind err with empty mobile") # 绑定错误,手机号为空
notice_bind_failed = "绑定失败: {}" notice_bind_failed = _l("Notice bind failed: {}") # 绑定失败: {}
notice_bind_success = "绑定成功" notice_bind_success = _l("Notice bind success") # 绑定成功
notice_remove_bind_success = "解绑成功" notice_remove_bind_success = _l("Notice remove bind success") # 解绑成功
not_support_test = "不支持的测试类型: {}" not_support_test = _l("Not support test type: {}") # 不支持的测试类型: {}
not_support_auth_type = "不支持的认证类型: {}" not_support_auth_type = _l("Not support auth type: {}") # 不支持的认证类型: {}
ldap_server_connect_timeout = "LDAP服务器连接超时" ldap_server_connect_timeout = _l("LDAP server connect timeout") # LDAP服务器连接超时
ldap_server_connect_not_available = "LDAP服务器连接不可用" ldap_server_connect_not_available = _l("LDAP server connect not available") # LDAP服务器连接不可用
ldap_test_unknown_error = "LDAP测试未知错误: {}" ldap_test_unknown_error = _l("LDAP test unknown error: {}") # LDAP测试未知错误: {}
common_data_not_support_auth_type = "通用数据不支持auth类型: {}" common_data_not_support_auth_type = _l("Common data not support auth type: {}") # 通用数据不支持auth类型: {}
ldap_test_username_required = "LDAP测试用户名必填" ldap_test_username_required = _l("LDAP test username required") # LDAP测试用户名必填
company_wide = _l("Company wide") # 全公司

View File

@@ -1,3 +1,4 @@
import base64
import uuid import uuid
import os import os
from io import BytesIO from io import BytesIO
@@ -29,14 +30,14 @@ class CommonFileCRUD:
return CommonFile.create(**kwargs) return CommonFile.create(**kwargs)
@staticmethod @staticmethod
def get_file(file_name): def get_file(file_name, to_str=False):
existed = CommonFile.get_by(file_name=file_name, first=True, to_dict=False) existed = CommonFile.get_by(file_name=file_name, first=True, to_dict=False)
if not existed: if not existed:
abort(400, ErrFormat.file_not_found) abort(400, ErrFormat.file_not_found)
uncompressed_data = lz4.frame.decompress(existed.binary) uncompressed_data = lz4.frame.decompress(existed.binary)
return BytesIO(uncompressed_data) return base64.b64encode(uncompressed_data).decode('utf-8') if to_str else BytesIO(uncompressed_data)
@staticmethod @staticmethod
def sync_file_to_db(): def sync_file_to_db():
@@ -66,3 +67,28 @@ class CommonFileCRUD:
current_app.logger.info(f'sync file {file} to db') current_app.logger.info(f'sync file {file} to db')
except Exception as e: except Exception as e:
current_app.logger.error(f'sync file {file} to db error: {e}') current_app.logger.error(f'sync file {file} to db error: {e}')
def get_file_binary_str(self, file_name):
return self.get_file(file_name, True)
def save_str_to_file(self, file_name, str_data):
try:
self.get_file(file_name)
current_app.logger.info(f'file {file_name} already exists')
return
except Exception as e:
# file not found
pass
bytes_data = base64.b64decode(str_data)
compressed_data = lz4.frame.compress(bytes_data)
try:
self.add_file(
origin_name=file_name,
file_name=file_name,
binary=compressed_data
)
current_app.logger.info(f'save_str_to_file {file_name} success')
except Exception as e:
current_app.logger.error(f"save_str_to_file error: {e}")

View File

@@ -117,15 +117,15 @@ class ACLManager(object):
if group: if group:
PermissionCRUD.grant(role.id, permissions, group_id=group.id) PermissionCRUD.grant(role.id, permissions, group_id=group.id)
def grant_resource_to_role_by_rid(self, name, rid, resource_type_name=None, permissions=None): def grant_resource_to_role_by_rid(self, name, rid, resource_type_name=None, permissions=None, rebuild=True):
resource = self._get_resource(name, resource_type_name) resource = self._get_resource(name, resource_type_name)
if resource: if resource:
PermissionCRUD.grant(rid, permissions, resource_id=resource.id) PermissionCRUD.grant(rid, permissions, resource_id=resource.id, rebuild=rebuild)
else: else:
group = self._get_resource_group(name) group = self._get_resource_group(name)
if group: if group:
PermissionCRUD.grant(rid, permissions, group_id=group.id) PermissionCRUD.grant(rid, permissions, group_id=group.id, rebuild=rebuild)
def revoke_resource_from_role(self, name, role, resource_type_name=None, permissions=None): def revoke_resource_from_role(self, name, role, resource_type_name=None, permissions=None):
resource = self._get_resource(name, resource_type_name) resource = self._get_resource(name, resource_type_name)
@@ -138,20 +138,20 @@ class ACLManager(object):
if group: if group:
PermissionCRUD.revoke(role.id, permissions, group_id=group.id) PermissionCRUD.revoke(role.id, permissions, group_id=group.id)
def revoke_resource_from_role_by_rid(self, name, rid, resource_type_name=None, permissions=None): def revoke_resource_from_role_by_rid(self, name, rid, resource_type_name=None, permissions=None, rebuild=True):
resource = self._get_resource(name, resource_type_name) resource = self._get_resource(name, resource_type_name)
if resource: if resource:
PermissionCRUD.revoke(rid, permissions, resource_id=resource.id) PermissionCRUD.revoke(rid, permissions, resource_id=resource.id, rebuild=rebuild)
else: else:
group = self._get_resource_group(name) group = self._get_resource_group(name)
if group: if group:
PermissionCRUD.revoke(rid, permissions, group_id=group.id) PermissionCRUD.revoke(rid, permissions, group_id=group.id, rebuild=rebuild)
def del_resource(self, name, resource_type_name=None): def del_resource(self, name, resource_type_name=None):
resource = self._get_resource(name, resource_type_name) resource = self._get_resource(name, resource_type_name)
if resource: if resource:
ResourceCRUD.delete(resource.id) return ResourceCRUD.delete(resource.id)
def has_permission(self, resource_name, resource_type, perm, resource_id=None): def has_permission(self, resource_name, resource_type, perm, resource_id=None):
if is_app_admin(self.app_id): if is_app_admin(self.app_id):

View File

@@ -394,4 +394,10 @@ class AuditCRUD(object):
if logout_at is None: if logout_at is None:
payload['login_at'] = datetime.datetime.now() payload['login_at'] = datetime.datetime.now()
try:
from api.lib.common_setting.employee import EmployeeCRUD
EmployeeCRUD.update_last_login_by_uid(current_user.uid)
except:
pass
return AuditLoginLog.create(**payload).id return AuditLoginLog.create(**payload).id

View File

@@ -328,6 +328,8 @@ class ResourceCRUD(object):
AuditCRUD.add_resource_log(resource.app_id, AuditOperateType.delete, AuditCRUD.add_resource_log(resource.app_id, AuditOperateType.delete,
AuditScope.resource, resource.id, origin, {}, {}) AuditScope.resource, resource.id, origin, {}, {})
return rebuilds
@classmethod @classmethod
def delete_by_name(cls, name, type_id, app_id): def delete_by_name(cls, name, type_id, app_id):
resource = Resource.get_by(name=name, resource_type_id=type_id, app_id=app_id) or abort( resource = Resource.get_by(name=name, resource_type_id=type_id, app_id=app_id) or abort(

View File

@@ -1,46 +1,50 @@
# -*- coding:utf-8 -*- # -*- coding:utf-8 -*-
from flask_babel import lazy_gettext as _l
from api.lib.resp_format import CommonErrFormat from api.lib.resp_format import CommonErrFormat
class ErrFormat(CommonErrFormat): class ErrFormat(CommonErrFormat):
login_succeed = "登录成功" login_succeed = _l("login successful") # 登录成功
ldap_connection_failed = "连接LDAP服务失败" ldap_connection_failed = _l("Failed to connect to LDAP service") # 连接LDAP服务失败
invalid_password = "密码验证失败" invalid_password = _l("Password verification failed") # 密码验证失败
auth_only_with_app_token_failed = "应用 Token验证失败" auth_only_with_app_token_failed = _l("Application Token verification failed") # 应用 Token验证失败
session_invalid = "您不是应用管理员 或者 session失效(尝试一下退出重新登录)" # 您不是应用管理员 或者 session失效(尝试一下退出重新登录)
session_invalid = _l(
"You are not the application administrator or the session has expired (try logging out and logging in again)")
resource_type_not_found = "资源类型 {} 不存在!" resource_type_not_found = _l("Resource type {} does not exist!") # 资源类型 {} 不存在!
resource_type_exists = "资源类型 {} 已经存在!" resource_type_exists = _l("Resource type {} already exists!") # 资源类型 {} 已经存在!
resource_type_cannot_delete = "因为该类型下有资源的存在, 不能删除!" # 因为该类型下有资源的存在, 不能删除!
resource_type_cannot_delete = _l("Because there are resources under this type, they cannot be deleted!")
user_not_found = "用户 {} 不存在!" user_not_found = _l("User {} does not exist!") # 用户 {} 不存在!
user_exists = "用户 {} 已经存在!" user_exists = _l("User {} already exists!") # 用户 {} 已经存在!
role_not_found = "角色 {} 不存在!" role_not_found = _l("Role {} does not exist!") # 角色 {} 不存在!
role_exists = "角色 {} 已经存在!" role_exists = _l("Role {} already exists!") # 角色 {} 已经存在!
global_role_not_found = "全局角色 {} 不存在!" global_role_not_found = _l("Global role {} does not exist!") # 全局角色 {} 不存在!
global_role_exists = "全局角色 {} 已经存在!" global_role_exists = _l("Global role {} already exists!") # 全局角色 {} 已经存在!
resource_no_permission = "您没有资源: {}{} 权限" resource_no_permission = _l("You do not have {} permission on resource: {}") # 您没有资源: {} 的 {} 权限
admin_required = "需要管理员权限" admin_required = _l("Requires administrator permissions") # 需要管理员权限
role_required = "需要角色: {}" role_required = _l("Requires role: {}") # 需要角色: {}
user_role_delete_invalid = "删除用户角色, 请在 用户管理 页面操作!" # 删除用户角色, 请在 用户管理 页面操作!
user_role_delete_invalid = _l("To delete a user role, please operate on the User Management page!")
app_is_ready_existed = "应用 {} 已经存在" app_is_ready_existed = _l("Application {} already exists") # 应用 {} 已经存在
app_not_found = "应用 {} 不存在!" app_not_found = _l("Application {} does not exist!") # 应用 {} 不存在!
app_secret_invalid = "应用的Secret无效" app_secret_invalid = _l("The Secret is invalid") # 应用的Secret无效
resource_not_found = "资源 {} 不存在!" resource_not_found = _l("Resource {} does not exist!") # 资源 {} 不存在!
resource_exists = "资源 {} 已经存在!" resource_exists = _l("Resource {} already exists!") # 资源 {} 已经存在!
resource_group_not_found = "资源组 {} 不存在!" resource_group_not_found = _l("Resource group {} does not exist!") # 资源组 {} 不存在!
resource_group_exists = "资源组 {} 已经存在!" resource_group_exists = _l("Resource group {} already exists!") # 资源组 {} 已经存在!
inheritance_dead_loop = "继承检测到了死循环" inheritance_dead_loop = _l("Inheritance detected infinite loop") # 继承检测到了死循环
role_relation_not_found = "角色关系 {} 不存在!" role_relation_not_found = _l("Role relationship {} does not exist!") # 角色关系 {} 不存在!
trigger_not_found = "触发器 {} 不存在!" trigger_not_found = _l("Trigger {} does not exist!") # 触发器 {} 不存在!
trigger_exists = "触发器 {} 已经存在!" trigger_exists = _l("Trigger {} already exists!") # 触发器 {} 已经存在!
trigger_disabled = "触发器 {} 已经被禁用!" trigger_disabled = _l("Trigger {} has been disabled!") # Trigger {} has been disabled!
invalid_password = "密码不正确!"

View File

@@ -63,6 +63,7 @@ class UserCRUD(object):
AuditCRUD.add_role_log(None, AuditOperateType.create, AuditCRUD.add_role_log(None, AuditOperateType.create,
AuditScope.user, user.uid, {}, user.to_dict(), {}, {} AuditScope.user, user.uid, {}, user.to_dict(), {}, {}
) )
if add_from != 'common': if add_from != 'common':
from api.lib.common_setting.employee import EmployeeCRUD from api.lib.common_setting.employee import EmployeeCRUD
payload = {column: getattr(user, column) for column in ['uid', 'username', 'nickname', 'email', 'block']} payload = {column: getattr(user, column) for column in ['uid', 'username', 'nickname', 'email', 'block']}

View File

@@ -23,13 +23,13 @@ from api.models.acl import User
def authenticate_with_ldap(username, password): def authenticate_with_ldap(username, password):
config = AuthenticateDataCRUD(AuthenticateType.LDAP).get() config = AuthenticateDataCRUD(AuthenticateType.LDAP).get()
server = Server(config.get('LDAP').get('ldap_server'), get_info=ALL, connect_timeout=3) server = Server(config.get('ldap_server'), get_info=ALL, connect_timeout=3)
if '@' in username: if '@' in username:
email = username email = username
who = config['LDAP'].get('ldap_user_dn').format(username.split('@')[0]) who = config.get('ldap_user_dn').format(username.split('@')[0])
else: else:
who = config['LDAP'].get('ldap_user_dn').format(username) who = config.get('ldap_user_dn').format(username)
email = "{}@{}".format(who, config['LDAP'].get('ldap_domain')) email = "{}@{}".format(who, config.get('ldap_domain'))
username = username.split('@')[0] username = username.split('@')[0]
user = User.query.get_by_username(username) user = User.query.get_by_username(username)
@@ -41,7 +41,7 @@ def authenticate_with_ldap(username, password):
conn = Connection(server, user=who, password=password, auto_bind=AUTO_BIND_NO_TLS) conn = Connection(server, user=who, password=password, auto_bind=AUTO_BIND_NO_TLS)
except LDAPBindError: except LDAPBindError:
conn = Connection(server, conn = Connection(server,
user=f"{username}@{config['LDAP'].get('ldap_domain')}", user=f"{username}@{config.get('ldap_domain')}",
password=password, password=password,
auto_bind=AUTO_BIND_NO_TLS) auto_bind=AUTO_BIND_NO_TLS)

View File

@@ -1,29 +1,34 @@
# -*- coding:utf-8 -*- # -*- coding:utf-8 -*-
from flask_babel import lazy_gettext as _l
class CommonErrFormat(object): class CommonErrFormat(object):
unauthorized = "未认证" unauthorized = _l("unauthorized") # 未认证
unknown_error = "未知错误" unknown_error = _l("unknown error") # 未知错误
invalid_request = "不合法的请求" invalid_request = _l("Illegal request") # 不合法的请求
invalid_operation = "无效的操作" invalid_operation = _l("Invalid operation") # 无效的操作
not_found = "不存在" not_found = _l("does not exist") # 不存在
circular_dependency_error = "存在循环依赖!" circular_dependency_error = _l("There is a circular dependency!") # 存在循环依赖!
unknown_search_error = "未知搜索错误" unknown_search_error = _l("Unknown search error") # 未知搜索错误
invalid_json = "json格式似乎不正确了, 请仔细确认一下!" # json格式似乎不正确了, 请仔细确认一下!
invalid_json = _l("The json format seems to be incorrect, please confirm carefully!")
datetime_argument_invalid = "参数 {} 格式不正确, 格式必须是: yyyy-mm-dd HH:MM:SS" # 参数 {} 格式不正确, 格式必须是: yyyy-mm-dd HH:MM:SS
datetime_argument_invalid = _l("The format of parameter {} is incorrect, the format must be: yyyy-mm-dd HH:MM:SS")
argument_value_required = "参数 {} 的值不能为空!" argument_value_required = _l("The value of parameter {} cannot be empty!") # 参数 {} 的值不能为空!
argument_required = "请求缺少参数 {}" argument_required = _l("The request is missing parameters {}") # 请求缺少参数 {}
argument_invalid = "参数 {} 的值无效" argument_invalid = _l("Invalid value for parameter {}") # 参数 {} 的值无效
argument_str_length_limit = "参数 {} 的长度必须 <= {}" argument_str_length_limit = _l("The length of parameter {} must be <= {}") # 参数 {} 的长度必须 <= {}
role_required = "角色 {} 才能操作!" role_required = _l("Role {} can only operate!") # 角色 {} 才能操作!
user_not_found = "用户 {} 不存在" user_not_found = _l("User {} does not exist") # 用户 {} 不存在
no_permission = "您没有资源: {}{}权限!" no_permission = _l("You do not have {} permission for resource: {}!") # 您没有资源: {} 的{}权限!
no_permission2 = "您没有操作权限!" no_permission2 = _l("You do not have permission to operate!") # 您没有操作权限!
no_permission_only_owner = "只有创建人或者管理员才有权限!" no_permission_only_owner = _l("Only the creator or administrator has permission!") # 只有创建人或者管理员才有权限!

View File

@@ -145,7 +145,7 @@ class User(CRUDModel, SoftDeleteMixin):
class RoleQuery(BaseQuery): class RoleQuery(BaseQuery):
def authenticate(self, login, password): def authenticate(self, login, password):
role = self.filter(Role.name == login).first() role = self.filter(Role.name == login).filter(Role.deleted.is_(False)).first()
if role: if role:
authenticated = role.check_password(password) authenticated = role.check_password(password)

View File

@@ -2,7 +2,6 @@
import datetime import datetime
from sqlalchemy.dialects.mysql import DOUBLE from sqlalchemy.dialects.mysql import DOUBLE
from api.extensions import db from api.extensions import db
@@ -94,6 +93,8 @@ class Attribute(Model):
_choice_web_hook = db.Column('choice_web_hook', db.JSON) _choice_web_hook = db.Column('choice_web_hook', db.JSON)
choice_other = db.Column(db.JSON) choice_other = db.Column(db.JSON)
re_check = db.Column(db.Text)
uid = db.Column(db.Integer, index=True) uid = db.Column(db.Integer, index=True)
option = db.Column(db.JSON) option = db.Column(db.JSON)
@@ -464,6 +465,15 @@ class PreferenceSearchOption(Model):
option = db.Column(db.JSON) option = db.Column(db.JSON)
class PreferenceCITypeOrder(Model):
__tablename__ = "c_pcto"
uid = db.Column(db.Integer, index=True, nullable=False)
type_id = db.Column(db.Integer, db.ForeignKey('c_ci_types.id'))
order = db.Column(db.SmallInteger, default=0)
is_tree = db.Column(db.Boolean, default=False) # True is tree view, False is resource view
# custom # custom
class CustomDashboard(Model): class CustomDashboard(Model):
__tablename__ = "c_c_d" __tablename__ = "c_c_d"

View File

@@ -25,10 +25,9 @@ from api.models.acl import Role
from api.models.acl import Trigger from api.models.acl import Trigger
@celery.task(base=QueueOnce, @celery.task(name="acl.role_rebuild",
name="acl.role_rebuild", queue=ACL_QUEUE,)
queue=ACL_QUEUE, @flush_db
once={"graceful": True, "unlock_before_run": True})
@reconnect_db @reconnect_db
def role_rebuild(rids, app_id): def role_rebuild(rids, app_id):
rids = rids if isinstance(rids, list) else [rids] rids = rids if isinstance(rids, list) else [rids]
@@ -190,18 +189,18 @@ def cancel_trigger(_id, resource_id=None, operator_uid=None):
@celery.task(name="acl.op_record", queue=ACL_QUEUE) @celery.task(name="acl.op_record", queue=ACL_QUEUE)
@reconnect_db @reconnect_db
def op_record(app, rolename, operate_type, obj): def op_record(app, role_name, operate_type, obj):
if isinstance(app, int): if isinstance(app, int):
app = AppCache.get(app) app = AppCache.get(app)
app = app and app.name app = app and app.name
if isinstance(rolename, int): if isinstance(role_name, int):
u = UserCache.get(rolename) u = UserCache.get(role_name)
if u: if u:
rolename = u.username role_name = u.username
if not u: if not u:
r = RoleCache.get(rolename) r = RoleCache.get(role_name)
if r: if r:
rolename = r.name role_name = r.name
OperateRecordCRUD.add(app, rolename, operate_type, obj) OperateRecordCRUD.add(app, role_name, operate_type, obj)

View File

@@ -1,24 +1,24 @@
# -*- coding:utf-8 -*- # -*- coding:utf-8 -*-
import requests
from flask import current_app from flask import current_app
from api.extensions import celery from api.extensions import celery
from api.extensions import db
from api.lib.common_setting.acl import ACLManager from api.lib.common_setting.acl import ACLManager
from api.lib.common_setting.const import COMMON_SETTING_QUEUE from api.lib.cmdb.const import CMDB_QUEUE
from api.lib.common_setting.resp_format import ErrFormat from api.lib.common_setting.resp_format import ErrFormat
from api.models.common_setting import Department from api.models.common_setting import Department, Employee
from api.lib.decorator import flush_db
from api.lib.decorator import reconnect_db
@celery.task(name="common_setting.edit_employee_department_in_acl", queue=COMMON_SETTING_QUEUE) @celery.task(name="common_setting.edit_employee_department_in_acl", queue=CMDB_QUEUE)
@flush_db
@reconnect_db
def edit_employee_department_in_acl(e_list, new_d_id, op_uid): def edit_employee_department_in_acl(e_list, new_d_id, op_uid):
""" """
:param e_list:{acl_rid: 11, department_id: 22} :param e_list:{acl_rid: 11, department_id: 22}
:param new_d_id :param new_d_id
:param op_uid :param op_uid
""" """
db.session.remove()
result = [] result = []
new_department = Department.get_by( new_department = Department.get_by(
first=True, department_id=new_d_id, to_dict=False) first=True, department_id=new_d_id, to_dict=False)
@@ -75,3 +75,41 @@ def edit_employee_department_in_acl(e_list, new_d_id, op_uid):
result.append(ErrFormat.acl_add_user_to_role_failed.format(str(e))) result.append(ErrFormat.acl_add_user_to_role_failed.format(str(e)))
return result return result
@celery.task(name="common_setting.refresh_employee_acl_info", queue=CMDB_QUEUE)
@flush_db
@reconnect_db
def refresh_employee_acl_info():
acl = ACLManager('acl')
role_map = {role['name']: role for role in acl.get_all_roles()}
criterion = [
Employee.deleted == 0
]
query = Employee.query.filter(*criterion).order_by(
Employee.created_at.desc()
)
for em in query.all():
if em.acl_uid and em.acl_rid:
continue
role = role_map.get(em.username, None)
if not role:
continue
params = dict()
if not em.acl_uid:
params['acl_uid'] = role.get('uid', 0)
if not em.acl_rid:
params['acl_rid'] = role.get('id', 0)
try:
em.update(**params)
current_app.logger.info(
f"refresh_employee_acl_info success, employee_id: {em.employee_id}, uid: {em.acl_uid}, "
f"rid: {em.acl_rid}")
except Exception as e:
current_app.logger.error(str(e))
continue

Binary file not shown.

View File

@@ -0,0 +1,819 @@
# Chinese translations for PROJECT.
# Copyright (C) 2023 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2023.
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2024-01-03 11:39+0800\n"
"PO-Revision-Date: 2023-12-25 20:21+0800\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: zh\n"
"Language-Team: zh <LL@li.org>\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.14.0\n"
#: api/lib/resp_format.py:7
msgid "unauthorized"
msgstr "未认证"
#: api/lib/resp_format.py:8
msgid "unknown error"
msgstr "未知错误"
#: api/lib/resp_format.py:10
msgid "Illegal request"
msgstr "不合法的请求"
#: api/lib/resp_format.py:11
msgid "Invalid operation"
msgstr "无效的操作"
#: api/lib/resp_format.py:13
msgid "does not exist"
msgstr "不存在"
#: api/lib/resp_format.py:15
msgid "There is a circular dependency!"
msgstr "存在循环依赖!"
#: api/lib/resp_format.py:17
msgid "Unknown search error"
msgstr "未知搜索错误"
#: api/lib/resp_format.py:20
msgid "The json format seems to be incorrect, please confirm carefully!"
msgstr "# json格式似乎不正确了, 请仔细确认一下!"
#: api/lib/resp_format.py:23
msgid ""
"The format of parameter {} is incorrect, the format must be: yyyy-mm-dd "
"HH:MM:SS"
msgstr "参数 {} 格式不正确, 格式必须是: yyyy-mm-dd HH:MM:SS"
#: api/lib/resp_format.py:25
msgid "The value of parameter {} cannot be empty!"
msgstr "参数 {} 的值不能为空!"
#: api/lib/resp_format.py:26
msgid "The request is missing parameters {}"
msgstr "请求缺少参数 {}"
#: api/lib/resp_format.py:27
msgid "Invalid value for parameter {}"
msgstr "参数 {} 的值无效"
#: api/lib/resp_format.py:28
msgid "The length of parameter {} must be <= {}"
msgstr "参数 {} 的长度必须 <= {}"
#: api/lib/resp_format.py:30
msgid "Role {} can only operate!"
msgstr "角色 {} 才能操作!"
#: api/lib/resp_format.py:31
msgid "User {} does not exist"
msgstr "用户 {} 不存在"
#: api/lib/resp_format.py:32
msgid "You do not have {} permission for resource: {}!"
msgstr "您没有资源: {} 的{}权限!"
#: api/lib/resp_format.py:33
msgid "You do not have permission to operate!"
msgstr "您没有操作权限!"
#: api/lib/resp_format.py:34
msgid "Only the creator or administrator has permission!"
msgstr "只有创建人或者管理员才有权限!"
#: api/lib/cmdb/resp_format.py:9
msgid "CI Model"
msgstr "模型配置"
#: api/lib/cmdb/resp_format.py:11
msgid "Invalid relation type: {}"
msgstr "无效的关系类型: {}"
#: api/lib/cmdb/resp_format.py:12
msgid "CIType is not found"
msgstr "模型不存在!"
#: api/lib/cmdb/resp_format.py:15
msgid "The type of parameter attributes must be a list"
msgstr "参数 attributes 类型必须是列表"
#: api/lib/cmdb/resp_format.py:16
msgid "The file doesn't seem to be uploaded"
msgstr "文件似乎并未上传"
#: api/lib/cmdb/resp_format.py:18
msgid "Attribute {} does not exist!"
msgstr "属性 {} 不存在!"
#: api/lib/cmdb/resp_format.py:19
msgid ""
"This attribute is the unique identifier of the model and cannot be "
"deleted!"
msgstr "该属性是模型的唯一标识,不能被删除!"
#: api/lib/cmdb/resp_format.py:21
msgid "This attribute is referenced by model {} and cannot be deleted!"
msgstr "该属性被模型 {} 引用, 不能删除!"
#: api/lib/cmdb/resp_format.py:23
msgid "The value type of the attribute is not allowed to be modified!"
msgstr "属性的值类型不允许修改!"
#: api/lib/cmdb/resp_format.py:25
msgid "Multiple values are not allowed to be modified!"
msgstr "多值不被允许修改!"
#: api/lib/cmdb/resp_format.py:27
msgid "Modifying the index is not allowed for non-administrators!"
msgstr "修改索引 非管理员不被允许!"
#: api/lib/cmdb/resp_format.py:28
msgid "Index switching failed!"
msgstr "索引切换失败!"
#: api/lib/cmdb/resp_format.py:29
msgid "The predefined value is of the wrong type!"
msgstr "预定义值的类型不对!"
#: api/lib/cmdb/resp_format.py:30
msgid "Duplicate attribute name {}"
msgstr "重复的属性名 {}"
#: api/lib/cmdb/resp_format.py:31
msgid "Failed to create attribute {}!"
msgstr "创建属性 {} 失败!"
#: api/lib/cmdb/resp_format.py:32
msgid "Modify attribute {} failed!"
msgstr "修改属性 {} 失败!"
#: api/lib/cmdb/resp_format.py:33
msgid "You do not have permission to modify this attribute!"
msgstr "您没有权限修改该属性!"
#: api/lib/cmdb/resp_format.py:34
msgid "Only creators and administrators are allowed to delete attributes!"
msgstr "目前只允许 属性创建人、管理员 删除属性!"
#: api/lib/cmdb/resp_format.py:37
msgid ""
"Attribute field names cannot be built-in fields: id, _id, ci_id, type, "
"_type, ci_type"
msgstr "属性字段名不能是内置字段: id, _id, ci_id, type, _type, ci_type"
#: api/lib/cmdb/resp_format.py:39
msgid "Predefined value: Other model request parameters are illegal!"
msgstr "预定义值: 其他模型请求参数不合法!"
#: api/lib/cmdb/resp_format.py:42
msgid "CI {} does not exist"
msgstr "CI {} 不存在"
#: api/lib/cmdb/resp_format.py:43
msgid "Multiple attribute joint unique verification failed: {}"
msgstr "多属性联合唯一校验不通过: {}"
#: api/lib/cmdb/resp_format.py:44
msgid "The model's primary key {} does not exist!"
msgstr "模型的主键 {} 不存在!"
#: api/lib/cmdb/resp_format.py:45
msgid "Primary key {} is missing"
msgstr "主键字段 {} 缺失"
#: api/lib/cmdb/resp_format.py:46
msgid "CI already exists!"
msgstr "CI 已经存在!"
#: api/lib/cmdb/resp_format.py:47
msgid "Relationship constraint: {}, verification failed"
msgstr "关系约束: {}, 校验失败"
#: api/lib/cmdb/resp_format.py:49
msgid ""
"Many-to-many relationship constraint: Model {} <-> {} already has a many-"
"to-many relationship!"
msgstr "多对多关系 限制: 模型 {} <-> {} 已经存在多对多关系!"
#: api/lib/cmdb/resp_format.py:52
msgid "CI relationship: {} does not exist"
msgstr "CI关系: {} 不存在"
#: api/lib/cmdb/resp_format.py:55
msgid "In search expressions, not supported before parentheses: or, not"
msgstr "搜索表达式里小括号前不支持: 或、非"
#: api/lib/cmdb/resp_format.py:57
msgid "Model {} does not exist"
msgstr "模型 {} 不存在"
#: api/lib/cmdb/resp_format.py:58
msgid "Model {} already exists"
msgstr "模型 {} 已经存在"
#: api/lib/cmdb/resp_format.py:59
msgid "The primary key is undefined or has been deleted"
msgstr "主键未定义或者已被删除"
#: api/lib/cmdb/resp_format.py:60
msgid "Only the creator can delete it!"
msgstr "只有创建人才能删除它!"
#: api/lib/cmdb/resp_format.py:61
msgid "The model cannot be deleted because the CI already exists"
msgstr "因为CI已经存在不能删除模型"
#: api/lib/cmdb/resp_format.py:65
msgid ""
"The model cannot be deleted because the model is referenced by the "
"relational view {}"
msgstr "因为关系视图 {} 引用了该模型,不能删除模型"
#: api/lib/cmdb/resp_format.py:67
msgid "Model group {} does not exist"
msgstr "模型分组 {} 不存在"
#: api/lib/cmdb/resp_format.py:68
msgid "Model group {} already exists"
msgstr "模型分组 {} 已经存在"
#: api/lib/cmdb/resp_format.py:69
msgid "Model relationship {} does not exist"
msgstr "模型关系 {} 不存在"
#: api/lib/cmdb/resp_format.py:70
msgid "Attribute group {} already exists"
msgstr "属性分组 {} 已存在"
#: api/lib/cmdb/resp_format.py:71
msgid "Attribute group {} does not exist"
msgstr "属性分组 {} 不存在"
#: api/lib/cmdb/resp_format.py:73
msgid "Attribute group <{0}> - attribute <{1}> does not exist"
msgstr "属性组<{0}> - 属性<{1}> 不存在"
#: api/lib/cmdb/resp_format.py:74
msgid "The unique constraint already exists!"
msgstr "唯一约束已经存在!"
#: api/lib/cmdb/resp_format.py:76
msgid "Uniquely constrained attributes cannot be JSON and multi-valued"
msgstr "唯一约束的属性不能是 JSON 和 多值"
#: api/lib/cmdb/resp_format.py:77
msgid "Duplicated trigger"
msgstr "重复的触发器"
#: api/lib/cmdb/resp_format.py:78
msgid "Trigger {} does not exist"
msgstr "触发器 {} 不存在"
#: api/lib/cmdb/resp_format.py:80
msgid "Operation record {} does not exist"
msgstr "操作记录 {} 不存在"
#: api/lib/cmdb/resp_format.py:81
msgid "Unique identifier cannot be deleted"
msgstr "不能删除唯一标识"
#: api/lib/cmdb/resp_format.py:82
msgid "Cannot delete default sorted attributes"
msgstr "不能删除默认排序的属性"
#: api/lib/cmdb/resp_format.py:84
msgid "No node selected"
msgstr "没有选择节点"
#: api/lib/cmdb/resp_format.py:85
msgid "This search option does not exist!"
msgstr "该搜索选项不存在!"
#: api/lib/cmdb/resp_format.py:86
msgid "This search option has a duplicate name!"
msgstr "该搜索选项命名重复!"
#: api/lib/cmdb/resp_format.py:88
msgid "Relationship type {} already exists"
msgstr "关系类型 {} 已经存在"
#: api/lib/cmdb/resp_format.py:89
msgid "Relationship type {} does not exist"
msgstr "关系类型 {} 不存在"
#: api/lib/cmdb/resp_format.py:91
msgid "Invalid attribute value: {}"
msgstr "无效的属性值: {}"
#: api/lib/cmdb/resp_format.py:92
msgid "{} Invalid value: {}"
msgstr "无效的值: {}"
#: api/lib/cmdb/resp_format.py:93
msgid "{} is not in the predefined values"
msgstr "{} 不在预定义值里"
#: api/lib/cmdb/resp_format.py:95
msgid "The value of attribute {} must be unique, {} already exists"
msgstr "属性 {} 的值必须是唯一的, 当前值 {} 已存在"
#: api/lib/cmdb/resp_format.py:96
msgid "Attribute {} value must exist"
msgstr "属性 {} 值必须存在"
#: api/lib/cmdb/resp_format.py:99
msgid "Unknown error when adding or modifying attribute value: {}"
msgstr "新增或者修改属性值未知错误: {}"
#: api/lib/cmdb/resp_format.py:101
msgid "Duplicate custom name"
msgstr "订制名重复"
#: api/lib/cmdb/resp_format.py:103
msgid "Number of models exceeds limit: {}"
msgstr "模型数超过限制: {}"
#: api/lib/cmdb/resp_format.py:104
msgid "The number of CIs exceeds the limit: {}"
msgstr "CI数超过限制: {}"
#: api/lib/cmdb/resp_format.py:106
msgid "Auto-discovery rule: {} already exists!"
msgstr "自动发现规则: {} 已经存在!"
#: api/lib/cmdb/resp_format.py:107
msgid "Auto-discovery rule: {} does not exist!"
msgstr "自动发现规则: {} 不存在!"
#: api/lib/cmdb/resp_format.py:109
msgid "This auto-discovery rule is referenced by the model and cannot be deleted!"
msgstr "该自动发现规则被模型引用, 不能删除!"
#: api/lib/cmdb/resp_format.py:111
msgid "The application of auto-discovery rules cannot be defined repeatedly!"
msgstr "自动发现规则的应用不能重复定义!"
#: api/lib/cmdb/resp_format.py:112
msgid "The auto-discovery you want to modify: {} does not exist!"
msgstr "您要修改的自动发现: {} 不存在!"
#: api/lib/cmdb/resp_format.py:113
msgid "Attribute does not include unique identifier: {}"
msgstr "属性字段没有包括唯一标识: {}"
#: api/lib/cmdb/resp_format.py:114
msgid "The auto-discovery instance does not exist!"
msgstr "自动发现的实例不存在!"
#: api/lib/cmdb/resp_format.py:115
msgid "The model is not associated with this auto-discovery!"
msgstr "模型并未关联该自动发现!"
#: api/lib/cmdb/resp_format.py:116
msgid "Only the creator can modify the Secret!"
msgstr "只有创建人才能修改Secret!"
#: api/lib/cmdb/resp_format.py:118
msgid "This rule already has auto-discovery instances and cannot be deleted!"
msgstr "该规则已经有自动发现的实例, 不能被删除!"
#: api/lib/cmdb/resp_format.py:120
msgid "The default auto-discovery rule is already referenced by model {}!"
msgstr "该默认的自动发现规则 已经被模型 {} 引用!"
#: api/lib/cmdb/resp_format.py:122
msgid "The unique_key method must return a non-empty string!"
msgstr "unique_key方法必须返回非空字符串!"
#: api/lib/cmdb/resp_format.py:123
msgid "The attributes method must return a list"
msgstr "attributes方法必须返回的是list"
#: api/lib/cmdb/resp_format.py:125
msgid "The list returned by the attributes method cannot be empty!"
msgstr "attributes方法返回的list不能为空!"
#: api/lib/cmdb/resp_format.py:127
msgid "Only administrators can define execution targets as: all nodes!"
msgstr "只有管理员才可以定义执行机器为: 所有节点!"
#: api/lib/cmdb/resp_format.py:128
msgid "Execute targets permission check failed: {}"
msgstr "执行机器权限检查不通过: {}"
#: api/lib/cmdb/resp_format.py:130
msgid "CI filter authorization must be named!"
msgstr "CI过滤授权 必须命名!"
#: api/lib/cmdb/resp_format.py:131
msgid "CI filter authorization is currently not supported or query"
msgstr "CI过滤授权 暂时不支持 或 查询"
#: api/lib/cmdb/resp_format.py:134
msgid "You do not have permission to operate attribute {}!"
msgstr "您没有属性 {} 的操作权限!"
#: api/lib/cmdb/resp_format.py:135
msgid "You do not have permission to operate this CI!"
msgstr "您没有该CI的操作权限!"
#: api/lib/cmdb/resp_format.py:137
msgid "Failed to save password: {}"
msgstr "保存密码失败: {}"
#: api/lib/cmdb/resp_format.py:138
msgid "Failed to get password: {}"
msgstr "获取密码失败: {}"
#: api/lib/common_setting/resp_format.py:8
msgid "Company info already existed"
msgstr "公司信息已存在,无法创建!"
#: api/lib/common_setting/resp_format.py:10
msgid "No file part"
msgstr "没有文件部分"
#: api/lib/common_setting/resp_format.py:11
msgid "File is required"
msgstr "文件是必须的"
#: api/lib/common_setting/resp_format.py:12
msgid "File not found"
msgstr "文件不存在!"
#: api/lib/common_setting/resp_format.py:13
msgid "File type not allowed"
msgstr "文件类型不允许!"
#: api/lib/common_setting/resp_format.py:14
msgid "Upload failed: {}"
msgstr "上传失败: {}"
#: api/lib/common_setting/resp_format.py:16
msgid "Direct supervisor is not self"
msgstr "直属上级不能是自己"
#: api/lib/common_setting/resp_format.py:17
msgid "Parent department is not self"
msgstr "上级部门不能是自己"
#: api/lib/common_setting/resp_format.py:18
msgid "Employee list is empty"
msgstr "员工列表为空"
#: api/lib/common_setting/resp_format.py:20
msgid "Column name not support"
msgstr "不支持的列名"
#: api/lib/common_setting/resp_format.py:21
msgid "Password is required"
msgstr "密码是必须的"
#: api/lib/common_setting/resp_format.py:22
msgid "Employee acl rid is zero"
msgstr "员工ACL角色ID不能为0"
#: api/lib/common_setting/resp_format.py:24
msgid "Generate excel failed: {}"
msgstr "生成excel失败: {}"
#: api/lib/common_setting/resp_format.py:25
msgid "Rename columns failed: {}"
msgstr "重命名字段失败: {}"
#: api/lib/common_setting/resp_format.py:26
msgid "Cannot block this employee is other direct supervisor"
msgstr "该员工是其他员工的直属上级, 不能禁用"
#: api/lib/common_setting/resp_format.py:28
msgid "Cannot block this employee is department manager"
msgstr "该员工是部门负责人, 不能禁用"
#: api/lib/common_setting/resp_format.py:30
msgid "Employee id [{}] not found"
msgstr "员工ID [{}] 不存在!"
#: api/lib/common_setting/resp_format.py:31
msgid "Value is required"
msgstr "值是必须的"
#: api/lib/common_setting/resp_format.py:32
msgid "Email already exists"
msgstr "邮箱已存在!"
#: api/lib/common_setting/resp_format.py:33
msgid "Query {} none keep value empty"
msgstr "查询 {} 空值时请保持value为空"
#: api/lib/common_setting/resp_format.py:34
msgid "Not support operator: {}"
msgstr "不支持的操作符: {}"
#: api/lib/common_setting/resp_format.py:35
msgid "Not support relation: {}"
msgstr "不支持的关系: {}"
#: api/lib/common_setting/resp_format.py:36
msgid "Conditions field missing"
msgstr " conditions内元素字段缺失请检查"
#: api/lib/common_setting/resp_format.py:37
msgid "Datetime format error: {}"
msgstr "{}格式错误,应该为:%Y-%m-%d %H:%M:%S"
#: api/lib/common_setting/resp_format.py:38
msgid "Department level relation error"
msgstr "部门层级关系不正确"
#: api/lib/common_setting/resp_format.py:39
msgid "Delete reserved department name"
msgstr "保留部门,无法删除!"
#: api/lib/common_setting/resp_format.py:40
msgid "Department id is required"
msgstr "部门ID是必须的"
#: api/lib/common_setting/resp_format.py:41
msgid "Department list is required"
msgstr "部门列表是必须的"
#: api/lib/common_setting/resp_format.py:42
msgid "{} Cannot to be parent department"
msgstr "{} 不能设置为上级部门"
#: api/lib/common_setting/resp_format.py:43
msgid "Department id [{}] not found"
msgstr "部门ID [{}] 不存在"
#: api/lib/common_setting/resp_format.py:44
msgid "Parent department id must more than zero"
msgstr "上级部门ID必须大于0"
#: api/lib/common_setting/resp_format.py:45
msgid "Department name [{}] already exists"
msgstr "部门名称 [{}] 已存在"
#: api/lib/common_setting/resp_format.py:46
msgid "New department is none"
msgstr "新部门是空的"
#: api/lib/common_setting/resp_format.py:48
msgid "ACL edit user failed: {}"
msgstr "ACL 修改用户失败: {}"
#: api/lib/common_setting/resp_format.py:49
msgid "ACL uid not found: {}"
msgstr "ACL 用户UID [{}] 不存在"
#: api/lib/common_setting/resp_format.py:50
msgid "ACL add user failed: {}"
msgstr "ACL 添加用户失败: {}"
#: api/lib/common_setting/resp_format.py:51
msgid "ACL add role failed: {}"
msgstr "ACL 添加角色失败: {}"
#: api/lib/common_setting/resp_format.py:52
msgid "ACL update role failed: {}"
msgstr "ACL 更新角色失败: {}"
#: api/lib/common_setting/resp_format.py:53
msgid "ACL get all users failed: {}"
msgstr "ACL 获取所有用户失败: {}"
#: api/lib/common_setting/resp_format.py:54
msgid "ACL remove user from role failed: {}"
msgstr "ACL 从角色中移除用户失败: {}"
#: api/lib/common_setting/resp_format.py:55
msgid "ACL add user to role failed: {}"
msgstr "ACL 添加用户到角色失败: {}"
#: api/lib/common_setting/resp_format.py:56
msgid "ACL import user failed: {}"
msgstr "ACL 导入用户失败: {}"
#: api/lib/common_setting/resp_format.py:58
msgid "Nickname is required"
msgstr "昵称不能为空"
#: api/lib/common_setting/resp_format.py:59
msgid "Username is required"
msgstr "用户名不能为空"
#: api/lib/common_setting/resp_format.py:60
msgid "Email is required"
msgstr "邮箱不能为空"
#: api/lib/common_setting/resp_format.py:61
msgid "Email format error"
msgstr "邮箱格式错误"
#: api/lib/common_setting/resp_format.py:62
msgid "Email send timeout"
msgstr "邮件发送超时"
#: api/lib/common_setting/resp_format.py:64
msgid "Common data not found {} "
msgstr "ID {} 找不到记录"
#: api/lib/common_setting/resp_format.py:65
msgid "Common data {} already existed"
msgstr "{} 已经存在"
#: api/lib/common_setting/resp_format.py:66
msgid "Notice platform {} existed"
msgstr "{} 已经存在"
#: api/lib/common_setting/resp_format.py:67
msgid "Notice {} not existed"
msgstr "{} 配置项不存在"
#: api/lib/common_setting/resp_format.py:68
msgid "Notice please config messenger first"
msgstr "请先配置messenger URL"
#: api/lib/common_setting/resp_format.py:69
msgid "Notice bind err with empty mobile"
msgstr "绑定错误,手机号为空"
#: api/lib/common_setting/resp_format.py:70
msgid "Notice bind failed: {}"
msgstr "绑定失败: {}"
#: api/lib/common_setting/resp_format.py:71
msgid "Notice bind success"
msgstr "绑定成功"
#: api/lib/common_setting/resp_format.py:72
msgid "Notice remove bind success"
msgstr "解绑成功"
#: api/lib/common_setting/resp_format.py:74
msgid "Not support test type: {}"
msgstr "不支持的测试类型: {}"
#: api/lib/common_setting/resp_format.py:75
msgid "Not support auth type: {}"
msgstr "不支持的认证类型: {}"
#: api/lib/common_setting/resp_format.py:76
msgid "LDAP server connect timeout"
msgstr "LDAP服务器连接超时"
#: api/lib/common_setting/resp_format.py:77
msgid "LDAP server connect not available"
msgstr "LDAP服务器连接不可用"
#: api/lib/common_setting/resp_format.py:78
msgid "LDAP test unknown error: {}"
msgstr "LDAP测试未知错误: {}"
#: api/lib/common_setting/resp_format.py:79
msgid "Common data not support auth type: {}"
msgstr "通用数据不支持auth类型: {}"
#: api/lib/common_setting/resp_format.py:80
msgid "LDAP test username required"
msgstr "LDAP测试用户名必填"
#: api/lib/common_setting/resp_format.py:82
msgid "Company wide"
msgstr "全公司"
#: api/lib/perm/acl/resp_format.py:9
msgid "login successful"
msgstr "登录成功"
#: api/lib/perm/acl/resp_format.py:10
msgid "Failed to connect to LDAP service"
msgstr "连接LDAP服务失败"
#: api/lib/perm/acl/resp_format.py:11
msgid "Password verification failed"
msgstr "密码验证失败"
#: api/lib/perm/acl/resp_format.py:12
msgid "Application Token verification failed"
msgstr "应用 Token验证失败"
#: api/lib/perm/acl/resp_format.py:14
msgid ""
"You are not the application administrator or the session has expired (try"
" logging out and logging in again)"
msgstr "您不是应用管理员 或者 session失效(尝试一下退出重新登录)"
#: api/lib/perm/acl/resp_format.py:17
msgid "Resource type {} does not exist!"
msgstr "资源类型 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:18
msgid "Resource type {} already exists!"
msgstr "资源类型 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:20
msgid "Because there are resources under this type, they cannot be deleted!"
msgstr "因为该类型下有资源的存在, 不能删除!"
#: api/lib/perm/acl/resp_format.py:22
msgid "User {} does not exist!"
msgstr "用户 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:23
msgid "User {} already exists!"
msgstr "用户 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:24
msgid "Role {} does not exist!"
msgstr "角色 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:25
msgid "Role {} already exists!"
msgstr "角色 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:26
msgid "Global role {} does not exist!"
msgstr "全局角色 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:27
msgid "Global role {} already exists!"
msgstr "全局角色 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:29
msgid "You do not have {} permission on resource: {}"
msgstr "您没有资源: {} 的 {} 权限"
#: api/lib/perm/acl/resp_format.py:30
msgid "Requires administrator permissions"
msgstr "需要管理员权限"
#: api/lib/perm/acl/resp_format.py:31
msgid "Requires role: {}"
msgstr "需要角色: {}"
#: api/lib/perm/acl/resp_format.py:33
msgid "To delete a user role, please operate on the User Management page!"
msgstr "删除用户角色, 请在 用户管理 页面操作!"
#: api/lib/perm/acl/resp_format.py:35
msgid "Application {} already exists"
msgstr "应用 {} 已经存在"
#: api/lib/perm/acl/resp_format.py:36
msgid "Application {} does not exist!"
msgstr "应用 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:37
msgid "The Secret is invalid"
msgstr "应用的Secret无效"
#: api/lib/perm/acl/resp_format.py:39
msgid "Resource {} does not exist!"
msgstr "资源 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:40
msgid "Resource {} already exists!"
msgstr "资源 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:42
msgid "Resource group {} does not exist!"
msgstr "资源组 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:43
msgid "Resource group {} already exists!"
msgstr "资源组 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:45
msgid "Inheritance detected infinite loop"
msgstr "继承检测到了死循环"
#: api/lib/perm/acl/resp_format.py:46
msgid "Role relationship {} does not exist!"
msgstr "角色关系 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:48
msgid "Trigger {} does not exist!"
msgstr "触发器 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:49
msgid "Trigger {} already exists!"
msgstr "触发器 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:50
msgid "Trigger {} has been disabled!"
msgstr "Trigger {} has been disabled!"
#~ msgid "Not a valid date value."
#~ msgstr ""

View File

@@ -39,7 +39,7 @@ class LoginView(APIView):
password = request.values.get("password") password = request.values.get("password")
_role = None _role = None
config = AuthenticateDataCRUD(AuthenticateType.LDAP).get() config = AuthenticateDataCRUD(AuthenticateType.LDAP).get()
if config.get('LDAP', {}).get('enabled') or config.get('LDAP', {}).get('enable'): if config.get('enabled') or config.get('enable'):
from api.lib.perm.authentication.ldap import authenticate_with_ldap from api.lib.perm.authentication.ldap import authenticate_with_ldap
user, authenticated = authenticate_with_ldap(username, password) user, authenticated = authenticate_with_ldap(username, password)
else: else:

View File

@@ -43,9 +43,11 @@ class CIRelationSearchView(APIView):
facet = handle_arg_list(request.values.get("facet", "")) facet = handle_arg_list(request.values.get("facet", ""))
sort = request.values.get("sort") sort = request.values.get("sort")
reverse = request.values.get("reverse") in current_app.config.get('BOOL_TRUE') reverse = request.values.get("reverse") in current_app.config.get('BOOL_TRUE')
has_m2m = request.values.get("has_m2m") in current_app.config.get('BOOL_TRUE')
start = time.time() start = time.time()
s = Search(root_id, level, query, fl, facet, page, count, sort, reverse, ancestor_ids=ancestor_ids) s = Search(root_id, level, query, fl, facet, page, count, sort, reverse,
ancestor_ids=ancestor_ids, has_m2m=has_m2m)
try: try:
response, counter, total, page, numfound, facet = s.search() response, counter, total, page, numfound, facet = s.search()
except SearchError as e: except SearchError as e:
@@ -69,9 +71,10 @@ class CIRelationStatisticsView(APIView):
level = request.values.get('level', 1) level = request.values.get('level', 1)
type_ids = set(map(int, handle_arg_list(request.values.get('type_ids', [])))) type_ids = set(map(int, handle_arg_list(request.values.get('type_ids', []))))
ancestor_ids = request.values.get('ancestor_ids') or None # only for many to many ancestor_ids = request.values.get('ancestor_ids') or None # only for many to many
has_m2m = request.values.get("has_m2m") in current_app.config.get('BOOL_TRUE')
start = time.time() start = time.time()
s = Search(root_ids, level, ancestor_ids=ancestor_ids) s = Search(root_ids, level, ancestor_ids=ancestor_ids, has_m2m=has_m2m)
try: try:
result = s.statistics(type_ids) result = s.statistics(type_ids)
except SearchError as e: except SearchError as e:

View File

@@ -105,7 +105,6 @@ class CITypeGroupView(APIView):
return self.jsonify(group.to_dict()) return self.jsonify(group.to_dict())
@role_required(RoleEnum.CONFIG)
@args_validate(CITypeGroupManager.cls) @args_validate(CITypeGroupManager.cls)
def put(self, gid=None): def put(self, gid=None):
if "/order" in request.url: if "/order" in request.url:
@@ -167,7 +166,8 @@ class CITypeAttributeView(APIView):
t = CITypeCache.get(type_id) or CITypeCache.get(type_name) or abort(404, ErrFormat.ci_type_not_found) t = CITypeCache.get(type_id) or CITypeCache.get(type_name) or abort(404, ErrFormat.ci_type_not_found)
type_id = t.id type_id = t.id
unique_id = t.unique_id unique_id = t.unique_id
unique = AttributeCache.get(unique_id).name unique = AttributeCache.get(unique_id)
unique = unique and unique.name
attr_filter = CIFilterPermsCRUD.get_attr_filter(type_id) attr_filter = CIFilterPermsCRUD.get_attr_filter(type_id)
attributes = CITypeAttributeManager.get_attributes_by_type_id(type_id) attributes = CITypeAttributeManager.get_attributes_by_type_id(type_id)
@@ -319,12 +319,14 @@ class CITypeAttributeGroupView(APIView):
class CITypeTemplateView(APIView): class CITypeTemplateView(APIView):
url_prefix = ("/ci_types/template/import", "/ci_types/template/export") url_prefix = ("/ci_types/template/import", "/ci_types/template/export", "/ci_types/<int:type_id>/template/export")
@role_required(RoleEnum.CONFIG) @role_required(RoleEnum.CONFIG)
def get(self): # export def get(self, type_id=None): # export
return self.jsonify( if type_id is not None:
dict(ci_type_template=CITypeTemplateManager.export_template())) return self.jsonify(dict(ci_type_template=CITypeTemplateManager.export_template_by_type(type_id)))
return self.jsonify(dict(ci_type_template=CITypeTemplateManager.export_template()))
@role_required(RoleEnum.CONFIG) @role_required(RoleEnum.CONFIG)
def post(self): # import def post(self): # import
@@ -458,13 +460,21 @@ class CITypeGrantView(APIView):
_type = CITypeCache.get(type_id) _type = CITypeCache.get(type_id)
type_name = _type and _type.name or abort(404, ErrFormat.ci_type_not_found) type_name = _type and _type.name or abort(404, ErrFormat.ci_type_not_found)
acl = ACLManager('cmdb') acl = ACLManager('cmdb')
if not acl.has_permission(type_name, ResourceTypeEnum.CI_TYPE, PermEnum.GRANT) and \ if not acl.has_permission(type_name, ResourceTypeEnum.CI_TYPE, PermEnum.GRANT) and not is_app_admin('cmdb'):
not is_app_admin('cmdb'):
return abort(403, ErrFormat.no_permission.format(type_name, PermEnum.GRANT)) return abort(403, ErrFormat.no_permission.format(type_name, PermEnum.GRANT))
acl.grant_resource_to_role_by_rid(type_name, rid, ResourceTypeEnum.CI_TYPE, perms) acl.grant_resource_to_role_by_rid(type_name, rid, ResourceTypeEnum.CI_TYPE, perms, rebuild=False)
CIFilterPermsCRUD().add(type_id=type_id, rid=rid, **request.values) resource = None
if 'ci_filter' in request.values or 'attr_filter' in request.values:
resource = CIFilterPermsCRUD().add(type_id=type_id, rid=rid, **request.values)
if not resource:
from api.tasks.acl import role_rebuild
from api.lib.perm.acl.const import ACL_QUEUE
app_id = AppCache.get('cmdb').id
role_rebuild.apply_async(args=(rid, app_id), queue=ACL_QUEUE)
return self.jsonify(code=200) return self.jsonify(code=200)
@@ -482,21 +492,27 @@ class CITypeRevokeView(APIView):
_type = CITypeCache.get(type_id) _type = CITypeCache.get(type_id)
type_name = _type and _type.name or abort(404, ErrFormat.ci_type_not_found) type_name = _type and _type.name or abort(404, ErrFormat.ci_type_not_found)
acl = ACLManager('cmdb') acl = ACLManager('cmdb')
if not acl.has_permission(type_name, ResourceTypeEnum.CI_TYPE, PermEnum.GRANT) and \ if not acl.has_permission(type_name, ResourceTypeEnum.CI_TYPE, PermEnum.GRANT) and not is_app_admin('cmdb'):
not is_app_admin('cmdb'):
return abort(403, ErrFormat.no_permission.format(type_name, PermEnum.GRANT)) return abort(403, ErrFormat.no_permission.format(type_name, PermEnum.GRANT))
acl.revoke_resource_from_role_by_rid(type_name, rid, ResourceTypeEnum.CI_TYPE, perms) acl.revoke_resource_from_role_by_rid(type_name, rid, ResourceTypeEnum.CI_TYPE, perms, rebuild=False)
if PermEnum.READ in perms: app_id = AppCache.get('cmdb').id
CIFilterPermsCRUD().delete(type_id=type_id, rid=rid) resource = None
if PermEnum.READ in perms or not perms:
resource = CIFilterPermsCRUD().delete(type_id=type_id, rid=rid)
app_id = AppCache.get('cmdb').id if not resource:
users = RoleRelationCRUD.get_users_by_rid(rid, app_id) from api.tasks.acl import role_rebuild
for i in (users or []): from api.lib.perm.acl.const import ACL_QUEUE
if i.get('role', {}).get('id') and not RoleCRUD.has_permission(
i.get('role').get('id'), type_name, ResourceTypeEnum.CI_TYPE, app_id, PermEnum.READ): role_rebuild.apply_async(args=(rid, app_id), queue=ACL_QUEUE)
PreferenceManager.delete_by_type_id(type_id, i.get('uid'))
users = RoleRelationCRUD.get_users_by_rid(rid, app_id)
for i in (users or []):
if i.get('role', {}).get('id') and not RoleCRUD.has_permission(
i.get('role').get('id'), type_name, ResourceTypeEnum.CI_TYPE, app_id, PermEnum.READ):
PreferenceManager.delete_by_type_id(type_id, i.get('uid'))
return self.jsonify(type_id=type_id, rid=rid) return self.jsonify(type_id=type_id, rid=rid)
@@ -507,4 +523,3 @@ class CITypeFilterPermissionView(APIView):
@auth_with_app_token @auth_with_app_token
def get(self, type_id): def get(self, type_id):
return self.jsonify(CIFilterPermsCRUD().get(type_id)) return self.jsonify(CIFilterPermsCRUD().get(type_id))

View File

@@ -2,6 +2,7 @@
from flask import abort from flask import abort
from flask import current_app
from flask import request from flask import request
from api.lib.cmdb.ci_type import CITypeManager from api.lib.cmdb.ci_type import CITypeManager
@@ -187,3 +188,15 @@ class PreferenceRelationRevokeView(APIView):
acl.revoke_resource_from_role_by_rid(name, rid, ResourceTypeEnum.RELATION_VIEW, perms) acl.revoke_resource_from_role_by_rid(name, rid, ResourceTypeEnum.RELATION_VIEW, perms)
return self.jsonify(code=200) return self.jsonify(code=200)
class PreferenceCITypeOrderView(APIView):
url_prefix = ("/preference/ci_types/order",)
def post(self):
type_ids = request.values.get("type_ids")
is_tree = request.values.get("is_tree") in current_app.config.get('BOOL_TRUE')
PreferenceManager.upsert_ci_type_order(type_ids, is_tree)
return self.jsonify(type_ids=type_ids, is_tree=is_tree)

View File

@@ -62,7 +62,7 @@ class DepartmentView(APIView):
class DepartmentIDView(APIView): class DepartmentIDView(APIView):
url_prefix = (f'{prefix}/<int:_id>',) url_prefix = (f'{prefix}/<int:_id>',)
def get(self, _id): def put(self, _id):
form = DepartmentForm(MultiDict(request.json)) form = DepartmentForm(MultiDict(request.json))
if not form.validate(): if not form.validate():
abort(400, ','.join(['{}: {}'.format(filed, ','.join(msg)) abort(400, ','.join(['{}: {}'.format(filed, ','.join(msg))

View File

@@ -46,6 +46,8 @@ class PostFileView(APIView):
if not file: if not file:
abort(400, ErrFormat.file_is_required) abort(400, ErrFormat.file_is_required)
extension = file.mimetype.split('/')[-1] extension = file.mimetype.split('/')[-1]
if '+' in extension:
extension = file.filename.split('.')[-1]
if file.filename == '': if file.filename == '':
filename = f'.{extension}' filename = f'.{extension}'
else: else:

1
cmdb-api/babel.cfg Normal file
View File

@@ -0,0 +1 @@
[python: api/**.py]

View File

@@ -8,8 +8,9 @@ elasticsearch==7.17.9
email-validator==1.3.1 email-validator==1.3.1
environs==4.2.0 environs==4.2.0
flasgger==0.9.5 flasgger==0.9.5
Flask==2.3.2 Flask==2.2.5
Flask-Bcrypt==1.0.1 Flask-Bcrypt==1.0.1
flask-babel==4.0.0
Flask-Caching==2.0.2 Flask-Caching==2.0.2
Flask-Cors==4.0.0 Flask-Cors==4.0.0
Flask-Login>=0.6.2 Flask-Login>=0.6.2
@@ -45,7 +46,7 @@ supervisor==4.0.3
timeout-decorator==0.5.0 timeout-decorator==0.5.0
toposort==1.10 toposort==1.10
treelib==1.6.1 treelib==1.6.1
Werkzeug>=2.3.6 Werkzeug==2.2.3
WTForms==3.0.0 WTForms==3.0.0
shamir~=17.12.0 shamir~=17.12.0
pycryptodomex>=3.19.0 pycryptodomex>=3.19.0

View File

@@ -13,7 +13,7 @@ const getAntdSerials = (color) => {
const themePluginOption = { const themePluginOption = {
fileName: 'css/theme-colors-[contenthash:8].css', fileName: 'css/theme-colors-[contenthash:8].css',
matchColors: getAntdSerials('#1890ff'), // 主色系列 matchColors: getAntdSerials('#2f54eb'), // 主色系列
// 改变样式选择器,解决样式覆盖问题 // 改变样式选择器,解决样式覆盖问题
changeSelector (selector) { changeSelector (selector) {
switch (selector) { switch (selector) {

View File

@@ -27,7 +27,8 @@
"core-js": "^3.31.0", "core-js": "^3.31.0",
"echarts": "^5.3.2", "echarts": "^5.3.2",
"element-ui": "^2.15.10", "element-ui": "^2.15.10",
"exceljs": "^4.3.0", "exceljs": "^4.4.0",
"file-saver": "^2.0.5",
"html2canvas": "^1.0.0-rc.5", "html2canvas": "^1.0.0-rc.5",
"is-buffer": "^2.0.5", "is-buffer": "^2.0.5",
"jquery": "^3.6.0", "jquery": "^3.6.0",
@@ -47,6 +48,7 @@
"vue-codemirror": "^4.0.6", "vue-codemirror": "^4.0.6",
"vue-cropper": "^0.6.2", "vue-cropper": "^0.6.2",
"vue-grid-layout": "2.3.12", "vue-grid-layout": "2.3.12",
"vue-i18n": "8.28.2",
"vue-infinite-scroll": "^2.0.2", "vue-infinite-scroll": "^2.0.2",
"vue-json-editor": "^1.4.3", "vue-json-editor": "^1.4.3",
"vue-ls": "^3.2.1", "vue-ls": "^3.2.1",

View File

@@ -1,5 +1,5 @@
<template> <template>
<a-config-provider :locale="locale"> <a-config-provider :locale="antdLocale">
<div id="app" :class="{ 'ops-fullscreen': isOpsFullScreen, 'ops-only-topmenu': isOpsOnlyTopMenu }"> <div id="app" :class="{ 'ops-fullscreen': isOpsFullScreen, 'ops-only-topmenu': isOpsOnlyTopMenu }">
<router-view v-if="alive" /> <router-view v-if="alive" />
</div> </div>
@@ -7,8 +7,9 @@
</template> </template>
<script> <script>
import { mapActions } from 'vuex' import { mapState, mapActions, mapMutations } from 'vuex'
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN' import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import enUS from 'ant-design-vue/lib/locale-provider/en_US'
import { AppDeviceEnquire } from '@/utils/mixin' import { AppDeviceEnquire } from '@/utils/mixin'
import { debounce } from './utils/util' import { debounce } from './utils/util'
@@ -24,20 +25,28 @@ export default {
}, },
data() { data() {
return { return {
locale: zhCN,
alive: true, alive: true,
timer: null, timer: null,
} }
}, },
computed: { computed: {
...mapState(['locale']),
antdLocale() {
if (this.locale === 'zh') {
return zhCN
}
return enUS
},
isOpsFullScreen() { isOpsFullScreen() {
return this.$route.name === 'cmdb_screen' return ['cmdb_screen'].includes(this.$route.name)
}, },
isOpsOnlyTopMenu() { isOpsOnlyTopMenu() {
return ['fullscreen_index', 'setting_person'].includes(this.$route.name) return ['fullscreen_index', 'setting_person', 'notice_center'].includes(this.$route.name)
}, },
}, },
created() { created() {
this.SET_LOCALE(localStorage.getItem('ops_locale') || 'zh')
this.$i18n.locale = localStorage.getItem('ops_locale') || 'zh'
this.timer = setInterval(() => { this.timer = setInterval(() => {
this.setTime(new Date().getTime()) this.setTime(new Date().getTime())
}, 1000) }, 1000)
@@ -184,6 +193,7 @@ export default {
}, },
methods: { methods: {
...mapActions(['setTime']), ...mapActions(['setTime']),
...mapMutations(['SET_LOCALE']),
reload() { reload() {
this.alive = false this.alive = false
this.$nextTick(() => { this.$nextTick(() => {

View File

@@ -1,29 +1,37 @@
export const ruleTypeList = [ import i18n from '@/lang'
{ value: 'and', label: '与' },
{ value: 'or', label: '或' },
// { value: 'not', label: '非' },
]
export const expList = [ export const ruleTypeList = () => {
{ value: 'is', label: '等于' }, return [
{ value: '~is', label: '不等于' }, { value: 'and', label: i18n.t('cmdbFilterComp.and') },
{ value: 'contain', label: '包含' }, { value: 'or', label: i18n.t('cmdbFilterComp.or') },
{ value: '~contain', label: '不包含' }, // { value: 'not', label: '非' },
{ value: 'start_with', label: '以...开始' }, ]
{ value: '~start_with', label: '不以...开始' }, }
{ value: 'end_with', label: '以...结束' },
{ value: '~end_with', label: '不以...结束' },
{ value: '~value', label: '为空' }, // 为空的定义有点绕
{ value: 'value', label: '不为空' },
]
export const advancedExpList = [ export const expList = () => {
{ value: 'in', label: 'in查询' }, return [
{ value: '~in', label: '非in查询' }, { value: 'is', label: i18n.t('cmdbFilterComp.is') },
{ value: 'range', label: '范围' }, { value: '~is', label: i18n.t('cmdbFilterComp.~is') },
{ value: '~range', label: '范围外' }, { value: 'contain', label: i18n.t('cmdbFilterComp.contain') },
{ value: 'compare', label: '比较' }, { value: '~contain', label: i18n.t('cmdbFilterComp.~contain') },
] { value: 'start_with', label: i18n.t('cmdbFilterComp.start_with') },
{ value: '~start_with', label: i18n.t('cmdbFilterComp.~start_with') },
{ value: 'end_with', label: i18n.t('cmdbFilterComp.end_with') },
{ value: '~end_with', label: i18n.t('cmdbFilterComp.~end_with') },
{ value: '~value', label: i18n.t('cmdbFilterComp.~value') }, // 为空的定义有点绕
{ value: 'value', label: i18n.t('cmdbFilterComp.value') },
]
}
export const advancedExpList = () => {
return [
{ value: 'in', label: i18n.t('cmdbFilterComp.in') },
{ value: '~in', label: i18n.t('cmdbFilterComp.~in') },
{ value: 'range', label: i18n.t('cmdbFilterComp.range') },
{ value: '~range', label: i18n.t('cmdbFilterComp.~range') },
{ value: 'compare', label: i18n.t('cmdbFilterComp.compare') },
]
}
export const compareTypeList = [ export const compareTypeList = [
{ value: '1', label: '>' }, { value: '1', label: '>' },

View File

@@ -1,293 +1,332 @@
<template> <template>
<div> <div>
<a-space :style="{ display: 'flex', marginBottom: '10px' }" v-for="(item, index) in ruleList" :key="item.id"> <a-space :style="{ display: 'flex', marginBottom: '10px' }" v-for="(item, index) in ruleList" :key="item.id">
<div :style="{ width: '50px', height: '24px', position: 'relative' }"> <div :style="{ width: '70px', height: '24px', position: 'relative' }">
<treeselect <treeselect
v-if="index" v-if="index"
class="custom-treeselect" class="custom-treeselect"
:style="{ width: '50px', '--custom-height': '24px', position: 'absolute', top: '-17px', left: 0 }" :style="{ width: '70px', '--custom-height': '24px', position: 'absolute', top: '-17px', left: 0 }"
v-model="item.type" v-model="item.type"
:multiple="false" :multiple="false"
:clearable="false" :clearable="false"
searchable searchable
:options="ruleTypeList" :options="ruleTypeList"
:normalizer=" :normalizer="
(node) => { (node) => {
return { return {
id: node.value, id: node.value,
label: node.label, label: node.label,
children: node.children, children: node.children,
} }
} }
" "
> >
</treeselect> </treeselect>
</div> </div>
<treeselect <treeselect
class="custom-treeselect" class="custom-treeselect"
:style="{ width: '130px', '--custom-height': '24px' }" :style="{ width: '130px', '--custom-height': '24px' }"
v-model="item.property" v-model="item.property"
:multiple="false" :multiple="false"
:clearable="false" :clearable="false"
searchable searchable
:options="canSearchPreferenceAttrList" :options="canSearchPreferenceAttrList"
:normalizer=" :normalizer="
(node) => { (node) => {
return { return {
id: node.name, id: node.name,
label: node.alias || node.name, label: node.alias || node.name,
children: node.children, children: node.children,
} }
} }
" "
appendToBody appendToBody
:zIndex="1050" :zIndex="1050"
> >
<div <div
:title="node.label" :title="node.label"
slot="option-label" slot="option-label"
slot-scope="{ node }" slot-scope="{ node }"
:style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }" :style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }"
> >
<ValueTypeMapIcon :attr="node.raw" /> <ValueTypeMapIcon :attr="node.raw" />
{{ node.label }} {{ node.label }}
</div> </div>
<div <div
:style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }" :style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }"
slot="value-label" slot="value-label"
slot-scope="{ node }" slot-scope="{ node }"
> >
<ValueTypeMapIcon :attr="node.raw" /> {{ node.label }} <ValueTypeMapIcon :attr="node.raw" /> {{ node.label }}
</div> </div>
</treeselect> </treeselect>
<treeselect <treeselect
class="custom-treeselect" class="custom-treeselect"
:style="{ width: '100px', '--custom-height': '24px' }" :style="{ width: '100px', '--custom-height': '24px' }"
v-model="item.exp" v-model="item.exp"
:multiple="false" :multiple="false"
:clearable="false" :clearable="false"
searchable searchable
:options="[...getExpListByProperty(item.property), ...advancedExpList]" :options="[...getExpListByProperty(item.property), ...advancedExpList]"
:normalizer=" :normalizer="
(node) => { (node) => {
return { return {
id: node.value, id: node.value,
label: node.label, label: node.label,
children: node.children, children: node.children,
} }
} }
" "
@select="(value) => handleChangeExp(value, item, index)" @select="(value) => handleChangeExp(value, item, index)"
appendToBody appendToBody
:zIndex="1050" :zIndex="1050"
> >
</treeselect> </treeselect>
<treeselect <treeselect
class="custom-treeselect" class="custom-treeselect"
:style="{ width: '175px', '--custom-height': '24px' }" :style="{ width: '175px', '--custom-height': '24px' }"
v-model="item.value" v-model="item.value"
:multiple="false" :multiple="false"
:clearable="false" :clearable="false"
searchable searchable
v-if="isChoiceByProperty(item.property) && (item.exp === 'is' || item.exp === '~is')" v-if="isChoiceByProperty(item.property) && (item.exp === 'is' || item.exp === '~is')"
:options="getChoiceValueByProperty(item.property)" :options="getChoiceValueByProperty(item.property)"
placeholder="请选择" :placeholder="$t('placeholder2')"
:normalizer=" :normalizer="
(node) => { (node) => {
return { return {
id: node[0], id: node[0],
label: node[0], label: node[0],
children: node.children, children: node.children,
} }
} }
" "
appendToBody appendToBody
:zIndex="1050" :zIndex="1050"
> >
<div <div
:title="node.label" :title="node.label"
slot="option-label" slot="option-label"
slot-scope="{ node }" slot-scope="{ node }"
:style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }" :style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }"
> >
{{ node.label }} {{ node.label }}
</div> </div>
</treeselect> </treeselect>
<a-input-group <a-input-group
size="small" size="small"
compact compact
v-else-if="item.exp === 'range' || item.exp === '~range'" v-else-if="item.exp === 'range' || item.exp === '~range'"
:style="{ width: '175px' }" :style="{ width: '175px' }"
> >
<a-input class="ops-input" size="small" v-model="item.min" :style="{ width: '78px' }" placeholder="最小值" /> <a-input
~ class="ops-input"
<a-input class="ops-input" size="small" v-model="item.max" :style="{ width: '78px' }" placeholder="最大值" /> size="small"
</a-input-group> v-model="item.min"
<a-input-group size="small" compact v-else-if="item.exp === 'compare'" :style="{ width: '175px' }"> :style="{ width: '78px' }"
<treeselect :placeholder="$t('min')"
class="custom-treeselect" />
:style="{ width: '60px', '--custom-height': '24px' }" ~
v-model="item.compareType" <a-input
:multiple="false" class="ops-input"
:clearable="false" size="small"
searchable v-model="item.max"
:options="compareTypeList" :style="{ width: '78px' }"
:normalizer=" :placeholder="$t('max')"
(node) => { />
return { </a-input-group>
id: node.value, <a-input-group size="small" compact v-else-if="item.exp === 'compare'" :style="{ width: '175px' }">
label: node.label, <treeselect
children: node.children, class="custom-treeselect"
} :style="{ width: '60px', '--custom-height': '24px' }"
} v-model="item.compareType"
" :multiple="false"
appendToBody :clearable="false"
:zIndex="1050" searchable
> :options="compareTypeList"
</treeselect> :normalizer="
<a-input class="ops-input" v-model="item.value" size="small" style="width: 113px" /> (node) => {
</a-input-group> return {
<a-input id: node.value,
v-else-if="item.exp !== 'value' && item.exp !== '~value'" label: node.label,
size="small" children: node.children,
v-model="item.value" }
:placeholder="item.exp === 'in' || item.exp === '~in' ? '以 ; 分隔' : ''" }
class="ops-input" "
></a-input> appendToBody
<div v-else :style="{ width: '175px' }"></div> :zIndex="1050"
<a-tooltip title="复制"> >
<a class="operation" @click="handleCopyRule(item)"><ops-icon type="icon-xianxing-copy"/></a> </treeselect>
</a-tooltip> <a-input class="ops-input" v-model="item.value" size="small" style="width: 113px" />
<a-tooltip title="删除"> </a-input-group>
<a class="operation" @click="handleDeleteRule(item)"><ops-icon type="icon-xianxing-delete"/></a> <a-input
</a-tooltip> v-else-if="item.exp !== 'value' && item.exp !== '~value'"
</a-space> size="small"
<div class="table-filter-add"> v-model="item.value"
<a @click="handleAddRule">+ 新增</a> :placeholder="item.exp === 'in' || item.exp === '~in' ? $t('cmdbFilterComp.split', { separator: ';' }) : ''"
</div> class="ops-input"
</div> :style="{ width: '175px' }"
</template> ></a-input>
<div v-else :style="{ width: '175px' }"></div>
<script> <a-tooltip :title="$t('copy')">
import _ from 'lodash' <a class="operation" @click="handleCopyRule(item)"><ops-icon type="icon-xianxing-copy"/></a>
import { v4 as uuidv4 } from 'uuid' </a-tooltip>
import { ruleTypeList, expList, advancedExpList, compareTypeList } from './constants' <a-tooltip :title="$t('delete')">
import ValueTypeMapIcon from '../CMDBValueTypeMapIcon' <a class="operation" @click="handleDeleteRule(item)"><ops-icon type="icon-xianxing-delete"/></a>
</a-tooltip>
export default { <a-tooltip :title="$t('cmdbFilterComp.addHere')" v-if="needAddHere">
name: 'Expression', <a class="operation" @click="handleAddRuleAt(item)"><a-icon type="plus-circle"/></a>
components: { ValueTypeMapIcon }, </a-tooltip>
model: { </a-space>
prop: 'value', <div class="table-filter-add">
event: 'change', <a @click="handleAddRule">+ {{ $t('new') }}</a>
}, </div>
props: { </div>
value: { </template>
type: Array,
default: () => [], <script>
}, import _ from 'lodash'
canSearchPreferenceAttrList: { import { v4 as uuidv4 } from 'uuid'
type: Array, import { ruleTypeList, expList, advancedExpList, compareTypeList } from './constants'
required: true, import ValueTypeMapIcon from '../CMDBValueTypeMapIcon'
default: () => [],
}, export default {
}, name: 'Expression',
data() { components: { ValueTypeMapIcon },
return { model: {
ruleTypeList, prop: 'value',
expList, event: 'change',
advancedExpList, },
compareTypeList, props: {
} value: {
}, type: Array,
computed: { default: () => [],
ruleList: { },
get() { canSearchPreferenceAttrList: {
return this.value type: Array,
}, required: true,
set(val) { default: () => [],
this.$emit('change', val) },
return val needAddHere: {
}, type: Boolean,
}, default: false,
}, },
methods: { },
getExpListByProperty(property) { data() {
if (property) { return {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property) compareTypeList,
if (_find && ['0', '1', '3', '4', '5'].includes(_find.value_type)) { }
return [ },
{ value: 'is', label: '等于' }, computed: {
{ value: '~is', label: '不等于' }, ruleList: {
{ value: '~value', label: '为空' }, // 为空的定义有点绕 get() {
{ value: 'value', label: '不为空' }, return this.value
] },
} set(val) {
return this.expList this.$emit('change', val)
} return val
return this.expList },
}, },
isChoiceByProperty(property) { ruleTypeList() {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property) return ruleTypeList()
if (_find) { },
return _find.is_choice expList() {
} return expList()
return false },
}, advancedExpList() {
handleAddRule() { return advancedExpList()
this.ruleList.push({ },
id: uuidv4(), },
type: 'and', methods: {
property: this.canSearchPreferenceAttrList[0]?.name, getExpListByProperty(property) {
exp: 'is', if (property) {
value: null, const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property)
}) if (_find && ['0', '1', '3', '4', '5'].includes(_find.value_type)) {
this.$emit('change', this.ruleList) return [
}, { value: 'is', label: this.$t('cmdbFilterComp.is') },
handleCopyRule(item) { { value: '~is', label: this.$t('cmdbFilterComp.~is') },
this.ruleList.push({ ...item, id: uuidv4() }) { value: '~value', label: this.$t('cmdbFilterComp.~value') }, // 为空的定义有点绕
this.$emit('change', this.ruleList) { value: 'value', label: this.$t('cmdbFilterComp.value') },
}, ]
handleDeleteRule(item) { }
const idx = this.ruleList.findIndex((r) => r.id === item.id) return this.expList
if (idx > -1) { }
this.ruleList.splice(idx, 1) return this.expList
} },
this.$emit('change', this.ruleList) isChoiceByProperty(property) {
}, const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property)
getChoiceValueByProperty(property) { if (_find) {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property) return _find.is_choice
if (_find) { }
return _find.choice_value return false
} },
return [] handleAddRule() {
}, this.ruleList.push({
handleChangeExp({ value }, item, index) { id: uuidv4(),
const _ruleList = _.cloneDeep(this.ruleList) type: 'and',
if (value === 'range') { property: this.canSearchPreferenceAttrList[0]?.name,
_ruleList[index] = { exp: 'is',
..._ruleList[index], value: null,
min: '', })
max: '', this.$emit('change', this.ruleList)
exp: value, },
} handleCopyRule(item) {
} else if (value === 'compare') { this.ruleList.push({ ...item, id: uuidv4() })
_ruleList[index] = { this.$emit('change', this.ruleList)
..._ruleList[index], },
compareType: '1', handleDeleteRule(item) {
exp: value, const idx = this.ruleList.findIndex((r) => r.id === item.id)
} if (idx > -1) {
} else { this.ruleList.splice(idx, 1)
_ruleList[index] = { }
..._ruleList[index], this.$emit('change', this.ruleList)
exp: value, },
} handleAddRuleAt(item) {
} const idx = this.ruleList.findIndex((r) => r.id === item.id)
this.ruleList = _ruleList if (idx > -1) {
this.$emit('change', this.ruleList) this.ruleList.splice(idx, 0, {
}, id: uuidv4(),
}, type: 'and',
} property: this.canSearchPreferenceAttrList[0]?.name,
</script> exp: 'is',
value: null,
<style></style> })
}
this.$emit('change', this.ruleList)
},
getChoiceValueByProperty(property) {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property)
if (_find) {
return _find.choice_value
}
return []
},
handleChangeExp({ value }, item, index) {
const _ruleList = _.cloneDeep(this.ruleList)
if (value === 'range') {
_ruleList[index] = {
..._ruleList[index],
min: '',
max: '',
exp: value,
}
} else if (value === 'compare') {
_ruleList[index] = {
..._ruleList[index],
compareType: '1',
exp: value,
}
} else {
_ruleList[index] = {
..._ruleList[index],
exp: value,
}
}
this.ruleList = _ruleList
this.$emit('change', this.ruleList)
},
},
}
</script>
<style></style>

View File

@@ -1,290 +1,296 @@
<template> <template>
<div> <div>
<a-popover <a-popover
v-if="isDropdown" v-if="isDropdown"
v-model="visible" v-model="visible"
trigger="click" trigger="click"
:placement="placement" :placement="placement"
overlayClassName="table-filter" overlayClassName="table-filter"
@visibleChange="visibleChange" @visibleChange="visibleChange"
> >
<slot name="popover_item"> <slot name="popover_item">
<a-button type="primary" ghost>条件过滤<a-icon type="filter"/></a-button> <a-button type="primary" ghost>{{ $t('cmdbFilterComp.conditionFilter') }}<a-icon type="filter"/></a-button>
</slot> </slot>
<template slot="content"> <template slot="content">
<Expression <Expression
v-model="ruleList" :needAddHere="needAddHere"
:canSearchPreferenceAttrList="canSearchPreferenceAttrList.filter((attr) => !attr.is_password)" v-model="ruleList"
/> :canSearchPreferenceAttrList="canSearchPreferenceAttrList.filter((attr) => !attr.is_password)"
<a-divider :style="{ margin: '10px 0' }" /> />
<div style="width:534px"> <a-divider :style="{ margin: '10px 0' }" />
<a-space :style="{ display: 'flex', justifyContent: 'flex-end' }"> <div style="width:554px">
<a-button type="primary" size="small" @click="handleSubmit">确定</a-button> <a-space :style="{ display: 'flex', justifyContent: 'flex-end' }">
<a-button size="small" @click="handleClear">清空</a-button> <a-button type="primary" size="small" @click="handleSubmit">{{ $t('confirm') }}</a-button>
</a-space> <a-button size="small" @click="handleClear">{{ $t('clear') }}</a-button>
</div> </a-space>
</template> </div>
</a-popover> </template>
<Expression </a-popover>
v-else <Expression
v-model="ruleList" :needAddHere="needAddHere"
:canSearchPreferenceAttrList="canSearchPreferenceAttrList.filter((attr) => !attr.is_password)" v-else
/> v-model="ruleList"
</div> :canSearchPreferenceAttrList="canSearchPreferenceAttrList.filter((attr) => !attr.is_password)"
</template> />
</div>
<script> </template>
import { v4 as uuidv4 } from 'uuid'
import Expression from './expression.vue' <script>
import { advancedExpList, compareTypeList } from './constants' import { v4 as uuidv4 } from 'uuid'
import Expression from './expression.vue'
export default { import { advancedExpList, compareTypeList } from './constants'
name: 'FilterComp',
components: { Expression }, export default {
props: { name: 'FilterComp',
canSearchPreferenceAttrList: { components: { Expression },
type: Array, props: {
required: true, canSearchPreferenceAttrList: {
default: () => [], type: Array,
}, required: true,
expression: { default: () => [],
type: String, },
default: '', expression: {
}, type: String,
regQ: { default: '',
type: String, },
default: '(?<=q=).+(?=&)|(?<=q=).+$', regQ: {
}, type: String,
placement: { default: '(?<=q=).+(?=&)|(?<=q=).+$',
type: String, },
default: 'bottomRight', placement: {
}, type: String,
isDropdown: { default: 'bottomRight',
type: Boolean, },
default: true, isDropdown: {
}, type: Boolean,
}, default: true,
data() { },
return { needAddHere: {
advancedExpList, type: Boolean,
compareTypeList, default: false,
visible: false, },
ruleList: [], },
filterExp: '', data() {
} return {
}, advancedExpList,
compareTypeList,
methods: { visible: false,
visibleChange(open, isInitOne = true) { ruleList: [],
// isInitOne 初始化exp为空时ruleList是否默认给一条 filterExp: '',
// const regQ = /(?<=q=).+(?=&)|(?<=q=).+$/g }
const exp = this.expression.match(new RegExp(this.regQ, 'g')) },
? this.expression.match(new RegExp(this.regQ, 'g'))[0]
: null methods: {
if (open && exp) { visibleChange(open, isInitOne = true) {
const expArray = exp.split(',').map((item) => { // isInitOne 初始化exp为空时ruleList是否默认给一条
let has_not = '' // const regQ = /(?<=q=).+(?=&)|(?<=q=).+$/g
const key = item.split(':')[0] const exp = this.expression.match(new RegExp(this.regQ, 'g'))
const val = item ? this.expression.match(new RegExp(this.regQ, 'g'))[0]
.split(':') : null
.slice(1) if (open && exp) {
.join(':') const expArray = exp.split(',').map((item) => {
let type, property, exp, value, min, max, compareType let has_not = ''
if (key.includes('-')) { const key = item.split(':')[0]
type = 'or' const val = item
if (key.includes('~')) { .split(':')
property = key.substring(2) .slice(1)
has_not = '~' .join(':')
} else { let type, property, exp, value, min, max, compareType
property = key.substring(1) if (key.includes('-')) {
} type = 'or'
} else { if (key.includes('~')) {
type = 'and' property = key.substring(2)
if (key.includes('~')) { has_not = '~'
property = key.substring(1) } else {
has_not = '~' property = key.substring(1)
} else { }
property = key } else {
} type = 'and'
} if (key.includes('~')) {
property = key.substring(1)
const in_reg = /(?<=\().+(?=\))/g has_not = '~'
const range_reg = /(?<=\[).+(?=\])/g } else {
const compare_reg = /(?<=>=|<=|>(?!=)|<(?!=)).+/ property = key
if (val === '*') { }
exp = has_not + 'value' }
value = ''
} else if (in_reg.test(val)) { const in_reg = /(?<=\().+(?=\))/g
exp = has_not + 'in' const range_reg = /(?<=\[).+(?=\])/g
value = val.match(in_reg)[0] const compare_reg = /(?<=>=|<=|>(?!=)|<(?!=)).+/
} else if (range_reg.test(val)) { if (val === '*') {
exp = has_not + 'range' exp = has_not + 'value'
value = val.match(range_reg)[0] value = ''
min = value.split('_TO_')[0] } else if (in_reg.test(val)) {
max = value.split('_TO_')[1] exp = has_not + 'in'
} else if (compare_reg.test(val)) { value = val.match(in_reg)[0]
exp = has_not + 'compare' } else if (range_reg.test(val)) {
value = val.match(compare_reg)[0] exp = has_not + 'range'
const _compareType = val.substring(0, val.match(compare_reg)['index']) value = val.match(range_reg)[0]
const idx = compareTypeList.findIndex((item) => item.label === _compareType) min = value.split('_TO_')[0]
compareType = compareTypeList[idx].value max = value.split('_TO_')[1]
} else if (!val.includes('*')) { } else if (compare_reg.test(val)) {
exp = has_not + 'is' exp = has_not + 'compare'
value = val value = val.match(compare_reg)[0]
} else { const _compareType = val.substring(0, val.match(compare_reg)['index'])
const resList = [ const idx = compareTypeList.findIndex((item) => item.label === _compareType)
['contain', /(?<=\*).*(?=\*)/g], compareType = compareTypeList[idx].value
['end_with', /(?<=\*).+/g], } else if (!val.includes('*')) {
['start_with', /.+(?=\*)/g], exp = has_not + 'is'
] value = val
for (let i = 0; i < 3; i++) { } else {
const reg = resList[i] const resList = [
if (reg[1].test(val)) { ['contain', /(?<=\*).*(?=\*)/g],
exp = has_not + reg[0] ['end_with', /(?<=\*).+/g],
value = val.match(reg[1])[0] ['start_with', /.+(?=\*)/g],
break ]
} for (let i = 0; i < 3; i++) {
} const reg = resList[i]
} if (reg[1].test(val)) {
return { exp = has_not + reg[0]
id: uuidv4(), value = val.match(reg[1])[0]
type, break
property, }
exp, }
value, }
min, return {
max, id: uuidv4(),
compareType, type,
} property,
}) exp,
this.ruleList = [...expArray] value,
} else if (open) { min,
const _canSearchPreferenceAttrList = this.canSearchPreferenceAttrList.filter((attr) => !attr.is_password) max,
this.ruleList = isInitOne compareType,
? [ }
{ })
id: uuidv4(), this.ruleList = [...expArray]
type: 'and', } else if (open) {
property: const _canSearchPreferenceAttrList = this.canSearchPreferenceAttrList.filter((attr) => !attr.is_password)
_canSearchPreferenceAttrList && _canSearchPreferenceAttrList.length this.ruleList = isInitOne
? _canSearchPreferenceAttrList[0].name ? [
: undefined, {
exp: 'is', id: uuidv4(),
value: null, type: 'and',
}, property:
] _canSearchPreferenceAttrList && _canSearchPreferenceAttrList.length
: [] ? _canSearchPreferenceAttrList[0].name
} : undefined,
}, exp: 'is',
handleClear() { value: null,
this.ruleList = [ },
{ ]
id: uuidv4(), : []
type: 'and', }
property: this.canSearchPreferenceAttrList[0].name, },
exp: 'is', handleClear() {
value: null, this.ruleList = [
}, {
] id: uuidv4(),
this.filterExp = '' type: 'and',
this.visible = false property: this.canSearchPreferenceAttrList[0].name,
this.$emit('setExpFromFilter', this.filterExp) exp: 'is',
}, value: null,
handleSubmit() { },
if (this.ruleList && this.ruleList.length) { ]
this.ruleList[0].type = 'and' // 增删后以防万一第一个不是and this.filterExp = ''
this.filterExp = '' this.visible = false
const expList = this.ruleList.map((rule) => { this.$emit('setExpFromFilter', this.filterExp)
let singleRuleExp = '' },
let _exp = rule.exp handleSubmit() {
if (rule.type === 'or') { if (this.ruleList && this.ruleList.length) {
singleRuleExp += '-' this.ruleList[0].type = 'and' // 增删后以防万一第一个不是and
} this.filterExp = ''
if (rule.exp.includes('~')) { const expList = this.ruleList.map((rule) => {
singleRuleExp += '~' let singleRuleExp = ''
_exp = rule.exp.split('~')[1] let _exp = rule.exp
} if (rule.type === 'or') {
singleRuleExp += `${rule.property}:` singleRuleExp += '-'
if (_exp === 'is') { }
singleRuleExp += `${rule.value ?? ''}` if (rule.exp.includes('~')) {
} singleRuleExp += '~'
if (_exp === 'contain') { _exp = rule.exp.split('~')[1]
singleRuleExp += `*${rule.value ?? ''}*` }
} singleRuleExp += `${rule.property}:`
if (_exp === 'start_with') { if (_exp === 'is') {
singleRuleExp += `${rule.value ?? ''}*` singleRuleExp += `${rule.value ?? ''}`
} }
if (_exp === 'end_with') { if (_exp === 'contain') {
singleRuleExp += `*${rule.value ?? ''}` singleRuleExp += `*${rule.value ?? ''}*`
} }
if (_exp === 'value') { if (_exp === 'start_with') {
singleRuleExp += `*` singleRuleExp += `${rule.value ?? ''}*`
} }
if (_exp === 'in') { if (_exp === 'end_with') {
singleRuleExp += `(${rule.value ?? ''})` singleRuleExp += `*${rule.value ?? ''}`
} }
if (_exp === 'range') { if (_exp === 'value') {
singleRuleExp += `[${rule.min}_TO_${rule.max}]` singleRuleExp += `*`
} }
if (_exp === 'compare') { if (_exp === 'in') {
const idx = compareTypeList.findIndex((item) => item.value === rule.compareType) singleRuleExp += `(${rule.value ?? ''})`
singleRuleExp += `${compareTypeList[idx].label}${rule.value ?? ''}` }
} if (_exp === 'range') {
return singleRuleExp singleRuleExp += `[${rule.min}_TO_${rule.max}]`
}) }
this.filterExp = expList.join(',') if (_exp === 'compare') {
this.$emit('setExpFromFilter', this.filterExp) const idx = compareTypeList.findIndex((item) => item.value === rule.compareType)
} else { singleRuleExp += `${compareTypeList[idx].label}${rule.value ?? ''}`
this.$emit('setExpFromFilter', '') }
} return singleRuleExp
this.visible = false })
}, this.filterExp = expList.join(',')
}, this.$emit('setExpFromFilter', this.filterExp)
} } else {
</script> this.$emit('setExpFromFilter', '')
}
<style lang="less" scoped> this.visible = false
.table-filter { },
.table-filter-add { },
margin-top: 10px; }
& > a { </script>
padding: 2px 8px;
&:hover { <style lang="less" scoped>
background-color: #f0faff; .table-filter {
border-radius: 5px; .table-filter-add {
} margin-top: 10px;
} & > a {
} padding: 2px 8px;
.table-filter-extra-icon { &:hover {
padding: 0px 2px; background-color: #f0faff;
&:hover { border-radius: 5px;
display: inline-block; }
border-radius: 5px; }
background-color: #f0faff; }
} .table-filter-extra-icon {
} padding: 0px 2px;
} &:hover {
</style> display: inline-block;
border-radius: 5px;
<style lang="less"> background-color: #f0faff;
.table-filter-extra-operation { }
.ant-popover-inner-content { }
padding: 3px 4px; }
.operation { </style>
cursor: pointer;
width: 90px; <style lang="less">
height: 30px; .table-filter-extra-operation {
line-height: 30px; .ant-popover-inner-content {
padding: 3px 4px; padding: 3px 4px;
border-radius: 5px; .operation {
transition: all 0.3s; cursor: pointer;
&:hover { width: 90px;
background-color: #f0faff; height: 30px;
} line-height: 30px;
> .anticon { padding: 3px 4px;
margin-right: 10px; border-radius: 5px;
} transition: all 0.3s;
} &:hover {
} background-color: #f0faff;
} }
</style> > .anticon {
margin-right: 10px;
}
}
}
}
</style>

View File

@@ -89,20 +89,23 @@ export default {
}, },
}, },
data() { data() {
const keyMapList = [
{ value: 'default', label: '默认' },
{ value: 'vim', label: 'vim' },
{ value: 'emacs', label: 'emacs' },
{ value: 'sublime', label: 'sublime' },
]
return { return {
keyMapList,
coder: null, coder: null,
fontSize: 14, fontSize: 14,
keyMap: 'default', keyMap: 'default',
fullscreenExitVisible: false, fullscreenExitVisible: false,
} }
}, },
computed: {
keyMapList() {
return [
{ value: 'default', label: this.$t('default') },
{ value: 'vim', label: 'vim' },
{ value: 'emacs', label: 'emacs' },
{ value: 'sublime', label: 'sublime' },
]
},
},
mounted() {}, mounted() {},
methods: { methods: {
initCodeMirror(codeContent) { initCodeMirror(codeContent) {

View File

@@ -1,8 +1,10 @@
export const iconTypeList = [ import i18n from '@/lang'
export const iconTypeList = () => [
// { value: '0', label: '常用' }, // { value: '0', label: '常用' },
{ value: '1', label: '线性' }, { value: '1', label: i18n.t('customIconSelect.outlined') },
{ value: '2', label: '实底' }, { value: '2', label: i18n.t('customIconSelect.filled') },
{ value: '3', label: '多色' } { value: '3', label: i18n.t('customIconSelect.multicolor') }
] ]
export const commonIconList = ['changyong-ubuntu', export const commonIconList = ['changyong-ubuntu',

View File

@@ -16,7 +16,7 @@
{{ item.label }} {{ item.label }}
</div> </div>
<div :class="`${currentIconType === '4' ? 'selected' : ''}`" @click="handleChangeIconType('4')"> <div :class="`${currentIconType === '4' ? 'selected' : ''}`" @click="handleChangeIconType('4')">
自定义 {{ this.$t('customIconSelect.custom') }}
</div> </div>
<a-upload <a-upload
slot="description" slot="description"
@@ -26,7 +26,7 @@
accept=".svg,.png,.jpg,.jpeg" accept=".svg,.png,.jpg,.jpeg"
v-if="currentIconType === '4'" v-if="currentIconType === '4'"
> >
<a-button icon="plus" size="small" type="primary">添加</a-button> <a-button icon="plus" size="small" type="primary">{{ $t('add') }}</a-button>
</a-upload> </a-upload>
</div> </div>
<div class="custom-icon-select-popover-content"> <div class="custom-icon-select-popover-content">
@@ -55,11 +55,11 @@
@click="clickCustomIcon(icon)" @click="clickCustomIcon(icon)"
> >
<div class="custom-icon-select-popover-content-img-box"> <div class="custom-icon-select-popover-content-img-box">
<img :src="`/api/common-setting/v1/file/${icon.data.url}`" /> <img v-if="icon.data && icon.data.url" :src="`/api/common-setting/v1/file/${icon.data.url}`" />
<a-popconfirm <a-popconfirm
overlayClassName="custom-icon-select-confirm-popover" overlayClassName="custom-icon-select-confirm-popover"
:getPopupContainer="(trigger) => trigger.parentNode" :getPopupContainer="(trigger) => trigger.parentNode"
title="确认删除?" :title="$t('confirmDelete')"
@confirm="(e) => deleteIcon(e, icon)" @confirm="(e) => deleteIcon(e, icon)"
@cancel=" @cancel="
(e) => { (e) => {
@@ -92,7 +92,7 @@
:show-upload-list="false" :show-upload-list="false"
accept=".svg,.png,.jpg,.jpeg" accept=".svg,.png,.jpg,.jpeg"
> >
<a> 暂无自定义图标点击此处上传 </a> <a> {{ $t('customIconSelect.nodata') }} </a>
</a-upload> </a-upload>
</a-empty> </a-empty>
</div> </div>
@@ -102,27 +102,27 @@
</template> </template>
<a-form class="custom-icon-select-form" :form="form" v-show="currentIconType === '4' && formVisible"> <a-form class="custom-icon-select-form" :form="form" v-show="currentIconType === '4' && formVisible">
<a-form-item <a-form-item
label="名称" :label="$t('name')"
:labelCol="{ span: 4 }" :labelCol="{ span: 4 }"
:wrapperCol="{ span: 16 }" :wrapperCol="{ span: 16 }"
><a-input ><a-input
v-decorator="['name', { rules: [{ required: true, message: '请输入名称' }] }]" v-decorator="['name', { rules: [{ required: true, message: $t('placeholder1') }] }]"
/></a-form-item> /></a-form-item>
<a-form-item label="预览" :labelCol="{ span: 4 }"> <a-form-item :label="$t('customIconSelect.preview')" :labelCol="{ span: 4 }">
<div class="custom-icon-select-form-img"> <div class="custom-icon-select-form-img">
<img :src="formImg" /> <img :src="formImg" />
</div> </div>
</a-form-item> </a-form-item>
<a-form-item label=" " :colon="false" :labelCol="{ span: 16 }"> <a-form-item label=" " :colon="false" :labelCol="{ span: 16 }">
<a-space> <a-space>
<a-button size="small" @click="handleCancel">取消</a-button> <a-button size="small" @click="handleCancel">{{ $t('cancel') }}</a-button>
<a-button size="small" type="primary" @click="handleOk">确定</a-button> <a-button size="small" type="primary" @click="handleOk">{{ $t('confirm') }}</a-button>
</a-space> </a-space>
</a-form-item> </a-form-item>
</a-form> </a-form>
</div> </div>
<div class="custom-icon-select-block" id="custom-icon-select-block" @click="showSelect"> <div class="custom-icon-select-block" :id="`custom-icon-select-block-${uuid}`" @click="showSelect">
<img v-if="value.id && value.url" :src="`/api/common-setting/v1/file/${value.url}`" /> <img v-if="value.id && value.url" :src="`/api/common-setting/v1/file/${value.url}`" />
<ops-icon <ops-icon
v-else v-else
@@ -134,6 +134,7 @@
</template> </template>
<script> <script>
import { v4 as uuidv4 } from 'uuid'
import { ColorPicker } from 'element-ui' import { ColorPicker } from 'element-ui'
import { import {
iconTypeList, iconTypeList,
@@ -166,7 +167,6 @@ export default {
data() { data() {
return { return {
form: this.$form.createForm(this), form: this.$form.createForm(this),
iconTypeList,
commonIconList, commonIconList,
linearIconList, linearIconList,
fillIconList, fillIconList,
@@ -177,6 +177,7 @@ export default {
formVisible: false, formVisible: false,
formImg: null, formImg: null,
file: null, file: null,
uuid: uuidv4(),
} }
}, },
computed: { computed: {
@@ -200,6 +201,9 @@ export default {
const splitFileName = this.file.name.split('.') const splitFileName = this.file.name.split('.')
return splitFileName.splice(0, splitFileName.length - 1).join('') return splitFileName.splice(0, splitFileName.length - 1).join('')
}, },
iconTypeList() {
return iconTypeList()
},
}, },
mounted() { mounted() {
document.addEventListener('click', this.eventListener) document.addEventListener('click', this.eventListener)
@@ -217,7 +221,7 @@ export default {
eventListener(e) { eventListener(e) {
if (this.visible) { if (this.visible) {
const dom = document.getElementById(`custom-icon-select-popover`) const dom = document.getElementById(`custom-icon-select-popover`)
const dom_icon = document.getElementById(`custom-icon-select-block`) const dom_icon = document.getElementById(`custom-icon-select-block-${this.uuid}`)
e.stopPropagation() e.stopPropagation()
e.preventDefault() e.preventDefault()
if (dom) { if (dom) {
@@ -249,12 +253,11 @@ export default {
color: '', color: '',
}) })
} else { } else {
this.$emit('change', { name: icon.data.name, id: icon.id, url: icon.data.url }) this.$emit('change', { name: icon.data.name, id: icon.id, url: icon?.data?.url })
} }
}, },
showSelect() { showSelect() {
this.visible = true this.visible = true
console.log(this.value)
if (!this.value.name) { if (!this.value.name) {
this.currentIconType = '3' this.currentIconType = '3'
return return
@@ -278,7 +281,7 @@ export default {
beforeUpload(file) { beforeUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 2 const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) { if (!isLt2M) {
this.$message.error('图片大小不可超过2MB!') this.$message.error(this.$t('customIconSelect.sizeLimit'))
return false return false
} }
@@ -306,7 +309,7 @@ export default {
this.form.validateFields((err, values) => { this.form.validateFields((err, values) => {
if (!err) { if (!err) {
addFileData('ops-custom-icon', { data: { name: values.name, url: res.file_name } }).then(() => { addFileData('ops-custom-icon', { data: { name: values.name, url: res.file_name } }).then(() => {
this.$message.success('上传成功!') this.$message.success(this.$t('uploadSuccess'))
this.handleCancel() this.handleCancel()
this.getFileData() this.getFileData()
}) })
@@ -318,7 +321,7 @@ export default {
e.stopPropagation() e.stopPropagation()
e.preventDefault() e.preventDefault()
deleteFileData('ops-custom-icon', icon.id).then(() => { deleteFileData('ops-custom-icon', icon.id).then(() => {
this.$message.success('删除成功!') this.$message.success(this.$t('deleteSuccess'))
this.handleCancel() this.handleCancel()
this.getFileData() this.getFileData()
}) })

View File

@@ -6,17 +6,17 @@
:flat="true" :flat="true"
:multiple="true" :multiple="true"
:options="employeeTreeSelectOption" :options="employeeTreeSelectOption"
placeholder="请输入搜索内容" :placeholder="$t('placeholderSearch')"
v-model="treeValue" v-model="treeValue"
:max-height="height - 50" :max-height="height - 50"
noChildrenText="" noChildrenText=""
noOptionsText="" noOptionsText=""
:clearable="false" :clearable="false"
:always-open="true" :always-open="true"
:default-expand-level="1" :default-expand-level="showInternship ? 0 : 1"
:class="{ 'employee-transfer': true, 'employee-transfer-has-input': !!inputValue }" :class="{ 'employee-transfer': true, 'employee-transfer-has-input': !!inputValue }"
@search-change="changeInputValue" @search-change="changeInputValue"
noResultsText="暂无数据" :noResultsText="$t('noData')"
openDirection="below" openDirection="below"
> >
</treeselect> </treeselect>
@@ -85,6 +85,10 @@ export default {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
showInternship: {
type: Boolean,
default: false,
},
}, },
data() { data() {
return { return {
@@ -99,13 +103,22 @@ export default {
}, },
computed: { computed: {
employeeTreeSelectOption() { employeeTreeSelectOption() {
return formatOption( const formatOptions = formatOption(
this.allTreeDepAndEmp, this.allTreeDepAndEmp,
2, 2,
this.isDisabledAllCompany, this.isDisabledAllCompany,
this.uniqueKey || 'department_id', this.uniqueKey || 'department_id',
this.uniqueKey || 'employee_id' this.uniqueKey || 'employee_id'
) )
if (this.showInternship) {
formatOptions.push(
...[
{ id: -2, label: '全职' },
{ id: -3, label: '实习生' },
]
)
}
return formatOptions
}, },
allTreeDepAndEmp() { allTreeDepAndEmp() {
if (this.getDataBySelf) { if (this.getDataBySelf) {
@@ -148,11 +161,15 @@ export default {
const department = [] const department = []
const user = [] const user = []
this.rightData.forEach((item) => { this.rightData.forEach((item) => {
const _split = item.split('-') if (item === -2 || item === -3) {
if (_split[0] === 'department') { department.push(item)
department.push(Number(_split[1]))
} else { } else {
user.push(Number(_split[1])) const _split = item.split('-')
if (_split[0] === 'department') {
department.push(Number(_split[1]))
} else {
user.push(Number(_split[1]))
}
} }
}) })
const _idx = department.findIndex((item) => item === 0) const _idx = department.findIndex((item) => item === 0)
@@ -191,6 +208,12 @@ export default {
} }
}, },
getLabel(id) { getLabel(id) {
if (id === -2) {
return '全职'
}
if (id === -3) {
return '实习生'
}
const _split = id.split('-') const _split = id.split('-')
const type = _split[0] const type = _split[0]
const _id = Number(_split[1]) const _id = Number(_split[1])

View File

@@ -81,25 +81,23 @@ export default {
}, },
inject: ['reload'], inject: ['reload'],
methods: { methods: {
// 取消订阅
cancelAttributes(e, menu) { cancelAttributes(e, menu) {
const that = this const that = this
e.preventDefault() e.preventDefault()
e.stopPropagation() e.stopPropagation()
this.$confirm({ this.$confirm({
title: '警告', title: this.$t('alert'),
content: `确认取消订阅 ${menu.meta.title}?`, content: this.$t('cmdb.preference.confirmcancelSub2', { name: menu.meta.title }),
onOk() { onOk() {
const citypeId = menu.meta.typeId const citypeId = menu.meta.typeId
const unsubCIType = subscribeCIType(citypeId, '') const unsubCIType = subscribeCIType(citypeId, '')
const unsubTree = subscribeTreeView(citypeId, '') const unsubTree = subscribeTreeView(citypeId, '')
Promise.all([unsubCIType, unsubTree]).then(() => { Promise.all([unsubCIType, unsubTree]).then(() => {
that.$message.success('取消订阅成功') that.$message.success(that.$t('cmdb.preference.cancelSubSuccess'))
const lastTypeId = window.localStorage.getItem('ops_ci_typeid') || undefined const lastTypeId = window.localStorage.getItem('ops_ci_typeid') || undefined
if (Number(citypeId) === Number(lastTypeId)) { if (Number(citypeId) === Number(lastTypeId)) {
localStorage.setItem('ops_ci_typeid', '') localStorage.setItem('ops_ci_typeid', '')
} }
// 删除路由
const href = window.location.href const href = window.location.href
const hrefSplit = href.split('/') const hrefSplit = href.split('/')
if (Number(hrefSplit[hrefSplit.length - 1]) === Number(citypeId)) { if (Number(hrefSplit[hrefSplit.length - 1]) === Number(citypeId)) {
@@ -119,12 +117,10 @@ export default {
}, },
// select menu item // select menu item
onOpenChange(openKeys) { onOpenChange(openKeys) {
// 在水平模式下时执行,并且不再执行后续
if (this.mode === 'horizontal') { if (this.mode === 'horizontal') {
this.openKeys = openKeys this.openKeys = openKeys
return return
} }
// 非水平模式时
const latestOpenKey = openKeys.find(key => !this.openKeys.includes(key)) const latestOpenKey = openKeys.find(key => !this.openKeys.includes(key))
if (!this.rootSubmenuKeys.includes(latestOpenKey)) { if (!this.rootSubmenuKeys.includes(latestOpenKey)) {
this.openKeys = openKeys this.openKeys = openKeys
@@ -161,6 +157,12 @@ export default {
} }
return null return null
}, },
renderI18n(title) {
if (Object.prototype.toString.call(this.$t(`${title}`)) === '[object Object]') {
return title
}
return this.$t(`${title}`)
},
renderMenuItem(menu) { renderMenuItem(menu) {
const isShowDot = menu.path.substr(0, 22) === '/cmdb/instances/types/' const isShowDot = menu.path.substr(0, 22) === '/cmdb/instances/types/'
const isShowGrant = menu.path.substr(0, 20) === '/cmdb/relationviews/' const isShowGrant = menu.path.substr(0, 20) === '/cmdb/relationviews/'
@@ -170,9 +172,6 @@ export default {
const attrs = { href: menu.meta.targetHref || menu.path, target: menu.meta.target } const attrs = { href: menu.meta.targetHref || menu.path, target: menu.meta.target }
if (menu.children && menu.hideChildrenInMenu) { if (menu.children && menu.hideChildrenInMenu) {
// 把有子菜单的 并且 父菜单是要隐藏子菜单的
// 都给子菜单增加一个 hidden 属性
// 用来给刷新页面时, selectedKeys 做控制用
menu.children.forEach(item => { menu.children.forEach(item => {
item.meta = Object.assign(item.meta, { hidden: true }) item.meta = Object.assign(item.meta, { hidden: true })
}) })
@@ -183,7 +182,7 @@ export default {
<tag {...{ props, attrs }}> <tag {...{ props, attrs }}>
{this.renderIcon({ icon: menu.meta.icon, customIcon: menu.meta.customIcon, name: menu.meta.name, typeId: menu.meta.typeId, routeName: menu.name, selectedIcon: menu.meta.selectedIcon, })} {this.renderIcon({ icon: menu.meta.icon, customIcon: menu.meta.customIcon, name: menu.meta.name, typeId: menu.meta.typeId, routeName: menu.name, selectedIcon: menu.meta.selectedIcon, })}
<span> <span>
<span class={menu.meta.title.length > 10 ? 'scroll' : ''}>{menu.meta.title}</span> <span class={this.renderI18n(menu.meta.title).length > 10 ? 'scroll' : ''}>{this.renderI18n(menu.meta.title)}</span>
{isShowDot && {isShowDot &&
<a-popover <a-popover
overlayClassName="custom-menu-extra-submenu" overlayClassName="custom-menu-extra-submenu"
@@ -193,8 +192,8 @@ export default {
getPopupContainer={(trigger) => trigger} getPopupContainer={(trigger) => trigger}
content={() => content={() =>
<div> <div>
<div onClick={e => this.handlePerm(e, menu, 'CIType')} class="custom-menu-extra-submenu-item"><a-icon type="user-add" />授权</div> <div onClick={e => this.handlePerm(e, menu, 'CIType')} class="custom-menu-extra-submenu-item"><a-icon type="user-add" />{ this.renderI18n('grant') }</div>
<div onClick={e => this.cancelAttributes(e, menu)} class="custom-menu-extra-submenu-item"><a-icon type="star" />取消订阅</div> <div onClick={e => this.cancelAttributes(e, menu)} class="custom-menu-extra-submenu-item"><a-icon type="star" />{ this.renderI18n('cmdb.preference.cancelSub') }</div>
</div>} </div>}
> >
<a-icon type="menu" ref="extraEllipsis" class="custom-menu-extra-ellipsis"></a-icon> <a-icon type="menu" ref="extraEllipsis" class="custom-menu-extra-ellipsis"></a-icon>
@@ -217,7 +216,7 @@ export default {
<SubMenu {...{ key: menu.path }}> <SubMenu {...{ key: menu.path }}>
<span slot="title"> <span slot="title">
{this.renderIcon({ icon: menu.meta.icon, selectedIcon: menu.meta.selectedIcon, routeName: menu.name })} {this.renderIcon({ icon: menu.meta.icon, selectedIcon: menu.meta.selectedIcon, routeName: menu.name })}
<span>{menu.meta.title}</span> <span>{this.renderI18n(menu.meta.title)}</span>
</span> </span>
{itemArr} {itemArr}
</SubMenu> </SubMenu>
@@ -284,7 +283,7 @@ export default {
this.$refs.cmdbGrantRelationView.open({ name: menu.meta.name, cmdbGrantType: 'relation_view' }) this.$refs.cmdbGrantRelationView.open({ name: menu.meta.name, cmdbGrantType: 'relation_view' })
} }
} else { } else {
this.$message.error('权限不足!') this.$message.error(this.$t('noPermission'))
} }
}) })
} }

View File

@@ -3,9 +3,9 @@
<slot></slot> <slot></slot>
<template #empty> <template #empty>
<slot name="empty"> <slot name="empty">
<div> <div :style="{ paddingTop: '10px' }">
<img :style="{ width: '100px' }" :src="require('@/assets/data_empty.png')" /> <img :style="{ width: '100px', height: '90px' }" :src="require('@/assets/data_empty.png')" />
<div>暂无数据</div> <div>{{ $t('noData') }}</div>
</div> </div>
</slot> </slot>
</template> </template>

View File

@@ -0,0 +1,2 @@
import Pager from './index.vue'
export default Pager

View File

@@ -0,0 +1,137 @@
<template>
<div>
<a-row class="row" type="flex" justify="end">
<a-col>
<a-space align="end">
<a-button
class="left-button"
size="small"
:disabled="prevIsDisabled"
@click="prevPage"
><a-icon
type="left"
/></a-button>
<a-button class="page-button" size="small">{{ currentPage }}</a-button>
<a-button
class="right-button"
size="small"
:disabled="nextIsDisabled"
@click="nextPage"
><a-icon
type="right"
/></a-button>
<a-dropdown
class="dropdown"
size="small"
placement="topCenter"
:trigger="['click']"
:disabled="dropdownIsDisabled"
>
<a-menu slot="overlay">
<a-menu-item v-for="(size, index) in pageSizes" :key="index" @click="handleItemClick(size)">
{{ `${size}${$t('itemsPerPage')}` }}
</a-menu-item>
</a-menu>
<a-button size="small">{{ `${pageSize}${$t('itemsPerPage')}` }}<a-icon type="down" /> </a-button>
</a-dropdown>
</a-space>
</a-col>
</a-row>
</div>
</template>
<script>
export default {
name: 'Pager',
props: {
currentPage: {
type: Number,
required: true,
},
pageSize: {
type: Number,
required: true,
},
pageSizes: {
type: Array,
required: true,
},
total: {
type: Number,
required: true,
},
isLoading: {
type: Boolean,
required: false,
},
},
data() {
return {
dropdownIsDisabled: false,
prevIsDisabled: true,
}
},
computed: {
nextIsDisabled() {
return this.isLoading || this.total < this.pageSize
},
},
watch: {
isLoading: {
immediate: true,
handler: function(val) {
if (val) {
this.dropdownIsDisabled = true
this.prevIsDisabled = true
} else {
this.dropdownIsDisabled = false
if (this.currentPage === 1) {
this.prevIsDisabled = true
} else {
this.prevIsDisabled = false
}
}
},
},
currentPage: {
immediate: true,
handler: function(val) {
if (val === 1) {
this.prevIsDisabled = true
}
},
},
},
methods: {
handleItemClick(size) {
this.$emit('showSizeChange', size)
},
nextPage() {
const pageNum = this.currentPage + 1
this.$emit('change', pageNum)
},
prevPage() {
const pageNum = this.currentPage - 1
this.$emit('change', pageNum)
},
},
}
</script>
<style lang="less" scoped>
.row {
margin-top: 5px;
.left-button {
padding: 0;
width: 24px;
}
.right-button {
padding: 0;
width: 24px;
}
.page-button {
padding: 0;
width: 24px;
}
}
</style>

View File

@@ -0,0 +1,19 @@
/* eslint-disable no-useless-escape */
import i18n from '@/lang'
export const regList = () => {
return [
{ id: 'letter', label: i18n.t('regexSelect.letter'), value: '^[A-Za-z]+$', message: '请输入字母' },
{ id: 'number', label: i18n.t('regexSelect.number'), value: '^-?(?!0\\d+)\\d+(\\.\\d+)?$', message: '请输入数字' },
{ id: 'letterAndNumber', label: i18n.t('regexSelect.letterAndNumber'), value: '^[A-Za-z0-9.]+$', message: '请输入字母和数字' },
{ id: 'phone', label: i18n.t('regexSelect.phone'), value: '^1[3-9]\\d{9}$', message: '请输入正确手机号码' },
{ id: 'landline', label: i18n.t('regexSelect.landline'), value: '^(?:(?:\\d{3}-)?\\d{8}|^(?:\\d{4}-)?\\d{7,8})(?:-\\d+)?$', message: '请输入正确座机' },
{ id: 'zipCode', label: i18n.t('regexSelect.zipCode'), value: '^(0[1-7]|1[0-356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[0-5]|8[013-6])\\d{4}$', message: '请输入正确邮政编码' },
{ id: 'IDCard', label: i18n.t('regexSelect.IDCard'), value: '(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)', message: '请输入正确身份证号' },
{ id: 'ip', label: i18n.t('regexSelect.ip'), value: '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', message: '请输入正确IP地址' },
{ id: 'email', label: i18n.t('regexSelect.email'), value: '^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\.\\w+([-.]\\w+)*$', message: '请输入正确邮箱' },
{ id: 'link', label: i18n.t('regexSelect.link'), value: '^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?$', message: '请输入链接' },
{ id: 'monetaryAmount', label: i18n.t('regexSelect.monetaryAmount'), value: '^-?\\d+(,\\d{3})*(\.\\d{1,2})?$', message: '请输入货币金额' },
{ id: 'custom', label: i18n.t('regexSelect.custom'), value: '', message: '' }
]
}

View File

@@ -0,0 +1,2 @@
import RegexSelect from './regexSelect.vue'
export default RegexSelect

View File

@@ -0,0 +1,208 @@
<template>
<a-popover
trigger="click"
placement="bottom"
ref="regexSelect"
overlayClassName="regex-select-wrapper"
:overlayStyle="{ '--overlay-width': `${width}px` }"
@visibleChange="visibleChange"
>
<div class="regex-select" slot="content">
<div class="regex-select-left">
<div class="regex-select-left-header">{{ $t('regexSelect.limitedFormat') }}</div>
<div
@click="
() => {
current = reg
testInput = ''
showMessage = false
}
"
:class="{
'regex-select-left-reg': true,
'regex-select-left-reg-selected': current && current.label === reg.label,
}"
v-for="(reg, index) in regList"
:key="reg.label"
>
<a-divider :style="{ margin: '2px -12px', width: 'calc(100% + 24px)' }" v-if="index === regList.length - 1" />
{{ reg.label }}
</div>
</div>
<div class="regex-select-right">
<template v-if="current">
<div class="regex-select-right-header">{{ $t('regexSelect.regExp') }}</div>
<div
v-if="current.label !== $t('regexSelect.custom')"
:style="{ color: '#000', fontSize: '12px', margin: '12px 0' }"
>
{{ current.value }}
</div>
<a-input
:style="{ margin: '12px 0' }"
size="small"
v-else
v-model="current.value"
@change="
() => {
this.$emit('change', current)
}
"
/>
<template v-if="isShowErrorMsg">
<div class="regex-select-right-header">{{ $t('regexSelect.errMsg') }}</div>
<a-input :style="{ margin: '12px 0' }" size="small" v-model="current.message" />
</template>
<div class="regex-select-right-header">{{ $t('regexSelect.test') }}</div>
<a-input v-model="testInput" :style="{ margin: '12px 0 4px' }" size="small" @change="validate" />
<span :style="{ color: 'red', fontSize: '12px' }" v-if="showMessage">{{
locale === 'zh' ? current.message || '错误' : $t('regexSelect.error')
}}</span>
</template>
</div>
</div>
<a-input ref="regInput" :placeholder="$t('regexSelect.placeholder')" :value="current.label" @change="changeLabel">
</a-input>
</a-popover>
</template>
<script>
import { mapState } from 'vuex'
import { regList } from './constants'
export default {
name: 'RegexSelect',
model: {
prop: 'value',
event: 'change',
},
props: {
value: {
type: Object,
default: () => {},
},
isShowErrorMsg: {
type: Boolean,
default: true,
},
limitedFormat: {
type: Array,
default: () => [],
},
},
data() {
return {
showMessage: false,
width: 370,
testInput: '',
}
},
computed: {
...mapState(['locale']),
regList() {
if (this.limitedFormat.length) {
return regList().filter((item) => this.limitedFormat.includes(item.id))
}
return regList()
},
current: {
get() {
if (this.value?.value && !this.value?.label) {
const _find = this.regList.find((reg) => reg.value === this.value?.value)
return { ...this.value, label: _find?.label ?? this.$t('regexSelect.custom') }
}
return this.value ?? {}
},
set(val) {
this.showMessage = false
this.$emit('change', val)
return val
},
},
},
mounted() {
this.$nextTick(() => {
const regInput = this.$refs.regInput.$refs.input
this.width = regInput.offsetWidth || 370
})
},
methods: {
validate(e) {
const reg = RegExp(this.current.value, 'g')
this.showMessage = !reg.test(e.target.value)
},
changeLabel(e) {
this.current = {}
},
visibleChange(visible) {
if (visible) {
this.$nextTick(() => {
this.testInput = ''
this.showMessage = false
})
}
},
},
}
</script>
<style lang="less" scoped>
@import '~@/style/static.less';
.regex-select {
width: 100%;
height: 300px;
display: flex;
.regex-select-left {
width: 40%;
height: 100%;
border: 1px solid #cacdd9;
border-radius: 4px;
padding: 12px;
&-reg {
padding-left: 2px;
cursor: pointer;
&-selected,
&:hover {
color: #custom_colors[color_1];
}
}
}
&-right {
flex: 1;
height: 100%;
border: 1px solid #cacdd9;
border-radius: 4px;
margin-left: 8px;
padding: 12px;
}
&-left,
&-right {
&-header {
font-weight: 400;
font-size: 14px;
color: #000000;
border-left: 2px solid #custom_colors[color_1];
padding-left: 6px;
margin-left: -6px;
}
}
}
</style>
<style lang="less">
.regex-select-wrapper {
.ant-popover-arrow {
display: none;
}
.ant-popover-inner-content {
padding: 0;
min-width: 370px;
width: var(--overlay-width);
}
}
.regex-select-wrapper.ant-popover-placement-bottom .ant-popover-content {
margin-top: -8px;
}
.regex-select-wrapper.ant-popover-placement-top .ant-popover-content {
margin-bottom: -8px;
}
</style>

View File

@@ -3,12 +3,12 @@
<a-switch <a-switch
class="role-transfer-switch" class="role-transfer-switch"
v-model="isUserRole" v-model="isUserRole"
checked-children="用户" :checked-children="$t('user')"
un-checked-children="虚拟" :un-checked-children="$t('visual')"
@change="loadRoles" @change="loadRoles"
/> />
<div class="role-transfer-left"> <div class="role-transfer-left">
<a-input placeholder="请输入搜索内容" v-model="searchValue" /> <a-input :placeholder="$t('placeholderSearch')" v-model="searchValue" />
<div v-for="item in filterAllRoles" :key="item.id" @click="handleSelectedLeft(item.id)"> <div v-for="item in filterAllRoles" :key="item.id" @click="handleSelectedLeft(item.id)">
<a-checkbox :checked="selectedLeft.includes(item.id)" /> <a-checkbox :checked="selectedLeft.includes(item.id)" />
<div :title="item.name" class="role-transfer-left-role">{{ item.name }}</div> <div :title="item.name" class="role-transfer-left-role">{{ item.name }}</div>

View File

@@ -119,7 +119,8 @@ export default {
border-radius: 4px; border-radius: 4px;
color: @layout-header-font-color; color: @layout-header-font-color;
height: @layout-header-height; height: @layout-header-height;
line-height: @layout-header-height; display: inline-flex;
align-items: center;
&:hover { &:hover {
background: linear-gradient(0deg, rgba(0, 80, 201, 0.2) 0%, rgba(174, 207, 255, 0.06) 86.76%); background: linear-gradient(0deg, rgba(0, 80, 201, 0.2) 0%, rgba(174, 207, 255, 0.06) 86.76%);
color: @layout-header-font-selected-color; color: @layout-header-font-selected-color;

View File

@@ -10,9 +10,10 @@
> >
<a-icon type="setting" /> <a-icon type="setting" />
</span> </span>
<span class="locale" @click="changeLang">{{ locale === 'zh' ? 'English' : '中文' }}</span>
<a-popover <a-popover
trigger="click" trigger="click"
:overlayStyle="{ width: '120px' }" :overlayStyle="{ width: '150px' }"
placement="bottomRight" placement="bottomRight"
overlayClassName="custom-user" overlayClassName="custom-user"
> >
@@ -20,12 +21,12 @@
<router-link :to="{ name: 'setting_person' }" :style="{ color: '#000000a6' }"> <router-link :to="{ name: 'setting_person' }" :style="{ color: '#000000a6' }">
<div class="custom-user-item"> <div class="custom-user-item">
<a-icon type="user" :style="{ marginRight: '10px' }" /> <a-icon type="user" :style="{ marginRight: '10px' }" />
<span>个人中心</span> <span>{{ $t('topMenu.personalCenter') }}</span>
</div> </div>
</router-link> </router-link>
<div @click="handleLogout" class="custom-user-item"> <div @click="handleLogout" class="custom-user-item">
<a-icon type="logout" :style="{ marginRight: '10px' }" /> <a-icon type="logout" :style="{ marginRight: '10px' }" />
<span>退出登录</span> <span>{{ $t('topMenu.logout') }}</span>
</div> </div>
</template> </template>
<span class="action ant-dropdown-link user-dropdown-menu"> <span class="action ant-dropdown-link user-dropdown-menu">
@@ -44,8 +45,9 @@
</template> </template>
<script> <script>
import { mapState, mapActions, mapGetters, mapMutations } from 'vuex'
import DocumentLink from './DocumentLink.vue' import DocumentLink from './DocumentLink.vue'
import { mapState, mapActions, mapGetters } from 'vuex' import { setDocumentTitle, domTitle } from '@/utils/domUtil'
export default { export default {
name: 'UserMenu', name: 'UserMenu',
@@ -53,20 +55,21 @@ export default {
DocumentLink, DocumentLink,
}, },
computed: { computed: {
...mapState(['user']), ...mapState(['user', 'locale']),
hasBackendPermission() { hasBackendPermission() {
return this.user?.roles?.permissions.includes('acl_admin', 'backend_admin') || false return this.user?.detailPermissions?.backend?.length
}, },
}, },
methods: { methods: {
...mapActions(['Logout']), ...mapActions(['Logout']),
...mapGetters(['nickname', 'avatar']), ...mapGetters(['nickname', 'avatar']),
...mapMutations(['SET_LOCALE']),
handleLogout() { handleLogout() {
const that = this const that = this
this.$confirm({ this.$confirm({
title: '提示', title: this.$t('tip'),
content: '确认注销登录 ?', content: this.$t('topMenu.confirmLogout'),
onOk() { onOk() {
return that.Logout() return that.Logout()
}, },
@@ -76,9 +79,22 @@ export default {
handleClick() { handleClick() {
this.$router.push('/setting') this.$router.push('/setting')
}, },
changeLang() {
if (this.locale === 'zh') {
this.SET_LOCALE('en')
this.$i18n.locale = 'en'
} else {
this.SET_LOCALE('zh')
this.$i18n.locale = 'zh'
}
this.$nextTick(() => {
setDocumentTitle(`${this.$t(this.$route.meta.title)} - ${domTitle}`)
})
},
}, },
} }
</script> </script>
<style lang="less"> <style lang="less">
@import '~@/style/static.less'; @import '~@/style/static.less';
.color { .color {
@@ -98,4 +114,11 @@ export default {
color: #000000a6; color: #000000a6;
} }
} }
.locale {
cursor: pointer;
&:hover {
color: #custom_colors[color_1];
}
}
</style> </style>

View File

@@ -14,7 +14,7 @@
*/ */
export default { export default {
primaryColor: '#1890ff', // primary color of ant design primaryColor: '#2f54eb', // primary color of ant design
navTheme: 'dark', // theme for nav menu navTheme: 'dark', // theme for nav menu
layout: 'sidemenu', // nav menu position: sidemenu or topmenu layout: 'sidemenu', // nav menu position: sidemenu or topmenu
contentWidth: 'Fixed', // layout of content: Fluid or Fixed, only works when layout is topmenu contentWidth: 'Fixed', // layout of content: Fluid or Fixed, only works when layout is topmenu

View File

@@ -38,11 +38,18 @@ import CardTitle from '@/components/CardTitle'
import ElementUI from 'element-ui' import ElementUI from 'element-ui'
import Treeselect from '@riophae/vue-treeselect' import Treeselect from '@riophae/vue-treeselect'
import OpsTable from '@/components/OpsTable' import OpsTable from '@/components/OpsTable'
import VueI18n from 'vue-i18n'
import i18n from '@/lang'
Vue.config.productionTip = false Vue.config.productionTip = false
Vue.prototype.$bus = EventBus Vue.prototype.$bus = EventBus
VXETable.setup({
i18n: (key, args) => i18n.t(key, args)
})
Vue.use(VXETable) Vue.use(VXETable)
VXETable.use(VXETablePluginExportXLSX) VXETable.use(VXETablePluginExportXLSX)
Vue.use(VueI18n)
Vue.config.productionTip = false Vue.config.productionTip = false
@@ -75,4 +82,3 @@ Vue.component('CustomRadio', CustomRadio)
Vue.component('CardTitle', CardTitle) Vue.component('CardTitle', CardTitle)
Vue.component('Treeselect', Treeselect) Vue.component('Treeselect', Treeselect)
Vue.component('OpsTable', OpsTable) Vue.component('OpsTable', OpsTable)

View File

@@ -7,6 +7,7 @@ import NProgress from 'nprogress'
import 'nprogress/nprogress.css' import 'nprogress/nprogress.css'
import { setDocumentTitle, domTitle } from '@/utils/domUtil' import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from './store/global/mutation-types' import { ACCESS_TOKEN } from './store/global/mutation-types'
import i18n from '@/lang'
NProgress.configure({ showSpinner: false }) NProgress.configure({ showSpinner: false })
@@ -17,7 +18,7 @@ const whitePath = ['/user/login', '/user/logout', '/user/register', '/api/sso/lo
// 登录页面处理处理 是否使用单点登录 // 登录页面处理处理 是否使用单点登录
router.beforeEach(async (to, from, next) => { router.beforeEach(async (to, from, next) => {
NProgress.start() // start progress bar NProgress.start() // start progress bar
to.meta && (!!to.meta.title && setDocumentTitle(`${to.meta.title} - ${domTitle}`)) to.meta && (!!to.meta.title && setDocumentTitle(`${i18n.t(to.meta.title)} - ${domTitle}`))
const authed = store.state.authed const authed = store.state.authed
const auth_type = localStorage.getItem('ops_auth_type') const auth_type = localStorage.getItem('ops_auth_type')

171
cmdb-ui/src/lang/en.js Normal file
View File

@@ -0,0 +1,171 @@
import cmdb_en from '@/modules/cmdb/lang/en.js'
import cs_en from '../views/setting/lang/en.js'
import acl_en from '@/modules/acl/lang/en.js'
export default {
commonMenu: {
permission: 'Permission',
role: 'Roles',
resource: 'Resources',
resourceType: 'Resource Types',
trigger: 'Triggers',
},
screen: 'Big Screen',
dashboard: 'Dashboard',
admin: 'Admin',
user: 'User',
role: 'Role',
operation: 'Operation',
login: 'Login',
refresh: 'Refresh',
cancel: 'Cancel',
confirm: 'Confirm',
create: 'Create',
edit: 'Edit',
deleting: 'Deleting',
deletingTip: 'Deleting, total of {total}, {successNum} succeeded, {errorNum} failed',
grant: 'Grant',
login_at: 'Login At',
logout_at: 'Logout At',
createSuccess: 'Create Success',
editSuccess: 'edit Success',
warning: 'Warning',
export: 'Export',
placeholderSearch: 'Please Search',
success: 'Success',
fail: 'Fail',
browser: 'Browser',
status: 'Status',
type: 'Type',
description: 'Description',
new: 'New',
add: 'Add',
define: 'Define',
update: 'Update',
clear: 'Clear',
delete: 'Delete',
copy: 'Copy',
created_at: 'Created At',
updated_at: 'Updated At',
placeholder1: 'Please Input',
placeholder2: 'Please Select',
confirmDelete: 'Confirm delete?',
confirmDelete2: 'Confirm delete [{name}]?',
query: 'Query',
search: 'Search',
hide: 'Hide',
expand: 'Expand',
save: 'Save',
submit: 'Submit',
upload: 'Import',
download: 'Export',
name: 'Name',
alias: 'Alias',
desc: 'Description',
other: 'Other',
icon: 'Icon',
addSuccess: 'Added successfully',
uploadSuccess: 'Import successfully',
saveSuccess: 'Save successfully',
copySuccess: 'Copy successfully',
updateSuccess: 'Updated successfully',
deleteSuccess: 'Deleted successfully',
operateSuccess: 'The operation was successful',
noPermission: 'No Permission',
noData: 'No Data',
seconds: 'Seconds',
createdAt: 'Created At',
updatedAt: 'Updated At',
deletedAt: 'Deleted At',
required: 'required',
email: 'Email',
wechat: 'Wechat',
dingding: 'DingTalk',
feishu: 'Feishu',
bot: 'Robot',
checkAll: 'Select All',
loading: 'Loading...',
view: 'View',
reset: 'Reset',
yes: 'Yes',
no: 'No',
all: 'All',
selectRows: 'Selected: {rows} items',
itemsPerPage: '/page',
'星期一': 'Monday',
'星期二': 'Tuesday',
'星期三': 'Wednesday',
'星期四': 'Thursday',
'星期五': 'Friday',
'星期六': 'Saturday',
'星期日': 'Sunday',
hour: 'hour',
'items/page': '{items} items/page',
max: 'Max',
min: 'Min',
visual: 'Visual',
default: 'default',
tip: 'Tip',
pagination: {
total: '{range0}-{range1} of {total} items'
},
topMenu: {
personalCenter: 'My Profile',
logout: 'Logout',
confirmLogout: 'Are you sure to log out?'
},
cmdbFilterComp: {
conditionFilter: 'Conditional filtering',
and: 'and',
or: 'or',
is: 'equal',
'~is': 'not equal',
contain: 'contain',
'~contain': 'not contain',
start_with: 'start_with',
'~start_with': 'not start_with',
end_with: 'end_with',
'~end_with': 'not end_with',
'~value': 'null',
value: 'not null',
in: 'in',
'~in': 'not in',
range: 'range',
'~range': 'out of range',
compare: 'compare',
addHere: 'Add Here',
split: 'split by {separator}'
},
customIconSelect: {
outlined: 'Outlined',
filled: 'Filled',
multicolor: 'Multicolor',
custom: 'Custom',
preview: 'Preview',
sizeLimit: 'The image size cannot exceed 2MB!',
nodata: 'There are currently no custom icons available. Click here to upload'
},
regexSelect: {
limitedFormat: 'Limited Format',
regExp: 'RegExp',
errMsg: 'Error Message',
test: 'Test',
placeholder: 'Please Select RegExp',
error: 'Error',
letter: 'letter',
number: 'number',
letterAndNumber: 'letter&number',
phone: 'phone',
landline: 'landline',
zipCode: 'zip code',
IDCard: 'ID card',
ip: 'IP',
email: 'email',
link: 'link',
monetaryAmount: 'monetary amount',
custom: 'custom',
},
cmdb: cmdb_en,
cs: cs_en,
acl: acl_en,
}

18
cmdb-ui/src/lang/index.js Normal file
View File

@@ -0,0 +1,18 @@
import VueI18n from 'vue-i18n'
import zh from './zh'
import en from './en'
import Vue from 'vue'
import zhCN from 'vxe-table/lib/locale/lang/zh-CN'
import enUS from 'vxe-table/lib/locale/lang/en-US'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh', // 初始化中文
messages: {
'zh': { ...zh, ...zhCN },
'en': { ...en, ...enUS },
},
silentTranslationWarn: true
})
export default i18n

171
cmdb-ui/src/lang/zh.js Normal file
View File

@@ -0,0 +1,171 @@
import cmdb_zh from '@/modules/cmdb/lang/zh.js'
import cs_zh from '../views/setting/lang/zh.js'
import acl_zh from '@/modules/acl/lang/zh.js'
export default {
commonMenu: {
permission: '权限管理',
role: '角色管理',
resource: '资源管理',
resourceType: '资源类型',
trigger: '触发器',
},
screen: '大屏',
dashboard: '仪表盘',
admin: '管理员',
user: '用户',
role: '角色',
operation: '操作',
login: '登录',
refresh: '刷新',
cancel: '取消',
confirm: '确定',
create: '创建',
edit: '编辑',
deleting: '正在删除',
deletingTip: '正在删除,共{total}个,成功{successNum}个,失败{errorNum}个',
grant: '授权',
login_at: '登录时间',
logout_at: '登出时间',
createSuccess: '创建成功',
editSuccess: '修改成功',
warning: '警告',
export: '导出',
placeholderSearch: '请查找',
success: '成功',
fail: '失败',
browser: '浏览器',
status: '状态',
type: '类型',
description: '描述',
new: '新增',
add: '添加',
define: '定义',
update: '修改',
clear: '清空',
delete: '删除',
copy: '复制',
created_at: '创建日期',
updated_at: '更新日期',
placeholder1: '请输入',
placeholder2: '请选择',
confirmDelete: '确认删除?',
confirmDelete2: '确认删除【{name}】?',
query: '查询',
search: '搜索',
hide: '隐藏',
expand: '展开',
save: '保存',
submit: '提交',
upload: '导入',
download: '导出',
name: '名称',
alias: '别名',
desc: '描述',
other: '其他',
icon: '图标',
addSuccess: '新增成功',
uploadSuccess: '导入成功',
saveSuccess: '保存成功',
copySuccess: '复制成功',
updateSuccess: '更新成功',
deleteSuccess: '删除成功',
operateSuccess: '操作成功',
noPermission: '权限不足',
noData: '暂无数据',
seconds: '秒',
createdAt: '创建时间',
updatedAt: '更新时间',
deletedAt: '删除时间',
required: '必须',
email: '邮件',
wechat: '企业微信',
dingding: '钉钉',
feishu: '飞书',
bot: '机器人',
checkAll: '全选',
loading: '加载中...',
view: '查看',
reset: '重置',
yes: '是',
no: '否',
all: '全部',
selectRows: '选取:{rows} 项',
itemsPerPage: '/页',
'星期一': '星期一',
'星期二': '星期二',
'星期三': '星期三',
'星期四': '星期四',
'星期五': '星期五',
'星期六': '星期六',
'星期日': '星期日',
hour: '小时',
'items/page': '{items} 条/页',
max: '最大值',
min: '最小值',
visual: '虚拟',
default: '默认',
tip: '提示',
pagination: {
total: '当前展示 {range0}-{range1} 条数据, 共 {total} 条'
},
topMenu: {
personalCenter: '个人中心',
logout: '退出登录',
confirmLogout: '确认退出登录吗?'
},
cmdbFilterComp: {
conditionFilter: '条件过滤',
and: '与',
or: '或',
is: '等于',
'~is': '不等于',
contain: '包含',
'~contain': '不包含',
start_with: '以...开始',
'~start_with': '不以...开始',
end_with: '以...结束',
'~end_with': '不以...结束',
'~value': '为空',
value: '不为空',
in: 'in查询',
'~in': '非in查询',
range: '范围',
'~range': '范围外',
compare: '比较',
addHere: '在此处添加',
split: '以 {separator} 分隔'
},
customIconSelect: {
outlined: '线框',
filled: '实底',
multicolor: '多色',
custom: '自定义',
preview: '预览',
sizeLimit: '图片大小不可超过2MB',
nodata: '暂无自定义图标,点击此处上传'
},
regexSelect: {
limitedFormat: '限定格式',
regExp: '正则表达式',
errMsg: '错误时提示',
test: '测试',
placeholder: '请选择正则表达式',
error: '错误',
letter: '字母',
number: '数字',
letterAndNumber: '字母和数字',
phone: '手机号码',
landline: '座机',
zipCode: '邮政编码',
IDCard: '身份证号',
ip: 'IP地址',
email: '邮箱',
link: '链接',
monetaryAmount: '货币金额',
custom: '自定义',
},
cmdb: cmdb_zh,
cs: cs_zh,
acl: acl_zh,
}

View File

@@ -10,6 +10,7 @@ import './guard' // guard permission control
import './utils/filter' // global filter import './utils/filter' // global filter
import Setting from './config/setting' import Setting from './config/setting'
import { Icon } from 'ant-design-vue' import { Icon } from 'ant-design-vue'
import i18n from './lang'
import iconFont from '../public/iconfont/iconfont' import iconFont from '../public/iconfont/iconfont'
@@ -22,6 +23,7 @@ async function start() {
const _vue = new Vue({ const _vue = new Vue({
router, router,
store, store,
i18n,
created: bootstrap, created: bootstrap,
render: h => h(App) render: h => h(App)
}).$mount('#app') }).$mount('#app')

View File

@@ -0,0 +1,125 @@
const acl_en = {
date: 'Date',
operator: 'Operator',
resource: 'Resource',
resourceType: 'Resource Type',
addResourceType: 'Add Resource Type',
app: 'App',
operateTime: 'Operate Time',
permission: 'Permission',
permission_placeholder: 'please select permission',
permissionList: 'Permission List',
summaryPermissions: 'Summary of permissions',
source: 'Source',
username: 'Username',
username_placeholder: 'please input username',
userList: 'User List',
groupUser: 'Group User',
addUser: 'Add User',
subordinateUsers: 'Subordinate Users',
nickname: 'Nickname',
nickname_placeholder: 'please input nickname',
password: 'Password',
password_placeholder: 'please input password',
department: 'Department',
group: 'Group',
email: 'Email',
email_placeholder: 'please input email',
mobile: 'Mobile',
isBlock: 'Is Block',
block: 'Block',
joined_at: 'Joined At',
role: 'Role',
role_placeholder1: 'please input role',
role_placeholder2: 'please select role',
role_placeholder3: 'please select a role name, multiple choices are allowed',
allRole: 'All Roles',
visualRole: 'Virtual Role',
addVisualRole: 'Add Virtual Role',
inheritedFrom: 'Inherited from',
heir: 'Inherit Roles',
permissionChange: 'Permissions',
roleChange: 'Roles',
resourceChange: 'Resources',
resourceTypeChange: 'Resource Type',
trigger: 'Triggers',
triggerNameInput: 'Please enter trigger name',
triggerChange: 'Triggers',
roleManage: 'Roles',
userManage: 'Users',
appManage: 'Applications',
resourceManage: 'Resources',
history: 'Audits',
userSecret: 'Secrets',
none: 'none',
danger: 'Dangerous',
confirmDeleteApp: 'Are you sure you want to delete this app?',
revoke: 'Revoke',
convenient: 'Quick Grant',
group2: 'Group',
groupName: 'Group Name',
resourceName: 'Resource Name',
creator: 'Creator',
member: 'Members',
viewAuth: 'view Auth',
addTypeTips: 'There is no type information yet, please add the resource type first!',
addResource: 'Add Resource',
resourceList: 'Resource List',
confirmResetSecret: 'Are you sure you want to reset the user secrets?',
addTrigger: 'Add Trigger',
deleteTrigger: 'Delete Trigger',
applyTrigger: 'Apply Trigger',
cancelTrigger: 'Cancel Trigger',
enable: 'Enable',
disable: 'Disable',
viewMatchResult: 'View regular matching results',
confirmDeleteTrigger: 'Are you sure you want to delete this trigger?',
ruleApply: 'Apply',
triggerTip1: 'Are you sure you want to apply this trigger?',
triggerTip2: 'Cancel applying this trigger?',
appNameInput: 'Please enter an application name',
descInput: 'Please enter a description',
addApp: 'Add',
updateApp: 'Update',
cancel: 'Cancel',
typeName: 'Name',
typeNameInput: 'Please enter a type name',
resourceNameInput: 'Please enter resource name',
pressEnter: 'Press Enter to confirm filtering',
groupMember: 'Group Members:',
isGroup: 'Group?',
errorTips: 'Error message',
roleList: 'Role List',
virtual: 'Virtual',
resourceBatchTips: 'Please enter the resource name, separated by newlines',
memberManage: 'Members: ',
newResource: 'New Resource: ',
deleteResource: 'Delete Resource: ',
deleteResourceType: 'Delete Resource Type: ',
noChange: 'No change',
batchOperate: 'Batch Operations',
batchGrant: 'Batch Grant',
batchRevoke: 'Batch Revoke',
editPerm: 'Add authorization: ',
permInput: 'Please enter permission name',
resourceTypeName: 'Resource Type Name',
selectedParents: 'Optionally inherit roles',
isAppAdmin: 'is app admin',
addRole: 'Add Role',
roleRelation: 'Role Relation',
roleRelationAdd: 'Add Role Relation',
roleRelationDelete: 'Delete Role Relation',
role2: 'Role',
admin: 'Admin',
involvingRP: 'Involving resources and permissions',
startAt: 'Start Time',
endAt: 'End Time',
triggerTips1: 'Priority regular pattern (secondary wildcard)',
pleaseSelectType: 'Please select resource type',
apply: 'Apply',
mobileTips: 'Please enter the correct phone number',
remove: 'Remove',
deleteUserConfirm: 'Are you sure you want to remove this user?',
copyResource: 'Copy resource name'
}
export default acl_en

View File

@@ -0,0 +1,125 @@
const acl_zh = {
date: '日期',
operator: '操作员',
resource: '资源',
resourceType: '资源类型',
addResourceType: '新增资源类型',
app: '应用',
operateTime: '操作时间',
permission: '权限',
permission_placeholder: '请选择权限',
permissionList: '权限列表',
summaryPermissions: '权限汇总',
source: '来源',
username: '用户名',
username_placeholder: '请输入用户名',
userList: '用户列表',
groupUser: '组用户',
addUser: '新增用户',
subordinateUsers: '下属用户',
nickname: '中文名',
nickname_placeholder: '请输入中文名',
password: '密码',
password_placeholder: '请输入密码',
department: '部门',
group: '小组',
email: '邮箱',
email_placeholder: '请输入邮箱',
mobile: '手机号',
isBlock: '是否锁定',
block: '锁定',
joined_at: '加入时间',
role: '角色名',
role_placeholder1: '请输入角色名',
role_placeholder2: '请选择角色名称',
role_placeholder3: '请选择角色名称,可多选',
allRole: '所有角色',
visualRole: '虚拟角色',
addVisualRole: '新增虚拟角色',
inheritedFrom: '继承自',
heir: '继承者',
permissionChange: '权限变更',
roleChange: '角色变更',
resourceChange: '资源变更',
resourceTypeChange: '资源类型变更',
trigger: '触发器',
triggerNameInput: '请输入触发器名',
triggerChange: '触发器变更',
roleManage: '角色管理',
userManage: '用户管理',
appManage: '应用管理',
resourceManage: '资源管理',
history: '操作审计',
userSecret: '用户密钥',
none: '无',
danger: '危险操作',
confirmDeleteApp: '确定要删除该App吗',
revoke: '权限回收',
convenient: '便捷授权',
group2: '组',
groupName: '资源组名',
resourceName: '资源名',
creator: '创建者',
member: '成员',
viewAuth: '查看授权',
addTypeTips: '暂无类型信息,请先添加资源类型!',
addResource: '新增资源',
resourceList: '资源列表',
confirmResetSecret: '确定重置用户密钥?',
addTrigger: '新增触发器',
deleteTrigger: '删除触发器',
applyTrigger: '应用触发器',
cancelTrigger: '取消触发器',
enable: '启用',
disable: '禁用',
viewMatchResult: '查看正则匹配结果',
confirmDeleteTrigger: '确认删除该触发器吗?',
ruleApply: '规则应用',
triggerTip1: '是否确定应用该触发器?',
triggerTip2: '是否取消应用该触发器?',
appNameInput: '请输入应用名称',
descInput: '请输入描述',
addApp: '创建应用',
updateApp: '更新应用',
cancel: '撤销',
typeName: '类型名',
typeNameInput: '请输入类型名',
resourceNameInput: '请输入资源名',
pressEnter: '按回车确认筛选',
groupMember: '组成员:',
isGroup: '是否组',
errorTips: '错误提示',
roleList: '角色列表',
virtual: '虚拟',
resourceBatchTips: '请输入资源名,换行分隔',
memberManage: '成员管理:',
newResource: '新建资源:',
deleteResource: '删除资源:',
deleteResourceType: '删除资源类型:',
noChange: '没有修改',
batchOperate: '批量操作',
batchGrant: '批量授权',
batchRevoke: '批量权限回收',
editPerm: '添加授权:',
permInput: '请输入权限名',
resourceTypeName: '资源类型名',
selectedParents: '可选择继承角色',
isAppAdmin: '是否应用管理员',
addRole: '新增角色',
roleRelation: '角色关系',
roleRelationAdd: '添加角色关系',
roleRelationDelete: '删除角色关系',
role2: '角色',
admin: '管理员',
involvingRP: '涉及资源及权限',
startAt: '开始时间',
endAt: '结束时间',
triggerTips1: '优先正则模式(次通配符)',
pleaseSelectType: '请选择资源类型',
apply: '应用',
mobileTips: '请输入正确的手机号码',
remove: '移除',
deleteUserConfirm: '是否确定要移除该用户',
copyResource: '复制资源名'
}
export default acl_zh

View File

@@ -12,35 +12,35 @@ const genAppRoute = ({ name }) => {
name: `${name}_roles_acl`, name: `${name}_roles_acl`,
hideChildrenInMenu: true, hideChildrenInMenu: true,
component: () => import('../views/roles'), component: () => import('../views/roles'),
meta: { title: '角色管理', icon: 'team', keepAlive: true } meta: { title: 'acl.roleManage', icon: 'team', keepAlive: true }
}, },
{ {
path: `/acl/${name}/resources`, path: `/acl/${name}/resources`,
name: `${name}_resources_acl`, name: `${name}_resources_acl`,
hideChildrenInMenu: true, hideChildrenInMenu: true,
component: () => import('../views/resources'), component: () => import('../views/resources'),
meta: { title: '资源管理', icon: 'credit-card', keepAlive: false } meta: { title: 'acl.resourceManage', icon: 'credit-card', keepAlive: false }
}, },
{ {
path: `/acl/${name}/resource_types`, path: `/acl/${name}/resource_types`,
name: `${name}_resource_types_acl`, name: `${name}_resource_types_acl`,
hideChildrenInMenu: true, hideChildrenInMenu: true,
component: () => import('../views/resource_types'), component: () => import('../views/resource_types'),
meta: { title: '资源类型', icon: 'file-text', keepAlive: true } meta: { title: 'acl.resourceType', icon: 'file-text', keepAlive: true }
}, },
{ {
path: `/acl/${name}/trigger`, path: `/acl/${name}/trigger`,
name: `${name}_trigger_acl`, name: `${name}_trigger_acl`,
hideChildrenInMenu: true, hideChildrenInMenu: true,
component: () => import('../views/trigger'), component: () => import('../views/trigger'),
meta: { title: '触发器', icon: 'clock-circle', keepAlive: true } meta: { title: 'acl.trigger', icon: 'clock-circle', keepAlive: true }
}, },
{ {
path: `/acl/${name}/history`, path: `/acl/${name}/history`,
name: `${name}_history_acl`, name: `${name}_history_acl`,
hideChildrenInMenu: true, hideChildrenInMenu: true,
component: () => import('../views/history'), component: () => import('../views/history'),
meta: { title: '操作审计', icon: 'search', keepAlive: false } meta: { title: 'acl.history', icon: 'search', keepAlive: false }
} }
] ]
} }
@@ -59,32 +59,31 @@ const genAclRoutes = async () => {
path: `/acl/secret_key`, path: `/acl/secret_key`,
name: 'acl_secret_key', name: 'acl_secret_key',
component: () => import('../views/secretKey'), component: () => import('../views/secretKey'),
meta: { title: '用户密钥', icon: 'key' } meta: { title: 'acl.userSecret', icon: 'key' }
}, },
{ {
path: `/acl/operate_history`, path: `/acl/operate_history`,
name: 'acl_operate_history', name: 'acl_operate_history',
component: () => import('../views/operation_history/index.vue'), component: () => import('../views/operation_history/index.vue'),
// meta: { title: '操作审计', icon: 'search', permission: ['acl_admin'] }, meta: { title: 'acl.history', icon: 'search', permission: ['acl_admin'] }
meta: { title: '操作审计', icon: 'search' }
}, },
{ {
path: `/acl/user`, path: `/acl/user`,
name: 'acl_user', name: 'acl_user',
component: () => import('../views/users'), component: () => import('../views/users'),
meta: { title: '用户管理', icon: 'user', permission: ['acl_admin'] } meta: { title: 'acl.userManage', icon: 'user', permission: ['acl_admin'] }
}, },
{ {
path: `/acl/roles`, path: `/acl/roles`,
name: `acl_roles`, name: `acl_roles`,
component: () => import('../views/roles'), component: () => import('../views/roles'),
meta: { title: '角色管理', icon: 'team', keepAlive: true, permission: ['acl_admin'] } meta: { title: 'acl.roleManage', icon: 'team', keepAlive: true, permission: ['acl_admin'] }
}, },
{ {
path: `/acl/apps`, path: `/acl/apps`,
name: 'acl_apps', name: 'acl_apps',
component: () => import('../views/apps'), component: () => import('../views/apps'),
meta: { title: '应用管理', icon: 'appstore', permission: ['acl_admin'] } meta: { title: 'acl.appManage', icon: 'appstore', permission: ['acl_admin'] }
} }
] ]
} }

View File

@@ -11,7 +11,7 @@
:xs="24"> :xs="24">
<a-card> <a-card>
<a-card-meta :title="app.name"> <a-card-meta :title="app.name">
<div slot="description" :title="app.description || ''">{{ app.description || '' }}</div> <div slot="description" :title="app.description || ''">{{ app.description || $t('none') }}</div>
<a-avatar style="background-color: #5dc2f1" slot="avatar">{{ app.name[0].toUpperCase() }}</a-avatar> <a-avatar style="background-color: #5dc2f1" slot="avatar">{{ app.name[0].toUpperCase() }}</a-avatar>
</a-card-meta> </a-card-meta>
<template slot="actions"> <template slot="actions">
@@ -65,11 +65,11 @@ export default {
handleDeleteApp(app) { handleDeleteApp(app) {
const that = this const that = this
this.$confirm({ this.$confirm({
title: '危险操作', title: that.$t('danger'),
content: '确定要删除该App吗?', content: that.$t('confirmDeleteApp'),
onOk() { onOk() {
deleteApp(app.id).then((res) => { deleteApp(app.id).then((res) => {
that.$message.success(`删除成功${app.name}`) that.$message.success(that.$t('deleteSuccess'))
that.loadApps() that.loadApps()
}) })
}, },

View File

@@ -1,7 +1,7 @@
<template> <template>
<div class="acl-history"> <div class="acl-history">
<a-tabs default-active-key="1"> <a-tabs default-active-key="1">
<a-tab-pane key="1" tab="权限变更"> <a-tab-pane key="1" :tab="$t('acl.permissionChange')">
<permisson-history-table <permisson-history-table
v-if="isloaded" v-if="isloaded"
:allResourceTypes="allResourceTypes" :allResourceTypes="allResourceTypes"
@@ -17,7 +17,7 @@
@resourceClear="resourceClear" @resourceClear="resourceClear"
></permisson-history-table> ></permisson-history-table>
</a-tab-pane> </a-tab-pane>
<a-tab-pane key="2" tab="角色变更"> <a-tab-pane key="2" :tab="$t('acl.roleChange')">
<role-history-table <role-history-table
v-if="isloaded" v-if="isloaded"
:allUsers="allUsers" :allUsers="allUsers"
@@ -26,7 +26,7 @@
:allUsersMap="allUsersMap" :allUsersMap="allUsersMap"
></role-history-table> ></role-history-table>
</a-tab-pane> </a-tab-pane>
<a-tab-pane key="3" tab="资源变更"> <a-tab-pane key="3" :tab="$t('acl.resourceChange')">
<resource-history-table <resource-history-table
v-if="isloaded" v-if="isloaded"
:allResources="allResources" :allResources="allResources"
@@ -41,7 +41,7 @@
@resourceClear="resourceClear" @resourceClear="resourceClear"
></resource-history-table> ></resource-history-table>
</a-tab-pane> </a-tab-pane>
<a-tab-pane key="4" tab="资源类型变更"> <a-tab-pane key="4" :tab="$t('acl.resourceTypeChange')">
<resource-type-history-table <resource-type-history-table
v-if="isloaded" v-if="isloaded"
:allResourceTypes="allResourceTypes" :allResourceTypes="allResourceTypes"
@@ -52,7 +52,7 @@
:allResourceTypesMap="allResourceTypesMap" :allResourceTypesMap="allResourceTypesMap"
></resource-type-history-table> ></resource-type-history-table>
</a-tab-pane> </a-tab-pane>
<a-tab-pane key="5" tab="触发器变更"> <a-tab-pane key="5" :tab="$t('acl.triggerChange')">
<trigger-history-table <trigger-history-table
v-if="isloaded" v-if="isloaded"
:allTriggers="allTriggers" :allTriggers="allTriggers"

View File

@@ -1,11 +1,12 @@
<template> <template>
<CustomDrawer @close="handleClose" width="500" :title="title" :visible="visible" :closable="false"> <CustomDrawer @close="handleClose" width="500" :title="title" :visible="visible" :closable="false">
<a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }"> <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="应用名称"> <a-form-item :label="$t('acl.app')">
<a-input v-decorator="['name', { rules: [{ required: true, message: '请输入应用名称' }] }]"> </a-input> <a-input v-decorator="['name', { rules: [{ required: true, message: $t('acl.appNameInput') }] }]"> </a-input>
</a-form-item> </a-form-item>
<a-form-item label="描述"> <a-form-item :label="$t('desc')">
<a-input v-decorator="['description', { rules: [{ required: true, message: '请输入描述' }] }]"> </a-input> <a-input v-decorator="['description', { rules: [{ required: true, message: $t('acl.descInput') }] }]">
</a-input>
</a-form-item> </a-form-item>
<a-form-item label="AppId"> <a-form-item label="AppId">
<a-input v-decorator="['app_id', { rules: [{ required: false }] }]" :disabled="mode === 'update'"> </a-input> <a-input v-decorator="['app_id', { rules: [{ required: false }] }]" :disabled="mode === 'update'"> </a-input>
@@ -19,8 +20,8 @@
</a-form-item> </a-form-item>
</a-form> </a-form>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="handleClose">取消</a-button> <a-button @click="handleClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">提交</a-button> <a-button @click="handleSubmit" type="primary">{{ $t('submit') }}</a-button>
</div> </div>
</CustomDrawer> </CustomDrawer>
</template> </template>
@@ -32,10 +33,14 @@ export default {
data() { data() {
return { return {
visible: false, visible: false,
title: '创建应用',
mode: 'create', mode: 'create',
} }
}, },
computed: {
title() {
return this.$t('acl.addApp')
},
},
beforeCreate() { beforeCreate() {
this.form = this.$form.createForm(this) this.form = this.$form.createForm(this)
}, },
@@ -43,7 +48,7 @@ export default {
handleEdit(ele) { handleEdit(ele) {
this.visible = true this.visible = true
if (ele) { if (ele) {
this.title = '修改应用' this.title = this.$t('updateApp')
this.mode = 'update' this.mode = 'update'
console.log(ele) console.log(ele)
const { name, description } = ele const { name, description } = ele
@@ -55,7 +60,7 @@ export default {
}) })
} else { } else {
this.mode = 'create' this.mode = 'create'
this.title = '创建应用' this.title = this.$t('acl.addApp')
} }
}, },
handleClose() { handleClose() {
@@ -69,11 +74,11 @@ export default {
} }
if (values.id) { if (values.id) {
await updateApp(values.id, values).then((res) => { await updateApp(values.id, values).then((res) => {
this.$message.success('修改成功!') this.$message.success(this.$t('updateSuccess'))
}) })
} else { } else {
await addApp(values).then((res) => { await addApp(values).then((res) => {
this.$message.success('创建成功!') this.$message.success(this.$t('addSuccess'))
}) })
} }
this.handleClose() this.handleClose()

View File

@@ -1,116 +0,0 @@
<template>
<div>
<a-row class="row" type="flex" justify="end">
<a-col>
<a-space align="end">
<a-button class="left-button" size="small" :disabled="prevIsDisabled" @click="prevPage"><a-icon type="left" /></a-button>
<a-button class="page-button" size="small">{{ currentPage }}</a-button>
<a-button class="right-button" size="small" :disabled="nextIsDisabled" @click="nextPage"><a-icon type="right" /></a-button>
<a-dropdown class="dropdown" size="small" placement="topCenter" :trigger="['click']" :disabled="dropdownIsDisabled">
<a-menu slot="overlay">
<a-menu-item v-for="(size,index) in pageSizes" :key="index" @click="handleItemClick(size)">
{{ size }}/
</a-menu-item>
</a-menu>
<a-button size="small"> {{ pageSize }}/ <a-icon type="down" /> </a-button>
</a-dropdown>
</a-space>
</a-col>
</a-row>
</div>
</template>
<script>
export default {
props: {
currentPage: {
type: Number,
required: true
},
pageSize: {
type: Number,
required: true
},
pageSizes: {
type: Array,
required: true
},
total: {
type: Number,
required: true
},
isLoading: {
type: Boolean,
required: false
}
},
data() {
return {
dropdownIsDisabled: false,
prevIsDisabled: true,
}
},
computed: {
nextIsDisabled() {
return this.isLoading || this.total < this.pageSize
}
},
watch: {
isLoading: {
immediate: true,
handler: function (val) {
if (val === true) {
this.dropdownIsDisabled = true
this.prevIsDisabled = true
} else {
this.dropdownIsDisabled = false
if (this.currentPage === 1) {
this.prevIsDisabled = true
} else {
this.prevIsDisabled = false
}
}
}
},
currentPage: {
immediate: true,
handler: function (val) {
if (val === 1) {
this.prevIsDisabled = true
}
}
}
},
methods: {
handleItemClick(size) {
this.$emit('showSizeChange', size)
},
nextPage() {
const pageNum = this.currentPage + 1
this.$emit('change', pageNum)
},
prevPage() {
const pageNum = this.currentPage - 1
this.$emit('change', pageNum)
}
}
}
</script>
<style lang="less" scoped>
.row{
margin-top: 5px;
.left-button{
padding: 0;
width: 24px;
}
.right-button{
padding: 0;
width: 24px;
}
.page-button{
padding: 0;
width: 24px;
}
}
</style>

View File

@@ -1,6 +1,6 @@
<template> <template>
<CustomDrawer <CustomDrawer
:title="`权限汇总: ${user.nickname}`" :title="`${$t('acl.summaryPermissions')}: ${user.nickname}`"
:visible="visible" :visible="visible"
placement="left" placement="left"
width="100%" width="100%"
@@ -24,7 +24,7 @@
<vxe-table :max-height="`${windowHeight - 230}px`" :data="resources" ref="rTable"> <vxe-table :max-height="`${windowHeight - 230}px`" :data="resources" ref="rTable">
<vxe-column <vxe-column
field="name" field="name"
title="资源名" :title="$t('acl.resourceName')"
width="30%" width="30%"
:filters="[{ data: '' }]" :filters="[{ data: '' }]"
:filter-method="filterNameMethod" :filter-method="filterNameMethod"
@@ -39,62 +39,17 @@
v-model="option.data" v-model="option.data"
@input="$panel.changeOption($event, !!option.data, option)" @input="$panel.changeOption($event, !!option.data, option)"
@keyup.enter="$panel.confirmFilter()" @keyup.enter="$panel.confirmFilter()"
placeholder="按回车确认筛选" :placeholder="$t('acl.pressEnter')"
/> />
</template> </template>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="permissions" title="权限列表" width="70%"> <vxe-column field="permissions" :title="$t('acl.permissionList')" width="70%">
<template #default="{row}"> <template #default="{row}">
<a-tag color="cyan" v-for="(r, index) in row.permissions" :key="index">{{ r }}</a-tag> <a-tag color="cyan" v-for="(r, index) in row.permissions" :key="index">{{ r }}</a-tag>
</template> </template>
</vxe-column> </vxe-column>
</vxe-table> </vxe-table>
<!-- <a-table
:columns="tableColumns"
:dataSource="resources"
:rowKey="record=>record.id"
:pagination="{ showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条记录` }"
showPagination="auto"
ref="rTable"
size="middle">
<div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" class="custom-filter-dropdown">
<a-input
v-ant-ref="c => searchInput = c"
:placeholder="` ${column.title}`"
:value="selectedKeys[0]"
@change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
@pressEnter="() => handleSearch(selectedKeys, confirm, column)"
style="width: 188px; margin-bottom: 8px; display: block;"
/>
<a-button
type="primary"
@click="() => handleSearch(selectedKeys, confirm, column)"
icon="search"
size="small"
style="width: 90px; margin-right: 8px"
>搜索</a-button>
<a-button
@click="() => handleReset(clearFilters, column)"
size="small"
style="width: 90px"
>重置</a-button>
</div>
<a-icon slot="filterIcon" slot-scope="filtered" type="search" :style="{ color: filtered ? '#108ee9' : undefined }" />
<template slot="nameSearchRender" slot-scope="text">
<span v-if="columnSearchText.name">
<template v-for="(fragment, i) in text.toString().split(new RegExp(`(?<=${columnSearchText.name})|(?=${columnSearchText.name})`, 'i'))">
<mark v-if="fragment.toLowerCase() === columnSearchText.name.toLowerCase()" :key="i" class="highlight">{{ fragment }}</mark>
<template v-else>{{ fragment }}</template>
</template>
</span>
<template v-else>{{ text }}</template>
</template>
<template slot="permissions" slot-scope="record">
<a-tag color="cyan" v-for="(r, index) in record" :key="index">{{ r }}</a-tag>
</template>
</a-table> -->
</a-spin> </a-spin>
</a-tab-pane> </a-tab-pane>
</a-tabs> </a-tabs>
@@ -122,33 +77,6 @@ export default {
resourceTypes: [], resourceTypes: [],
resourceTypePerms: [], resourceTypePerms: [],
resources: [], resources: [],
// tableColumns: [
// {
// title: '资源名',
// dataIndex: 'name',
// sorter: false,
// width: 150,
// // scopedSlots: {
// // customRender: 'nameSearchRender',
// // filterDropdown: 'filterDropdown',
// // filterIcon: 'filterIcon'
// // },
// // onFilter: (value, record) => record.name && record.name.toLowerCase().includes(value.toLowerCase()),
// // onFilterDropdownVisibleChange: (visible) => {
// // if (visible) {
// // setTimeout(() => {
// // this.searchInput.focus()
// // }, 0)
// // }
// // }
// },
// {
// title: '权限列表',
// dataIndex: 'permissions',
// width: 300,
// scopedSlots: { customRender: 'permissions' },
// },
// ],
columnSearchText: { columnSearchText: {
name: '', name: '',
}, },
@@ -156,14 +84,14 @@ export default {
}, },
computed: { computed: {
...mapState({ ...mapState({
windowHeight: state => state.windowHeight, windowHeight: (state) => state.windowHeight,
}), }),
displayApps() { displayApps() {
const roles = this.$store.state.user.roles.permissions const roles = this.$store.state.user.roles.permissions
if (roles.includes('acl_admin')) { if (roles.includes('acl_admin')) {
return this.apps return this.apps
} }
return this.apps.filter(item => { return this.apps.filter((item) => {
if (roles.includes(`${item.name}_admin`)) { if (roles.includes(`${item.name}_admin`)) {
return true return true
} }
@@ -192,7 +120,7 @@ export default {
}, },
async loadRoles(_appId) { async loadRoles(_appId) {
const res = await searchRole({ app_id: _appId, page_size: 9999, is_all: true }) const res = await searchRole({ app_id: _appId, page_size: 9999, is_all: true })
this.roles = res.roles.filter(item => item.uid) this.roles = res.roles.filter((item) => item.uid)
}, },
async handleSwitchApp(appId) { async handleSwitchApp(appId) {
this.currentAppId = appId this.currentAppId = appId
@@ -218,7 +146,7 @@ export default {
}, },
async loadResource() { async loadResource() {
this.spinning = true this.spinning = true
const fil = this.roles.filter(role => role.uid === this.user.uid) const fil = this.roles.filter((role) => role.uid === this.user.uid)
if (!fil[0]) { if (!fil[0]) {
return return
} }

View File

@@ -1,29 +1,33 @@
<template> <template>
<CustomDrawer <CustomDrawer
:closable="false" :closable="false"
:title="drawerTitle" :title="$t('acl.addResourceType')"
:visible="drawerVisible" :visible="drawerVisible"
@close="onClose" @close="onClose"
placement="right" placement="right"
width="30%" width="30%"
> >
<a-form :form="form" :layout="formLayout" @submit="handleSubmit"> <a-form :form="form" :layout="formLayout" @submit="handleSubmit">
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="类型名"> <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" :label="$t('acl.typeName')">
<a-input <a-input
name="name" name="name"
placeholder="" placeholder=""
v-decorator="['name', { rules: [{ required: true, message: '请输入资源名' }] }]" v-decorator="['name', { rules: [{ required: true, message: $t('acl.resourceNameInput') }] }]"
/> />
</a-form-item> </a-form-item>
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="描述"> <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" :label="$t('desc')">
<a-textarea placeholder="请输入描述信息..." name="description" :rows="4" /> <a-textarea :placeholder="$t('acl.descInput')" name="description" :rows="4" />
</a-form-item> </a-form-item>
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="权限"> <a-form-item
:label-col="formItemLayout.labelCol"
:wrapper-col="formItemLayout.wrapperCol"
:label="$t('acl.permission')"
>
<div :style="{ borderBottom: '1px solid #E9E9E9' }"> <div :style="{ borderBottom: '1px solid #E9E9E9' }">
<a-checkbox :indeterminate="indeterminate" @change="onCheckAllChange" :checked="checkAll"> <a-checkbox :indeterminate="indeterminate" @change="onCheckAllChange" :checked="checkAll">
全选 {{ $t('checkAll') }}
</a-checkbox> </a-checkbox>
</div> </div>
<br /> <br />
@@ -35,8 +39,8 @@
</a-form-item> </a-form-item>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="onClose">取消</a-button> <a-button @click="onClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">确定</a-button> <a-button @click="handleSubmit" type="primary">{{ $t('confirm') }}</a-button>
</div> </div>
</a-form> </a-form>
</CustomDrawer> </CustomDrawer>
@@ -49,7 +53,6 @@ export default {
name: 'ResourceForm', name: 'ResourceForm',
data() { data() {
return { return {
drawerTitle: '新增资源类型',
drawerVisible: false, drawerVisible: false,
formLayout: 'vertical', formLayout: 'vertical',
perms: ['1'], perms: ['1'],
@@ -142,8 +145,8 @@ export default {
}) })
}, },
updateResourceType(id, data) { updateResourceType(id, data) {
updateResourceTypeById(id, data).then(res => { updateResourceTypeById(id, data).then((res) => {
this.$message.success(`更新成功`) this.$message.success(this.$t('updateSuccess'))
this.handleOk() this.handleOk()
this.onClose() this.onClose()
}) })
@@ -151,18 +154,12 @@ export default {
}, },
createResourceType(data) { createResourceType(data) {
addResourceType(data).then(res => { addResourceType(data).then((res) => {
this.$message.success(`添加成功`) this.$message.success(this.$t('addSuccess'))
this.handleOk() this.handleOk()
this.onClose() this.onClose()
}) })
// .catch(err => this.requestFailed(err))
}, },
// requestFailed (err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// }
}, },
watch: {}, watch: {},
props: { props: {

View File

@@ -21,22 +21,22 @@
:height="`${windowHeight - windowHeightMinus}px`" :height="`${windowHeight - windowHeightMinus}px`"
:scroll-y="{ enabled: false }" :scroll-y="{ enabled: false }"
> >
<vxe-column field="created_at" width="144px" title="操作时间"> <vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')">
<template #default="{ row }"> <template #default="{ row }">
<span>{{ row.deleted_at || row.updated_at || row.created_at }}</span> <span>{{ row.deleted_at || row.updated_at || row.created_at }}</span>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="operate_uid" width="130px" title="操作员"></vxe-column> <vxe-column field="operate_uid" width="130px" :title="$t('acl.operator')"></vxe-column>
<vxe-column field="operate_type" width="80px" title="操作"> <vxe-column field="operate_type" width="100px" :title="$t('operation')">
<template #default="{ row }"> <template #default="{ row }">
<a-tag :color="row.operate_type === 'grant' ? 'green' : 'red'">{{ <a-tag :color="row.operate_type === 'grant' ? 'green' : 'red'">{{
operateTypeMap.get(row.operate_type) operateTypeMap.get(row.operate_type)
}}</a-tag> }}</a-tag>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="rid" title="用户"></vxe-column> <vxe-column field="rid" :title="$t('user')"></vxe-column>
<vxe-column field="resource_type_id" title="资源类型"></vxe-column> <vxe-column field="resource_type_id" :title="$t('acl.resourceType')"></vxe-column>
<vxe-column field="resources" title="资源"> <vxe-column field="resources" :title="$t('acl.resource')">
<template #default="{ row }"> <template #default="{ row }">
<template v-if="row.resource_ids.length > 0"> <template v-if="row.resource_ids.length > 0">
<a-tooltip placement="top"> <a-tooltip placement="top">
@@ -55,14 +55,14 @@
</template> </template>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column title="权限"> <vxe-column :title="$t('acl.permission')">
<template #default="{ row }"> <template #default="{ row }">
<a-tag v-for="(perm, index) in row.permission_ids" :key="'perms_' + perm + index"> <a-tag v-for="(perm, index) in row.permission_ids" :key="'perms_' + perm + index">
{{ perm }} {{ perm }}
</a-tag> </a-tag>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="source" width="100px" title="来源"></vxe-column> <vxe-column field="source" width="100px" :title="$t('acl.source')"></vxe-column>
</vxe-table> </vxe-table>
<pager <pager
:current-page.sync="queryParams.page" :current-page.sync="queryParams.page"
@@ -79,7 +79,7 @@
<script> <script>
import _ from 'lodash' import _ from 'lodash'
import Pager from './pager.vue' import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue' import SearchForm from './searchForm.vue'
import { searchPermissonHistory } from '@/modules/acl/api/history' import { searchPermissonHistory } from '@/modules/acl/api/history'
import debounce from 'lodash/debounce' import debounce from 'lodash/debounce'
@@ -122,10 +122,6 @@ export default {
loading: true, loading: true,
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
tableData: [], tableData: [],
operateTypeMap: new Map([
['grant', '授权'],
['revoke', '撤销'],
]),
queryParams: { queryParams: {
page: 1, page: 1,
page_size: 50, page_size: 50,
@@ -135,45 +131,45 @@ export default {
}, },
permissionTableAttrList: [ permissionTableAttrList: [
{ {
alias: '日期', alias: this.$t('acl.date'),
is_choice: false, is_choice: false,
name: 'datetime', name: 'datetime',
value_type: '3', value_type: '3',
}, },
{ {
alias: '操作员', alias: this.$t('acl.operator'),
is_choice: true, is_choice: true,
name: 'operate_uid', name: 'operate_uid',
value_type: '2', value_type: '2',
choice_value: this.allUsers, choice_value: this.allUsers,
}, },
{ {
alias: '用户', alias: this.$t('user'),
is_choice: true, is_choice: true,
name: 'rid', name: 'rid',
value_type: '2', value_type: '2',
choice_value: this.allRoles, choice_value: this.allRoles,
}, },
{ {
alias: '资源类型', alias: this.$t('acl.resourceType'),
is_choice: true, is_choice: true,
name: 'resource_type_id', name: 'resource_type_id',
value_type: '2', value_type: '2',
choice_value: this.allResourceTypes, choice_value: this.allResourceTypes,
}, },
{ {
alias: '资源', alias: this.$t('acl.resource'),
is_choice: true, is_choice: true,
name: 'resource_id', name: 'resource_id',
value_type: '2', value_type: '2',
choice_value: this.allResources, choice_value: this.allResources,
}, },
{ {
alias: '操作', alias: this.$t('operation'),
is_choice: true, is_choice: true,
name: 'operate_type', name: 'operate_type',
value_type: '2', value_type: '2',
choice_value: [{ 授权: 'grant' }, { 撤销: 'revoke' }], choice_value: [{ [this.$t('grant')]: 'grant' }, { [this.$t('acl.cancel')]: 'revoke' }],
}, },
], ],
} }
@@ -198,6 +194,12 @@ export default {
}, },
}, },
computed: { computed: {
operateTypeMap() {
return new Map([
['grant', this.$t('grant')],
['revoke', this.$t('acl.cancel')],
])
},
windowHeight() { windowHeight() {
return this.$store.state.windowHeight return this.$store.state.windowHeight
}, },

View File

@@ -1,6 +1,6 @@
<template> <template>
<CustomDrawer <CustomDrawer
title="便捷授权" :title="$t('acl.convenient')"
width="500px" width="500px"
:maskClosable="false" :maskClosable="false"
:closable="true" :closable="true"
@@ -10,12 +10,12 @@
<a-form :form="form"> <a-form :form="form">
<a-form-item> <a-form-item>
<div slot="label" style="display: inline-block"> <div slot="label" style="display: inline-block">
<span>角色列表</span> <span>{{ $t('acl.roleList') }}</span>
<a-divider type="vertical" /> <a-divider type="vertical" />
<a-switch <a-switch
style="display: inline-block" style="display: inline-block"
checked-children="用户" :checked-children="$t('user')"
un-checked-children="虚拟" :un-checked-children="$t('acl.virtual')"
@change="handleRoleTypeChange" @change="handleRoleTypeChange"
v-model="roleType" v-model="roleType"
/> />
@@ -23,37 +23,37 @@
<el-select <el-select
:style="{ width: '100%' }" :style="{ width: '100%' }"
size="small" size="small"
v-decorator="['roleIdList', { rules: [{ required: true, message: '请选择角色名称' }] }]" v-decorator="['roleIdList', { rules: [{ required: true, message: $t('acl.role_placeholder2') }] }]"
multiple multiple
filterable filterable
placeholder="请选择角色名称,可多选!" :placeholder="$t('acl.role_placeholder3')"
> >
<el-option v-for="role in allRoles" :key="role.id" :value="role.id" :label="role.name"></el-option> <el-option v-for="role in allRoles" :key="role.id" :value="role.id" :label="role.name"></el-option>
</el-select> </el-select>
</a-form-item> </a-form-item>
<a-form-item label="权限列表"> <a-form-item :label="$t('acl.permissionList')">
<el-select <el-select
:style="{ width: '100%' }" :style="{ width: '100%' }"
size="small" size="small"
name="permName" name="permName"
v-decorator="['permName', { rules: [{ required: true, message: '请选择权限' }] }]" v-decorator="['permName', { rules: [{ required: true, message: this.$t('acl.permission_placeholder') }] }]"
multiple multiple
placeholder="请选择权限,可多选!" :placeholder="this.$t('acl.permission_placeholder')"
> >
<el-option v-for="perm in allPerms" :key="perm.name" :value="perm.name" :label="perm.name"></el-option> <el-option v-for="perm in allPerms" :key="perm.name" :value="perm.name" :label="perm.name"></el-option>
</el-select> </el-select>
</a-form-item> </a-form-item>
<a-form-item label="资源名"> <a-form-item :label="$t('acl.resourceName')">
<a-textarea <a-textarea
v-decorator="['resource_names', { rules: [{ required: true, message: '请输入资源名,换行分隔' }] }]" v-decorator="['resource_names', { rules: [{ required: true, message: $t('acl.resourceBatchTips') }] }]"
:autoSize="{ minRows: 4 }" :autoSize="{ minRows: 4 }"
placeholder="请输入资源名,换行分隔" :placeholder="$t('acl.resourceBatchTips')"
/> />
</a-form-item> </a-form-item>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="handleRevoke" type="danger" ghost>权限回收</a-button> <a-button @click="handleRevoke" type="danger" ghost>{{ $t('acl.revoke') }}</a-button>
<a-button @click="handleSubmit" type="primary">授权</a-button> <a-button @click="handleSubmit" type="primary">{{ $t('grant') }}</a-button>
</div> </div>
</a-form> </a-form>
</CustomDrawer> </CustomDrawer>
@@ -98,12 +98,12 @@ export default {
this.loadRoles(Number(target)) this.loadRoles(Number(target))
}, },
loadRoles(isUserRole) { loadRoles(isUserRole) {
searchRole({ page_size: 9999, app_id: this.$route.name.split('_')[0], user_role: isUserRole }).then(res => { searchRole({ page_size: 9999, app_id: this.$route.name.split('_')[0], user_role: isUserRole }).then((res) => {
this.allRoles = res.roles this.allRoles = res.roles
}) })
}, },
loadPerm(resourceTypeId) { loadPerm(resourceTypeId) {
getResourceTypePerms(resourceTypeId).then(res => { getResourceTypePerms(resourceTypeId).then((res) => {
this.allPerms = res this.allPerms = res
}) })
}, },
@@ -111,13 +111,13 @@ export default {
this.form.validateFields((err, values) => { this.form.validateFields((err, values) => {
if (!err) { if (!err) {
console.log(values) console.log(values)
values.roleIdList.forEach(roleId => { values.roleIdList.forEach((roleId) => {
setBatchRoleResourceByResourceName(roleId, { setBatchRoleResourceByResourceName(roleId, {
resource_names: values.resource_names.split('\n'), resource_names: values.resource_names.split('\n'),
perms: values.permName, perms: values.permName,
resource_type_id: this.resource_type_id, resource_type_id: this.resource_type_id,
}).then(res => { }).then((res) => {
this.$message.success('授权成功') this.$message.success(this.$t('operateSuccess'))
this.form.resetFields() this.form.resetFields()
}) })
}) })
@@ -128,13 +128,13 @@ export default {
this.form.validateFields((err, values) => { this.form.validateFields((err, values) => {
if (!err) { if (!err) {
console.log(values) console.log(values)
values.roleIdList.forEach(roleId => { values.roleIdList.forEach((roleId) => {
setBatchRoleResourceRevokeByResourceName(roleId, { setBatchRoleResourceRevokeByResourceName(roleId, {
resource_names: values.resource_names.split('\n'), resource_names: values.resource_names.split('\n'),
perms: values.permName, perms: values.permName,
resource_type_id: this.resource_type_id, resource_type_id: this.resource_type_id,
}).then(res => { }).then((res) => {
this.$message.success('权限回收成功') this.$message.success(this.$t('operateSuccess'))
this.form.resetFields() this.form.resetFields()
}) })
}) })

View File

@@ -8,27 +8,27 @@
width="30%" width="30%"
> >
<a-form :form="form" @submit="handleSubmit" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }"> <a-form :form="form" @submit="handleSubmit" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="资源名"> <a-form-item :label="$t('acl.resourceName')">
<a-input <a-input
name="name" name="name"
placeholder="" placeholder=""
v-decorator="['name', { rules: [{ required: true, message: '请输入资源名' }] }]" v-decorator="['name', { rules: [{ required: true, message: $t('acl.resourceNameInput') }] }]"
/> />
</a-form-item> </a-form-item>
<a-form-item label="资源类型"> <a-form-item :label="$t('acl.resourceType')">
<a-select v-model="selectedTypeId"> <a-select v-model="selectedTypeId">
<a-select-option v-for="type in allTypes" :key="type.id">{{ type.name }}</a-select-option> <a-select-option v-for="type in allTypes" :key="type.id">{{ type.name }}</a-select-option>
</a-select> </a-select>
</a-form-item> </a-form-item>
<a-form-item label="是否组"> <a-form-item :label="$t('acl.isGroup')">
<a-radio-group v-model="isGroup"> <a-radio-group v-model="isGroup">
<a-radio :value="true"> <a-radio :value="true">
{{ $t('yes') }}
</a-radio> </a-radio>
<a-radio :value="false"> <a-radio :value="false">
{{ $t('no') }}
</a-radio> </a-radio>
</a-radio-group> </a-radio-group>
</a-form-item> </a-form-item>
@@ -36,8 +36,8 @@
<a-input name="id" type="hidden" v-decorator="['id', { rules: [] }]" /> <a-input name="id" type="hidden" v-decorator="['id', { rules: [] }]" />
</a-form-item> </a-form-item>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="onClose">取消</a-button> <a-button @click="onClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">确定</a-button> <a-button @click="handleSubmit" type="primary">{{ $t('confirm') }}</a-button>
</div> </div>
</a-form> </a-form>
</CustomDrawer> </CustomDrawer>
@@ -52,7 +52,6 @@ export default {
name: 'ResourceForm', name: 'ResourceForm',
data() { data() {
return { return {
drawerTitle: '新增资源',
drawerVisible: false, drawerVisible: false,
allTypes: [], allTypes: [],
isGroup: false, isGroup: false,
@@ -68,7 +67,11 @@ export default {
this.getAllResourceTypes() this.getAllResourceTypes()
}, },
computed: {}, computed: {
drawerTitle() {
return this.$t('acl.addResource')
},
},
mounted() {}, mounted() {},
methods: { methods: {
getAllResourceTypes() { getAllResourceTypes() {
@@ -95,7 +98,7 @@ export default {
values.type_id = this.selectedTypeId values.type_id = this.selectedTypeId
values.app_id = this.$route.name.split('_')[0] values.app_id = this.$route.name.split('_')[0]
if (values.id) { if (values.id) {
this.$message.error('错误提示') this.$message.error(this.$t('acl.errorTips'))
} else { } else {
this.createResource(values) this.createResource(values)
} }
@@ -105,23 +108,17 @@ export default {
createResource(data) { createResource(data) {
if (!this.isGroup) { if (!this.isGroup) {
addResource(data).then((res) => { addResource(data).then((res) => {
this.$message.success(`添加成功`) this.$message.success(this.$t('addSuccess'))
this.onClose() this.onClose()
}) })
// .catch(err => this.requestFailed(err)) // .catch(err => this.requestFailed(err))
} else { } else {
addResourceGroup(data).then((res) => { addResourceGroup(data).then((res) => {
this.$message.success(`添加成功`) this.$message.success(this.$t('addSuccess'))
this.onClose() this.onClose()
}) })
// .catch(err => this.requestFailed(err))
} }
}, },
// requestFailed(err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// },
}, },
watch: { watch: {
'$route.name': function(newValue, oldValue) { '$route.name': function(newValue, oldValue) {

View File

@@ -1,5 +1,5 @@
<template> <template>
<a-modal v-model="visible" :title="`组成员:${editRecord.name}`" :width="800" :footer="null"> <a-modal v-model="visible" :title="`${$t('acl.groupMember')}${editRecord.name}`" :width="800" :footer="null">
<div :style="{ maxHeight: '500px', overflow: 'auto' }"> <div :style="{ maxHeight: '500px', overflow: 'auto' }">
<a-tag :style="{ marginBottom: '5px' }" v-for="mem in members" :key="mem.name"> <a-tag :style="{ marginBottom: '5px' }" v-for="mem in members" :key="mem.name">
{{ mem.name }} {{ mem.name }}

View File

@@ -1,5 +1,5 @@
<template> <template>
<a-modal v-model="visible" :title="`成员管理:${editRecord.name}`" @ok="handleSubmit" :width="690"> <a-modal v-model="visible" :title="`${$t('acl.memberManage')}${editRecord.name}`" @ok="handleSubmit" :width="690">
<!-- <CustomTransfer <!-- <CustomTransfer
ref="customTransfer" ref="customTransfer"
:show-search="true" :show-search="true"
@@ -26,7 +26,7 @@
@selectChange="selectChange" @selectChange="selectChange"
:selectedKeys="selectedKeys" :selectedKeys="selectedKeys"
> >
<span slot="notFoundContent">暂无数据</span> <span slot="notFoundContent">{{ $t('noData') }}</span>
<template slot="children" slot-scope="{ props: { direction, filteredItems } }"> <template slot="children" slot-scope="{ props: { direction, filteredItems } }">
<div class="ant-transfer-list-content" v-if="direction === 'right'"> <div class="ant-transfer-list-content" v-if="direction === 'right'">
<div <div
@@ -104,7 +104,7 @@ export default {
}) })
updateResourceGroup(this.editRecord['id'], { items: items.join(',') }).then(() => { updateResourceGroup(this.editRecord['id'], { items: items.join(',') }).then(() => {
this.visible = false this.visible = false
this.$message.success('更新成功!') this.$message.success(this.$t('updateSuccess'))
}) })
// .catch(err => this.$httpError(err)) // .catch(err => this.$httpError(err))
}, },

View File

@@ -4,7 +4,7 @@
ref="child" ref="child"
:attrList="resourceTableAttrList" :attrList="resourceTableAttrList"
:hasSwitch="true" :hasSwitch="true"
switchValue="" :switchValue="$t('acl.group2')"
@onSwitchChange="onSwitchChange" @onSwitchChange="onSwitchChange"
@search="handleSearch" @search="handleSearch"
@searchFormReset="searchFormReset" @searchFormReset="searchFormReset"
@@ -22,30 +22,30 @@
resizable resizable
:height="`${windowHeight - 310}px`" :height="`${windowHeight - 310}px`"
> >
<vxe-column field="created_at" width="144px" title="操作时间"></vxe-column> <vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')"></vxe-column>
<vxe-column field="operate_uid" width="130px" title="操作员"></vxe-column> <vxe-column field="operate_uid" width="130px" :title="$t('acl.operator')"></vxe-column>
<vxe-column field="operate_type" width="80px" title="操作"> <vxe-column field="operate_type" width="100px" :title="$t('operation')">
<template #default="{ row }"> <template #default="{ row }">
<a-tag :color="handleTagColor(row.operate_type)"> <a-tag :color="handleTagColor(row.operate_type)">
{{ operateTypeMap.get(row.operate_type) }} {{ operateTypeMap.get(row.operate_type) }}
</a-tag> </a-tag>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="link_id" title="资源名"> <vxe-column field="link_id" :title="$t('acl.resourceName')">
<template #default="{ row }"> <template #default="{ row }">
<span> <span>
{{ row.current.name || row.origin.name }} {{ row.current.name || row.origin.name }}
</span> </span>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column title="描述"> <vxe-column :title="$t('desc')">
<template #default="{ row }"> <template #default="{ row }">
<p> <p>
{{ row.description }} {{ row.description }}
</p> </p>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="source" width="100px" title="来源"></vxe-column> <vxe-column field="source" width="100px" :title="$t('acl.source')"></vxe-column>
</vxe-table> </vxe-table>
<pager <pager
:current-page.sync="queryParams.page" :current-page.sync="queryParams.page"
@@ -62,7 +62,7 @@
<script> <script>
import _ from 'lodash' import _ from 'lodash'
import Pager from './pager.vue' import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue' import SearchForm from './searchForm.vue'
import { searchResourceHistory } from '@/modules/acl/api/history' import { searchResourceHistory } from '@/modules/acl/api/history'
export default { export default {
@@ -99,40 +99,6 @@ export default {
checked: false, checked: false,
tableData: [], tableData: [],
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
resourceTableAttrList: [
{
alias: '日期',
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: '操作员',
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: '操作',
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [{ 新建: 'create' }, { 修改: 'update' }, { 删除: 'delete' }],
},
{
alias: '资源名',
is_choice: true,
name: 'link_id',
value_type: '2',
choice_value: this.allResources,
},
],
operateTypeMap: new Map([
['create', '新建'],
['update', '修改'],
['delete', '删除'],
]),
colorMap: new Map([ colorMap: new Map([
['create', 'green'], ['create', 'green'],
['update', 'orange'], ['update', 'orange'],
@@ -146,6 +112,39 @@ export default {
start: '', start: '',
end: '', end: '',
}, },
resourceTableAttrList: [
{
alias: this.$t('acl.date'),
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: this.$t('acl.operator'),
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: this.$t('operation'),
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [
{ [this.$t('create')]: 'create' },
{ [this.$t('update')]: 'update' },
{ [this.$t('delete')]: 'delete' },
],
},
{
alias: this.$t('acl.resourceName'),
is_choice: true,
name: 'link_id',
value_type: '2',
choice_value: this.allResources,
},
],
} }
}, },
async created() { async created() {
@@ -170,6 +169,13 @@ export default {
windowHeight() { windowHeight() {
return this.$store.state.windowHeight return this.$store.state.windowHeight
}, },
operateTypeMap() {
return new Map([
['create', this.$t('create')],
['update', this.$t('update')],
['delete', this.$t('delete')],
])
},
tableDataLength() { tableDataLength() {
return this.tableData.length return this.tableData.length
}, },
@@ -280,7 +286,7 @@ export default {
switch (operate_type) { switch (operate_type) {
// create // create
case 'create': { case 'create': {
item.description = `新建资源${item.current.name}` item.description = `${this.$t('acl.newResource')}${item.current.name}`
break break
} }
case 'update': { case 'update': {
@@ -290,9 +296,9 @@ export default {
const oldVal = item.origin[key] const oldVal = item.origin[key]
if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') { if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') {
if (oldVal === null) { if (oldVal === null) {
item.description += ` ${key} : 改为 ${newVal} ` item.description += ` ${key} : -> ${newVal} `
} else { } else {
item.description += ` ${key} : ${oldVal} 改为 ${newVal} ` item.description += ` ${key} : ${oldVal} -> ${newVal} `
} }
} }
} }
@@ -300,18 +306,18 @@ export default {
const currentResource_ids = item.currentResource_ids const currentResource_ids = item.currentResource_ids
if (!_.isEqual(originResource_ids, currentResource_ids)) { if (!_.isEqual(originResource_ids, currentResource_ids)) {
if (originResource_ids.length === 0) { if (originResource_ids.length === 0) {
const str = ` resource_ids : 新增 ${currentResource_ids} ` const str = ` resource_ids : ${this.$t('new')} ${currentResource_ids} `
item.description += str item.description += str
} else { } else {
const str = ` resource_ids : ${originResource_ids} 改为 ${currentResource_ids} ` const str = ` resource_ids : ${originResource_ids} -> ${currentResource_ids} `
item.description += str item.description += str
} }
} }
if (!item.description) item.description = '没有修改' if (!item.description) item.description = this.$t('acl.noChange')
break break
} }
case 'delete': { case 'delete': {
item.description = `删除资源${item.origin.name}` item.description = `${this.$t('acl.deleteResource')}${item.origin.name}`
break break
} }
} }

View File

@@ -17,7 +17,7 @@
> >
<vxe-column <vxe-column
field="name" field="name"
title="角色名" :title="$t('acl.role')"
width="20%" width="20%"
:filters="[{ data: '' }]" :filters="[{ data: '' }]"
:filter-method="filterNameMethod" :filter-method="filterNameMethod"
@@ -32,19 +32,19 @@
v-model="option.data" v-model="option.data"
@input="$panel.changeOption($event, !!option.data, option)" @input="$panel.changeOption($event, !!option.data, option)"
@keyup.enter="$panel.confirmFilter()" @keyup.enter="$panel.confirmFilter()"
placeholder="按回车确认筛选" :placeholder="$t('acl.pressEnter')"
/> />
</template> </template>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="users" title="下属用户" width="35%"> <vxe-column field="users" :title="$t('acl.subordinateUsers')" width="35%">
<template #default="{row}"> <template #default="{row}">
<a-tag color="green" v-for="user in row.users" :key="user.nickname"> <a-tag color="green" v-for="user in row.users" :key="user.nickname">
{{ user.nickname }} {{ user.nickname }}
</a-tag> </a-tag>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="perms" title="权限列表" width="35%"> <vxe-column field="perms" :title="$t('acl.permissionList')" width="35%">
<template #default="{row}"> <template #default="{row}">
<a-tag <a-tag
closable closable
@@ -57,43 +57,18 @@
</a-tag> </a-tag>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="operate" title="批量操作"> <vxe-column field="operate" :title="$t('acl.batchOperate')">
<template #default="{row}"> <template #default="{row}">
<a-button size="small" type="danger" @click="handleClearAll(row)"> <a-button size="small" type="danger" @click="handleClearAll(row)">
清空 {{ $t('clear') }}
</a-button> </a-button>
</template> </template>
</vxe-column> </vxe-column>
<template slot="empty"> <template slot="empty">
<img :src="require(`@/assets/data_empty.png`)" /> <img :src="require(`@/assets/data_empty.png`)" />
<p style="font-size: 14px; line-height: 17px; color: rgba(0, 0, 0, 0.6)">暂无数据</p> <p style="font-size: 14px; line-height: 17px; color: rgba(0, 0, 0, 0.6)">{{ $t('noData') }}</p>
</template> </template>
</vxe-table> </vxe-table>
<!-- <a-table
:columns="columns"
:dataSource="resPerms"
:rowKey="record => record.name"
:pagination="{ showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条记录` }"
showPagination="auto"
ref="rTable"
size="middle"
>
<div slot="perms" slot-scope="text">
<a-tag closable color="cyan" v-for="perm in text" :key="perm.name" @close="deletePerm(perm.rid, perm.name)">
{{ perm.name }}
</a-tag>
</div>
<div slot="users" slot-scope="text">
<a-tag color="green" v-for="user in text" :key="user.nickname">
{{ user.nickname }}
</a-tag>
</div>
<div slot="operate" slot-scope="text">
<a-button size="small" type="danger" @click="handleClearAll(text)">
清空
</a-button>
</div>
</a-table> -->
</CustomDrawer> </CustomDrawer>
</template> </template>
<script> <script>
@@ -112,40 +87,11 @@ export default {
data() { data() {
return { return {
isGroup: false, isGroup: false,
drawerTitle: '权限列表',
drawerVisible: false, drawerVisible: false,
record: null, record: null,
allPerms: [], allPerms: [],
resPerms: [], resPerms: [],
roleID: null, roleID: null,
// columns: [
// {
// title: '角色名',
// dataIndex: 'name',
// sorter: false,
// width: 50,
// },
// {
// title: '下属用户',
// dataIndex: 'users',
// sorter: false,
// width: 150,
// scopedSlots: { customRender: 'users' },
// },
// {
// title: '权限列表',
// dataIndex: 'perms',
// sorter: false,
// width: 150,
// scopedSlots: { customRender: 'perms' },
// },
// {
// title: '批量操作',
// sorter: false,
// width: 50,
// scopedSlots: { customRender: 'operate' },
// },
// ],
childrenDrawer: false, childrenDrawer: false,
allRoles: [], allRoles: [],
} }
@@ -154,6 +100,9 @@ export default {
...mapState({ ...mapState({
windowHeight: (state) => state.windowHeight, windowHeight: (state) => state.windowHeight,
}), }),
drawerTitle() {
return this.$t('acl.permissionList')
}
}, },
beforeCreate() { beforeCreate() {
this.form = this.$form.createForm(this) this.form = this.$form.createForm(this)
@@ -175,7 +124,7 @@ export default {
perms: [], perms: [],
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
}).then((res) => { }).then((res) => {
this.$message.success('删除成功') this.$message.success(this.$t('deleteSuccess'))
this.$nextTick(() => { this.$nextTick(() => {
this.getResPerms(this.record.id) this.getResPerms(this.record.id)
}) })
@@ -185,7 +134,7 @@ export default {
perms: [], perms: [],
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
}).then((res) => { }).then((res) => {
this.$message.success('删除成功') this.$message.success(this.$t('deleteSuccess'))
// for (let i = 0; i < this.resPerms.length; i++) { // for (let i = 0; i < this.resPerms.length; i++) {
// if (this.resPerms[i].name === text.name) { // if (this.resPerms[i].name === text.name) {
// this.resPerms[i].perms = [] // this.resPerms[i].perms = []
@@ -227,7 +176,7 @@ export default {
perms: [permName], perms: [permName],
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
}).then((res) => { }).then((res) => {
this.$message.success(`删除成功`) this.$message.success(this.$t('deleteSuccess'))
}) })
// .catch(err => this.requestFailed(err)) // .catch(err => this.requestFailed(err))
} else { } else {
@@ -235,18 +184,13 @@ export default {
perms: [permName], perms: [permName],
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
}).then((res) => { }).then((res) => {
this.$message.success(`删除成功`) this.$message.success(this.$t('deleteSuccess'))
}) })
// .catch(err => this.requestFailed(err))
} }
}, },
handleCancel(e) { handleCancel(e) {
this.drawerVisible = false this.drawerVisible = false
}, },
// requestFailed(err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// },
filterNameMethod({ option, row }) { filterNameMethod({ option, row }) {
return row.name.toLowerCase().includes(option.data.toLowerCase()) return row.name.toLowerCase().includes(option.data.toLowerCase())
}, },

View File

@@ -3,42 +3,42 @@
<a-form :form="form"> <a-form :form="form">
<a-form-item> <a-form-item>
<div slot="label" style="display: inline-block"> <div slot="label" style="display: inline-block">
<span>角色列表</span> <span>{{ $t('acl.roleList') }}</span>
<a-divider type="vertical" /> <a-divider type="vertical" />
<a-switch <a-switch
style="display: inline-block" style="display: inline-block"
checked-children="用户" :checked-children="$t('user')"
un-checked-children="虚拟" :un-checked-children="$t('acl.virtual')"
@change="handleRoleTypeChange" @change="handleRoleTypeChange"
/> />
</div> </div>
<el-select <el-select
:style="{ width: '100%' }" :style="{ width: '100%' }"
size="small" size="small"
v-decorator="['roleIdList', { rules: [{ required: true, message: '请选择角色名称' }] }]" v-decorator="['roleIdList', { rules: [{ required: true, message: $t('acl.role_placeholder2') }] }]"
multiple multiple
filterable filterable
placeholder="请选择角色名称,可多选!" :placeholder="$t('acl.role_placeholder3')"
> >
<el-option v-for="role in allRoles" :key="role.id" :value="role.id" :label="role.name"></el-option> <el-option v-for="role in allRoles" :key="role.id" :value="role.id" :label="role.name"></el-option>
</el-select> </el-select>
</a-form-item> </a-form-item>
<a-form-item label="权限列表"> <a-form-item :label="$t('acl.permissionList')">
<el-select <el-select
:style="{ width: '100%' }" :style="{ width: '100%' }"
size="small" size="small"
name="permName" name="permName"
v-decorator="['permName', { rules: [{ required: true, message: '请选择权限' }] }]" v-decorator="['permName', { rules: [{ required: true, message: $t('acl.permission_placeholder') }] }]"
multiple multiple
placeholder="请选择权限,可多选!" :placeholder="$t('acl.permission_placeholder') "
> >
<el-option v-for="perm in allPerms" :key="perm.name" :value="perm.name" :label="perm.name"></el-option> <el-option v-for="perm in allPerms" :key="perm.name" :value="perm.name" :label="perm.name"></el-option>
</el-select> </el-select>
</a-form-item> </a-form-item>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="closeForm">取消</a-button> <a-button @click="closeForm">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary" :loading="loading">确定</a-button> <a-button @click="handleSubmit" type="primary" :loading="loading">{{ $t('confirm') }}</a-button>
</div> </div>
</a-form> </a-form>
</CustomDrawer> </CustomDrawer>
@@ -117,16 +117,12 @@ export default {
this.type = type this.type = type
if (Array.isArray(record)) { if (Array.isArray(record)) {
this.loadPerm(record[0]['resource_type_id']) this.loadPerm(record[0]['resource_type_id'])
this.title = `${type === 'grant' ? '批量授权' : '批量权限回收'}` this.title = `${type === 'grant' ? this.$t('acl.batchGrant') : this.$t('acl.batchRevoke')}`
} else { } else {
this.title = `添加授权${record.name}` this.title = `${this.$t('acl.editPerm')}${record.name}`
this.loadPerm(record['resource_type_id']) this.loadPerm(record['resource_type_id'])
} }
}, },
// requestFailed(err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// },
handleSubmit(e) { handleSubmit(e) {
e.preventDefault() e.preventDefault()
this.form.validateFields((err, values) => { this.form.validateFields((err, values) => {
@@ -136,16 +132,10 @@ export default {
this.loading = true this.loading = true
if (!this.isGroup) { if (!this.isGroup) {
if (Array.isArray(this.instance)) { if (Array.isArray(this.instance)) {
// const promises = this.instance.map(item => {
// return setRoleResourcePerm(roleId, item.id, params)
// })
// Promise.all(promises).then(() => {
// this.$message.success('添加授权成功')
// })
if (this.type === 'grant') { if (this.type === 'grant') {
setBatchRoleResourcePerm(roleId, { ...params, resource_ids: this.instance.map((a) => a.id) }) setBatchRoleResourcePerm(roleId, { ...params, resource_ids: this.instance.map((a) => a.id) })
.then((res) => { .then((res) => {
this.$message.success('添加授权成功') this.$message.success(this.$t('operateSuccess'))
}) })
.finally(() => { .finally(() => {
this.loading = false this.loading = false
@@ -153,7 +143,7 @@ export default {
} else { } else {
setBatchRoleResourceRevoke(roleId, { ...params, resource_ids: this.instance.map((a) => a.id) }) setBatchRoleResourceRevoke(roleId, { ...params, resource_ids: this.instance.map((a) => a.id) })
.then((res) => { .then((res) => {
this.$message.success('批量权限回收成功') this.$message.success(this.$t('operateSuccess'))
}) })
.finally(() => { .finally(() => {
this.loading = false this.loading = false
@@ -162,7 +152,7 @@ export default {
} else { } else {
setRoleResourcePerm(roleId, this.instance.id, params) setRoleResourcePerm(roleId, this.instance.id, params)
.then((res) => { .then((res) => {
this.$message.success('添加授权成功') this.$message.success(this.$t('operateSuccess'))
}) })
.finally(() => { .finally(() => {
this.loading = false this.loading = false
@@ -170,16 +160,10 @@ export default {
} }
} else { } else {
if (Array.isArray(this.instance)) { if (Array.isArray(this.instance)) {
// const promises = this.instance.map(item => {
// return setRoleResourceGroupPerm(roleId, item.id, params)
// })
// Promise.all(promises).then(() => {
// this.$message.success('添加授权成功')
// })
if (this.type === 'grant') { if (this.type === 'grant') {
setBatchRoleResourceGroupPerm(roleId, { ...params, group_ids: this.instance.map((a) => a.id) }) setBatchRoleResourceGroupPerm(roleId, { ...params, group_ids: this.instance.map((a) => a.id) })
.then((res) => { .then((res) => {
this.$message.success('添加授权成功') this.$message.success(this.$t('operateSuccess'))
}) })
.finally(() => { .finally(() => {
this.loading = false this.loading = false
@@ -190,7 +174,7 @@ export default {
group_ids: this.instance.map((a) => a.id), group_ids: this.instance.map((a) => a.id),
}) })
.then((res) => { .then((res) => {
this.$message.success('批量权限回收成功') this.$message.success(this.$t('operateSuccess'))
}) })
.finally(() => { .finally(() => {
this.loading = false this.loading = false
@@ -199,7 +183,7 @@ export default {
} else { } else {
setRoleResourceGroupPerm(roleId, this.instance.id, params) setRoleResourceGroupPerm(roleId, this.instance.id, params)
.then((res) => { .then((res) => {
this.$message.success('添加授权成功') this.$message.success(this.$t('operateSuccess'))
}) })
.finally(() => { .finally(() => {
this.loading = false this.loading = false

View File

@@ -1,32 +1,32 @@
<template> <template>
<CustomDrawer <CustomDrawer
:closable="false" :closable="false"
:title="drawerTitle" :title="$t('acl.addResourceType')"
:visible="drawerVisible" :visible="drawerVisible"
@close="onClose" @close="onClose"
placement="right" placement="right"
width="500px" width="500px"
> >
<a-form :form="form" @submit="handleSubmit" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }"> <a-form :form="form" @submit="handleSubmit" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="类型名"> <a-form-item :label="$t('acl.typeName')">
<a-input <a-input
name="name" name="name"
placeholder="类型名称" :placeholder="$t('acl.typeName')"
v-decorator="['name', { rules: [{ required: true, message: '请输入类型名' }] }]" v-decorator="['name', { rules: [{ required: true, message: $t('acl.typeNameInput') }] }]"
/> />
</a-form-item> </a-form-item>
<a-form-item label="描述"> <a-form-item :label="$t('desc')">
<a-textarea <a-textarea
placeholder="请输入描述信息..." :placeholder="$t('acl.descInput')"
name="description" name="description"
:rows="4" :rows="4"
v-decorator="['description', { rules: [] }]" v-decorator="['description', { rules: [] }]"
/> />
</a-form-item> </a-form-item>
<a-form-item label="权限"> <a-form-item :label="$t('acl.permission')">
<a-select mode="tags" v-model="perms" style="width: 100%" placeholder="请输入权限名..."> </a-select> <a-select mode="tags" v-model="perms" style="width: 100%" :placeholder="$t('acl.permInput')"> </a-select>
</a-form-item> </a-form-item>
<a-form-item> <a-form-item>
@@ -34,8 +34,8 @@
</a-form-item> </a-form-item>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="onClose">取消</a-button> <a-button @click="onClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">确定</a-button> <a-button @click="handleSubmit" type="primary">{{ $t('confirm') }}</a-button>
</div> </div>
</a-form> </a-form>
</CustomDrawer> </CustomDrawer>
@@ -48,7 +48,6 @@ export default {
name: 'ResourceForm', name: 'ResourceForm',
data() { data() {
return { return {
drawerTitle: '新增资源类型',
drawerVisible: false, drawerVisible: false,
perms: [], perms: [],
} }
@@ -104,7 +103,7 @@ export default {
}, },
updateResourceType(id, data) { updateResourceType(id, data) {
updateResourceTypeById(id, data).then((res) => { updateResourceTypeById(id, data).then((res) => {
this.$message.success(`更新成功`) this.$message.success(this.$t('updateSuccess'))
this.handleOk() this.handleOk()
this.onClose() this.onClose()
}) })
@@ -113,17 +112,11 @@ export default {
createResourceType(data) { createResourceType(data) {
addResourceType(data).then((res) => { addResourceType(data).then((res) => {
this.$message.success(`添加成功`) this.$message.success(this.$t('addSuccess'))
this.handleOk() this.handleOk()
this.onClose() this.onClose()
}) })
// .catch(err => this.requestFailed(err))
}, },
// requestFailed (err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// }
}, },
watch: {}, watch: {},
props: { props: {

View File

@@ -16,30 +16,30 @@
:loading="loading" :loading="loading"
:height="`${windowHeight - 310}px`" :height="`${windowHeight - 310}px`"
> >
<vxe-column field="created_at" width="144px" title="操作时间"></vxe-column> <vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')"></vxe-column>
<vxe-column field="operate_uid" width="130px" title="操作员"></vxe-column> <vxe-column field="operate_uid" width="130px" :title="$t('acl.operator')"></vxe-column>
<vxe-column field="operate_type" width="80px" title="操作"> <vxe-column field="operate_type" width="100px" :title="$t('operation')">
<template #default="{ row }"> <template #default="{ row }">
<a-tag :color="handleTagColor(row.operate_type)"> <a-tag :color="handleTagColor(row.operate_type)">
{{ operateTypeMap.get(row.operate_type) }} {{ operateTypeMap.get(row.operate_type) }}
</a-tag> </a-tag>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="link_id" title="资源类型名"> <vxe-column field="link_id" :title="$t('acl.resourceTypeName')">
<template #default="{ row }"> <template #default="{ row }">
<span> <span>
{{ row.current.name || row.origin.name }} {{ row.current.name || row.origin.name }}
</span> </span>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column title="描述"> <vxe-column :title="$t('desc')">
<template #default="{ row }"> <template #default="{ row }">
<p> <p>
{{ row.changeDescription }} {{ row.changeDescription }}
</p> </p>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="source" width="100px" title="来源"></vxe-column> <vxe-column field="source" width="100px" :title="$t('acl.source')"></vxe-column>
</vxe-table> </vxe-table>
<pager <pager
:current-page.sync="queryParams.page" :current-page.sync="queryParams.page"
@@ -56,7 +56,7 @@
<script> <script>
import _ from 'lodash' import _ from 'lodash'
import Pager from './pager.vue' import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue' import SearchForm from './searchForm.vue'
import { searchResourceHistory } from '@/modules/acl/api/history' import { searchResourceHistory } from '@/modules/acl/api/history'
export default { export default {
@@ -93,40 +93,6 @@ export default {
checked: false, checked: false,
tableData: [], tableData: [],
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
resourceTableAttrList: [
{
alias: '日期',
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: '操作员',
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: '操作',
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [{ 新建: 'create' }, { 修改: 'update' }, { 删除: 'delete' }],
},
{
alias: '资源类型',
is_choice: true,
name: 'link_id',
value_type: '2',
choice_value: this.allResourceTypes,
},
],
operateTypeMap: new Map([
['create', '新建'],
['update', '修改'],
['delete', '删除'],
]),
colorMap: new Map([ colorMap: new Map([
['create', 'green'], ['create', 'green'],
['update', 'orange'], ['update', 'orange'],
@@ -155,12 +121,50 @@ export default {
}, },
}, },
computed: { computed: {
operateTypeMap() {
return new Map([
['create', this.$t('create')],
['update', this.$t('update')],
['delete', this.$t('delete')],
])
},
windowHeight() { windowHeight() {
return this.$store.state.windowHeight return this.$store.state.windowHeight
}, },
tableDataLength() { tableDataLength() {
return this.tableData.length return this.tableData.length
}, },
resourceTableAttrList() {
return [
{
alias: this.$t('acl.date'),
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: this.$t('acl.operator'),
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: this.$t('operation'),
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [{ [this.$t('create')]: 'create' }, { [this.$t('update')]: 'update' }, { [this.$t('delete')]: 'delete' }],
},
{
alias: this.$t('acl.resourceType'),
is_choice: true,
name: 'link_id',
value_type: '2',
choice_value: this.allResourceTypes,
},
]
},
}, },
methods: { methods: {
async getTable(queryParams) { async getTable(queryParams) {
@@ -236,7 +240,9 @@ export default {
switch (operate_type) { switch (operate_type) {
// create // create
case 'create': { case 'create': {
item.changeDescription = `新增资源类型${item.current.name}\n描述${item.current.description}\n权限${item.extra.permission_ids.current}` item.changeDescription = `${this.$t('acl.addResourceType')}${item.current.name}\n${this.$t('desc')}${
item.current.description
}\n${this.$t('acl.permission')}: ${item.extra.permission_ids.current}`
break break
} }
case 'update': { case 'update': {
@@ -246,10 +252,10 @@ export default {
const oldVal = item.origin[key] const oldVal = item.origin[key]
if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') { if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') {
if (oldVal === null || oldVal === '') { if (oldVal === null || oldVal === '') {
const str = ` ${key} : 改为 ${newVal} \n` const str = ` ${key} : -> ${newVal} \n`
item.changeDescription += str item.changeDescription += str
} else { } else {
const str = ` ${key} : ${oldVal} 改为 ${newVal} \n` const str = ` ${key} : ${oldVal} -> ${newVal} \n`
item.changeDescription += str item.changeDescription += str
} }
} }
@@ -257,13 +263,13 @@ export default {
const currentPerms = item.extra.permission_ids.current const currentPerms = item.extra.permission_ids.current
const originPerms = item.extra.permission_ids.origin const originPerms = item.extra.permission_ids.origin
if (!_.isEqual(currentPerms, originPerms)) { if (!_.isEqual(currentPerms, originPerms)) {
item.changeDescription += ` permission_ids : ${originPerms} 改为 ${currentPerms} ` item.changeDescription += ` permission_ids : ${originPerms} -> ${currentPerms} `
} }
if (!item.changeDescription) item.changeDescription = '没有修改' if (!item.changeDescription) item.changeDescription = this.$t('acl.noChange')
break break
} }
case 'delete': { case 'delete': {
item.changeDescription = `删除资源类型${item.origin.name}\n描述${item.origin.description}\n权限${item.extra.permission_ids.origin}` item.changeDescription = `${this.$t('acl.deleteResourceType')}${item.origin.name}\n${this.$t('desc')}: ${item.origin.description}\n${this.$t('acl.permission')}: ${item.extra.permission_ids.origin}`
break break
} }
} }

View File

@@ -2,17 +2,17 @@
<CustomDrawer <CustomDrawer
width="800px" width="800px"
placement="left" placement="left"
title="资源列表" :title="$t('acl.resourceList')"
@close="handleCancel" @close="handleCancel"
:visible="visible" :visible="visible"
:hasFooter="false" :hasFooter="false"
> >
<a-form-item label="资源类型" :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }"> <a-form-item :label="$t('acl.resourceType')" :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }">
<a-select v-model="typeSelected" style="width:100%" @change="refresh"> <a-select v-model="typeSelected" style="width:100%" @change="refresh">
<a-select-option v-for="type in resourceTypes" :value="type.id" :key="type.id">{{ type.name }}</a-select-option> <a-select-option v-for="type in resourceTypes" :value="type.id" :key="type.id">{{ type.name }}</a-select-option>
</a-select> </a-select>
</a-form-item> </a-form-item>
<vxe-table <ops-table
size="mini" size="mini"
stripe stripe
class="ops-stripe-table" class="ops-stripe-table"
@@ -22,7 +22,7 @@
> >
<vxe-column <vxe-column
field="name" field="name"
title="资源名" :title="$t('acl.resourceName')"
width="30%" width="30%"
:filters="[{ data: '' }]" :filters="[{ data: '' }]"
:filter-method="filterNameMethod" :filter-method="filterNameMethod"
@@ -30,7 +30,7 @@
> >
<template #header="{ column }"> <template #header="{ column }">
<span>{{ column.title }}</span> <span>{{ column.title }}</span>
<a-tooltip title="复制资源名"> <a-tooltip :title="$t('acl.copyResource')">
<a-icon @click="copyResourceName" class="resource-user-form-copy" theme="filled" type="copy" /> <a-icon @click="copyResourceName" class="resource-user-form-copy" theme="filled" type="copy" />
</a-tooltip> </a-tooltip>
</template> </template>
@@ -43,84 +43,17 @@
v-model="option.data" v-model="option.data"
@input="$panel.changeOption($event, !!option.data, option)" @input="$panel.changeOption($event, !!option.data, option)"
@keyup.enter="$panel.confirmFilter()" @keyup.enter="$panel.confirmFilter()"
placeholder="按回车确认筛选" :placeholder="$t('acl.pressEnter')"
/> />
</template> </template>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="permissions" title="权限列表" width="70%"> <vxe-column field="permissions" :title="$t('acl.permissionList')" width="70%">
<template #default="{row}"> <template #default="{row}">
<a-tag color="cyan" v-for="(r, index) in row.permissions" :key="index">{{ r }}</a-tag> <a-tag color="cyan" v-for="(r, index) in row.permissions" :key="index">{{ r }}</a-tag>
</template> </template>
</vxe-column> </vxe-column>
<template slot="empty"> </ops-table>
<img :src="require(`@/assets/data_empty.png`)" />
<p style="font-size: 14px; line-height: 17px; color: rgba(0, 0, 0, 0.6)">暂无数据</p>
</template>
</vxe-table>
<!-- <a-table
:columns="columns"
:dataSource="records"
:rowKey="record => record.id"
:pagination="false"
ref="rTable"
size="middle"
:scroll="{ y: 300 }"
> -->
<!-- <div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" class="custom-filter-dropdown">
<a-input
v-ant-ref="c => searchInput = c"
:placeholder="` ${column.title}`"
:value="selectedKeys[0]"
@change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
@pressEnter="() => handleSearch(selectedKeys, confirm, column)"
style="width: 188px; margin-bottom: 8px; display: block;"
/>
<a-button
type="primary"
@click="() => handleSearch(selectedKeys, confirm, column)"
icon="search"
size="small"
style="width: 90px; margin-right: 8px"
>搜索</a-button>
<a-button
@click="() => handleReset(clearFilters, column)"
size="small"
style="width: 90px"
>重置</a-button>
</div>
<a-icon slot="filterIcon" slot-scope="filtered" type="search" :style="{ color: filtered ? '#108ee9' : undefined }" />
<template slot="nameSearchRender" slot-scope="text">
<span v-if="columnSearchText.name">
<template v-for="(fragment, i) in text.toString().split(new RegExp(`(?<=${columnSearchText.name})|(?=${columnSearchText.name})`, 'i'))">
<mark v-if="fragment.toLowerCase() === columnSearchText.name.toLowerCase()" :key="i" class="highlight">{{ fragment }}</mark>
<template v-else>{{ fragment }}</template>
</template>
</span>
<template v-else>{{ text }}</template>
</template> -->
<!-- <template slot="permissions" slot-scope="record">
<a-tag color="cyan" v-for="(r, index) in record" :key="index">{{ r }}</a-tag>
</template>
</a-table> -->
<!-- <div
:style="{
position: 'absolute',
left: 0,
bottom: 0,
width: '100%',
borderTop: '1px solid #e9e9e9',
padding: '10px 16px',
background: '#fff',
textAlign: 'right',
}"
>
<a-button :style="{marginRight: '8px'}" @click="handleCancel">
取消
</a-button>
<a-button @click="handleOk" type="primary">确定</a-button>
</div> -->
</CustomDrawer> </CustomDrawer>
</template> </template>
<script> <script>
@@ -141,38 +74,11 @@ export default {
name: '', name: '',
}, },
filterName: '', filterName: '',
// columns: [
// {
// title: '资源名',
// field: 'name',
// sorter: false,
// width: '30%',
// // scopedSlots: {
// // customRender: 'nameSearchRender',
// // filterDropdown: 'filterDropdown',
// // filterIcon: 'filterIcon'
// // },
// // onFilter: (value, record) => record.name && record.name.toLowerCase().includes(value.toLowerCase()),
// // onFilterDropdownVisibleChange: (visible) => {
// // if (visible) {
// // setTimeout(() => {
// // this.searchInput.focus()
// // }, 0)
// // }
// // }
// },
// {
// title: '权限列表',
// field: 'permissions',
// width: '70%',
// slots: { default: 'permissions_default' },
// },
// ],
} }
}, },
computed: { computed: {
...mapState({ ...mapState({
windowHeight: state => state.windowHeight, windowHeight: (state) => state.windowHeight,
}), }),
}, },
mounted() { mounted() {
@@ -184,18 +90,10 @@ export default {
this.rid = record.id this.rid = record.id
this.refresh() this.refresh()
}, },
// handleSearch(selectedKeys, confirm, column) {
// confirm()
// this.columnSearchText[column.dataIndex] = selectedKeys[0]
// },
// handleReset(clearFilters, column) {
// clearFilters()
// this.columnSearchText[column.dataIndex] = ''
// },
loadResourceTypes() { loadResourceTypes() {
this.resourceTypes = [] this.resourceTypes = []
const appId = this.$route.name.split('_')[0] const appId = this.$route.name.split('_')[0]
searchResourceType({ app_id: appId }).then(res => { searchResourceType({ app_id: appId }).then((res) => {
this.resourceTypes = res.groups this.resourceTypes = res.groups
if (res.groups && res.groups.length > 0) { if (res.groups && res.groups.length > 0) {
this.typeSelected = res.groups[0].id this.typeSelected = res.groups[0].id
@@ -204,7 +102,6 @@ export default {
this.typeSelected = null this.typeSelected = null
} }
}) })
// .catch(err => this.$httpError(err))
}, },
handleOk() { handleOk() {
this.visible = false this.visible = false
@@ -214,10 +111,9 @@ export default {
searchPermResourceByRoleId(this.rid, { searchPermResourceByRoleId(this.rid, {
resource_type_id: this.typeSelected, resource_type_id: this.typeSelected,
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
}).then(res => { }).then((res) => {
this.records = res.resources this.records = res.resources
}) })
// .catch(err=>this.$httpError(err))
} }
}, },
handleCancel() { handleCancel() {
@@ -233,12 +129,12 @@ export default {
}, },
copyResourceName() { copyResourceName() {
const val = this.records const val = this.records
.filter(item => item.name.toLowerCase().includes(this.filterName.toLowerCase())) .filter((item) => item.name.toLowerCase().includes(this.filterName.toLowerCase()))
.map(item => item.name) .map((item) => item.name)
.join('\n') .join('\n')
this.copy(val, () => { this.copy(val, () => {
this.$message.success('复制成功') this.$message.success(this.$t('copySuccess'))
}) })
}, },
copy(value, cb) { copy(value, cb) {

View File

@@ -8,40 +8,29 @@
width="500px" width="500px"
> >
<a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" @submit="handleSubmit"> <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" @submit="handleSubmit">
<a-form-item label="角色名"> <a-form-item :label="$t('acl.role')">
<a-input <a-input
name="name" name="name"
placeholder="角色名" :placeholder="$t('acl.role_placeholder1')"
v-decorator="['name', { rules: [{ required: true, message: '请输入角色名' }] }]" v-decorator="['name', { rules: [{ required: true, message: $t('acl.role_placeholder1') }] }]"
/> />
</a-form-item> </a-form-item>
<a-form-item v-if="$route.name.split('_')[0] !== 'acl'" label="密码"> <a-form-item v-if="$route.name.split('_')[0] !== 'acl'" :label="$t('acl.password')">
<a-input name="password" placeholder="密码" v-decorator="['password', { rules: [{ required: false }] }]" /> <a-input name="password" :placeholder="$t('acl.password')" v-decorator="['password', { rules: [{ required: false }] }]" />
</a-form-item> </a-form-item>
<!-- <a-form-item label="继承自"> <a-form-item :label="$t('acl.inheritedFrom')">
<a-select
showSearch
v-model="selectedParents"
:filterOption="false"
placeholder="可选择继承角色"
mode="multiple"
>
<a-select-option v-for="role in scrollData" :key="role.id">{{ role.name }}</a-select-option>
</a-select>
</a-form-item> -->
<a-form-item label="继承自">
<el-select <el-select
:style="{ width: '100%' }" :style="{ width: '100%' }"
size="small" size="small"
v-model="selectedParents" v-model="selectedParents"
multiple multiple
filterable filterable
placeholder="可选择继承角色" :placeholder="$t('acl.selectedParents')"
> >
<el-option v-for="role in allRoles" :key="role.id" :value="role.id" :label="role.name"></el-option> <el-option v-for="role in allRoles" :key="role.id" :value="role.id" :label="role.name"></el-option>
</el-select> </el-select>
</a-form-item> </a-form-item>
<a-form-item label="是否应用管理员"> <a-form-item :label="$t('acl.isAppAdmin')">
<a-switch <a-switch
@change="onChange" @change="onChange"
name="is_app_admin" name="is_app_admin"
@@ -53,8 +42,8 @@
</a-form-item> </a-form-item>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="onClose">取消</a-button> <a-button @click="onClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">确定</a-button> <a-button @click="handleSubmit" type="primary">{{ $t('confirm') }}</a-button>
</div> </div>
</a-form> </a-form>
</CustomDrawer> </CustomDrawer>
@@ -93,7 +82,7 @@ export default {
// return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0 // return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
// }, // },
handleCreate() { handleCreate() {
this.drawerTitle = '新增角色' this.drawerTitle = this.$t('acl.addRole')
this.drawerVisible = true this.drawerVisible = true
}, },
onClose() { onClose() {
@@ -107,7 +96,7 @@ export default {
}, },
handleEdit(record) { handleEdit(record) {
this.drawerTitle = `编辑${record.name}` this.drawerTitle = `${this.$t('edit')}: ${record.name}`
this.drawerVisible = true this.drawerVisible = true
this.current_id = record.id this.current_id = record.id
const _parents = this.id2parents[record.id] const _parents = this.id2parents[record.id]
@@ -142,7 +131,7 @@ export default {
updateRole(id, data) { updateRole(id, data) {
this.updateParents(id) this.updateParents(id)
updateRoleById(id, { ...data, app_id: this.$route.name.split('_')[0] }).then((res) => { updateRoleById(id, { ...data, app_id: this.$route.name.split('_')[0] }).then((res) => {
this.$message.success(`更新成功`) this.$message.success(this.$t('updateSuccess'))
this.handleOk() this.handleOk()
this.onClose() this.onClose()
}) })
@@ -151,7 +140,7 @@ export default {
createRole(data) { createRole(data) {
addRole({ ...data, app_id: this.$route.name.split('_')[0] }).then((res) => { addRole({ ...data, app_id: this.$route.name.split('_')[0] }).then((res) => {
this.$message.success(`添加成功`) this.$message.success(this.$t('addSuccess'))
this.updateParents(res.id) this.updateParents(res.id)
this.handleOk() this.handleOk()
this.onClose() this.onClose()
@@ -171,16 +160,9 @@ export default {
child_ids: [id], child_ids: [id],
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
}) })
// addParentRole(id, item, { app_id: this.$route.name.split('_')[0] })
// .catch(err => this.requestFailed(err))
} }
}) })
}, },
// requestFailed(err) {
// console.log(err)
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// },
}, },
watch: {}, watch: {},
props: { props: {

View File

@@ -4,7 +4,7 @@
ref="child" ref="child"
:attrList="roleTableAttrList" :attrList="roleTableAttrList"
:hasSwitch="true" :hasSwitch="true"
switchValue="角色关系" :switchValue="$t('acl.roleRelation')"
@onSwitchChange="onSwitchChange" @onSwitchChange="onSwitchChange"
@search="handleSearch" @search="handleSearch"
@searchFormReset="searchFormReset" @searchFormReset="searchFormReset"
@@ -19,16 +19,16 @@
resizable resizable
:height="`${windowHeight - 310}px`" :height="`${windowHeight - 310}px`"
> >
<vxe-column field="created_at" width="144px" title="操作时间"></vxe-column> <vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')"></vxe-column>
<vxe-column field="operate_uid" title="操作员" width="130px"></vxe-column> <vxe-column field="operate_uid" :title="$t('acl.operator')" width="130px"></vxe-column>
<vxe-column field="operate_type" title="操作" width="112px"> <vxe-column field="operate_type" :title="$t('operation')" width="112px">
<template #default="{ row }"> <template #default="{ row }">
<template> <template>
<a-tag :color="handleTagColor(row.operate_type)">{{ operateTypeMap.get(row.operate_type) }}</a-tag> <a-tag :color="handleTagColor(row.operate_type)">{{ operateTypeMap.get(row.operate_type) }}</a-tag>
</template> </template>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column :title="checked ? '角色' : '角色'"> <vxe-column :title="checked ? $t('acl.role2') : $t('acl.role2')">
<template #default="{ row }"> <template #default="{ row }">
<template v-if="!checked"> <template v-if="!checked">
<a-tag color="blue">{{ row.current.name || row.origin.name }}</a-tag> <a-tag color="blue">{{ row.current.name || row.origin.name }}</a-tag>
@@ -40,7 +40,7 @@
</template> </template>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column :title="checked ? '继承自' : '管理员'" :width="checked ? '350px' : '80px'"> <vxe-column :title="checked ? $t('acl.inheritedFrom') : $t('acl.admin')" :width="checked ? '350px' : '80px'">
<template #default="{ row }"> <template #default="{ row }">
<template v-if="!checked"> <template v-if="!checked">
<a-icon type="check" v-if="row.current.is_app_admin" /> <a-icon type="check" v-if="row.current.is_app_admin" />
@@ -52,14 +52,14 @@
</template> </template>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column title="描述" v-if="!checked"> <vxe-column :title="$t('desc')" v-if="!checked">
<template #default="{ row }"> <template #default="{ row }">
<p> <p>
{{ row.description }} {{ row.description }}
</p> </p>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="source" title="来源" width="100px"></vxe-column> <vxe-column field="source" :title="$t('acl.source')" width="100px"></vxe-column>
</vxe-table> </vxe-table>
<pager <pager
:current-page.sync="queryParams.page" :current-page.sync="queryParams.page"
@@ -76,7 +76,7 @@
<script> <script>
import _ from 'lodash' import _ from 'lodash'
import Pager from './pager.vue' import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue' import SearchForm from './searchForm.vue'
import { searchRoleHistory } from '@/modules/acl/api/history' import { searchRoleHistory } from '@/modules/acl/api/history'
export default { export default {
@@ -105,13 +105,6 @@ export default {
checked: false, checked: false,
tableData: [], tableData: [],
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
operateTypeMap: new Map([
['create', '新建'],
['delete', '删除'],
['update', '修改'],
['role_relation_add', '添加角色关系'],
['role_relation_delete', '删除角色关系'],
]),
colorMap: new Map([ colorMap: new Map([
['create', 'green'], ['create', 'green'],
['delete', 'red'], ['delete', 'red'],
@@ -127,42 +120,53 @@ export default {
start: '', start: '',
end: '', end: '',
}, },
roleTableAttrList: [ }
},
computed: {
operateTypeMap() {
return new Map([
['create', this.$t('create')],
['update', this.$t('update')],
['delete', this.$t('delete')],
['role_relation_add', this.$t('acl.roleRelationAdd')],
['role_relation_delete', this.$t('acl.roleRelationDelete')],
])
},
windowHeight() {
return this.$store.state.windowHeight
},
tableDataLength() {
return this.tableData.length
},
roleTableAttrList() {
return [
{ {
alias: '日期', alias: this.$t('acl.date'),
is_choice: false, is_choice: false,
name: 'datetime', name: 'datetime',
value_type: '3', value_type: '3',
}, },
{ {
alias: '操作员', alias: this.$t('acl.operator'),
is_choice: true, is_choice: true,
name: 'operate_uid', name: 'operate_uid',
value_type: '2', value_type: '2',
choice_value: this.allUsers, choice_value: this.allUsers,
}, },
{ {
alias: '操作', alias: this.$t('operation'),
is_choice: true, is_choice: true,
name: 'operate_type', name: 'operate_type',
value_type: '2', value_type: '2',
choice_value: [ choice_value: [
{ 新建: 'create' }, { [this.$t('create')]: 'create' },
{ 修改: 'update' }, { [this.$t('update')]: 'update' },
{ 删除: 'delete' }, { [this.$t('delete')]: 'delete' },
{ 添加角色关系: 'role_relation_add' }, { [this.$t('acl.roleRelationAdd')]: 'role_relation_add' },
{ 删除角色关系: 'role_relation_delete' }, { [this.$t('acl.roleRelationDelete')]: 'role_relation_delete' },
], ],
}, },
], ]
}
},
computed: {
windowHeight() {
return this.$store.state.windowHeight
},
tableDataLength() {
return this.tableData.length
}, },
}, },
async created() { async created() {
@@ -273,7 +277,7 @@ export default {
switch (operate_type) { switch (operate_type) {
// create // create
case 'create': { case 'create': {
item.description = `新建角色${item.current.name}` item.description = `${this.$t('acl.addRole')}${item.current.name}`
break break
} }
case 'update': { case 'update': {
@@ -283,15 +287,15 @@ export default {
const oldVal = item.origin[key] const oldVal = item.origin[key]
if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') { if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') {
if (oldVal === null) { if (oldVal === null) {
const str = ` ${key} : 改为 ${newVal} ` const str = ` ${key} : -> ${newVal} `
item.description += str item.description += str
} else { } else {
const str = ` ${key} : ${oldVal} 改为 ${newVal} ` const str = ` ${key} : ${oldVal} -> ${newVal} `
item.description += str item.description += ` ${key} : ${oldVal} -> ${newVal} `
} }
} }
} }
if (!item.description) item.description = '没有修改' if (!item.description) item.description = this.$t('acl.noChange')
break break
} }
case 'delete': { case 'delete': {
@@ -321,7 +325,7 @@ export default {
resourceMap.forEach((value, key) => { resourceMap.forEach((value, key) => {
permsArr.push(`${id2resources[key].name}${value}`) permsArr.push(`${id2resources[key].name}${value}`)
}) })
item.description = `继承者${child_ids}\n继承自${parent_ids}\n涉及资源及权限\n${permsArr.join(`\n`)}` item.description = `${this.$t('acl.heir')}${child_ids}\n${this.$t('acl.inheritedFrom')}${parent_ids}\n${this.$t('acl.involvingRP')}\n${permsArr.join(`\n`)}`
break break
} }
} }

View File

@@ -19,7 +19,7 @@
@popupScroll="loadMoreData(attr.name, $event)" @popupScroll="loadMoreData(attr.name, $event)"
@search="(value) => fetchData(value, attr.name)" @search="(value) => fetchData(value, attr.name)"
v-model="queryParams[attr.name]" v-model="queryParams[attr.name]"
placeholder="请选择" :placeholder="$t('placeholder2')"
v-if="attr.is_choice" v-if="attr.is_choice"
show-search show-search
:filter-option="filterOption" :filter-option="filterOption"
@@ -38,7 +38,6 @@
@change="onChange" @change="onChange"
:style="{ width: '100%' }" :style="{ width: '100%' }"
format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
:placeholder="['开始时间', '结束时间']"
:show-time="{ :show-time="{
hideDisabledOptions: true, hideDisabledOptions: true,
defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')], defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
@@ -67,7 +66,7 @@
@popupScroll="loadMoreData(item.name, $event)" @popupScroll="loadMoreData(item.name, $event)"
@search="(value) => fetchData(value, item.name)" @search="(value) => fetchData(value, item.name)"
v-model="queryParams[item.name]" v-model="queryParams[item.name]"
placeholder="请选择" :placeholder="$t('placeholder2')"
v-if="item.is_choice" v-if="item.is_choice"
show-search show-search
:filter-option="filterOption" :filter-option="filterOption"
@@ -85,7 +84,7 @@
:style="{ width: '100%' }" :style="{ width: '100%' }"
@change="onChange" @change="onChange"
format="YYYY-MM-DD HH:mm" format="YYYY-MM-DD HH:mm"
:placeholder="['开始时间', '结束时间']" :placeholder="[$t('acl.startAt'), $t('acl.endAt')]"
v-else-if="valueTypeMap[item.value_type] == 'date' || valueTypeMap[item.value_type] == 'datetime'" v-else-if="valueTypeMap[item.value_type] == 'date' || valueTypeMap[item.value_type] == 'datetime'"
:show-time="{ :show-time="{
hideDisabledOptions: true, hideDisabledOptions: true,
@@ -107,13 +106,13 @@
v-model="checked" v-model="checked"
/> />
<a-button :style="{ marginLeft: '8px' }" type="primary" html-type="submit" @click="handleSearch"> <a-button :style="{ marginLeft: '8px' }" type="primary" html-type="submit" @click="handleSearch">
查询 {{ $t('query') }}
</a-button> </a-button>
<a-button :style="{ marginLeft: '8px' }" @click="handleReset"> <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
重置 {{ $t('reset') }}
</a-button> </a-button>
<a :style="{ marginLeft: '8px', fontSize: '12px' }" @click="toggle" v-if="attrList.length >= 5"> <a :style="{ marginLeft: '8px', fontSize: '12px' }" @click="toggle" v-if="attrList.length >= 5">
{{ expand ? '隐藏' : '展开' }} <a-icon :type="expand ? 'up' : 'down'" /> {{ expand ? $t('expand') : $t('expand') }} <a-icon :type="expand ? 'up' : 'down'" />
</a> </a>
</a-col> </a-col>
</a-row> </a-row>

View File

@@ -2,30 +2,40 @@
<CustomDrawer <CustomDrawer
@close="handleClose" @close="handleClose"
width="500" width="500"
:title="`${triggerId ? '修改' : '新建'}触发器`" :title="`${triggerId ? $t('update') : $t('create')}${$t('acl.trigger')}`"
:visible="visible" :visible="visible"
:maskClosable="false" :maskClosable="false"
> >
<a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }"> <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }">
<a-form-item label="触发器名"> <a-form-item :label="$t('name')">
<a-input size="large" v-decorator="['name', { rules: [{ required: true, message: '请输入触发器名' }] }]"> <a-input
size="large"
v-decorator="['name', { rules: [{ required: true, message: $t('acl.triggerNameInput') }] }]"
>
</a-input> </a-input>
</a-form-item> </a-form-item>
<a-form-item label="资源名"> <a-form-item :label="$t('acl.resourceName')">
<a-input size="large" v-decorator="['wildcard']" placeholder="优先正则模式(次通配符)"> </a-input> <a-input size="large" v-decorator="['wildcard']" :placeholder="$t('acl.triggerTips1')"> </a-input>
</a-form-item> </a-form-item>
<a-form-item label="创建人"> <a-form-item :label="$t('acl.creator')">
<el-select :style="{ width: '100%' }" filterable multiple v-decorator="['uid']"> <el-select
:style="{ width: '100%' }"
filterable
multiple
v-decorator="['uid']"
:placeholder="$t('placeholder2')"
>
<template v-for="role in roles"> <template v-for="role in roles">
<el-option v-if="role.uid" :key="role.id" :value="role.uid" :label="role.name">{{ role.name }}</el-option> <el-option v-if="role.uid" :key="role.id" :value="role.uid" :label="role.name">{{ role.name }}</el-option>
</template> </template>
</el-select> </el-select>
</a-form-item> </a-form-item>
<a-form-item label="资源类型"> <a-form-item :label="$t('acl.resourceType')">
<el-select <el-select
:style="{ width: '100%' }" :style="{ width: '100%' }"
@change="handleRTChange" @change="handleRTChange"
v-decorator="['resource_type_id', { rules: [{ required: true, message: '请选择资源类型' }] }]" :placeholder="$t('placeholder2')"
v-decorator="['resource_type_id', { rules: [{ required: true, message: $t('acl.pleaseSelectType') }] }]"
> >
<el-option <el-option
v-for="resourceType in resourceTypeList" v-for="resourceType in resourceTypeList"
@@ -34,25 +44,27 @@
:label="resourceType.name" :label="resourceType.name"
></el-option> ></el-option>
</el-select> </el-select>
<a-tooltip title="查看正则匹配结果"> <a-tooltip :title="$t('acl.viewMatchResult')">
<a class="trigger-form-pattern" @click="handlePattern"><a-icon type="eye"/></a> <a class="trigger-form-pattern" @click="handlePattern"><a-icon type="eye"/></a>
</a-tooltip> </a-tooltip>
</a-form-item> </a-form-item>
<a-form-item label="角色"> <a-form-item :label="$t('acl.role2')">
<el-select <el-select
:style="{ width: '100%' }" :style="{ width: '100%' }"
filterable filterable
multiple multiple
v-decorator="['roles', { rules: [{ required: true, message: '请选择角色' }] }]" :placeholder="$t('placeholder2')"
v-decorator="['roles', { rules: [{ required: true, message: $t('acl.role_placeholder2') }] }]"
> >
<el-option v-for="role in roles" :key="role.id" :value="role.id" :label="role.name"></el-option> <el-option v-for="role in roles" :key="role.id" :value="role.id" :label="role.name"></el-option>
</el-select> </el-select>
</a-form-item> </a-form-item>
<a-form-item label="权限"> <a-form-item :label="$t('acl.permission')">
<el-select <el-select
:placeholder="$t('placeholder2')"
:style="{ width: '100%' }" :style="{ width: '100%' }"
multiple multiple
v-decorator="['permissions', { rules: [{ required: true, message: '请选择权限' }] }]" v-decorator="['permissions', { rules: [{ required: true, message: $t('acl.permission_placeholder') }] }]"
> >
<el-option <el-option
v-for="perm in selectResourceTypePerms" v-for="perm in selectResourceTypePerms"
@@ -62,13 +74,13 @@
></el-option> ></el-option>
</el-select> </el-select>
</a-form-item> </a-form-item>
<a-form-item label="启用/禁用"> <a-form-item :label="`${$t('acl.enable')} / ${$t('acl.disable')}`">
<a-switch v-decorator="['enabled', { rules: [], valuePropName: 'checked', initialValue: true }]" /> <a-switch v-decorator="['enabled', { rules: [], valuePropName: 'checked', initialValue: true }]" />
</a-form-item> </a-form-item>
</a-form> </a-form>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="handleClose">取消</a-button> <a-button @click="handleClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">提交</a-button> <a-button @click="handleSubmit" type="primary">{{ $t('submit') }}</a-button>
</div> </div>
<TriggerPattern ref="triggerPattern" :roles="roles" /> <TriggerPattern ref="triggerPattern" :roles="roles" />
</CustomDrawer> </CustomDrawer>
@@ -159,13 +171,13 @@ export default {
if (this.triggerId) { if (this.triggerId) {
updateTrigger(this.triggerId, { ...values, app_id: this.app_id }).then((res) => { updateTrigger(this.triggerId, { ...values, app_id: this.app_id }).then((res) => {
this.visible = false this.visible = false
this.$message.success('修改成功!') this.$message.success(this.$t('updateSuccess'))
this.$emit('refresh') this.$emit('refresh')
}) })
} else { } else {
addTrigger({ ...values, app_id: this.app_id }).then((res) => { addTrigger({ ...values, app_id: this.app_id }).then((res) => {
this.visible = false this.visible = false
this.$message.success('创建成功!') this.$message.success(this.$t('addSuccess'))
this.$emit('refresh') this.$emit('refresh')
}) })
} }

View File

@@ -16,23 +16,23 @@
resizable resizable
:height="`${windowHeight - 310}px`" :height="`${windowHeight - 310}px`"
> >
<vxe-column field="created_at" width="144px" title="操作时间"></vxe-column> <vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')"></vxe-column>
<vxe-column field="operate_uid" width="130px" title="操作员"></vxe-column> <vxe-column field="operate_uid" width="130px" :title="$t('acl.operator')"></vxe-column>
<vxe-column field="operate_type" width="80px" title="操作"> <vxe-column field="operate_type" width="100px" :title="$t('operation')">
<template #default="{ row }"> <template #default="{ row }">
<a-tag :color="handleTagColor(row.operate_type)"> <a-tag :color="handleTagColor(row.operate_type)">
{{ operateTypeMap.get(row.operate_type) }} {{ operateTypeMap.get(row.operate_type) }}
</a-tag> </a-tag>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="trigger_id" width="250px" title="触发器"> <vxe-column field="trigger_id" width="250px" :title="$t('acl.trigger')">
<template #default="{ row }"> <template #default="{ row }">
<span> <span>
{{ row.current.name || row.origin.name }} {{ row.current.name || row.origin.name }}
</span> </span>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column title="描述"> <vxe-column :title="$t('desc')">
<template #default="{ row }"> <template #default="{ row }">
<p> <p>
{{ row.changeDescription }} {{ row.changeDescription }}
@@ -55,7 +55,7 @@
<script> <script>
import _ from 'lodash' import _ from 'lodash'
import Pager from './pager.vue' import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue' import SearchForm from './searchForm.vue'
import { searchTriggerHistory } from '@/modules/acl/api/history' import { searchTriggerHistory } from '@/modules/acl/api/history'
export default { export default {
@@ -95,13 +95,6 @@ export default {
app_id: this.$route.name.split('_')[0], app_id: this.$route.name.split('_')[0],
loading: true, loading: true,
tableData: [], tableData: [],
operateTypeMap: new Map([
['create', '新建'],
['update', '修改'],
['delete', '删除'],
['trigger_apply', '应用'],
['trigger_cancel', '取消'],
]),
colorMap: new Map([ colorMap: new Map([
['create', 'green'], ['create', 'green'],
['delete', 'red'], ['delete', 'red'],
@@ -109,41 +102,6 @@ export default {
['trigger_apply', 'green'], ['trigger_apply', 'green'],
['trigger_cancel', 'red'], ['trigger_cancel', 'red'],
]), ]),
triggerTableAttrList: [
{
alias: '日期',
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: '操作员',
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: '操作',
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [
{ 新建: 'create' },
{ 修改: 'update' },
{ 删除: 'delete' },
{ 应用: 'trigger_apply' },
{ 取消: 'trigger_cancel' },
],
},
{
alias: '触发器',
is_choice: true,
name: 'trigger_id',
value_type: '2',
choice_value: this.allTriggers,
},
],
queryParams: { queryParams: {
page: 1, page: 1,
page_size: 50, page_size: 50,
@@ -164,12 +122,58 @@ export default {
}, },
}, },
computed: { computed: {
operateTypeMap() {
return new Map([
['create', this.$t('create')],
['update', this.$t('update')],
['delete', this.$t('delete')],
['trigger_apply', this.$t('acl.apply')],
['trigger_cancel', this.$t('cancel')],
])
},
windowHeight() { windowHeight() {
return this.$store.state.windowHeight return this.$store.state.windowHeight
}, },
tableDataLength() { tableDataLength() {
return this.tableData.length return this.tableData.length
}, },
triggerTableAttrList() {
return [
{
alias: this.$t('acl.date'),
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: this.$t('acl.operator'),
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: this.$t('operation'),
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [
{ [this.$t('create')]: 'create' },
{ [this.$t('update')]: 'update' },
{ [this.$t('delete')]: 'delete' },
{ [this.$t('acl.apply')]: 'trigger_apply' },
{ [this.$t('cancel')]: 'trigger_cancel' },
],
},
{
alias: this.$t('acl.trigger'),
is_choice: true,
name: 'trigger_id',
value_type: '2',
choice_value: this.allTriggers,
},
]
},
}, },
methods: { methods: {
async getTable(queryParams) { async getTable(queryParams) {
@@ -220,9 +224,9 @@ export default {
const str = item.current.roles const str = item.current.roles
const newArr = str.slice(1, str.length - 1).split(', ') const newArr = str.slice(1, str.length - 1).split(', ')
const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('') const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('')
item.changeDescription = `新增触发器${item.current.name}\n资源类型${this.allResourceTypesMap.get( item.changeDescription = `${this.$t('acl.addTrigger')}: ${item.current.name}\n${this.$t('acl.resourceType')}: ${this.allResourceTypesMap.get(
item.current.resource_type_id item.current.resource_type_id
)}资源名${item.current.wildcard}角色[${newStr}]\n权限${item.current.permissions}\n状态${ )}this.$t('acl.resourceName')${item.current.wildcard}${this.$t('acl.role2')}: [${newStr}]\n${this.$t('acl.permission')}: ${item.current.permissions}\n${this.$t('status')}: ${
item.current.enabled item.current.enabled
}` }`
break break
@@ -234,24 +238,24 @@ export default {
const oldVal = item.origin[key] const oldVal = item.origin[key]
if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') { if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') {
if (oldVal === null) { if (oldVal === null) {
const str = ` ${key} : 改为 ${newVal} ` const str = ` ${key} : -> ${newVal} `
item.changeDescription += str item.changeDescription += str
} else { } else {
const str = ` ${key} : ${oldVal} 改为 ${newVal} ` const str = ` ${key} : ${oldVal} -> ${newVal} `
item.changeDescription += str item.changeDescription += ` ${key} : ${oldVal} -> ${newVal} `
} }
} }
} }
if (!item.changeDescription) item.changeDescription = '没有修改' if (!item.changeDescription) item.changeDescription = this.$t('acl.noChange')
break break
} }
case 'delete': { case 'delete': {
const str = item.origin.roles const str = item.origin.roles
const newArr = str.slice(1, str.length - 1).split(', ') const newArr = str.slice(1, str.length - 1).split(', ')
const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('') const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('')
item.changeDescription = `删除触发器${item.origin.name}\n资源类型${this.allResourceTypesMap.get( item.changeDescription = `${this.$t('acl.deleteTrigger')}: ${item.origin.name}\n${this.$t('acl.resourceType')}: ${this.allResourceTypesMap.get(
item.origin.resource_type_id item.origin.resource_type_id
)}资源名${item.origin.wildcard}角色[${newStr}]\n权限${item.origin.permissions}\n状态${ )}this.$t('acl.resourceName')${item.origin.wildcard}${this.$t('acl.role2')}: [${newStr}]\n${this.$t('acl.permission')}: ${item.origin.permissions}\n${this.$t('status')}: ${
item.origin.enabled item.origin.enabled
}` }`
break break
@@ -260,9 +264,9 @@ export default {
const str = item.current.roles const str = item.current.roles
const newArr = str.slice(1, str.length - 1).split(', ') const newArr = str.slice(1, str.length - 1).split(', ')
const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('') const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('')
item.changeDescription = `应用触发器${item.current.name}\n资源类型${this.allResourceTypesMap.get( item.changeDescription = `${this.$t('acl.applyTrigger')}: ${item.current.name}\n${this.$t('acl.resourceType')}: ${this.allResourceTypesMap.get(
item.current.resource_type_id item.current.resource_type_id
)}资源名${item.current.wildcard}角色[${newStr}]\n权限${item.current.permissions}\n状态${ )}this.$t('acl.resourceName')${item.current.wildcard}${this.$t('acl.role2')}: [${newStr}]\n${this.$t('acl.permission')}: ${item.current.permissions}\n${this.$t('status')}: ${
item.current.enabled item.current.enabled
}` }`
break break
@@ -271,9 +275,9 @@ export default {
const str = item.current.roles const str = item.current.roles
const newArr = str.slice(1, str.length - 1).split(', ') const newArr = str.slice(1, str.length - 1).split(', ')
const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('') const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('')
item.changeDescription = `取消触发器${item.current.name}\n资源类型${this.allResourceTypesMap.get( item.changeDescription = `${this.$t('acl.cancelTrigger')}: ${item.current.name}\n${this.$t('acl.resourceType')}: ${this.allResourceTypesMap.get(
item.current.resource_type_id item.current.resource_type_id
)}资源名${item.current.wildcard}角色[${newStr}]\n权限${item.current.permissions}\n状态${ )}this.$t('acl.resourceName')${item.current.wildcard}${this.$t('acl.role2')}: [${newStr}]\n${this.$t('acl.permission')}: ${item.current.permissions}\n${this.$t('status')}: ${
item.current.enabled item.current.enabled
}` }`
break break

View File

@@ -1,7 +1,7 @@
<template> <template>
<CustomDrawer <CustomDrawer
:hasFooter="false" :hasFooter="false"
title="正则匹配结果" :title="$t('acl.viewMatchResult')"
:visible="patternVisible" :visible="patternVisible"
width="500" width="500"
@close=" @close="
@@ -16,16 +16,16 @@
class="ops-stripe-table" class="ops-stripe-table"
:data="tableData" :data="tableData"
:max-height="`${windowHeight - 110}px`"> :max-height="`${windowHeight - 110}px`">
<vxe-table-column field="name" title="资源名"></vxe-table-column> <vxe-table-column field="name" :title="$t('acl.resourceName')"></vxe-table-column>
<vxe-table-column field="uid" title="创建人"> <vxe-table-column field="uid" :title="$t('acl.creator')">
<template #default="{row}"> <template #default="{row}">
{{ getRoleName(row.uid) }} {{ getRoleName(row.uid) }}
</template> </template>
</vxe-table-column> </vxe-table-column>
<vxe-table-column field="created_at" title="创建时间"></vxe-table-column> <vxe-table-column field="created_at" :title="$t('created_at')"></vxe-table-column>
<template slot="empty"> <template slot="empty">
<img :src="require(`@/assets/data_empty.png`)" /> <img :src="require(`@/assets/data_empty.png`)" />
<p style="font-size: 14px; line-height: 17px; color: rgba(0, 0, 0, 0.6)">暂无数据</p> <p style="font-size: 14px; line-height: 17px; color: rgba(0, 0, 0, 0.6)">{{ $t('noData') }}</p>
</template> </template>
</vxe-table> </vxe-table>
</CustomDrawer> </CustomDrawer>

View File

@@ -8,33 +8,38 @@
width="500px" width="500px"
> >
<a-form :form="form" @submit="handleSubmit" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }"> <a-form :form="form" @submit="handleSubmit" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="用户名(英文)"> <a-form-item :label="$t('acl.username')">
<a-input <a-input
name="username" name="username"
placeholder="英文名" :placeholder="$t('acl.username_placeholder')"
v-decorator="['username', { rules: [{ required: true, message: '请输入用户名' }] }]" v-decorator="['username', { rules: [{ required: true, message: $t('acl.username_placeholder') }] }]"
/> />
</a-form-item> </a-form-item>
<a-form-item label="中文名"> <a-form-item :label="$t('acl.nickname')">
<a-input name="nickname" v-decorator="['nickname', { rules: [] }]" /> <a-input
name="nickname"
:placeholder="$t('acl.nickname_placeholder')"
v-decorator="['nickname', { rules: [] }]"
/>
</a-form-item> </a-form-item>
<a-form-item label="密码"> <a-form-item :label="$t('acl.password')">
<a-input <a-input
type="password" type="password"
name="password" name="password"
v-decorator="['password', { rules: [{ required: true, message: '请输入密码' }] }]" :placeholder="$t('acl.password_placeholder')"
v-decorator="['password', { rules: [{ required: true, message: $t('acl.password_placeholder') }] }]"
/> />
</a-form-item> </a-form-item>
<a-form-item label="部门"> <a-form-item :label="$t('acl.department')">
<a-input name="department" v-decorator="['department', { rules: [] }]" /> <a-input name="department" v-decorator="['department', { rules: [] }]" />
</a-form-item> </a-form-item>
<a-form-item label="小组"> <a-form-item :label="$t('acl.group')">
<a-input name="catalog" v-decorator="['catalog', { rules: [] }]" /> <a-input name="catalog" v-decorator="['catalog', { rules: [] }]" />
</a-form-item> </a-form-item>
<a-form-item label="邮箱"> <a-form-item :label="$t('acl.email')">
<a-input <a-input
name="email" name="email"
v-decorator="[ v-decorator="[
@@ -43,11 +48,11 @@
rules: [ rules: [
{ {
type: 'email', type: 'email',
message: '请输入正确的邮箱!', message: $t('acl.email_placeholder'),
}, },
{ {
required: true, required: true,
message: '请输入邮箱', message: $t('acl.email_placeholder'),
}, },
], ],
}, },
@@ -55,14 +60,14 @@
/> />
</a-form-item> </a-form-item>
<a-form-item label="手机号码"> <a-form-item :label="$t('acl.mobile')">
<a-input <a-input
name="mobile" name="mobile"
v-decorator="['mobile', { rules: [{ message: '请输入正确的手机号码', pattern: /^1\d{10}$/ }] }]" v-decorator="['mobile', { rules: [{ message: $t('acl.mobileTips'), pattern: /^1\d{10}$/ }] }]"
/> />
</a-form-item> </a-form-item>
<a-form-item label="是否锁定"> <a-form-item :label="$t('acl.isBlock')">
<a-switch @change="onChange" name="block" v-decorator="['block', { rules: [], valuePropName: 'checked' }]" /> <a-switch @change="onChange" name="block" v-decorator="['block', { rules: [], valuePropName: 'checked' }]" />
</a-form-item> </a-form-item>
@@ -71,8 +76,8 @@
</a-form-item> </a-form-item>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="onClose">取消</a-button> <a-button @click="onClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">确定</a-button> <a-button @click="handleSubmit" type="primary">{{ $t('confirm') }}</a-button>
</div> </div>
</a-form> </a-form>
</CustomDrawer> </CustomDrawer>
@@ -85,7 +90,6 @@ export default {
name: 'AttributeForm', name: 'AttributeForm',
data() { data() {
return { return {
drawerTitle: '新增用户',
drawerVisible: false, drawerVisible: false,
} }
}, },
@@ -94,7 +98,11 @@ export default {
this.form = this.$form.createForm(this) this.form = this.$form.createForm(this)
}, },
computed: {}, computed: {
drawerTitle() {
return this.$t('acl.addUser')
},
},
mounted() {}, mounted() {},
methods: { methods: {
handleCreate() { handleCreate() {
@@ -142,7 +150,7 @@ export default {
}, },
updateUser(attrId, data) { updateUser(attrId, data) {
updateUserById(attrId, data).then((res) => { updateUserById(attrId, data).then((res) => {
this.$message.success(`更新成功`) this.$message.success(this.$t('updateSuccess'))
this.handleOk() this.handleOk()
this.onClose() this.onClose()
}) })
@@ -151,17 +159,11 @@ export default {
createUser(data) { createUser(data) {
addUser(data).then((res) => { addUser(data).then((res) => {
this.$message.success(`添加成功`) this.$message.success(this.$t('addSuccess'))
this.handleOk() this.handleOk()
this.onClose() this.onClose()
}) })
// .catch(err => this.requestFailed(err))
}, },
// requestFailed (err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// }
}, },
watch: {}, watch: {},
props: { props: {

Some files were not shown because too many files have changed in this diff Show More