feat:预定义值支持脚本&&密码存储&&一些bugfix (#239)

This commit is contained in:
wang-liang0615 2023-10-27 11:10:43 +08:00 committed by GitHub
parent 9791a184e3
commit 3d716eff3e
30 changed files with 7382 additions and 6760 deletions

View File

@ -54,6 +54,48 @@
<div class="content unicode" style="display: block;"> <div class="content unicode" style="display: block;">
<ul class="icon_lists dib-box"> <ul class="icon_lists dib-box">
<li class="dib">
<span class="icon iconfont">&#xe894;</span>
<div class="name">icon-xianxing-password</div>
<div class="code-name">&amp;#xe894;</div>
</li>
<li class="dib">
<span class="icon iconfont">&#xe895;</span>
<div class="name">icon-xianxing-link</div>
<div class="code-name">&amp;#xe895;</div>
</li>
<li class="dib">
<span class="icon iconfont">&#xe892;</span>
<div class="name">itsm-oneclick download</div>
<div class="code-name">&amp;#xe892;</div>
</li>
<li class="dib">
<span class="icon iconfont">&#xe893;</span>
<div class="name">itsm-package download</div>
<div class="code-name">&amp;#xe893;</div>
</li>
<li class="dib">
<span class="icon iconfont">&#xe891;</span>
<div class="name">weixin</div>
<div class="code-name">&amp;#xe891;</div>
</li>
<li class="dib">
<span class="icon iconfont">&#xe88f;</span>
<div class="name">itsm-again</div>
<div class="code-name">&amp;#xe88f;</div>
</li>
<li class="dib">
<span class="icon iconfont">&#xe890;</span>
<div class="name">itsm-next</div>
<div class="code-name">&amp;#xe890;</div>
</li>
<li class="dib"> <li class="dib">
<span class="icon iconfont">&#xe88e;</span> <span class="icon iconfont">&#xe88e;</span>
<div class="name">wechatApp</div> <div class="name">wechatApp</div>
@ -4002,9 +4044,9 @@
<pre><code class="language-css" <pre><code class="language-css"
>@font-face { >@font-face {
font-family: 'iconfont'; font-family: 'iconfont';
src: url('iconfont.woff2?t=1696815443987') format('woff2'), src: url('iconfont.woff2?t=1698273699449') format('woff2'),
url('iconfont.woff?t=1696815443987') format('woff'), url('iconfont.woff?t=1698273699449') format('woff'),
url('iconfont.ttf?t=1696815443987') format('truetype'); url('iconfont.ttf?t=1698273699449') format('truetype');
} }
</code></pre> </code></pre>
<h3 id="-iconfont-">第二步:定义使用 iconfont 的样式</h3> <h3 id="-iconfont-">第二步:定义使用 iconfont 的样式</h3>
@ -4030,6 +4072,69 @@
<div class="content font-class"> <div class="content font-class">
<ul class="icon_lists dib-box"> <ul class="icon_lists dib-box">
<li class="dib">
<span class="icon iconfont icon-xianxing-password"></span>
<div class="name">
icon-xianxing-password
</div>
<div class="code-name">.icon-xianxing-password
</div>
</li>
<li class="dib">
<span class="icon iconfont icon-xianxing-link"></span>
<div class="name">
icon-xianxing-link
</div>
<div class="code-name">.icon-xianxing-link
</div>
</li>
<li class="dib">
<span class="icon iconfont a-itsm-oneclickdownload"></span>
<div class="name">
itsm-oneclick download
</div>
<div class="code-name">.a-itsm-oneclickdownload
</div>
</li>
<li class="dib">
<span class="icon iconfont a-itsm-packagedownload"></span>
<div class="name">
itsm-package download
</div>
<div class="code-name">.a-itsm-packagedownload
</div>
</li>
<li class="dib">
<span class="icon iconfont a-Frame4"></span>
<div class="name">
weixin
</div>
<div class="code-name">.a-Frame4
</div>
</li>
<li class="dib">
<span class="icon iconfont itsm-again"></span>
<div class="name">
itsm-again
</div>
<div class="code-name">.itsm-again
</div>
</li>
<li class="dib">
<span class="icon iconfont itsm-next"></span>
<div class="name">
itsm-next
</div>
<div class="code-name">.itsm-next
</div>
</li>
<li class="dib"> <li class="dib">
<span class="icon iconfont wechatApp"></span> <span class="icon iconfont wechatApp"></span>
<div class="name"> <div class="name">
@ -9952,6 +10057,62 @@
<div class="content symbol"> <div class="content symbol">
<ul class="icon_lists dib-box"> <ul class="icon_lists dib-box">
<li class="dib">
<svg class="icon svg-icon" aria-hidden="true">
<use xlink:href="#icon-xianxing-password"></use>
</svg>
<div class="name">icon-xianxing-password</div>
<div class="code-name">#icon-xianxing-password</div>
</li>
<li class="dib">
<svg class="icon svg-icon" aria-hidden="true">
<use xlink:href="#icon-xianxing-link"></use>
</svg>
<div class="name">icon-xianxing-link</div>
<div class="code-name">#icon-xianxing-link</div>
</li>
<li class="dib">
<svg class="icon svg-icon" aria-hidden="true">
<use xlink:href="#a-itsm-oneclickdownload"></use>
</svg>
<div class="name">itsm-oneclick download</div>
<div class="code-name">#a-itsm-oneclickdownload</div>
</li>
<li class="dib">
<svg class="icon svg-icon" aria-hidden="true">
<use xlink:href="#a-itsm-packagedownload"></use>
</svg>
<div class="name">itsm-package download</div>
<div class="code-name">#a-itsm-packagedownload</div>
</li>
<li class="dib">
<svg class="icon svg-icon" aria-hidden="true">
<use xlink:href="#a-Frame4"></use>
</svg>
<div class="name">weixin</div>
<div class="code-name">#a-Frame4</div>
</li>
<li class="dib">
<svg class="icon svg-icon" aria-hidden="true">
<use xlink:href="#itsm-again"></use>
</svg>
<div class="name">itsm-again</div>
<div class="code-name">#itsm-again</div>
</li>
<li class="dib">
<svg class="icon svg-icon" aria-hidden="true">
<use xlink:href="#itsm-next"></use>
</svg>
<div class="name">itsm-next</div>
<div class="code-name">#itsm-next</div>
</li>
<li class="dib"> <li class="dib">
<svg class="icon svg-icon" aria-hidden="true"> <svg class="icon svg-icon" aria-hidden="true">
<use xlink:href="#wechatApp"></use> <use xlink:href="#wechatApp"></use>

View File

@ -1,8 +1,8 @@
@font-face { @font-face {
font-family: "iconfont"; /* Project id 3857903 */ font-family: "iconfont"; /* Project id 3857903 */
src: url('iconfont.woff2?t=1696815443987') format('woff2'), src: url('iconfont.woff2?t=1698273699449') format('woff2'),
url('iconfont.woff?t=1696815443987') format('woff'), url('iconfont.woff?t=1698273699449') format('woff'),
url('iconfont.ttf?t=1696815443987') format('truetype'); url('iconfont.ttf?t=1698273699449') format('truetype');
} }
.iconfont { .iconfont {
@ -13,6 +13,34 @@
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
} }
.icon-xianxing-password:before {
content: "\e894";
}
.icon-xianxing-link:before {
content: "\e895";
}
.a-itsm-oneclickdownload:before {
content: "\e892";
}
.a-itsm-packagedownload:before {
content: "\e893";
}
.a-Frame4:before {
content: "\e891";
}
.itsm-again:before {
content: "\e88f";
}
.itsm-next:before {
content: "\e890";
}
.wechatApp:before { .wechatApp:before {
content: "\e88e"; content: "\e88e";
} }

File diff suppressed because one or more lines are too long

View File

@ -5,6 +5,55 @@
"css_prefix_text": "", "css_prefix_text": "",
"description": "", "description": "",
"glyphs": [ "glyphs": [
{
"icon_id": "37830610",
"name": "icon-xianxing-password",
"font_class": "icon-xianxing-password",
"unicode": "e894",
"unicode_decimal": 59540
},
{
"icon_id": "37830609",
"name": "icon-xianxing-link",
"font_class": "icon-xianxing-link",
"unicode": "e895",
"unicode_decimal": 59541
},
{
"icon_id": "37822199",
"name": "itsm-oneclick download",
"font_class": "a-itsm-oneclickdownload",
"unicode": "e892",
"unicode_decimal": 59538
},
{
"icon_id": "37822198",
"name": "itsm-package download",
"font_class": "a-itsm-packagedownload",
"unicode": "e893",
"unicode_decimal": 59539
},
{
"icon_id": "37772067",
"name": "weixin",
"font_class": "a-Frame4",
"unicode": "e891",
"unicode_decimal": 59537
},
{
"icon_id": "37632784",
"name": "itsm-again",
"font_class": "itsm-again",
"unicode": "e88f",
"unicode_decimal": 59535
},
{
"icon_id": "37632783",
"name": "itsm-next",
"font_class": "itsm-next",
"unicode": "e890",
"unicode_decimal": 59536
},
{ {
"icon_id": "37590786", "icon_id": "37590786",
"name": "wechatApp", "name": "wechatApp",

Binary file not shown.

View File

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

View File

@ -1,57 +1,45 @@
<template> <template>
<span> <span>
<ops-icon :type="getPropertyIcon(attr)" /> <ops-icon :type="getPropertyIcon(attr)" />
</span> </span>
</template> </template>
<script> <script>
export default { export default {
name: 'ValueTypeIcon', name: 'ValueTypeIcon',
props: { props: {
attr: { attr: {
type: Object, type: Object,
default: () => {}, default: () => {},
}, },
}, },
methods: { methods: {
getPropertyStyle(attr) { getPropertyIcon(attr) {
switch (attr.value_type) { switch (attr.value_type) {
case '0': case '0':
return { color: '#cf1322', backgroundColor: '#fff1f0' } return 'icon-xianxing-shishu'
case '1': case '1':
return { color: '#d4b106', backgroundColor: '#feffe6' } return 'icon-xianxing-fudianshu'
case '2': case '2':
return { color: '#d46b08', backgroundColor: '#fff7e6' } if (attr.is_password) {
case '3': return 'icon-xianxing-password'
return { color: '#531dab', backgroundColor: '#f9f0ff' } }
case '4': if (attr.is_link) {
return { color: '#389e0d', backgroundColor: '#f6ffed' } return 'icon-xianxing-link'
case '5': }
return { color: '#08979c', backgroundColor: '#e6fffb' } return 'icon-xianxing-wenben'
case '6': case '3':
return { color: '#c41d7f', backgroundColor: '#fff0f6' } return 'icon-xianxing-datetime'
} case '4':
}, return 'icon-xianxing-date'
getPropertyIcon(attr) { case '5':
switch (attr.value_type) { return 'icon-xianxing-time'
case '0': case '6':
return 'icon-xianxing-shishu' return 'icon-xianxing-json'
case '1': }
return 'icon-xianxing-fudianshu' },
case '2': },
return 'icon-xianxing-wenben' }
case '3': </script>
return 'icon-xianxing-datetime'
case '4': <style></style>
return 'icon-xianxing-date'
case '5':
return 'icon-xianxing-time'
case '6':
return 'icon-xianxing-json'
}
},
},
}
</script>
<style></style>

View File

@ -1,170 +1,177 @@
import { axios } from '@/utils/request' import { axios } from '@/utils/request'
/** /**
* 获取 ci_type 的属性 * 获取 ci_type 的属性
* @param CITypeName * @param CITypeName
* @param parameter * @param parameter
* @returns {AxiosPromise} * @returns {AxiosPromise}
*/ */
export function getCITypeAttributesByName(CITypeName, parameter) { export function getCITypeAttributesByName(CITypeName, parameter) {
return axios({ return axios({
url: `/v0.1/ci_types/${CITypeName}/attributes`, url: `/v0.1/ci_types/${CITypeName}/attributes`,
method: 'get', method: 'get',
params: parameter params: parameter
}) })
} }
/** /**
* 获取 ci_type 的属性 * 获取 ci_type 的属性
* @param CITypeId * @param CITypeId
* @param parameter * @param parameter
* @returns {AxiosPromise} * @returns {AxiosPromise}
*/ */
export function getCITypeAttributesById(CITypeId, parameter) { export function getCITypeAttributesById(CITypeId, parameter) {
return axios({ return axios({
url: `/v0.1/ci_types/${CITypeId}/attributes`, url: `/v0.1/ci_types/${CITypeId}/attributes`,
method: 'get', method: 'get',
params: parameter params: parameter
}) })
} }
/** /**
* 更新属性 * 更新属性
* @param attrId * @param attrId
* @param data * @param data
* @returns {AxiosPromise} * @returns {AxiosPromise}
*/ */
export function updateAttributeById(attrId, data) { export function updateAttributeById(attrId, data) {
return axios({ return axios({
url: `/v0.1/attributes/${attrId}`, url: `/v0.1/attributes/${attrId}`,
method: 'put', method: 'put',
data: data data: data
}) })
} }
/** /**
* 添加属性 * 添加属性
* @param data * @param data
* @returns {AxiosPromise} * @returns {AxiosPromise}
*/ */
export function createAttribute(data) { export function createAttribute(data) {
return axios({ return axios({
url: `/v0.1/attributes`, url: `/v0.1/attributes`,
method: 'post', method: 'post',
data: data data: data
}) })
} }
/** /**
* 搜索属性/ 获取所有的属性 * 搜索属性/ 获取所有的属性
* @param data * @param data
* @returns {AxiosPromise} * @returns {AxiosPromise}
*/ */
export function searchAttributes(params) { export function searchAttributes(params) {
return axios({ return axios({
url: `/v0.1/attributes/s`, url: `/v0.1/attributes/s`,
method: 'get', method: 'get',
params: params params: params
}) })
} }
export function getCITypeAttributesByTypeIds(params) { export function getCITypeAttributesByTypeIds(params) {
return axios({ return axios({
url: `/v0.1/ci_types/attributes`, url: `/v0.1/ci_types/attributes`,
method: 'get', method: 'get',
params: params params: params
}) })
} }
export function getCITypeCommonAttributesByTypeIds(params) { export function getCITypeCommonAttributesByTypeIds(params) {
return axios({ return axios({
url: `/v0.1/ci_types/common_attributes`, url: `/v0.1/ci_types/common_attributes`,
method: 'get', method: 'get',
params: params params: params
}) })
} }
/** /**
* 删除属性 * 删除属性
* @param attrId * @param attrId
* @returns {AxiosPromise} * @returns {AxiosPromise}
*/ */
export function deleteAttributesById(attrId) { export function deleteAttributesById(attrId) {
return axios({ return axios({
url: `/v0.1/attributes/${attrId}`, url: `/v0.1/attributes/${attrId}`,
method: 'delete' method: 'delete'
}) })
} }
/** /**
* 绑定ci_type 属性 * 绑定ci_type 属性
* @param CITypeId * @param CITypeId
* @param data * @param data
* @returns {AxiosPromise} * @returns {AxiosPromise}
*/ */
export function createCITypeAttributes(CITypeId, data) { export function createCITypeAttributes(CITypeId, data) {
return axios({ return axios({
url: `/v0.1/ci_types/${CITypeId}/attributes`, url: `/v0.1/ci_types/${CITypeId}/attributes`,
method: 'post', method: 'post',
data: data data: data
}) })
} }
/** /**
* 更新ci_type 属性 * 更新ci_type 属性
* @param CITypeId * @param CITypeId
* @param data * @param data
* @returns {AxiosPromise} * @returns {AxiosPromise}
*/ */
export function updateCITypeAttributesById(CITypeId, data) { export function updateCITypeAttributesById(CITypeId, data) {
return axios({ return axios({
url: `/v0.1/ci_types/${CITypeId}/attributes`, url: `/v0.1/ci_types/${CITypeId}/attributes`,
method: 'put', method: 'put',
data: data data: data
}) })
} }
/** /**
* 删除ci_type 属性 * 删除ci_type 属性
* @param CITypeId * @param CITypeId
* @param data * @param data
* @returns {AxiosPromise} * @returns {AxiosPromise}
*/ */
export function deleteCITypeAttributesById(CITypeId, data) { export function deleteCITypeAttributesById(CITypeId, data) {
return axios({ return axios({
url: `/v0.1/ci_types/${CITypeId}/attributes`, url: `/v0.1/ci_types/${CITypeId}/attributes`,
method: 'delete', method: 'delete',
data: data data: data
}) })
} }
export function transferCITypeAttrIndex(CITypeId, data) { export function transferCITypeAttrIndex(CITypeId, data) {
return axios({ return axios({
url: `/v0.1/ci_types/${CITypeId}/attributes/transfer`, url: `/v0.1/ci_types/${CITypeId}/attributes/transfer`,
method: 'POST', method: 'POST',
data: data data: data
}) })
} }
export function transferCITypeGroupIndex(CITypeId, data) { export function transferCITypeGroupIndex(CITypeId, data) {
return axios({ return axios({
url: `/v0.1/ci_types/${CITypeId}/attribute_groups/transfer`, url: `/v0.1/ci_types/${CITypeId}/attribute_groups/transfer`,
method: 'POST', method: 'POST',
data: data data: data
}) })
} }
export function canDefineComputed() { export function canDefineComputed() {
return axios({ return axios({
url: `/v0.1/ci_types/can_define_computed`, url: `/v0.1/ci_types/can_define_computed`,
method: 'HEAD', method: 'HEAD',
}) })
} }
export function calcComputedAttribute(attr_id) { export function calcComputedAttribute(attr_id) {
return axios({ return axios({
url: `/v0.1/attributes/${attr_id}/calc_computed_attribute`, url: `/v0.1/attributes/${attr_id}/calc_computed_attribute`,
method: 'PUT', method: 'PUT',
}) })
} }
export function getAttrPassword(ci_id, attr_id) {
return axios({
url: `/v0.1/ci/${ci_id}/attributes/${attr_id}/password`,
method: 'Get',
})
}

View File

@ -1,42 +1,51 @@
<template> <template>
<div> <div>
<span v-if="!isShow && !isTableLoading">{{ showPassword }}</span> <span v-if="!isShow && !isTableLoading">{{ showPassword }}</span>
<span v-else>{{ password }}</span> <span v-else>{{ password }}</span>
<a <a :style="{ marginLeft: '10px' }" @click="getPassword"><a-icon :type="isShow ? 'eye-invisible' : 'eye'"/></a>
:style="{ marginLeft: '10px' }" </div>
@click=" </template>
() => {
isShow = !isShow <script>
} import { mapState } from 'vuex'
" import { getAttrPassword } from '../../api/CITypeAttr'
><a-icon export default {
:type="isShow ? 'eye-invisible' : 'eye'" name: 'PasswordField',
/></a> props: {
</div> ci_id: {
</template> type: Number,
default: 0,
<script> },
import { mapState } from 'vuex' attr_id: {
export default { type: Number,
name: 'PasswordField', default: 0,
props: { },
password: { },
type: String, data() {
default: '', return {
}, isShow: false,
}, password: '',
data() { }
return { },
isShow: false, computed: {
} showPassword() {
}, return '******'
computed: { },
showPassword() { ...mapState('cmdbStore', ['isTableLoading']),
return '******' },
}, methods: {
...mapState('cmdbStore', ['isTableLoading']), getPassword() {
}, if (this.isShow) {
} this.isShow = false
</script> } else {
getAttrPassword(this.ci_id, this.attr_id).then((res) => {
<style></style> this.password = res.value
this.isShow = true
})
}
},
},
}
</script>
<style></style>

View File

@ -68,7 +68,6 @@ export default {
lineNumbers: true, lineNumbers: true,
mode: 'python', mode: 'python',
height: '200px', height: '200px',
smartIndent: true,
tabSize: 4, tabSize: 4,
lineWrapping: true, lineWrapping: true,
}, },

View File

@ -1,26 +1,28 @@
export const valueTypeMap = { export const valueTypeMap = {
'0': '整数', '0': '整数',
'1': '浮点数', '1': '浮点数',
'2': '文本', '2': '文本',
'3': 'datetime', '3': '日期时间',
'4': 'date', '4': '日期',
'5': 'time', '5': '时间',
'6': 'json' '6': 'JSON',
} '7': '密码',
'8': '链接'
export const defautValueColor = [ }
{ value: '#d9d9d9' },
{ value: '#ffccc7' }, export const defautValueColor = [
{ value: '#ffd8bf' }, { value: '#d9d9d9' },
{ value: '#ffe7ba' }, { value: '#ffccc7' },
{ value: '#fff1b8' }, { value: '#ffd8bf' },
{ value: '#f4ffb8' }, { value: '#ffe7ba' },
{ value: '#d9f7be' }, { value: '#fff1b8' },
{ value: '#b5f5ec' }, { value: '#f4ffb8' },
{ value: '#bae7ff' }, { value: '#d9f7be' },
{ value: '#d6e4ff' }, { value: '#b5f5ec' },
{ value: '#efdbff' }, { value: '#bae7ff' },
{ value: '#ffd6e7' }, { value: '#d6e4ff' },
] { value: '#efdbff' },
{ value: '#ffd6e7' },
export const defaultBGColors = ['#ffccc7', '#ffd8bf', '#ffe7ba', '#fff1b8', '#d9f7be', '#b5f5ec', '#bae7ff', '#d6e4ff', '#efdbff', '#ffd6e7'] ]
export const defaultBGColors = ['#ffccc7', '#ffd8bf', '#ffe7ba', '#fff1b8', '#d9f7be', '#b5f5ec', '#bae7ff', '#d6e4ff', '#efdbff', '#ffd6e7']

View File

@ -1,176 +1,181 @@
/* eslint-disable */ /* eslint-disable */
import _ from 'lodash' import _ from 'lodash'
import XLSX from 'xlsx' import XLSX from 'xlsx'
import XLSXS from 'xlsx-js-style' import XLSXS from 'xlsx-js-style'
export function sum(arr) { export function sum(arr) {
if (!arr.length) { if (!arr.length) {
return 0 return 0
} }
return arr.reduce(function (prev, curr, idx, arr) { return arr.reduce(function (prev, curr, idx, arr) {
return prev + curr return prev + curr
}) })
} }
const strLength = (fData) => { const strLength = (fData) => {
if (!fData) { if (!fData) {
return 0 return 0
} }
if (fData.length && typeof fData === 'object') { if (fData.length && typeof fData === 'object') {
fData = fData.join(' ') fData = fData.join(' ')
} }
let intLength = 0 let intLength = 0
for (let i = 0; i < fData.length; i++) { for (let i = 0; i < fData.length; i++) {
if ((fData.charCodeAt(i) < 0) || (fData.charCodeAt(i) > 255)) { if ((fData.charCodeAt(i) < 0) || (fData.charCodeAt(i) > 255)) {
intLength = intLength + 2 intLength = intLength + 2
} }
else { else {
intLength = intLength + 1 intLength = intLength + 1
} }
} }
return Math.floor(intLength * 7) return Math.floor(intLength * 7)
} }
String.prototype.pxWidth = function (font) { String.prototype.pxWidth = function (font) {
// re-use canvas object for better performance // re-use canvas object for better performance
const canvas = String.prototype.pxWidth.canvas || (String.prototype.pxWidth.canvas = document.createElement("canvas")), const canvas = String.prototype.pxWidth.canvas || (String.prototype.pxWidth.canvas = document.createElement("canvas")),
context = canvas.getContext("2d"); context = canvas.getContext("2d");
font && (context.font = font); font && (context.font = font);
const metrics = context.measureText(this); const metrics = context.measureText(this);
return metrics.width; return metrics.width;
} }
export function getCITableColumns(data, attrList, width = 1600, height) { export function getCITableColumns(data, attrList, width = 1600, height) {
// 计算出来 主table的列表 布局属性 // 计算出来 主table的列表 布局属性
const _attrList = _.orderBy(attrList, ['is_fixed'], ['desc']) const _attrList = _.orderBy(attrList, ['is_fixed'], ['desc'])
const columns = [] const columns = []
for (let attr of _attrList) { for (let attr of _attrList) {
const editRender = { name: 'input' } const editRender = { name: 'input' }
switch (attr.value_type) { switch (attr.value_type) {
case '0': case '0':
editRender['props'] = { 'type': 'float' } editRender['props'] = { 'type': 'float' }
break break
case '1': case '1':
editRender['props'] = { 'type': 'float' } editRender['props'] = { 'type': 'float' }
break break
case '2': case '2':
editRender['attrs'] = { 'type': 'text' } editRender['attrs'] = { 'type': 'text' }
break break
case '3': case '3':
editRender['props'] = { 'type': 'datetime' } editRender['props'] = { 'type': 'datetime' }
break break
case "4": case "4":
editRender['props'] = { 'type': 'date' } editRender['props'] = { 'type': 'date' }
break break
case '5': case '5':
editRender['props'] = { 'type': 'time' } editRender['props'] = { 'type': 'time' }
break break
case '6': case '6':
editRender['props'] = { 'type': 'text' } editRender['props'] = { 'type': 'text' }
break break
default: default:
editRender['props'] = { 'type': 'text' } editRender['props'] = { 'type': 'text' }
break break
} }
if (attr.is_choice) { if (attr.is_choice) {
editRender.name = '$select' editRender.name = '$select'
editRender.options = attr.choice_value ? attr.choice_value.map(item => { return { label: item, value: item } }) : [] editRender.options = attr.choice_value ? attr.choice_value.map(item => { return { label: item, value: item } }) : []
delete editRender.props delete editRender.props
} }
columns.push({ columns.push({
editRender, attr_id:attr.id,
title: attr.alias || attr.name, editRender,
field: attr.name, title: attr.alias || attr.name,
value_type: attr.value_type, field: attr.name,
sortable: !!attr.is_sortable, value_type: attr.value_type,
filters: attr.is_choice ? attr.choice_value : null, sortable: !!attr.is_sortable,
width: Math.min(Math.max(100, ...data.map(item => strLength(item[attr.name]))), 350), filters: attr.is_choice ? attr.choice_value : null,
is_link: attr.is_link, width: Math.min(Math.max(100, ...data.map(item => strLength(item[attr.name]))), 350),
is_password: attr.is_password, is_link: attr.is_link,
is_list: attr.is_list, is_password: attr.is_password,
is_choice: attr.is_choice, is_list: attr.is_list,
is_fixed: attr.is_fixed, is_choice: attr.is_choice,
}) is_fixed: attr.is_fixed,
} })
}
const totalWidth = sum(columns.map(col => col.width))
if (totalWidth < width) { const totalWidth = sum(columns.map(col => col.width))
columns.map(item => { if (totalWidth < width) {
// if (item.width === 100) { columns.map(item => {
delete item.width // if (item.width === 100) {
// } delete item.width
}) // }
} })
return columns }
} return columns
}
export const getPropertyStyle = (attr) => {
switch (attr.value_type) { export const getPropertyStyle = (attr) => {
case '0': switch (attr.value_type) {
return { color: '#cf1322', backgroundColor: '#fff1f0' } case '0':
case '1': return { color: '#cf1322', backgroundColor: '#fff1f0' }
return { color: '#d4b106', backgroundColor: '#feffe6' } case '1':
case '2': return { color: '#d4b106', backgroundColor: '#feffe6' }
return { color: '#d46b08', backgroundColor: '#fff7e6' } case '2':
case '3': return { color: '#d46b08', backgroundColor: '#fff7e6' }
return { color: '#531dab', backgroundColor: '#f9f0ff' } case '3':
case '4': return { color: '#531dab', backgroundColor: '#f9f0ff' }
return { color: '#389e0d', backgroundColor: '#f6ffed' } case '4':
case '5': return { color: '#389e0d', backgroundColor: '#f6ffed' }
return { color: '#08979c', backgroundColor: '#e6fffb' } case '5':
case '6': return { color: '#08979c', backgroundColor: '#e6fffb' }
return { color: '#c41d7f', backgroundColor: '#fff0f6' } case '6':
} return { color: '#c41d7f', backgroundColor: '#fff0f6' }
} case '7':
return { color: '#0390CC', backgroundColor: '#e6fffb' }
export const getLastLayout = (data, x1 = 0, y1 = 0, w1 = 0) => { case '8':
const _tempData = _.orderBy(data, ['y', 'x'], ['asc', 'asc']) return { color: '#144BD9', backgroundColor: '#fff0f6' }
if (!_tempData.length) { }
return { xLast: 0, yLast: 0, wLast: 0 } }
}
const { x, y, w } = _tempData[_tempData.length - 1] export const getLastLayout = (data, x1 = 0, y1 = 0, w1 = 0) => {
if (y < y1) { const _tempData = _.orderBy(data, ['y', 'x'], ['asc', 'asc'])
return { xLast: x1, yLast: y1, wLast: w1 } if (!_tempData.length) {
} else if (y > y1) { return { xLast: 0, yLast: 0, wLast: 0 }
return { xLast: x, yLast: y, wLast: w } }
} else { const { x, y, w } = _tempData[_tempData.length - 1]
const xLast = _.max([x, x1]) if (y < y1) {
return { xLast, yLast: y, wLast: xLast === x ? w : w1 } return { xLast: x1, yLast: y1, wLast: w1 }
} } else if (y > y1) {
} return { xLast: x, yLast: y, wLast: w }
} else {
// 数字加逗号 const xLast = _.max([x, x1])
export const toThousands = (num = 0) => { return { xLast, yLast: y, wLast: xLast === x ? w : w1 }
return num.toString().replace(/\d+/, function (n) { }
return n.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') }
})
} // 数字加逗号
export const toThousands = (num = 0) => {
export const downloadExcel = (data, fileName = `${moment().format('YYYY-MM-DD HH:mm:ss')}.xls`) => { return num.toString().replace(/\d+/, function (n) {
// STEP 1: Create a new workbook return n.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
const wb = XLSXS.utils.book_new() })
// STEP 2: Create data rows and styles }
const rowArray = data
// STEP 3: Create worksheet with rows; Add worksheet to workbook export const downloadExcel = (data, fileName = `${moment().format('YYYY-MM-DD HH:mm:ss')}.xls`) => {
const ws = XLSXS.utils.aoa_to_sheet(rowArray) // STEP 1: Create a new workbook
XLSXS.utils.book_append_sheet(wb, ws, fileName) const wb = XLSXS.utils.book_new()
// STEP 2: Create data rows and styles
let maxColumnNumber = 1 // 默认最大列数 const rowArray = data
rowArray.forEach(item => { if (item.length > maxColumnNumber) { maxColumnNumber = item.length } }) // STEP 3: Create worksheet with rows; Add worksheet to workbook
const ws = XLSXS.utils.aoa_to_sheet(rowArray)
// 添加列宽 XLSXS.utils.book_append_sheet(wb, ws, fileName)
ws['!cols'] = (rowArray[0].map(item => {
return { width: 22 } let maxColumnNumber = 1 // 默认最大列数
})) rowArray.forEach(item => { if (item.length > maxColumnNumber) { maxColumnNumber = item.length } })
// // 添加行高
// ws['!rows'] = [{ 'hpt': 80 }] // 添加列宽
// STEP 4: Write Excel file to browser #导出 ws['!cols'] = (rowArray[0].map(item => {
XLSXS.writeFile(wb, fileName + '.xlsx') return { width: 22 }
} }))
// // 添加行高
// ws['!rows'] = [{ 'hpt': 80 }]
// STEP 4: Write Excel file to browser #导出
XLSXS.writeFile(wb, fileName + '.xlsx')
}

File diff suppressed because it is too large Load Diff

View File

@ -30,7 +30,7 @@
:key="attr.name" :key="attr.name"
v-for="attr in group.attributes" v-for="attr in group.attributes"
> >
<CiDetailAttrContent :ci="ci" :attr="attr" @refresh="refresh" /> <CiDetailAttrContent :ci="ci" :attr="attr" @refresh="refresh" @updateCIByself="updateCIByself" />
</el-descriptions-item> </el-descriptions-item>
</el-descriptions> </el-descriptions>
</div> </div>
@ -97,6 +97,7 @@
</template> </template>
<script> <script>
import _ from 'lodash'
import { Descriptions, DescriptionsItem } from 'element-ui' import { Descriptions, DescriptionsItem } from 'element-ui'
import { getCITypeGroupById, getCITypes } from '@/modules/cmdb/api/CIType' import { getCITypeGroupById, getCITypes } from '@/modules/cmdb/api/CIType'
import { getCIHistory } from '@/modules/cmdb/api/history' import { getCIHistory } from '@/modules/cmdb/api/history'
@ -292,6 +293,19 @@ export default {
} }
} }
}, },
updateCIByself(params, editAttrName) {
const _ci = { ..._.cloneDeep(this.ci), ...params }
this.ci = _ci
const _find = this.treeViewsLevels.find((level) => level.name === editAttrName)
// 修改的字段为树形视图订阅的字段 则全部reload
setTimeout(() => {
if (_find) {
this.reload()
} else {
this.handleSearch()
}
}, 500)
},
}, },
} }
</script> </script>

View File

@ -1,359 +1,377 @@
<template> <template>
<CustomDrawer <CustomDrawer
:title="title + CIType.alias" :title="title + CIType.alias"
width="800" width="800"
@close="handleClose" @close="handleClose"
:maskClosable="false" :maskClosable="false"
:visible="visible" :visible="visible"
wrapClassName="create-instance-form" wrapClassName="create-instance-form"
:bodyStyle="{ paddingTop: 0 }" :bodyStyle="{ paddingTop: 0 }"
:headerStyle="{ borderBottom: 'none' }" :headerStyle="{ borderBottom: 'none' }"
> >
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="handleClose">取消</a-button> <a-button @click="handleClose">取消</a-button>
<a-button type="primary" @click="createInstance">提交</a-button> <a-button type="primary" @click="createInstance">提交</a-button>
</div> </div>
<template v-if="action === 'create'"> <template v-if="action === 'create'">
<template v-for="group in attributesByGroup"> <template v-for="group in attributesByGroup">
<CreateInstanceFormByGroup <CreateInstanceFormByGroup
:ref="`createInstanceFormByGroup_${group.id}`" :ref="`createInstanceFormByGroup_${group.id}`"
:key="group.id || group.name" :key="group.id || group.name"
:group="group" :group="group"
@handleFocusInput="handleFocusInput" @handleFocusInput="handleFocusInput"
:attributeList="attributeList" :attributeList="attributeList"
/> />
</template> </template>
<template v-if="parentsType && parentsType.length"> <template v-if="parentsType && parentsType.length">
<a-divider style="font-size:14px;margin:14px 0;font-weight:700;">模型关系</a-divider> <a-divider style="font-size:14px;margin:14px 0;font-weight:700;">模型关系</a-divider>
<a-form> <a-form>
<a-row :gutter="24" align="top" type="flex"> <a-row :gutter="24" align="top" type="flex">
<a-col :span="12" v-for="item in parentsType" :key="item.id"> <a-col :span="12" v-for="item in parentsType" :key="item.id">
<a-form-item :label="item.alias || item.name" :colon="false"> <a-form-item :label="item.alias || item.name" :colon="false">
<a-input-group compact style="width: 100%"> <a-input-group compact style="width: 100%">
<a-select v-model="parentsForm[item.name].attr"> <a-select v-model="parentsForm[item.name].attr">
<a-select-option <a-select-option
:title="attr.alias || attr.name" :title="attr.alias || attr.name"
v-for="attr in item.attributes" v-for="attr in item.attributes"
:key="attr.name" :key="attr.name"
:value="attr.name" :value="attr.name"
> >
{{ attr.alias || attr.name }} {{ attr.alias || attr.name }}
</a-select-option> </a-select-option>
</a-select> </a-select>
<a-input placeholder="多个值使用,分割" v-model="parentsForm[item.name].value" style="width: 50%" /> <a-input placeholder="多个值使用,分割" v-model="parentsForm[item.name].value" style="width: 50%" />
</a-input-group> </a-input-group>
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> </a-row>
</a-form> </a-form>
</template> </template>
</template> </template>
<template v-if="action === 'update'"> <template v-if="action === 'update'">
<a-form :form="form"> <a-form :form="form">
<p>可根据需要修改字段当值为<strong></strong>则该字段<strong>置空</strong></p> <p>可根据需要修改字段当值为<strong></strong>则该字段<strong>置空</strong></p>
<a-row :gutter="24" v-for="list in batchUpdateLists" :key="list.name"> <a-row :gutter="24" v-for="list in batchUpdateLists" :key="list.name">
<a-col :span="11"> <a-col :span="11">
<a-form-item> <a-form-item>
<el-select showSearch size="small" filterable v-model="list.name" placeholder="请选择需要修改的字段"> <el-select showSearch size="small" filterable v-model="list.name" placeholder="请选择需要修改的字段">
<el-option <el-option
v-for="attr in attributeList" v-for="attr in attributeList"
:key="attr.name" :key="attr.name"
:value="attr.name" :value="attr.name"
:disabled="batchUpdateLists.findIndex((item) => item.name === attr.name) > -1" :disabled="batchUpdateLists.findIndex((item) => item.name === attr.name) > -1"
:label="attr.alias || attr.name" :label="attr.alias || attr.name"
> >
</el-option> </el-option>
</el-select> </el-select>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="11"> <a-col :span="11">
<a-form-item> <a-form-item>
<a-select <a-select
:style="{ width: '100%' }" :style="{ width: '100%' }"
v-decorator="[list.name, { rules: [{ required: false }] }]" v-decorator="[list.name, { rules: [{ required: false }] }]"
placeholder="请选择" placeholder="请选择"
v-if="getFieldType(list.name).split('%%')[0] === 'select'" v-if="getFieldType(list.name).split('%%')[0] === 'select'"
:mode="getFieldType(list.name).split('%%')[1] === 'multiple' ? 'multiple' : 'default'" :mode="getFieldType(list.name).split('%%')[1] === 'multiple' ? 'multiple' : 'default'"
showSearch showSearch
allowClear allowClear
> >
<a-select-option <a-select-option
:value="choice[0]" :value="choice[0]"
:key="'New_' + choice + choice_idx" :key="'New_' + choice + choice_idx"
v-for="(choice, choice_idx) in getSelectFieldOptions(list.name)" v-for="(choice, choice_idx) in getSelectFieldOptions(list.name)"
> >
<span :style="choice[1] ? choice[1].style || {} : {}"> <span :style="choice[1] ? choice[1].style || {} : {}">
<ops-icon <ops-icon
:style="{ color: choice[1].icon.color }" :style="{ color: choice[1].icon.color }"
v-if="choice[1] && choice[1].icon && choice[1].icon.name" v-if="choice[1] && choice[1].icon && choice[1].icon.name"
:type="choice[1].icon.name" :type="choice[1].icon.name"
/> />
{{ choice[0] }} {{ choice[0] }}
</span> </span>
</a-select-option> </a-select-option>
</a-select> </a-select>
<a-input-number <a-input-number
v-decorator="[list.name, { rules: [{ required: false }] }]" v-decorator="[list.name, { rules: [{ required: false }] }]"
style="width: 100%" style="width: 100%"
v-if="getFieldType(list.name) === 'input_number'" v-if="getFieldType(list.name) === 'input_number'"
/> />
<a-date-picker <a-date-picker
v-decorator="[list.name, { rules: [{ required: false }] }]" v-decorator="[list.name, { rules: [{ required: false }] }]"
style="width: 100%" style="width: 100%"
:format="getFieldType(list.name) == 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'" :format="getFieldType(list.name) == 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'"
v-if="getFieldType(list.name) === 'date' || getFieldType(list.name) === 'datetime'" v-if="getFieldType(list.name) === 'date' || getFieldType(list.name) === 'datetime'"
:showTime="getFieldType(list.name) === 'date' ? false : { format: 'HH:mm:ss' }" :showTime="getFieldType(list.name) === 'date' ? false : { format: 'HH:mm:ss' }"
/> />
<a-input <a-input
v-if="getFieldType(list.name) === 'input'" v-if="getFieldType(list.name) === 'input'"
@focus="(e) => handleFocusInput(e, list)" @focus="(e) => handleFocusInput(e, list)"
v-decorator="[list.name, { rules: [{ required: false }] }]" v-decorator="[list.name, { rules: [{ required: false }] }]"
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="2"> <a-col :span="2">
<a-form-item> <a-form-item>
<a :style="{ color: 'red', marginTop: '2px' }" @click="handleDelete(list.name)"> <a :style="{ color: 'red', marginTop: '2px' }" @click="handleDelete(list.name)">
<a-icon type="delete"/> <a-icon type="delete" />
</a> </a>
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> </a-row>
<a-button type="primary" ghost icon="plus" @click="handleAdd">新增修改字段</a-button> <a-button type="primary" ghost icon="plus" @click="handleAdd">新增修改字段</a-button>
</a-form> </a-form>
</template> </template>
<JsonEditor ref="jsonEditor" @jsonEditorOk="jsonEditorOk" /> <!-- </a-form> -->
</CustomDrawer> <JsonEditor ref="jsonEditor" @jsonEditorOk="jsonEditorOk" />
</template> </CustomDrawer>
</template>
<script>
import moment from 'moment' <script>
import { Select, Option } from 'element-ui' import moment from 'moment'
import { getCIType, getCITypeGroupById } from '@/modules/cmdb/api/CIType' import { Select, Option } from 'element-ui'
import { addCI } from '@/modules/cmdb/api/ci' import { getCIType, getCITypeGroupById } from '@/modules/cmdb/api/CIType'
import JsonEditor from '../../../components/JsonEditor/jsonEditor.vue' import { addCI } from '@/modules/cmdb/api/ci'
import { valueTypeMap } from '../../../utils/const' import JsonEditor from '../../../components/JsonEditor/jsonEditor.vue'
import CreateInstanceFormByGroup from './createInstanceFormByGroup.vue' import { valueTypeMap } from '../../../utils/const'
import { getCITypeParent } from '@/modules/cmdb/api/CITypeRelation' import CreateInstanceFormByGroup from './createInstanceFormByGroup.vue'
import { getCITypeParent } from '@/modules/cmdb/api/CITypeRelation'
export default {
name: 'CreateInstanceForm', export default {
components: { name: 'CreateInstanceForm',
ElSelect: Select, components: {
ElOption: Option, ElSelect: Select,
JsonEditor, ElOption: Option,
CreateInstanceFormByGroup, JsonEditor,
}, CreateInstanceFormByGroup,
props: { },
typeIdFromRelation: { props: {
type: Number, typeIdFromRelation: {
default: 0, type: Number,
}, default: 0,
}, },
data() { },
return { data() {
valueTypeMap, return {
action: '', valueTypeMap,
form: this.$form.createForm(this), action: '',
visible: false, form: this.$form.createForm(this),
attributeList: [], visible: false,
attributeList: [],
CIType: {},
CIType: {},
batchUpdateLists: [],
editAttr: null, batchUpdateLists: [],
attributesByGroup: [], editAttr: null,
parentsType: [], attributesByGroup: [],
parentsForm: {}, parentsType: [],
} parentsForm: {},
}, }
computed: { },
title() { computed: {
return this.action === 'create' ? '创建 ' : '批量修改 ' title() {
}, return this.action === 'create' ? '创建 ' : '批量修改 '
typeId() { },
if (this.typeIdFromRelation) { typeId() {
return this.typeIdFromRelation if (this.typeIdFromRelation) {
} return this.typeIdFromRelation
return this.$router.currentRoute.meta.typeId }
}, return this.$router.currentRoute.meta.typeId
}, },
provide() { },
return { provide() {
getFieldType: this.getFieldType, return {
} getFieldType: this.getFieldType,
}, }
inject: ['attrList'], },
methods: { inject: ['attrList'],
moment, methods: {
async getCIType() { moment,
await getCIType(this.typeId).then((res) => { async getCIType() {
this.CIType = res.ci_types[0] await getCIType(this.typeId).then((res) => {
}) this.CIType = res.ci_types[0]
}, })
async getAttributeList() { },
const _attrList = this.attrList() async getAttributeList() {
this.attributeList = _attrList.sort((x, y) => y.is_required - x.is_required) const _attrList = this.attrList()
await getCITypeGroupById(this.typeId).then((res1) => { this.attributeList = _attrList.sort((x, y) => y.is_required - x.is_required)
const _attributesByGroup = res1.map((g) => { await getCITypeGroupById(this.typeId).then((res1) => {
g.attributes = g.attributes.filter((attr) => !attr.is_computed) const _attributesByGroup = res1.map((g) => {
return g g.attributes = g.attributes.filter((attr) => !attr.is_computed)
}) return g
const attrHasGroupIds = [] })
res1.forEach((g) => { const attrHasGroupIds = []
const id = g.attributes.map((attr) => attr.id) res1.forEach((g) => {
attrHasGroupIds.push(...id) const id = g.attributes.map((attr) => attr.id)
}) attrHasGroupIds.push(...id)
const otherGroupAttr = this.attributeList.filter( })
(attr) => !attrHasGroupIds.includes(attr.id) && !attr.is_computed const otherGroupAttr = this.attributeList.filter(
) (attr) => !attrHasGroupIds.includes(attr.id) && !attr.is_computed
if (otherGroupAttr.length) { )
_attributesByGroup.push({ id: -1, name: '其他', attributes: otherGroupAttr }) if (otherGroupAttr.length) {
} _attributesByGroup.push({ id: -1, name: '其他', attributes: otherGroupAttr })
this.attributesByGroup = _attributesByGroup }
}) this.attributesByGroup = _attributesByGroup
}, })
createInstance() { },
const _this = this createInstance() {
if (_this.action === 'update') { const _this = this
this.form.validateFields((err, values) => { if (_this.action === 'update') {
if (err) { this.form.validateFields((err, values) => {
return if (err) {
} return
Object.keys(values).forEach((k) => { }
const _tempFind = this.attributeList.find((item) => item.name === k) Object.keys(values).forEach((k) => {
if (_tempFind.value_type === '3' && values[k]) { const _tempFind = this.attributeList.find((item) => item.name === k)
values[k] = values[k].format('YYYY-MM-DD HH:mm:ss') if (
} _tempFind.value_type === '3' &&
if (_tempFind.value_type === '4' && values[k]) { values[k] &&
values[k] = values[k].format('YYYY-MM-DD') Object.prototype.toString.call(values[k]) === '[object Object]'
} ) {
if (_tempFind.value_type === '6') { values[k] = values[k].format('YYYY-MM-DD HH:mm:ss')
values[k] = values[k] ? JSON.parse(values[k]) : undefined }
} if (
}) _tempFind.value_type === '4' &&
values[k] &&
_this.$emit('submit', values) Object.prototype.toString.call(values[k]) === '[object Object]'
}) ) {
} else { values[k] = values[k].format('YYYY-MM-DD')
let values = {} }
for (let i = 0; i < this.attributesByGroup.length; i++) { if (_tempFind.value_type === '6') {
const data = this.$refs[`createInstanceFormByGroup_${this.attributesByGroup[i].id}`][0].getData() values[k] = values[k] ? JSON.parse(values[k]) : undefined
if (data === 'error') { }
return })
}
values = { ...values, ...data } _this.$emit('submit', values)
} })
} else {
Object.keys(values).forEach((k) => { let values = {}
const _tempFind = this.attributeList.find((item) => item.name === k) for (let i = 0; i < this.attributesByGroup.length; i++) {
if (_tempFind.value_type === '3' && values[k]) { const data = this.$refs[`createInstanceFormByGroup_${this.attributesByGroup[i].id}`][0].getData()
values[k] = values[k].format('YYYY-MM-DD HH:mm:ss') if (data === 'error') {
} return
if (_tempFind.value_type === '4' && values[k]) { }
values[k] = values[k].format('YYYY-MM-DD') values = { ...values, ...data }
} }
if (_tempFind.value_type === '6') {
values[k] = values[k] ? JSON.parse(values[k]) : undefined Object.keys(values).forEach((k) => {
} const _tempFind = this.attributeList.find((item) => item.name === k)
}) if (
values.ci_type = _this.typeId _tempFind.value_type === '3' &&
Object.keys(this.parentsForm).forEach((type) => { values[k] &&
if (this.parentsForm[type].value) { Object.prototype.toString.call(values[k]) === '[object Object]'
values[`$${type}.${this.parentsForm[type].attr}`] = this.parentsForm[type].value ) {
} values[k] = values[k].format('YYYY-MM-DD HH:mm:ss')
}) }
addCI(values).then((res) => { if (
_this.$message.success('新增成功!') _tempFind.value_type === '4' &&
_this.visible = false values[k] &&
_this.$emit('reload', { ci_id: res.ci_id }) Object.prototype.toString.call(values[k]) === '[object Object]'
}) ) {
} values[k] = values[k].format('YYYY-MM-DD')
}, }
handleClose() { if (_tempFind.value_type === '6') {
this.visible = false values[k] = values[k] ? JSON.parse(values[k]) : undefined
}, }
handleOpen(visible, action) { })
this.visible = visible values.ci_type = _this.typeId
this.action = action console.log(this.parentsForm)
this.$nextTick(() => { Object.keys(this.parentsForm).forEach((type) => {
this.form.resetFields() if (this.parentsForm[type].value) {
Promise.all([this.getCIType(), this.getAttributeList()]).then(() => { values[`$${type}.${this.parentsForm[type].attr}`] = this.parentsForm[type].value
this.batchUpdateLists = [{ name: this.attributeList[0].name }] }
}) })
if (action === 'create') { addCI(values).then((res) => {
getCITypeParent(this.typeId).then((res) => { _this.$message.success('新增成功!')
this.parentsType = res.parents _this.visible = false
const _parentsForm = {} _this.$emit('reload', { ci_id: res.ci_id })
res.parents.forEach((item) => { })
const _find = item.attributes.find((attr) => attr.id === item.unique_id) }
_parentsForm[item.name] = { attr: _find.name, value: '' } },
}) handleClose() {
this.parentsForm = _parentsForm this.visible = false
}) },
} handleOpen(visible, action) {
}) this.visible = visible
}, this.action = action
getFieldType(name) { this.$nextTick(() => {
const _find = this.attributeList.find((item) => item.name === name) this.form.resetFields()
if (_find) { Promise.all([this.getCIType(), this.getAttributeList()]).then(() => {
if (_find.is_choice) { this.batchUpdateLists = [{ name: this.attributeList[0].name }]
if (_find.is_list) { })
return 'select%%multiple' if (action === 'create') {
} getCITypeParent(this.typeId).then((res) => {
return 'select' this.parentsType = res.parents
} else if (_find.value_type === '0' || _find.value_type === '1') { const _parentsForm = {}
return 'input_number' res.parents.forEach((item) => {
} else if (_find.value_type === '4' || _find.value_type === '3') { const _find = item.attributes.find((attr) => attr.id === item.unique_id)
return valueTypeMap[_find.value_type] _parentsForm[item.name] = { attr: _find.name, value: '' }
} else { })
return 'input' this.parentsForm = _parentsForm
} })
} }
return 'input' })
}, },
getSelectFieldOptions(name) { getFieldType(name) {
const _find = this.attributeList.find((item) => item.name === name) const _find = this.attributeList.find((item) => item.name === name)
if (_find) { if (_find) {
return _find.choice_value if (_find.is_choice) {
} if (_find.is_list) {
return [] return 'select%%multiple'
}, }
handleAdd() { return 'select'
this.batchUpdateLists.push({ name: undefined }) } else if (_find.value_type === '0' || _find.value_type === '1') {
}, return 'input_number'
handleDelete(name) { } else if (_find.value_type === '4' || _find.value_type === '3') {
const _idx = this.batchUpdateLists.findIndex((item) => item.name === name) return valueTypeMap[_find.value_type]
if (_idx > -1) { } else {
this.batchUpdateLists.splice(_idx, 1) return 'input'
} }
}, }
handleFocusInput(e, attr) { return 'input'
console.log(attr) },
const _tempFind = this.attributeList.find((item) => item.name === attr.name) getSelectFieldOptions(name) {
if (_tempFind.value_type === '6') { const _find = this.attributeList.find((item) => item.name === name)
this.editAttr = attr if (_find) {
e.srcElement.blur() return _find.choice_value
const jsonData = this.form.getFieldValue(attr.name) }
this.$refs.jsonEditor.open(null, null, jsonData ? JSON.parse(jsonData) : {}) return []
} else { },
this.editAttr = null handleAdd() {
} this.batchUpdateLists.push({ name: undefined })
}, },
jsonEditorOk(jsonData) { handleDelete(name) {
this.form.setFieldsValue({ [this.editAttr.name]: JSON.stringify(jsonData) }) const _idx = this.batchUpdateLists.findIndex((item) => item.name === name)
}, if (_idx > -1) {
}, this.batchUpdateLists.splice(_idx, 1)
} }
</script> },
<style lang="less"> handleFocusInput(e, attr) {
.create-instance-form { console.log(attr)
.ant-form-item { const _tempFind = this.attributeList.find((item) => item.name === attr.name)
margin-bottom: 5px; if (_tempFind.value_type === '6') {
} this.editAttr = attr
.ant-drawer-body { e.srcElement.blur()
overflow-y: auto; const jsonData = this.form.getFieldValue(attr.name)
max-height: calc(100vh - 110px); this.$refs.jsonEditor.open(null, null, jsonData ? JSON.parse(jsonData) : {})
} } else {
} this.editAttr = null
</style> }
},
jsonEditorOk(jsonData) {
this.form.setFieldsValue({ [this.editAttr.name]: JSON.stringify(jsonData) })
},
},
}
</script>
<style lang="less">
.create-instance-form {
.ant-form-item {
margin-bottom: 5px;
}
.ant-drawer-body {
overflow-y: auto;
max-height: calc(100vh - 110px);
}
}
</style>

View File

@ -1,215 +1,225 @@
<template> <template>
<CustomDrawer <CustomDrawer
:visible="visible" :visible="visible"
:hasFooter="false" :hasFooter="false"
@close=" @close="
() => { () => {
visible = false visible = false
} }
" "
title="属性说明" title="属性说明"
width="72%" width="72%"
:bodyStyle="{ height: '100vh' }" :bodyStyle="{ height: '100vh' }"
> >
<vxe-toolbar> <vxe-toolbar>
<template #buttons> <template #buttons>
<a-input <a-input
v-model="searchKey" v-model="searchKey"
:style="{ display: 'inline-block', width: '244px' }" :style="{ display: 'inline-block', width: '244px' }"
class="ops-input ops-input-radius" class="ops-input ops-input-radius"
type="search" type="search"
placeholder="搜索 名称 | 别名" placeholder="搜索 名称 | 别名"
@keyup="searchAttributes" @keyup="searchAttributes"
> >
<a-icon type="search" slot="suffix" /> <a-icon type="search" slot="suffix" />
</a-input> </a-input>
</template> </template>
</vxe-toolbar> </vxe-toolbar>
<a-spin :spinning="loading"> <a-spin :spinning="loading">
<vxe-table <vxe-table
resizable resizable
border border
size="mini" size="mini"
:height="windowHeight - 160" :height="windowHeight - 160"
:data="list" :data="list"
:scroll-x="{ enabled: true, gt: 0 }" :scroll-x="{ enabled: true, gt: 0 }"
show-overflow show-overflow
show-header-overflow show-header-overflow
align="center" align="center"
highlight-hover-row highlight-hover-row
class="ops-stripe-table" class="ops-stripe-table"
> >
<vxe-column <vxe-column
v-for="(column, index) in columns" v-for="(column, index) in columns"
:field="column.field" :field="column.field"
:title="column.title" :title="column.title"
:min-width="column.width" :min-width="column.width"
:align="column.align" :align="column.align"
:key="column.field" :key="column.field"
:fixed="index < 3 ? 'left' : ''" :fixed="index < 3 ? 'left' : ''"
:sortable="index < 3 ? true : false" :sortable="index < 3 ? true : false"
:title-help="column.help !== null ? { message: column.help } : null" :title-help="column.help !== null ? { message: column.help } : null"
:filters=" :filters="
index < 2 ? null: index === 2 index < 2
? valueTypeFilters: [{ label: '', value: true }, { label: '', value: false },]" ? null
type="html" : index === 2
> ? valueTypeFilters
<template #default="{ row }"> : [
<span v-if="column.field !== 'name' && column.field !== 'alias' && column.field !== 'value_type'"> { label: '', value: true },
<a-icon :style="{ color: '#1fb51f' }" type="check" v-if="row[column.field]" /> { label: '', value: false },
</span> ]
<span v-else-if="column.field === 'value_type'" v-html="valueTypeMap[row.value_type]"> </span> "
<span v-else v-html="row[column.field]"> </span> type="html"
</template> >
</vxe-column> <template #default="{ row }">
</vxe-table> <span v-if="column.field !== 'name' && column.field !== 'alias' && column.field !== 'value_type'">
</a-spin> <a-icon :style="{ color: '#1fb51f' }" type="check" v-if="row[column.field]" />
</CustomDrawer> </span>
</template> <span v-else-if="column.field === 'value_type'" v-html="valueTypeMap[row.value_type]"> </span>
<span v-else v-html="row[column.field]"> </span>
<script> </template>
import XEUtils from 'xe-utils' </vxe-column>
import { getCITypeAttributesByName } from '@/modules/cmdb/api/CITypeAttr' </vxe-table>
import { valueTypeMap } from '@/modules/cmdb/utils/const' </a-spin>
export default { </CustomDrawer>
name: 'MetadataDrawer', </template>
data() {
const columns = [ <script>
{ import XEUtils from 'xe-utils'
field: 'name', import { getCITypeAttributesByName } from '@/modules/cmdb/api/CITypeAttr'
title: '名称', import { valueTypeMap } from '@/modules/cmdb/utils/const'
width: 150, export default {
align: 'left', name: 'MetadataDrawer',
help: null, data() {
}, const columns = [
{ {
field: 'alias', field: 'name',
title: '别名', title: '名称',
width: 150, width: 150,
align: 'left', align: 'left',
help: null, help: null,
}, },
{ {
field: 'value_type', field: 'alias',
title: '类型', title: '别名',
width: 100, width: 150,
align: 'left', align: 'left',
help: null, help: null,
}, },
{ {
field: 'is_index', field: 'value_type',
title: '是否索引', title: '类型',
width: 110, width: 100,
help: '加快检索, 可以全文搜索, 无需使用条件过滤\n\n json目前不支持建索引 \n\n文本字符长度超过190不能建索引', align: 'left',
}, help: null,
{ },
field: 'default_show', {
title: '默认显示', field: 'is_index',
width: 110, title: '是否索引',
help: '订阅CI默认显示在table里的属性', width: 110,
}, help: '加快检索, 可以全文搜索, 无需使用条件过滤\n\n json目前不支持建索引 \n\n文本字符长度超过190不能建索引',
{ },
field: 'is_unique', {
title: '是否唯一', field: 'default_show',
width: 110, title: '默认显示',
help: null, width: 110,
}, help: '订阅CI默认显示在table里的属性',
{ },
field: 'is_choice', {
title: '是否选择', field: 'is_unique',
width: 110, title: '是否唯一',
help: '表现形式是下拉框, 值必须在预定义值里', width: 110,
}, help: null,
{ },
field: 'is_list', {
title: '是否列表', field: 'is_choice',
width: 110, title: '是否选择',
help: '多值, 比如内网IP', width: 110,
}, help: '表现形式是下拉框, 值必须在预定义值里',
{ },
field: 'is_sortable', {
title: '可排序', field: 'is_list',
width: 100, title: '是否列表',
help: '仅针对前端', width: 110,
}, help: '多值, 比如内网IP',
{ },
field: 'is_password', {
title: '是否密码', field: 'is_sortable',
width: 100, title: '可排序',
help: null, width: 100,
}, help: '仅针对前端',
{ },
field: 'is_link', {
title: '是否链接', field: 'is_computed',
width: 110, title: '计算属性',
help: null, width: 110,
}, help: '模型的其他属性通过表达式的方式计算出来\n\n一个代码片段计算返回的值',
{ },
field: 'is_computed', ]
title: '计算属性', return {
width: 110, columns,
help: '模型的其他属性通过表达式的方式计算出来\n\n一个代码片段计算返回的值', visible: false,
}, list: [],
] tableData: [],
return { loading: false,
columns, valueTypeMap,
visible: false, valueTypeFilters: [],
list: [], searchKey: '',
tableData: [], }
loading: false, },
valueTypeMap, computed: {
valueTypeFilters: [], windowHeight() {
searchKey: '', return this.$store.state.windowHeight
} },
}, },
computed: { created: function() {
windowHeight() { this.valueTypeFilters = Object.keys(this.valueTypeMap).map((key) => {
return this.$store.state.windowHeight return { label: this.valueTypeMap[key], value: key }
}, })
}, },
created: function () { methods: {
this.valueTypeFilters = Object.keys(this.valueTypeMap).map((key) => { open(typeId) {
return { label: this.valueTypeMap[key], value: key } this.visible = true
}) this.typeId = typeId
}, this.getAttrs()
methods: { },
open(typeId) { async getAttrs() {
this.visible = true this.loading = true
this.typeId = typeId const { attributes = [] } = await getCITypeAttributesByName(this.typeId)
this.getAttrs() this.tableData = attributes.map((attr) => {
}, if (attr.is_password) {
async getAttrs() { attr.value_type = '7'
this.loading = true }
const { attributes = [] } = await getCITypeAttributesByName(this.typeId) if (attr.is_link) {
this.tableData = attributes attr.value_type = '8'
this.loading = false }
this.searchAttributes() return attr
}, })
searchAttributes() { this.loading = false
const filterName = XEUtils.toValueString(this.searchKey).trim().toLowerCase() this.searchAttributes()
if (filterName) { },
const filterRE = new RegExp(filterName, 'gi') searchAttributes() {
const searchProps = ['name', 'alias', 'value_type'] const filterName = XEUtils.toValueString(this.searchKey)
const rest = this.tableData.filter((item) => .trim()
searchProps.some((key) => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1) .toLowerCase()
) if (filterName) {
this.list = rest.map((row) => { const filterRE = new RegExp(filterName, 'gi')
const item = Object.assign({}, row) const searchProps = ['name', 'alias', 'value_type']
searchProps.forEach((key) => { const rest = this.tableData.filter((item) =>
item[key] = XEUtils.toValueString(item[key]).replace( searchProps.some(
filterRE, (key) =>
(match) => `<span style='background: yellow'>${match}</span>` XEUtils.toValueString(item[key])
) .toLowerCase()
}) .indexOf(filterName) > -1
return item )
}) )
} else { this.list = rest.map((row) => {
this.list = this.tableData const item = Object.assign({}, row)
} searchProps.forEach((key) => {
}, item[key] = XEUtils.toValueString(item[key]).replace(
}, filterRE,
} (match) => `<span style='background: yellow'>${match}</span>`
</script> )
})
<style></style> return item
})
} else {
this.list = this.tableData
}
},
},
}
</script>
<style></style>

View File

@ -1,234 +1,299 @@
<template> <template>
<span :id="`ci-detail-attr-${attr.name}`"> <span :id="`ci-detail-attr-${attr.name}`">
<span v-if="!isEdit || attr.value_type === '6'"> <span v-if="!isEdit || attr.value_type === '6'">
<template v-if="attr.value_type === '6'">{{ JSON.stringify(ci[attr.name] || {}) }}</template> <PasswordField
<template v-else-if="attr.is_choice"> :style="{ display: 'inline-block' }"
<template v-if="attr.is_list"> v-if="attr.is_password && ci[attr.name]"
<span :ci_id="ci._id"
v-for="value in ci[attr.name]" :attr_id="attr.id"
:key="value" ></PasswordField>
:style="{ <template v-else-if="attr.value_type === '6'">{{ JSON.stringify(ci[attr.name] || {}) }}</template>
borderRadius: '4px', <template v-else-if="attr.is_choice">
padding: '1px 5px', <template v-if="attr.is_list">
margin: '2px', <span
...getChoiceValueStyle(attr, value), v-for="value in ci[attr.name]"
}" :key="value"
> :style="{
<ops-icon borderRadius: '4px',
:style="{ color: getChoiceValueIcon(attr, value).color }" padding: '1px 5px',
:type="getChoiceValueIcon(attr, value).name" margin: '2px',
/> ...getChoiceValueStyle(attr, value),
{{ value }}</span display: 'inline-flex',
> alignItems: 'center',
</template> }"
<span >
v-else <img
:style="{ v-if="getChoiceValueIcon(attr, value).id && getChoiceValueIcon(attr, value).url"
borderRadius: '4px', :src="`/api/common-setting/v1/file/${getChoiceValueIcon(attr, value).url}`"
padding: '1px 5px', :style="{ maxHeight: '13px', maxWidth: '13px', marginRight: '5px' }"
margin: '2px 0', />
...getChoiceValueStyle(attr, ci[attr.name]), <ops-icon
}" v-else
> :style="{ color: getChoiceValueIcon(attr, value).color, marginRight: '5px' }"
<ops-icon :type="getChoiceValueIcon(attr, value).name"
:style="{ color: getChoiceValueIcon(attr, ci[attr.name]).color }" />
:type="getChoiceValueIcon(attr, ci[attr.name]).name" {{ value }}</span
/> >
{{ ci[attr.name] }} </template>
</span> <span
</template> v-else
<template v-else>{{ getName(ci[attr.name]) }}</template> :style="{
</span> borderRadius: '4px',
<template v-else> padding: '1px 5px',
<a-form :form="form"> margin: '2px 0',
<a-form-item label="" :colon="false"> ...getChoiceValueStyle(attr, ci[attr.name]),
<a-select display: 'inline-flex',
:style="{ width: '100%' }" alignItems: 'center',
v-decorator="[ }"
attr.name, >
{ <img
rules: [{ required: attr.is_required }], v-if="getChoiceValueIcon(attr, ci[attr.name]).id && getChoiceValueIcon(attr, ci[attr.name]).url"
}, :src="`/api/common-setting/v1/file/${getChoiceValueIcon(attr, ci[attr.name]).url}`"
]" :style="{ maxHeight: '13px', maxWidth: '13px', marginRight: '5px' }"
placeholder="请选择" />
v-if="attr.is_choice" <ops-icon
:mode="attr.is_list ? 'multiple' : 'default'" v-else
:multiple="attr.is_list" :style="{ color: getChoiceValueIcon(attr, ci[attr.name]).color, marginRight: '5px' }"
showSearch :type="getChoiceValueIcon(attr, ci[attr.name]).name"
allowClear />
size="small" {{ ci[attr.name] }}
:getPopupContainer="(trigger) => trigger.parentElement" </span>
> </template>
<a-select-option <template v-else>{{ getName(ci[attr.name]) }}</template>
:value="choice[0]" </span>
:key="'New_' + attr.name + choice_idx" <template v-else>
v-for="(choice, choice_idx) in attr.choice_value" <a-form :form="form">
> <a-form-item label="" :colon="false">
<span :style="choice[1] ? choice[1].style || {} : {}"> <a-select
<ops-icon :style="{ width: '100%' }"
:style="{ color: choice[1].icon.color }" v-decorator="[
v-if="choice[1] && choice[1].icon && choice[1].icon.name" attr.name,
:type="choice[1].icon.name" {
/> rules: [{ required: attr.is_required }],
{{ choice[0] }} },
</span> ]"
</a-select-option> placeholder="请选择"
</a-select> v-if="attr.is_choice"
<a-input-number :mode="attr.is_list ? 'multiple' : 'default'"
size="small" :multiple="attr.is_list"
v-decorator="[ showSearch
attr.name, allowClear
{ size="small"
rules: [{ required: attr.is_required }], :getPopupContainer="(trigger) => trigger.parentElement"
}, >
]" <a-select-option
style="width: 100%" :value="choice[0]"
v-else-if="attr.value_type === '0' || attr.value_type === '1'" :key="'New_' + attr.name + choice_idx"
/> v-for="(choice, choice_idx) in attr.choice_value"
<a-date-picker >
size="small" <span :style="{ ...(choice[1] ? choice[1].style : {}), display: 'inline-flex', alignItems: 'center' }">
v-decorator="[ <template v-if="choice[1] && choice[1].icon && choice[1].icon.name">
attr.name, <img
{ v-if="choice[1].icon.id && choice[1].icon.url"
rules: [{ required: attr.is_required }], :src="`/api/common-setting/v1/file/${choice[1].icon.url}`"
}, :style="{ maxHeight: '13px', maxWidth: '13px', marginRight: '5px' }"
]" />
style="width: 100%" <ops-icon
:format="attr.value_type === '4' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'" v-else
:valueFormat="attr.value_type === '4' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'" :style="{ color: choice[1].icon.color, marginRight: '5px' }"
v-else-if="attr.value_type === '4' || attr.value_type === '3'" :type="choice[1].icon.name"
:showTime="attr.value_type === '4' ? false : { format: 'HH:mm:ss' }" />
/> </template>
<a-input {{ choice[0] }}
size="small" </span>
v-decorator="[ </a-select-option>
attr.name, </a-select>
{ <a-input-number
validateTrigger: ['submit'], size="small"
rules: [{ required: attr.is_required }], v-decorator="[
}, attr.name,
]" {
style="width: 100%" rules: [{ required: attr.is_required }],
v-else },
/> ]"
</a-form-item> style="width: 100%"
</a-form> v-else-if="attr.value_type === '0' || attr.value_type === '1'"
</template> />
<a v-if="!isEdit && !attr.is_computed" @click="handleEdit" :style="{ opacity: 0 }"><a-icon type="edit"/></a> <a-date-picker
<JsonEditor ref="jsonEditor" @jsonEditorOk="jsonEditorOk" /> size="small"
</span> v-decorator="[
</template> attr.name,
{
<script> rules: [{ required: attr.is_required }],
import _ from 'lodash' },
import moment from 'moment' ]"
import { updateCI } from '@/modules/cmdb/api/ci' style="width: 100%"
import JsonEditor from '../../../components/JsonEditor/jsonEditor.vue' :format="attr.value_type === '4' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'"
export default { :valueFormat="attr.value_type === '4' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'"
name: 'CiDetailAttrContent', v-else-if="attr.value_type === '4' || attr.value_type === '3'"
components: { JsonEditor }, :showTime="attr.value_type === '4' ? false : { format: 'HH:mm:ss' }"
props: { />
ci: { <!-- <a-input
type: Object, size="small"
default: () => {}, @focus="(e) => handleFocusInput(e, attr)"
}, v-decorator="[
attr: { attr.name,
type: Object, {
default: () => {}, validateTrigger: ['submit'],
}, rules: [{ required: attr.is_required }],
}, },
data() { ]"
return { style="width: 100%"
isEdit: false, v-else-if="attr.value_type === '6'"
form: this.$form.createForm(this, this.attr.name), /> -->
} <a-input
}, size="small"
mounted() { v-decorator="[
document.addEventListener('click', this.eventListener) attr.name,
}, {
beforeDestroy() { validateTrigger: ['submit'],
document.removeEventListener('click', this.eventListener) rules: [{ required: attr.is_required }],
}, },
methods: { ]"
moment, style="width: 100%"
eventListener(e) { v-else
const datePickerContainer = document.getElementsByClassName('ant-calendar-picker-container') />
if (this.isEdit && !datePickerContainer.length) { </a-form-item>
const dom = document.getElementById(`ci-detail-attr-${this.attr.name}`) </a-form>
e.stopPropagation() </template>
e.preventDefault() <a v-if="!isEdit && !attr.is_computed" @click="handleEdit" :style="{ opacity: 0 }"><a-icon type="edit"/></a>
if (dom) { <JsonEditor ref="jsonEditor" @jsonEditorOk="jsonEditorOk" />
const isSelf = dom.contains(e.target) </span>
if (!isSelf) { </template>
this.handleCloseEdit()
} <script>
} import _ from 'lodash'
} import moment from 'moment'
}, import { updateCI } from '@/modules/cmdb/api/ci'
handleEdit(e) { import JsonEditor from '../../../components/JsonEditor/jsonEditor.vue'
e.stopPropagation() import PasswordField from '../../../components/passwordField/index.vue'
e.preventDefault() import { getAttrPassword } from '../../../api/CITypeAttr'
if (this.attr.value_type === '6') {
const jsonData = this.ci[this.attr.name] export default {
this.$refs.jsonEditor.open(null, null, jsonData || {}) name: 'CiDetailAttrContent',
return components: { JsonEditor, PasswordField },
} props: {
this.isEdit = true ci: {
this.$nextTick(() => { type: Object,
if (this.attr.is_list && !this.attr.is_choice) { default: () => {},
this.form.setFieldsValue({ },
[`${this.attr.name}`]: this.ci[this.attr.name].join(',') || null, attr: {
}) type: Object,
return default: () => {},
} },
this.form.setFieldsValue({ },
[`${this.attr.name}`]: this.ci[this.attr.name] ?? null, data() {
}) return {
}) isEdit: false,
}, form: this.$form.createForm(this, this.attr.name),
async handleCloseEdit() { }
const newData = this.form.getFieldValue(this.attr.name) },
if (!_.isEqual(this.ci[this.attr.name], newData)) { mounted() {
await updateCI(this.ci._id, { [`${this.attr.name}`]: newData }) document.addEventListener('click', this.eventListener)
.then(() => { },
this.$message.success('更新成功!') beforeDestroy() {
}) document.removeEventListener('click', this.eventListener)
.finally(() => { },
this.$emit('refresh', this.attr.name) methods: {
}) moment,
} eventListener(e) {
this.isEdit = false const datePickerContainer = document.getElementsByClassName('ant-calendar-picker-container')
}, if (this.isEdit && !datePickerContainer.length) {
jsonEditorOk(jsonData) { const dom = document.getElementById(`ci-detail-attr-${this.attr.name}`)
if (!_.isEqual(this.ci[this.attr.name], jsonData)) { e.stopPropagation()
updateCI(this.ci._id, { [`${this.attr.name}`]: jsonData }) e.preventDefault()
.then(() => { if (dom) {
this.$message.success('更新成功!') const isSelf = dom.contains(e.target)
}) if (!isSelf) {
.finally(() => { this.handleCloseEdit()
this.$emit('refresh', this.attr.name) }
}) }
} }
}, },
getChoiceValueStyle(col, colValue) { handleEdit(e) {
const _find = col.choice_value.find((item) => String(item[0]) === String(colValue)) e.stopPropagation()
if (_find) { e.preventDefault()
return _find[1]?.style || {} if (this.attr.value_type === '6') {
} const jsonData = this.ci[this.attr.name]
return {} this.$refs.jsonEditor.open(null, null, jsonData || {})
}, return
getChoiceValueIcon(col, colValue) { }
const _find = col.choice_value.find((item) => String(item[0]) === String(colValue)) this.isEdit = true
if (_find) { this.$nextTick(async () => {
return _find[1]?.icon || {} if (this.attr.is_list && !this.attr.is_choice) {
} this.form.setFieldsValue({
return {} [`${this.attr.name}`]: this.ci[this.attr.name].join(',') || null,
}, })
getName(name) { return
return name ?? '' }
}, if (this.attr.is_password) {
}, await getAttrPassword(this.ci._id, this.attr.id).then((res) => {
} this.form.setFieldsValue({
</script> [`${this.attr.name}`]: res.value ?? null,
})
<style></style> })
return
}
this.form.setFieldsValue({
[`${this.attr.name}`]: this.ci[this.attr.name] ?? null,
})
})
},
async handleCloseEdit() {
const newData = this.form.getFieldValue(this.attr.name)
if (!_.isEqual(this.ci[this.attr.name], newData)) {
await updateCI(this.ci._id, { [`${this.attr.name}`]: newData })
.then(() => {
this.$message.success('更新成功!')
this.$emit('updateCIByself', { [`${this.attr.name}`]: newData }, this.attr.name)
})
.catch(() => {
this.$emit('refresh', this.attr.name)
})
}
this.isEdit = false
},
// handleFocusInput(e, attr) {
// console.log('focus')
// if (this.attr.value_type === '6') {
// e.preventDefault()
// e.stopPropagation()
// // e.srcElement.blur()
// const jsonData = this.form.getFieldValue(attr.name)
// this.$refs.jsonEditor.open(null, null, jsonData ? JSON.parse(jsonData) : {})
// }
// },
jsonEditorOk(jsonData) {
if (!_.isEqual(this.ci[this.attr.name], jsonData)) {
updateCI(this.ci._id, { [`${this.attr.name}`]: jsonData })
.then(() => {
this.$message.success('更新成功!')
this.$emit('updateCIByself', { [`${this.attr.name}`]: jsonData }, this.attr.name)
})
.catch(() => {
this.$emit('refresh', this.attr.name)
})
}
},
getChoiceValueStyle(col, colValue) {
const _find = col.choice_value.find((item) => String(item[0]) === String(colValue))
if (_find) {
return _find[1]?.style || {}
}
return {}
},
getChoiceValueIcon(col, colValue) {
const _find = col.choice_value.find((item) => String(item[0]) === String(colValue))
if (_find) {
return _find[1]?.icon || {}
}
return {}
},
getName(name) {
return name ?? ''
},
},
}
</script>
<style></style>

View File

@ -1,280 +1,274 @@
<template> <template>
<div class="attribute-card"> <div class="attribute-card">
<div class="attribute-card-content"> <div class="attribute-card-content">
<div class="attribute-card-value-type-icon handle" :style="{ ...getPropertyStyle(property) }"> <div class="attribute-card-value-type-icon handle" :style="{ ...getPropertyStyle(property) }">
<ValueTypeIcon :attr="property" /> <ValueTypeIcon :attr="property" />
</div> </div>
<div :class="{ 'attribute-card-content-inner': true, 'attribute-card-name-required': property.is_required }"> <div :class="{ 'attribute-card-content-inner': true, 'attribute-card-name-required': property.is_required }">
<div :class="{ 'attribute-card-name': true, 'attribute-card-name-default-show': property.default_show }"> <div :class="{ 'attribute-card-name': true, 'attribute-card-name-default-show': property.default_show }">
{{ property.alias || property.name }} {{ property.alias || property.name }}
</div> </div>
<div class="attribute-card_value-type">{{ valueTypeMap[property.value_type] }}</div> <div v-if="property.is_password" class="attribute-card_value-type">密码</div>
</div> <div v-else-if="property.is_link" class="attribute-card_value-type">链接</div>
<div <div v-else class="attribute-card_value-type">{{ valueTypeMap[property.value_type] }}</div>
class="attribute-card-trigger" </div>
v-if="(property.value_type === '3' || property.value_type === '4') && !isStore" <div
> class="attribute-card-trigger"
<a @click="openTrigger"><ops-icon type="ops-trigger"/></a> v-if="(property.value_type === '3' || property.value_type === '4') && !isStore"
</div> >
</div> <a @click="openTrigger"><ops-icon type="ops-trigger"/></a>
<div class="attribute-card-footer"> </div>
<a-popover </div>
trigger="click" <div class="attribute-card-footer">
:arrowPointAtCenter="true" <a-popover
placement="bottom" trigger="click"
overlayClassName="attribute-card-footer-popover" :arrowPointAtCenter="true"
> placement="bottom"
<div slot="content"> overlayClassName="attribute-card-footer-popover"
<h3 :style="{ textAlign: 'center', paddingTop: '0.5em' }"> >
<span>{{ property.alias }}({{ property.name }})</span> <div slot="content">
</h3> <h3 :style="{ textAlign: 'center', paddingTop: '0.5em' }">
<a-descriptions layout="horizontal" bordered size="small" :column="2"> <span>{{ property.alias }}({{ property.name }})</span>
<a-descriptions-item v-for="item in propertyList" :key="item.property" :label="item.label"> </h3>
<components <a-descriptions layout="horizontal" bordered size="small" :column="2">
:is="`ops_${item.property}`" <a-descriptions-item v-for="item in propertyList" :key="item.property" :label="item.label">
v-if="property[item.property]" <components
:style="{ width: '1em', height: '1em' }" :is="`ops_${item.property}`"
/> v-if="property[item.property]"
<ops-icon v-else :type="`ops-${item.property}-disabled`" /> :style="{ width: '1em', height: '1em' }"
</a-descriptions-item> />
<a-descriptions-item label></a-descriptions-item> <ops-icon v-else :type="`ops-${item.property}-disabled`" />
</a-descriptions> </a-descriptions-item>
</div> <a-descriptions-item label></a-descriptions-item>
<a-space :style="{ cursor: 'pointer' }"> </a-descriptions>
<components </div>
v-for="item in propertyList.filter((p) => property[p.property])" <a-space :style="{ cursor: 'pointer' }">
:key="item.property" <components
:is="`ops_${item.property}`" v-for="item in propertyList.filter((p) => property[p.property])"
/> :key="item.property"
</a-space> :is="`ops_${item.property}`"
</a-popover> />
</a-space>
<a-space class="attribute-card-operation"> </a-popover>
<a v-if="!isStore"><a-icon type="edit" @click="handleEdit"/></a>
<a-tooltip title="所有CI触发计算"> <a-space class="attribute-card-operation">
<a v-if="!isStore && property.is_computed"><a-icon type="redo" @click="handleCalcComputed"/></a> <a v-if="!isStore"><a-icon type="edit" @click="handleEdit"/></a>
</a-tooltip> <a-tooltip title="所有CI触发计算">
<a style="color:red;"><a-icon type="delete" @click="handleDelete"/></a> <a v-if="!isStore && property.is_computed"><a-icon type="redo" @click="handleCalcComputed"/></a>
</a-space> </a-tooltip>
</div> <a style="color:red;"><a-icon type="delete" @click="handleDelete"/></a>
<TriggerForm ref="triggerForm" :CITypeId="CITypeId" /> </a-space>
</div> </div>
</template> <TriggerForm ref="triggerForm" :CITypeId="CITypeId" />
</div>
<script> </template>
import { deleteCITypeAttributesById, deleteAttributesById, calcComputedAttribute } from '@/modules/cmdb/api/CITypeAttr'
import ValueTypeIcon from '@/components/CMDBValueTypeMapIcon' <script>
import { import { deleteCITypeAttributesById, deleteAttributesById, calcComputedAttribute } from '@/modules/cmdb/api/CITypeAttr'
ops_default_show, import ValueTypeIcon from '@/components/CMDBValueTypeMapIcon'
ops_is_choice, import {
ops_is_index, ops_default_show,
ops_is_link, ops_is_choice,
ops_is_password, ops_is_index,
ops_is_sortable, ops_is_link,
ops_is_unique, ops_is_password,
} from '@/core/icons' ops_is_sortable,
import { valueTypeMap } from '../../utils/const' ops_is_unique,
import { getPropertyStyle } from '../../utils/helper' } from '@/core/icons'
import TriggerForm from './triggerForm.vue' import { valueTypeMap } from '../../utils/const'
export default { import { getPropertyStyle } from '../../utils/helper'
name: 'AttributeCard', import TriggerForm from './triggerForm.vue'
components: { export default {
ValueTypeIcon, name: 'AttributeCard',
TriggerForm, components: {
ops_default_show, ValueTypeIcon,
ops_is_choice, TriggerForm,
ops_is_index, ops_default_show,
ops_is_link, ops_is_choice,
ops_is_password, ops_is_index,
ops_is_sortable, ops_is_link,
ops_is_unique, ops_is_password,
}, ops_is_sortable,
props: { ops_is_unique,
property: { },
type: Object, props: {
default: () => {}, property: {
}, type: Object,
CITypeId: { default: () => {},
type: Number, },
default: null, CITypeId: {
}, type: Number,
isStore: { default: null,
type: Boolean, },
default: false, isStore: {
}, type: Boolean,
}, default: false,
data() { },
const propertyList = [ },
{ data() {
label: '是否唯一', const propertyList = [
property: 'is_unique', {
}, label: '是否唯一',
{ property: 'is_unique',
label: '是否选择', },
property: 'is_choice', {
}, label: '是否选择',
{ property: 'is_choice',
label: '默认显示', },
property: 'default_show', {
}, label: '默认显示',
{ property: 'default_show',
label: '可排序', },
property: 'is_sortable', {
}, label: '可排序',
{ property: 'is_sortable',
label: '是否索引', },
property: 'is_index', {
}, label: '是否索引',
{ property: 'is_index',
label: '是否密码', },
property: 'is_password', ]
}, return {
{ valueTypeMap,
label: '是否链接', propertyList,
property: 'is_link', }
}, },
] methods: {
return { getPropertyStyle,
valueTypeMap, handleEdit() {
propertyList, this.$emit('edit')
} },
}, handleDelete() {
methods: { const that = this
getPropertyStyle, this.$confirm({
handleEdit() { title: '警告',
this.$emit('edit') content: `确认删除 ${that.property.alias || that.property.name}`,
}, onOk() {
handleDelete() { if (that.isStore) {
const that = this deleteAttributesById(that.property.id).then(() => {
this.$confirm({ that.$message.success('删除成功!')
title: '警告', that.$emit('ok')
content: `确认删除 ${that.property.alias || that.property.name}`, })
onOk() { } else {
if (that.isStore) { deleteCITypeAttributesById(that.CITypeId, { attr_id: [that.property.id] }).then(() => {
deleteAttributesById(that.property.id).then(() => { that.$message.success('删除成功!')
that.$message.success('删除成功!') that.$emit('ok')
that.$emit('ok') })
}) }
} else { },
deleteCITypeAttributesById(that.CITypeId, { attr_id: [that.property.id] }).then(() => { onCancel() {},
that.$message.success('删除成功!') })
that.$emit('ok') },
}) openTrigger() {
} this.$refs.triggerForm.open(this.property)
}, },
onCancel() {}, handleCalcComputed() {
}) const that = this
}, this.$confirm({
openTrigger() { title: '警告',
this.$refs.triggerForm.open(this.property) content: `确认触发所有CI的计算`,
}, onOk() {
handleCalcComputed() { calcComputedAttribute(that.property.id).then(() => {
const that = this that.$message.success('触发成功!')
this.$confirm({ })
title: '警告', },
content: `确认触发所有CI的计算`, })
onOk() { },
calcComputedAttribute(that.property.id).then(() => { },
that.$message.success('触发成功!') }
}) </script>
},
}) <style lang="less" scoped>
}, .attribute-card {
}, width: 182px;
} height: 80px;
</script> background: #f8faff;
border-radius: 5px;
<style lang="less" scoped> position: relative;
.attribute-card { margin-bottom: 16px;
width: 182px; transition: all 0.3s;
height: 80px; &:hover {
background: #f8faff; box-shadow: 0 4px 12px #4e5ea066;
border-radius: 5px; .attribute-card-operation {
position: relative; visibility: visible !important;
margin-bottom: 16px; }
transition: all 0.3s; }
&:hover { .attribute-card-content {
box-shadow: 0 4px 12px #4e5ea066; height: 50px;
.attribute-card-operation { display: inline-flex;
visibility: visible !important; align-items: center;
} padding: 8px;
} width: 100%;
.attribute-card-content { .attribute-card-value-type-icon {
height: 50px; width: 32px;
display: inline-flex; height: 32px;
align-items: center; font-size: 12px;
padding: 8px; cursor: move;
width: 100%; background: #ffffff !important;
.attribute-card-value-type-icon { box-shadow: 0px 1px 2px rgba(47, 84, 235, 0.2);
width: 32px; border-radius: 2px;
height: 32px; text-align: center;
font-size: 12px; line-height: 32px;
cursor: move; }
background: #ffffff !important; .attribute-card-content-inner {
box-shadow: 0px 1px 2px rgba(47, 84, 235, 0.2); padding-left: 12px;
border-radius: 2px; font-weight: 400;
text-align: center; font-size: 12px;
line-height: 32px; width: 120px;
} position: relative;
.attribute-card-content-inner { .attribute-card-name {
padding-left: 12px; width: 100%;
font-weight: 400; color: rgba(0, 0, 0, 0.8);
font-size: 12px; overflow: hidden;
width: 120px; text-overflow: ellipsis;
position: relative; white-space: nowrap;
.attribute-card-name { }
width: 100%; .attribute-card-name-default-show {
color: rgba(0, 0, 0, 0.8); color: #2f54eb;
overflow: hidden; }
text-overflow: ellipsis; .attribute-card_value-type {
white-space: nowrap; font-size: 10px;
} color: rgba(0, 0, 0, 0.35);
.attribute-card-name-default-show { }
color: #2f54eb; }
} .attribute-card-name-required::before {
.attribute-card_value-type { content: '*';
font-size: 10px; width: 5px;
color: rgba(0, 0, 0, 0.35); color: red;
} position: absolute;
} left: 3px;
.attribute-card-name-required::before { }
content: '*'; .attribute-card-trigger {
width: 5px; position: absolute;
color: red; right: 8px;
position: absolute; top: 8px;
left: 3px; }
} }
.attribute-card-trigger { .attribute-card-footer {
position: absolute; width: 182px;
right: 8px; height: 30px;
top: 8px; padding: 0 8px;
} position: absolute;
} bottom: 0;
.attribute-card-footer { left: 0;
width: 182px; background: linear-gradient(180deg, #96abd6 0%, #ecf2ff 0.01%, #ffffff 143.33%);
height: 30px; border-radius: 0px 0px 5px 5px;
padding: 0 8px; display: inline-flex;
position: absolute; align-items: center;
bottom: 0; justify-content: space-between;
left: 0; .attribute-card-operation {
background: linear-gradient(180deg, #96abd6 0%, #ecf2ff 0.01%, #ffffff 143.33%); visibility: hidden;
border-radius: 0px 0px 5px 5px; }
display: inline-flex; }
align-items: center; }
justify-content: space-between; </style>
.attribute-card-operation { <style lang="less">
visibility: hidden; .attribute-card-footer-popover {
} .ant-popover-inner-content {
} padding: 0;
} }
</style> .ant-descriptions-bordered .ant-descriptions-item-label {
<style lang="less"> background-color: #f8faff;
.attribute-card-footer-popover { }
.ant-popover-inner-content { }
padding: 0; </style>
}
.ant-descriptions-bordered .ant-descriptions-item-label {
background-color: #f8faff;
}
}
</style>

View File

@ -84,7 +84,12 @@
</a-input-number> </a-input-number>
<a-input <a-input
style="width: 100%" style="width: 100%"
v-else-if="currentValueType === '2' || currentValueType === '5'" v-else-if="
currentValueType === '2' ||
currentValueType === '5' ||
currentValueType === '7' ||
currentValueType === '8'
"
v-decorator="['default_value', { rules: [{ required: false }] }]" v-decorator="['default_value', { rules: [{ required: false }] }]"
> >
</a-input> </a-input>
@ -148,13 +153,13 @@
label="必须" label="必须"
> >
<a-switch <a-switch
@change="onChange" @change="(checked) => onChange(checked, 'is_required')"
name="is_required" name="is_required"
v-decorator="['is_required', { rules: [], valuePropName: 'checked' }]" v-decorator="['is_required', { rules: [], valuePropName: 'checked' }]"
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="6" v-if="currentValueType !== '6'"> <a-col :span="6" v-if="currentValueType !== '6' && currentValueType !== '7'">
<a-form-item :label-col="{ span: 8 }" :wrapper-col="horizontalFormItemLayout.wrapperCol" label="唯一"> <a-form-item :label-col="{ span: 8 }" :wrapper-col="horizontalFormItemLayout.wrapperCol" label="唯一">
<a-switch <a-switch
:disabled="isShowComputedArea" :disabled="isShowComputedArea"
@ -228,7 +233,7 @@
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="6" v-if="currentValueType !== '6'"> <a-col :span="6" v-if="currentValueType !== '6' && currentValueType !== '7'">
<a-form-item <a-form-item
:label-col="currentValueType === '2' ? horizontalFormItemLayout.labelCol : { span: 8 }" :label-col="currentValueType === '2' ? horizontalFormItemLayout.labelCol : { span: 8 }"
:wrapper-col="horizontalFormItemLayout.wrapperCol" :wrapper-col="horizontalFormItemLayout.wrapperCol"
@ -236,14 +241,14 @@
> >
<a-switch <a-switch
:disabled="isShowComputedArea" :disabled="isShowComputedArea"
@change="onChange" @change="(checked) => onChange(checked, 'is_sortable')"
name="is_sortable" name="is_sortable"
v-decorator="['is_sortable', { rules: [], valuePropName: 'checked' }]" v-decorator="['is_sortable', { rules: [], valuePropName: 'checked' }]"
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="6" v-if="currentValueType !== '6'"> <a-col :span="6" v-if="currentValueType !== '6' && currentValueType !== '7'">
<a-form-item <a-form-item
:label-col="currentValueType === '2' ? { span: 8 } : horizontalFormItemLayout.labelCol" :label-col="currentValueType === '2' ? { span: 8 } : horizontalFormItemLayout.labelCol"
:wrapper-col="horizontalFormItemLayout.wrapperCol" :wrapper-col="horizontalFormItemLayout.wrapperCol"
@ -275,31 +280,6 @@
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="6" v-if="currentValueType === '2'">
<a-form-item
:label-col="horizontalFormItemLayout.labelCol"
:wrapper-col="horizontalFormItemLayout.wrapperCol"
label="密码"
>
<a-switch
:disabled="isShowComputedArea"
@change="(checked) => onChange(checked, 'is_password')"
name="is_password"
v-decorator="['is_password', { rules: [], valuePropName: 'checked' }]"
/>
</a-form-item>
</a-col>
<a-col :span="6" v-if="currentValueType === '2'">
<a-form-item :label-col="{ span: 8 }" :wrapper-col="horizontalFormItemLayout.wrapperCol" label="链接">
<a-switch
:disabled="isShowComputedArea"
@change="(checked) => onChange(checked, 'is_link')"
name="is_link"
v-decorator="['is_link', { rules: [], valuePropName: 'checked' }]"
/>
</a-form-item>
</a-col>
<a-divider style="font-size:14px;margin-top:6px;">高级设置</a-divider> <a-divider style="font-size:14px;margin-top:6px;">高级设置</a-divider>
<a-row> <a-row>
<a-col :span="24"> <a-col :span="24">
@ -307,12 +287,17 @@
<FontArea ref="fontArea" /> <FontArea ref="fontArea" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="24" v-if="currentValueType !== '6'"> <a-col :span="24" v-if="!['6', '7'].includes(currentValueType)">
<a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" label="预定义值"> <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" label="预定义值">
<PreValueArea v-if="drawerVisible" ref="preValueArea" :disabled="isShowComputedArea" /> <PreValueArea
v-if="drawerVisible"
:canDefineScript="canDefineScript"
ref="preValueArea"
:disabled="isShowComputedArea"
/>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="24" v-if="currentValueType !== '6'"> <a-col :span="24" v-if="!['6', '7'].includes(currentValueType)">
<a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }"> <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
<template slot="label"> <template slot="label">
<span <span
@ -340,7 +325,7 @@
<a-switch <a-switch
:disabled="!canDefineComputed" :disabled="!canDefineComputed"
@change="(checked) => onChange(checked, 'is_computed')" @change="(checked) => onChange(checked, 'is_computed')"
name="is_password" name="is_computed"
v-decorator="['is_computed', { rules: [], valuePropName: 'checked' }]" v-decorator="['is_computed', { rules: [], valuePropName: 'checked' }]"
/> />
<ComputedArea <ComputedArea
@ -366,6 +351,7 @@
</template> </template>
<script> <script>
import _ from 'lodash'
import moment from 'moment' import moment from 'moment'
import vueJsonEditor from 'vue-json-editor' import vueJsonEditor from 'vue-json-editor'
import { import {
@ -434,6 +420,9 @@ export default {
wrapperCol: { span: 4 }, wrapperCol: { span: 4 },
} }
}, },
canDefineScript() {
return this.canDefineComputed
},
}, },
mounted() {}, mounted() {},
methods: { methods: {
@ -463,28 +452,30 @@ export default {
}) })
if (this.currentValueType === '2') { if (this.currentValueType === '2') {
this.form.setFieldsValue({ this.form.setFieldsValue({
is_password: false,
is_link: false,
is_index: true, is_index: true,
}) })
} }
} }
} }
if (checked && property === 'is_password') {
this.form.setFieldsValue({
is_link: false,
})
}
if (checked && property === 'is_link') {
this.form.setFieldsValue({
is_password: false,
})
}
if (property === 'is_list') { if (property === 'is_list') {
this.form.setFieldsValue({ this.form.setFieldsValue({
default_value: checked ? [] : '', default_value: checked ? [] : '',
}) })
} }
if (checked && property === 'is_sortable') {
this.$message.warning('选中排序,则必须也要选中!')
this.form.setFieldsValue({
is_required: true,
})
}
if (!checked && property === 'is_required' && this.form.getFieldValue('is_sortable')) {
this.$message.warning('选中排序,则必须也要选中!')
this.$nextTick(() => {
this.form.setFieldsValue({
is_required: true,
})
})
}
}, },
async handleEdit(record, attributes) { async handleEdit(record, attributes) {
@ -494,90 +485,91 @@ export default {
} catch { } catch {
this.canDefineComputed = false this.canDefineComputed = false
} }
const _record = _.cloneDeep(record)
if (_record.is_password) {
_record.value_type = '7'
}
if (_record.is_link) {
_record.value_type = '8'
}
this.drawerTitle = '编辑属性' this.drawerTitle = '编辑属性'
this.drawerVisible = true this.drawerVisible = true
this.record = record this.record = _record
this.currentValueType = record.value_type this.currentValueType = _record.value_type
this.$nextTick(() => { this.$nextTick(() => {
this.form.setFieldsValue({ this.form.setFieldsValue({
id: record.id, id: _record.id,
alias: record.alias, alias: _record.alias,
name: record.name, name: _record.name,
value_type: record.value_type, value_type: _record.value_type,
is_required: record.is_required, is_required: _record.is_required,
default_show: record.default_show, default_show: _record.default_show,
}) })
if (record.value_type !== '6') { if (!['6', '7'].includes(_record.value_type)) {
this.form.setFieldsValue({ this.form.setFieldsValue({
is_list: record.is_list, is_list: _record.is_list,
is_unique: record.is_unique, is_unique: _record.is_unique,
is_index: record.is_index, is_index: _record.is_index,
is_sortable: record.is_sortable, is_sortable: _record.is_sortable,
is_computed: record.is_computed, is_computed: _record.is_computed,
}) })
} }
if (record.value_type === '2') { console.log(_record)
this.form.setFieldsValue({ if (_record.default) {
is_password: record.is_password,
is_link: record.is_link,
})
}
console.log(record)
if (record.default) {
this.$nextTick(() => { this.$nextTick(() => {
if (record.value_type === '0') { if (_record.value_type === '0') {
this.form.setFieldsValue({ this.form.setFieldsValue({
default_value: record.default.default ? [record.default.default] : [], default_value: _record.default.default ? [_record.default.default] : [],
}) })
} else if (record.value_type === '6') { } else if (_record.value_type === '6') {
this.default_value_json = record?.default?.default || null this.default_value_json = _record?.default?.default || null
} else if (record.value_type === '3' || record.value_type === '4') { } else if (_record.value_type === '3' || _record.value_type === '4') {
if (record?.default?.default === '$created_at' || record?.default?.default === '$updated_at') { if (_record?.default?.default === '$created_at' || _record?.default?.default === '$updated_at') {
this.defaultForDatetime = record.default.default this.defaultForDatetime = _record.default.default
this.form.setFieldsValue({ this.form.setFieldsValue({
default_value: record?.default?.default, default_value: _record?.default?.default,
}) })
} else { } else {
this.defaultForDatetime = '$custom_time' this.defaultForDatetime = '$custom_time'
this.form.setFieldsValue({ this.form.setFieldsValue({
default_value: record.default && record.default.default ? moment(record.default.default) : null, default_value: _record.default && _record.default.default ? moment(_record.default.default) : null,
}) })
} }
} else { } else {
this.$nextTick(() => { this.$nextTick(() => {
this.form.setFieldsValue({ this.form.setFieldsValue({
default_value: record.default && record.default.default ? record.default.default : null, default_value: _record.default && _record.default.default ? _record.default.default : null,
}) })
}) })
} }
}) })
} else { } else {
this.default_value_json = {} this.default_value_json = {}
if (record.value_type === '0') { if (_record.value_type === '0') {
this.form.setFieldsValue({ this.form.setFieldsValue({
default_value: [], default_value: [],
}) })
} else if (record.value_type !== '6') { } else if (_record.value_type !== '6') {
this.form.setFieldsValue({ this.form.setFieldsValue({
default_value: null, default_value: null,
}) })
} }
} }
this.isShowComputedArea = record.is_computed this.isShowComputedArea = _record.is_computed
if (record.is_computed) { if (_record.is_computed) {
this.$nextTick(() => { this.$nextTick(() => {
this.$refs.computedArea.setData({ this.$refs.computedArea.setData({
compute_expr: record.compute_expr, compute_expr: _record.compute_expr,
compute_script: record.compute_script, compute_script: _record.compute_script,
}) })
}) })
} }
const _find = attributes.find((item) => item.id === record.id) const _find = attributes.find((item) => item.id === _record.id)
if (record.value_type !== '6') { if (!['6', '7'].includes(_record.value_type)) {
this.$refs.preValueArea.setData({ this.$refs.preValueArea.setData({
choice_value: (_find || {}).choice_value || [], choice_value: (_find || {}).choice_value || [],
choice_web_hook: record.choice_web_hook, choice_web_hook: _record.choice_web_hook,
choice_other: record.choice_other || undefined, choice_other: _record.choice_other || undefined,
}) })
} }
this.$refs.fontArea.setData({ this.$refs.fontArea.setData({
@ -633,13 +625,20 @@ export default {
values = { ...values, ...computedAreaData } values = { ...values, ...computedAreaData }
} else { } else {
// 如果是非计算属性就看看有没有预定义值 // 如果是非计算属性就看看有没有预定义值
if (values.value_type !== '6') { if (!['6', '7'].includes(values.value_type)) {
const preValueAreaData = this.$refs.preValueArea.getData() const preValueAreaData = this.$refs.preValueArea.getData()
values = { ...values, ...preValueAreaData } values = { ...values, ...preValueAreaData }
} }
} }
const fontOptions = this.$refs.fontArea.getData() const fontOptions = this.$refs.fontArea.getData()
if (values.value_type === '7') {
values.value_type = '2'
values.is_password = true
}
if (values.value_type === '8') {
values.value_type = '2'
values.is_link = true
}
if (values.id) { if (values.id) {
await this.updateAttribute(values.id, { ...values, option: { fontOptions } }, isCalcComputed) await this.updateAttribute(values.id, { ...values, option: { fontOptions } }, isCalcComputed)
} else { } else {
@ -660,7 +659,6 @@ export default {
handleOk() { handleOk() {
this.$emit('ok') this.$emit('ok')
}, },
handleChangeValueType(value) { handleChangeValueType(value) {
this.currentValueType = value this.currentValueType = value
this.$nextTick(() => { this.$nextTick(() => {

View File

@ -1,9 +1,14 @@
<template> <template>
<a-form :form="form" class="create-new-attribute"> <a-form
:form="form"
class="create-new-attribute"
:label-col="formItemLayout.labelCol"
:wrapper-col="formItemLayout.wrapperCol"
>
<a-divider style="font-size:14px;margin-top:6px;">基础设置</a-divider> <a-divider style="font-size:14px;margin-top:6px;">基础设置</a-divider>
<a-row> <a-row>
<a-col :span="12"> <a-col :span="12">
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="属性名(英文)"> <a-form-item label="属性名(英文)">
<a-input <a-input
name="name" name="name"
placeholder="英文" placeholder="英文"
@ -24,28 +29,33 @@
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="12"> <a-col :span="12">
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="别名"> <a-form-item label="别名">
<a-input name="alias" v-decorator="['alias', { rules: [] }]" /> <a-input name="alias" v-decorator="['alias', { rules: [] }]" />
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> </a-row>
<a-row> <a-row>
<a-col :span="12"> <a-col :span="12">
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="数据类型"> <a-form-item label="数据类型">
<a-select <a-select
name="value_type" name="value_type"
style="width: 100%" style="width: 100%"
v-decorator="['value_type', { rules: [{ required: true }], initialValue: '2' }]" v-decorator="['value_type', { rules: [{ required: true }], initialValue: '2' }]"
@change="handleChangeValueType" @change="handleChangeValueType"
> >
<a-select-option :value="key" :key="key" v-for="(value, key) in valueTypeMap">{{ value }}</a-select-option> <a-select-option :value="key" :key="key" v-for="(value, key) in valueTypeMap">
{{ value }}
<span class="value-type-des" v-if="key === '3'">yyyy-mm-dd HH:MM:SS</span>
<span class="value-type-des" v-if="key === '4'">yyyy-mm-dd</span>
<span class="value-type-des" v-if="key === '5'">HH:MM:SS</span>
</a-select-option>
</a-select> </a-select>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="currentValueType === '6' ? 24 : 12"> <a-col :span="currentValueType === '6' ? 24 : 12">
<a-form-item <a-form-item
:label-col="{ span: currentValueType === '6' ? 4 : 8 }" :label-col="{ span: currentValueType === '6' ? 4 : 8 }"
:wrapper-col="{ span: currentValueType === '6' ? 18 : 12 }" :wrapper-col="{ span: currentValueType === '6' ? 18 : 15 }"
label="默认值" label="默认值"
> >
<template> <template>
@ -74,7 +84,12 @@
</a-select> </a-select>
<a-input <a-input
style="width: 100%" style="width: 100%"
v-else-if="currentValueType === '2' || currentValueType === '5'" v-else-if="
currentValueType === '2' ||
currentValueType === '5' ||
currentValueType === '7' ||
currentValueType === '8'
"
v-decorator="['default_value', { rules: [{ required: false }] }]" v-decorator="['default_value', { rules: [{ required: false }] }]"
> >
</a-input> </a-input>
@ -140,13 +155,13 @@
label="必须" label="必须"
> >
<a-switch <a-switch
@change="onChange" @change="(checked) => onChange(checked, 'is_required')"
name="is_required" name="is_required"
v-decorator="['is_required', { rules: [], valuePropName: 'checked' }]" v-decorator="['is_required', { rules: [], valuePropName: 'checked' }]"
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="6" v-if="currentValueType !== '6'"> <a-col :span="6" v-if="currentValueType !== '6' && currentValueType !== '7'">
<a-form-item :label-col="{ span: 8 }" :wrapper-col="horizontalFormItemLayout.wrapperCol" label="唯一"> <a-form-item :label-col="{ span: 8 }" :wrapper-col="horizontalFormItemLayout.wrapperCol" label="唯一">
<a-switch <a-switch
:disabled="isShowComputedArea" :disabled="isShowComputedArea"
@ -216,7 +231,7 @@
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="6" v-if="currentValueType !== '6'"> <a-col :span="6" v-if="currentValueType !== '6' && currentValueType !== '7'">
<a-form-item <a-form-item
:label-col="currentValueType === '2' ? horizontalFormItemLayout.labelCol : { span: 8 }" :label-col="currentValueType === '2' ? horizontalFormItemLayout.labelCol : { span: 8 }"
:wrapper-col="horizontalFormItemLayout.wrapperCol" :wrapper-col="horizontalFormItemLayout.wrapperCol"
@ -224,14 +239,14 @@
> >
<a-switch <a-switch
:disabled="isShowComputedArea" :disabled="isShowComputedArea"
@change="onChange" @change="(checked) => onChange(checked, 'is_sortable')"
name="is_sortable" name="is_sortable"
v-decorator="['is_sortable', { rules: [], valuePropName: 'checked' }]" v-decorator="['is_sortable', { rules: [], valuePropName: 'checked' }]"
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="6" v-if="currentValueType !== '6'"> <a-col :span="6" v-if="currentValueType !== '6' && currentValueType !== '7'">
<a-form-item <a-form-item
:label-col="currentValueType === '2' ? { span: 8 } : horizontalFormItemLayout.labelCol" :label-col="currentValueType === '2' ? { span: 8 } : horizontalFormItemLayout.labelCol"
:wrapper-col="horizontalFormItemLayout.wrapperCol" :wrapper-col="horizontalFormItemLayout.wrapperCol"
@ -263,30 +278,6 @@
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="6" v-if="currentValueType === '2'">
<a-form-item
:label-col="horizontalFormItemLayout.labelCol"
:wrapper-col="horizontalFormItemLayout.wrapperCol"
label="密码"
>
<a-switch
:disabled="isShowComputedArea"
@change="(checked) => onChange(checked, 'is_password')"
name="is_password"
v-decorator="['is_password', { rules: [], valuePropName: 'checked' }]"
/>
</a-form-item>
</a-col>
<a-col :span="6" v-if="currentValueType === '2'">
<a-form-item :label-col="{ span: 8 }" :wrapper-col="horizontalFormItemLayout.wrapperCol" label="链接">
<a-switch
:disabled="isShowComputedArea"
@change="(checked) => onChange(checked, 'is_link')"
name="is_link"
v-decorator="['is_link', { rules: [], valuePropName: 'checked' }]"
/>
</a-form-item>
</a-col>
<a-divider style="font-size:14px;margin-top:6px;">高级设置</a-divider> <a-divider style="font-size:14px;margin-top:6px;">高级设置</a-divider>
<a-row> <a-row>
<a-col :span="24"> <a-col :span="24">
@ -294,12 +285,12 @@
<FontArea ref="fontArea" /> <FontArea ref="fontArea" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="24" v-if="currentValueType !== '6'"> <a-col :span="24" v-if="!['6', '7'].includes(currentValueType)">
<a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" label="预定义值"> <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" label="预定义值">
<PreValueArea ref="preValueArea" :disabled="isShowComputedArea" /> <PreValueArea ref="preValueArea" :canDefineScript="canDefineScript" :disabled="isShowComputedArea" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :span="24"> <a-col :span="24" v-if="!['6', '7'].includes(currentValueType)">
<a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }"> <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
<template slot="label"> <template slot="label">
<span <span
@ -327,7 +318,7 @@
<a-switch <a-switch
:disabled="!canDefineComputed" :disabled="!canDefineComputed"
@change="(checked) => onChange(checked, 'is_computed')" @change="(checked) => onChange(checked, 'is_computed')"
name="is_password" name="is_computed"
v-decorator="['is_computed', { rules: [], valuePropName: 'checked' }]" v-decorator="['is_computed', { rules: [], valuePropName: 'checked' }]"
/> />
<ComputedArea ref="computedArea" v-if="isShowComputedArea" :canDefineComputed="canDefineComputed" /> <ComputedArea ref="computedArea" v-if="isShowComputedArea" :canDefineComputed="canDefineComputed" />
@ -369,7 +360,7 @@ export default {
valueTypeMap, valueTypeMap,
formItemLayout: { formItemLayout: {
labelCol: { span: 8 }, labelCol: { span: 8 },
wrapperCol: { span: 12 }, wrapperCol: { span: 15 },
}, },
horizontalFormItemLayout: { horizontalFormItemLayout: {
labelCol: { span: 16 }, labelCol: { span: 16 },
@ -386,6 +377,11 @@ export default {
defaultForDatetime: '', defaultForDatetime: '',
} }
}, },
computed: {
canDefineScript() {
return this.canDefineComputed
},
},
methods: { methods: {
handleSubmit(isCloseModal = true) { handleSubmit(isCloseModal = true) {
this.form.validateFields(async (err, values) => { this.form.validateFields(async (err, values) => {
@ -428,7 +424,7 @@ export default {
values = { ...values, ...computedAreaData } values = { ...values, ...computedAreaData }
} else { } else {
// 如果是非计算属性就看看有没有预定义值 // 如果是非计算属性就看看有没有预定义值
if (values.value_type !== '6') { if (!['6', '7'].includes(values.value_type)) {
const preValueAreaData = this.$refs.preValueArea.getData() const preValueAreaData = this.$refs.preValueArea.getData()
values = { ...values, ...preValueAreaData } values = { ...values, ...preValueAreaData }
} }
@ -437,17 +433,25 @@ export default {
// is_index进行操作除了文本 索引隐藏掉 文本 索引默认是true // is_index进行操作除了文本 索引隐藏掉 文本 索引默认是true
// 框里的5种类型 is_index=true // 框里的5种类型 is_index=true
// json类型 is_index=false // json类型密码链接 is_index=false
if (values.value_type === '6') { if (['6', '7', '8'].includes(values.value_type)) {
values.is_index = false values.is_index = false
} else if (values.value_type !== '2') { } else if (values.value_type !== '2') {
values.is_index = true values.is_index = true
} }
if (values.value_type === '7') {
values.value_type = '2'
values.is_password = true
}
if (values.value_type === '8') {
values.value_type = '2'
values.is_link = true
}
const { attr_id } = await createAttribute({ ...values, option: { fontOptions } }) const { attr_id } = await createAttribute({ ...values, option: { fontOptions } })
this.form.resetFields() this.form.resetFields()
this.currentValueType = '2' this.currentValueType = '2'
if (values.value_type !== '6') { if (!['6'].includes(values.value_type) && !values.is_password) {
this.$refs.preValueArea.valueList = [] this.$refs.preValueArea.valueList = []
} }
this.$emit('done', attr_id, data, isCloseModal) this.$emit('done', attr_id, data, isCloseModal)
@ -485,29 +489,27 @@ export default {
is_index: false, is_index: false,
is_sortable: false, is_sortable: false,
}) })
if (this.currentValueType === '2') {
this.form.setFieldsValue({
is_password: false,
is_link: false,
})
}
} }
} }
if (checked && property === 'is_password') {
this.form.setFieldsValue({
is_link: false,
})
}
if (checked && property === 'is_link') {
this.form.setFieldsValue({
is_password: false,
})
}
if (property === 'is_list') { if (property === 'is_list') {
this.form.setFieldsValue({ this.form.setFieldsValue({
default_value: checked ? [] : '', default_value: checked ? [] : '',
}) })
} }
if (checked && property === 'is_sortable') {
this.$message.warning('选中排序,则必须也要选中!')
this.form.setFieldsValue({
is_required: true,
})
}
if (!checked && property === 'is_required' && this.form.getFieldValue('is_sortable')) {
this.$message.warning('选中排序,则必须也要选中!')
this.$nextTick(() => {
this.form.setFieldsValue({
is_required: true,
})
})
}
}, },
onJsonChange(value) { onJsonChange(value) {
this.default_value_json_right = true this.default_value_json_right = true
@ -548,4 +550,8 @@ export default {
background-color: #2f54eb; background-color: #2f54eb;
} }
} }
.value-type-des {
font-size: 10px;
color: #a9a9a9;
}
</style> </style>

View File

@ -1,91 +1,90 @@
<template> <template>
<a-tabs v-model="activeKey" size="small" :tabBarStyle="{ borderBottom: 'none' }"> <a-tabs v-model="activeKey" size="small" :tabBarStyle="{ borderBottom: 'none' }">
<a-tab-pane key="expr" :disabled="!canDefineComputed"> <a-tab-pane key="expr" :disabled="!canDefineComputed">
<span style="font-size:12px;" slot="tab">表达式</span> <span style="font-size:12px;" slot="tab">表达式</span>
<a-textarea v-model="compute_expr" :placeholder="`{{a}}+{{b}}`" :rows="2" :disabled="!canDefineComputed" /> <a-textarea v-model="compute_expr" :placeholder="`{{a}}+{{b}}`" :rows="2" :disabled="!canDefineComputed" />
</a-tab-pane> </a-tab-pane>
<a-tab-pane key="script" :disabled="!canDefineComputed"> <a-tab-pane key="script" :disabled="!canDefineComputed">
<span style="font-size:12px;" slot="tab">代码</span> <span style="font-size:12px;" slot="tab">代码</span>
<codemirror style="z-index: 9999" :options="cmOptions" v-model="compute_script"></codemirror> <codemirror style="z-index: 9999" :options="cmOptions" v-model="compute_script"></codemirror>
</a-tab-pane> </a-tab-pane>
<template slot="tabBarExtraContent" v-if="showCalcComputed"> <template slot="tabBarExtraContent" v-if="showCalcComputed">
<a-button type="primary" size="small" @click="handleCalcComputed"> <a-button type="primary" size="small" @click="handleCalcComputed">
应用 应用
</a-button> </a-button>
<a-tooltip title="所有CI触发计算"> <a-tooltip title="所有CI触发计算">
<a-icon type="question-circle" style="margin-left:5px" /> <a-icon type="question-circle" style="margin-left:5px" />
</a-tooltip> </a-tooltip>
</template> </template>
</a-tabs> </a-tabs>
</template> </template>
<script> <script>
import { codemirror } from 'vue-codemirror' import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css' import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/monokai.css' import 'codemirror/theme/monokai.css'
require('codemirror/mode/python/python.js') require('codemirror/mode/python/python.js')
export default { export default {
name: 'ComputedArea', name: 'ComputedArea',
components: { codemirror }, components: { codemirror },
props: { props: {
canDefineComputed: { canDefineComputed: {
type: Boolean, type: Boolean,
default: true, default: true,
}, },
showCalcComputed: { showCalcComputed: {
type: Boolean, type: Boolean,
default: false, default: false,
} },
}, },
data() { data() {
return { return {
activeKey: 'expr', // expr script activeKey: 'expr', // expr script
compute_expr: '', compute_expr: '',
compute_script: 'def computed(): \n return', compute_script: 'def computed(): \n return',
cmOptions: { cmOptions: {
lineNumbers: true, lineNumbers: true,
mode: 'python', mode: 'python',
height: '200px', height: '200px',
theme: 'monokai', theme: 'monokai',
smartIndent: true, tabSize: 4,
tabSize: 4, lineWrapping: true,
lineWrapping: true, readOnly: !this.canDefineComputed,
readOnly: !this.canDefineComputed, },
}, }
} },
}, methods: {
methods: { getData() {
getData() { const { activeKey, compute_expr, compute_script } = this
const { activeKey, compute_expr, compute_script } = this if (activeKey === 'expr') {
if (activeKey === 'expr') { return { compute_expr, compute_script: null }
return { compute_expr, compute_script: null } } else if (activeKey === 'script') {
} else if (activeKey === 'script') { return { compute_script, compute_expr: null }
return { compute_script, compute_expr: null } }
} },
}, setData(data) {
setData(data) { const { compute_expr, compute_script } = data
const { compute_expr, compute_script } = data this.compute_expr = compute_expr
this.compute_expr = compute_expr this.compute_script = compute_script || 'def computed(): \n return'
this.compute_script = compute_script || 'def computed(): \n return' if (compute_script) {
if (compute_script) { this.activeKey = 'script'
this.activeKey = 'script' } else {
} else { this.activeKey = 'expr'
this.activeKey = 'expr' }
} },
}, handleCalcComputed() {
handleCalcComputed() { const that = this
const that = this this.$confirm({
this.$confirm({ title: '警告',
title: '警告', content: `确认触发将保存当前配置及触发所有CI的计算`,
content: `确认触发将保存当前配置及触发所有CI的计算`, onOk() {
onOk() { that.$emit('handleCalcComputed')
that.$emit('handleCalcComputed') },
}, })
}) },
}, },
}, }
} </script>
</script>
<style></style>
<style></style>

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,11 @@
<template> <template>
<a-tabs id="preValueArea" v-model="activeKey" size="small" :tabBarStyle="{ borderBottom: 'none' }"> <a-tabs
id="preValueArea"
v-model="activeKey"
@change="changeActiveKey"
size="small"
:tabBarStyle="{ borderBottom: 'none' }"
>
<a-tab-pane key="define" :disabled="disabled"> <a-tab-pane key="define" :disabled="disabled">
<span style="font-size:12px;" slot="tab">定义</span> <span style="font-size:12px;" slot="tab">定义</span>
<PreValueTag type="add" :item="[]" @add="addNewValue" :disabled="disabled"> <PreValueTag type="add" :item="[]" @add="addNewValue" :disabled="disabled">
@ -170,6 +176,15 @@
</a-col> </a-col>
</a-row> </a-row>
</a-tab-pane> </a-tab-pane>
<a-tab-pane key="script" :disabled="disabled || !canDefineScript">
<span style="font-size:12px;" slot="tab">脚本</span>
<CustomCodeMirror
codeMirrorId="cmdb-pre-value"
ref="codemirror"
@changeCodeContent="changeCodeContent"
></CustomCodeMirror>
<!-- <codemirror style="z-index: 9999" :options="cmOptions" v-model="script"></codemirror> -->
</a-tab-pane>
</a-tabs> </a-tabs>
</template> </template>
@ -184,14 +199,22 @@ import { getCITypeGroups } from '../../api/ciTypeGroup'
import { getCITypeCommonAttributesByTypeIds } from '../../api/CITypeAttr' import { getCITypeCommonAttributesByTypeIds } from '../../api/CITypeAttr'
import FilterComp from '@/components/CMDBFilterComp' import FilterComp from '@/components/CMDBFilterComp'
import CustomCodeMirror from '@/components/CustomCodeMirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/monokai.css'
require('codemirror/mode/python/python.js')
export default { export default {
name: 'PreValueArea', name: 'PreValueArea',
components: { draggable, PreValueTag, ColorPicker, Webhook, FilterComp }, components: { draggable, PreValueTag, ColorPicker, Webhook, FilterComp, CustomCodeMirror },
props: { props: {
disabled: { disabled: {
type: Boolean, type: Boolean,
default: true, default: true,
}, },
canDefineScript: {
type: Boolean,
default: false,
},
}, },
data() { data() {
return { return {
@ -208,6 +231,17 @@ export default {
ciTypeGroup: [], ciTypeGroup: [],
typeAttrs: [], typeAttrs: [],
filterExp: '', filterExp: '',
script:
'class ChoiceValue(object):\n @staticmethod\n def values():\n """\n 执行入口, 返回预定义值\n :return: 返回一个列表, 值的类型同属性的类型\n 例如:\n return ["在线", "下线"]\n """\n return []',
cmOptions: {
lineNumbers: true,
mode: 'python',
height: '200px',
theme: 'monokai',
tabSize: 4,
lineWrapping: true,
readOnly: this.disabled || !this.canDefineScript,
},
} }
}, },
watch: { watch: {
@ -281,6 +315,14 @@ export default {
const choice_web_hook = this.$refs.webhook.getParams() const choice_web_hook = this.$refs.webhook.getParams()
choice_web_hook.ret_key = this.form.ret_key choice_web_hook.ret_key = this.form.ret_key
return { choice_value: [], choice_web_hook, choice_other: null } return { choice_value: [], choice_web_hook, choice_other: null }
} else if (this.activeKey === 'script') {
return {
choice_value: [],
choice_web_hook: null,
choice_other: {
script: this.script,
},
}
} else { } else {
let choice_other = {} let choice_other = {}
if (this.choice_other.type_ids && this.choice_other.type_ids.length) { if (this.choice_other.type_ids && this.choice_other.type_ids.length) {
@ -302,14 +344,22 @@ export default {
this.form.ret_key = choice_web_hook.ret_key ?? '' this.form.ret_key = choice_web_hook.ret_key ?? ''
}) })
} else if (choice_other) { } else if (choice_other) {
this.activeKey = 'choice_other' if (choice_other.script) {
const { type_ids, attr_id, filter } = choice_other this.activeKey = 'script'
this.choice_other = { type_ids, attr_id } this.script = choice_other.script
this.filterExp = filter
if (type_ids && type_ids.length) {
this.$nextTick(() => { this.$nextTick(() => {
this.$refs.filterComp.visibleChange(true, false) this.$refs.codemirror.initCodeMirror(choice_other.script)
}) })
} else {
this.activeKey = 'choice_other'
const { type_ids, attr_id, filter } = choice_other
this.choice_other = { type_ids, attr_id }
this.filterExp = filter
if (type_ids && type_ids.length) {
this.$nextTick(() => {
this.$refs.filterComp.visibleChange(true, false)
})
}
} }
} else { } else {
this.valueList = choice_value this.valueList = choice_value
@ -330,6 +380,16 @@ export default {
this.filterExp = '' this.filterExp = ''
} }
}, },
changeCodeContent(value) {
this.script = value && value.replace('\t', ' ')
},
changeActiveKey(value) {
if (value === 'script') {
this.$nextTick(() => {
this.$refs.codemirror.initCodeMirror(this.script)
})
}
},
}, },
} }
</script> </script>

File diff suppressed because it is too large Load Diff

View File

@ -1,345 +1,344 @@
<template> <template>
<CustomDrawer width="800px" :title="title" :visible="visible" @close="handleClose"> <CustomDrawer width="800px" :title="title" :visible="visible" @close="handleClose">
<template v-if="adType === 'agent'"> <template v-if="adType === 'agent'">
<a-form-model <a-form-model
ref="autoDiscoveryForm" ref="autoDiscoveryForm"
:model="form" :model="form"
:rules="rules" :rules="rules"
:label-col="{ span: 2 }" :label-col="{ span: 2 }"
:wrapper-col="{ span: 20 }" :wrapper-col="{ span: 20 }"
> >
<a-divider :style="{ margin: '5px 0' }">基础设置</a-divider> <a-divider :style="{ margin: '5px 0' }">基础设置</a-divider>
<a-form-model-item label="名称" prop="name"> <a-form-model-item label="名称" prop="name">
<a-input v-model="form.name" /> <a-input v-model="form.name" />
</a-form-model-item> </a-form-model-item>
<a-form-model-item label="图标" v-if="is_inner"> <a-form-model-item label="图标" v-if="is_inner">
<CustomIconSelect v-model="customIcon" :style="{ marginTop: '6px' }" /> <CustomIconSelect v-model="customIcon" :style="{ marginTop: '6px' }" />
</a-form-model-item> </a-form-model-item>
<a-form-model-item label="模式" prop="is_plugin"> <a-form-model-item label="模式" prop="is_plugin">
<a-radio-group v-model="form.is_plugin" @change="changeIsPlugin" :disabled="!is_inner"> <a-radio-group v-model="form.is_plugin" @change="changeIsPlugin" :disabled="!is_inner">
<a-radio :value="false">默认</a-radio> <a-radio :value="false">默认</a-radio>
<a-radio :value="true">plugin</a-radio> <a-radio :value="true">plugin</a-radio>
</a-radio-group> </a-radio-group>
</a-form-model-item> </a-form-model-item>
</a-form-model> </a-form-model>
<a-divider :style="{ margin: '5px 0' }">采集设置</a-divider> <a-divider :style="{ margin: '5px 0' }">采集设置</a-divider>
<CustomCodeMirror <CustomCodeMirror
codeMirrorId="cmdb-adt" codeMirrorId="cmdb-adt"
v-if="form.is_plugin" v-if="form.is_plugin"
ref="codemirror" ref="codemirror"
@changeCodeContent="changeCodeContent" @changeCodeContent="changeCodeContent"
></CustomCodeMirror> ></CustomCodeMirror>
<div style="margin:10px 0;text-align:right;"> <div style="margin:10px 0;text-align:right;">
<a-button <a-button
v-show="form.is_plugin" v-show="form.is_plugin"
size="small" size="small"
type="primary" type="primary"
ghost ghost
@click="handleSubmit(true)" @click="handleSubmit(true)"
>更新字段</a-button >更新字段</a-button
> >
</div> </div>
<a-button <a-button
v-show="!form.is_plugin" v-show="!form.is_plugin"
size="small" size="small"
type="primary" type="primary"
ghost ghost
icon="plus" icon="plus"
:style="{ marginBottom: '10px' }" :style="{ marginBottom: '10px' }"
@click="insertEvent(-1)" @click="insertEvent(-1)"
>新增</a-button >新增</a-button
> >
<vxe-table <vxe-table
size="mini" size="mini"
stripe stripe
class="ops-stripe-table" class="ops-stripe-table"
show-overflow show-overflow
keep-source keep-source
ref="xTable" ref="xTable"
max-height="400" max-height="400"
:data="tableData" :data="tableData"
:edit-config="{ trigger: 'manual', mode: 'row' }" :edit-config="{ trigger: 'manual', mode: 'row' }"
> >
<vxe-column field="name" title="名称" :edit-render="{ autofocus: '.vxe-input--inner' }"> <vxe-column field="name" title="名称" :edit-render="{ autofocus: '.vxe-input--inner' }">
<template #edit="{ row }"> <template #edit="{ row }">
<vxe-input v-model="row.name" type="text"></vxe-input> <vxe-input v-model="row.name" type="text"></vxe-input>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="type" title="类型" :edit-render="{}"> <vxe-column field="type" title="类型" :edit-render="{}">
<template #edit="{ row }"> <template #edit="{ row }">
<vxe-select v-model="row.type" transfer> <vxe-select v-model="row.type" transfer>
<vxe-option v-for="item in typeList" :key="item" :value="item" :label="item"></vxe-option> <vxe-option v-for="item in typeList" :key="item" :value="item" :label="item"></vxe-option>
</vxe-select> </vxe-select>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column field="desc" title="描述" :edit-render="{ autofocus: '.vxe-input--inner' }"> <vxe-column field="desc" title="描述" :edit-render="{ autofocus: '.vxe-input--inner' }">
<template #edit="{ row }"> <template #edit="{ row }">
<vxe-input v-model="row.desc" type="text"></vxe-input> <vxe-input v-model="row.desc" type="text"></vxe-input>
</template> </template>
</vxe-column> </vxe-column>
<vxe-column title="操作" width="60" v-if="!form.is_plugin"> <vxe-column title="操作" width="60" v-if="!form.is_plugin">
<template #default="{ row }"> <template #default="{ row }">
<a-space v-if="$refs.xTable.isActiveByRow(row)"> <a-space v-if="$refs.xTable.isActiveByRow(row)">
<a @click="saveRowEvent(row)"><a-icon type="save"/></a> <a @click="saveRowEvent(row)"><a-icon type="save"/></a>
<a @click="cancelRowEvent(row)"><a-icon type="close"/></a> <a @click="cancelRowEvent(row)"><a-icon type="close"/></a>
</a-space> </a-space>
<a-space v-else> <a-space v-else>
<a @click="editRowEvent(row)"><a-icon type="edit"/></a> <a @click="editRowEvent(row)"><a-icon type="edit"/></a>
<a :style="{ color: 'red' }" @click="deleteRowEvent(row)"><a-icon type="delete"/></a> <a :style="{ color: 'red' }" @click="deleteRowEvent(row)"><a-icon type="delete"/></a>
</a-space> </a-space>
</template> </template>
</vxe-column> </vxe-column>
</vxe-table> </vxe-table>
<div class="custom-drawer-bottom-action"> <div class="custom-drawer-bottom-action">
<a-button @click="handleClose">取消</a-button> <a-button @click="handleClose">取消</a-button>
<a-button @click="handleSubmit(false)" type="primary">保存</a-button> <a-button @click="handleSubmit(false)" type="primary">保存</a-button>
</div> </div>
</template> </template>
<template v-else> <template v-else>
<HttpSnmpAD ref="httpSnmpAd" :ruleType="adType" :ruleName="ruleData.name" /> <HttpSnmpAD ref="httpSnmpAd" :ruleType="adType" :ruleName="ruleData.name" />
</template> </template>
</CustomDrawer> </CustomDrawer>
</template> </template>
<script> <script>
import CustomIconSelect from '@/components/CustomIconSelect' import CustomIconSelect from '@/components/CustomIconSelect'
import { postDiscovery, putDiscovery } from '../../api/discovery' import { postDiscovery, putDiscovery } from '../../api/discovery'
import HttpSnmpAD from '../../components/httpSnmpAD' import HttpSnmpAD from '../../components/httpSnmpAD'
import CustomCodeMirror from '@/components/CustomCodeMirror' import CustomCodeMirror from '@/components/CustomCodeMirror'
import 'codemirror/lib/codemirror.css' import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/monokai.css' import 'codemirror/theme/monokai.css'
export default { export default {
name: 'EditDrawer', name: 'EditDrawer',
components: { CustomIconSelect, CustomCodeMirror, HttpSnmpAD }, components: { CustomIconSelect, CustomCodeMirror, HttpSnmpAD },
props: { props: {
is_inner: { is_inner: {
type: Boolean, type: Boolean,
default: true, default: true,
}, },
}, },
data() { data() {
const default_plugin_script = `# -*- coding:utf-8 -*- const default_plugin_script = `# -*- coding:utf-8 -*-
import json import json
class AutoDiscovery(object): class AutoDiscovery(object):
@property @property
def unique_key(self): def unique_key(self):
""" """
:return: 返回唯一属性的名字 :return: 返回唯一属性的名字
""" """
return return
@staticmethod @staticmethod
def attributes(): def attributes():
""" """
定义属性字段 定义属性字段
:return: 返回属性字段列表, 列表项是(名称, 类型, 描述), 名称必须是英文 :return: 返回属性字段列表, 列表项是(名称, 类型, 描述), 名称必须是英文
类型: String Integer Float Date DateTime Time JSON 类型: String Integer Float Date DateTime Time JSON
例如: 例如:
return [ return [
("ci_type", "String", "模型名称"), ("ci_type", "String", "模型名称"),
("private_ip", "String", "内网IP, 多值逗号分隔") ("private_ip", "String", "内网IP, 多值逗号分隔")
] ]
""" """
return [] return []
@staticmethod @staticmethod
def run(): def run():
""" """
执行入口, 返回采集的属性值 执行入口, 返回采集的属性值
:return: 返回一个列表, 列表项是字典, 字典key是属性名称, value是属性值 :return: 返回一个列表, 列表项是字典, 字典key是属性名称, value是属性值
例如: 例如:
return [dict(ci_type="server", private_ip="192.168.1.1")] return [dict(ci_type="server", private_ip="192.168.1.1")]
""" """
return [] return []
if __name__ == "__main__": if __name__ == "__main__":
result = AutoDiscovery().run() result = AutoDiscovery().run()
if isinstance(result, list): if isinstance(result, list):
print("AutoDiscovery::Result::{}".format(json.dumps(result))) print("AutoDiscovery::Result::{}".format(json.dumps(result)))
else: else:
print("ERROR: 采集返回必须是列表") print("ERROR: 采集返回必须是列表")
` `
const typeList = ['String', 'Integer', 'Float', 'Date', 'DateTime', 'Time', 'JSON'] const typeList = ['String', 'Integer', 'Float', 'Date', 'DateTime', 'Time', 'JSON']
return { return {
default_plugin_script, default_plugin_script,
typeList, typeList,
visible: false, visible: false,
ruleData: {}, ruleData: {},
type: 'add', type: 'add',
adType: '', adType: '',
form: { name: '', is_plugin: false }, form: { name: '', is_plugin: false },
rules: {}, rules: {},
customIcon: { name: '', color: '' }, customIcon: { name: '', color: '' },
tableData: [], tableData: [],
editDefaultTableData: [], editDefaultTableData: [],
plugin_script: '', plugin_script: '',
cmOptions: { cmOptions: {
lineNumbers: true, lineNumbers: true,
mode: 'python', mode: 'python',
height: '200px', height: '200px',
theme: 'monokai', theme: 'monokai',
smartIndent: true, tabSize: 4,
tabSize: 4, lineWrapping: true,
lineWrapping: true, },
}, }
} },
}, computed: {
computed: { title() {
title() { if (this.adType === 'http' || this.adType === 'snmp') {
if (this.adType === 'http' || this.adType === 'snmp') { return this.ruleData.name
return this.ruleData.name }
} if (this.type === 'edit') {
if (this.type === 'edit') { return `编辑${this.ruleData.name}`
return `编辑${this.ruleData.name}` }
} return '新建'
return '新建' },
}, },
}, inject: {
inject: { getDiscovery: {
getDiscovery: { from: 'getDiscovery',
from: 'getDiscovery', default: () => {},
default: () => {}, },
}, },
}, methods: {
methods: { open(data, type, adType) {
open(data, type, adType) { this.visible = true
this.visible = true this.type = type
this.type = type this.ruleData = data
this.ruleData = data this.adType = adType
this.adType = adType if (!this.is_inner) {
if (!this.is_inner) { this.form = {
this.form = { name: '',
name: '', is_plugin: true,
is_plugin: true, }
} }
} if (adType === 'http' || adType === 'snmp') {
if (adType === 'http' || adType === 'snmp') { return
return }
} this.$nextTick(() => {
this.$nextTick(() => { if (this.type === 'edit') {
if (this.type === 'edit') { this.form = {
this.form = { name: data.name,
name: data.name, is_plugin: data.is_plugin,
is_plugin: data.is_plugin, }
} this.customIcon = data?.option?.icon ?? { name: 'caise-chajian', color: '' }
this.customIcon = data?.option?.icon ?? { name: 'caise-chajian', color: '' } this.tableData = data?.attributes ?? []
this.tableData = data?.attributes ?? [] this.editDefaultTableData = data?.attributes ?? []
this.editDefaultTableData = data?.attributes ?? [] this.plugin_script = data?.plugin_script ?? this.default_plugin_script
this.plugin_script = data?.plugin_script ?? this.default_plugin_script }
} if (this.type === 'add') {
if (this.type === 'add') { this.customIcon = { name: 'caise-chajian', color: '' }
this.customIcon = { name: 'caise-chajian', color: '' } // eslint-disable-next-line no-useless-escape
// eslint-disable-next-line no-useless-escape this.plugin_script = this.default_plugin_script
this.plugin_script = this.default_plugin_script }
} if (data?.is_plugin || !this.is_inner) {
if (data?.is_plugin || !this.is_inner) { this.$nextTick(() => {
this.$nextTick(() => { this.$refs.codemirror.initCodeMirror(this.plugin_script)
this.$refs.codemirror.initCodeMirror(this.plugin_script) })
}) }
} })
}) },
}, handleClose() {
handleClose() { this.tableData = []
this.tableData = [] this.customIcon = { name: '', color: '' }
this.customIcon = { name: '', color: '' } this.form = { name: '', is_plugin: false }
this.form = { name: '', is_plugin: false } if (this.adType === 'agent') {
if (this.adType === 'agent') { this.$refs.autoDiscoveryForm.clearValidate()
this.$refs.autoDiscoveryForm.clearValidate() } else {
} else { // this.$refs.httpSnmpAd.currentCate = ''
// this.$refs.httpSnmpAd.currentCate = '' }
} this.visible = false
this.visible = false },
}, async insertEvent(row) {
async insertEvent(row) { const $table = this.$refs.xTable
const $table = this.$refs.xTable const record = {}
const record = {} const { row: newRow } = await $table.insertAt(record, row)
const { row: newRow } = await $table.insertAt(record, row) await $table.setEditRow(newRow)
await $table.setEditRow(newRow) },
}, editRowEvent(row) {
editRowEvent(row) { const $table = this.$refs.xTable
const $table = this.$refs.xTable $table.setActiveRow(row)
$table.setActiveRow(row) },
}, saveRowEvent() {
saveRowEvent() { const $table = this.$refs.xTable
const $table = this.$refs.xTable $table.clearActived().then(() => {
$table.clearActived().then(() => { this.loading = true
this.loading = true setTimeout(() => {
setTimeout(() => { this.loading = false
this.loading = false }, 300)
}, 300) })
}) },
}, cancelRowEvent(row) {
cancelRowEvent(row) { const $table = this.$refs.xTable
const $table = this.$refs.xTable $table.clearActived().then(() => {
$table.clearActived().then(() => { // 还原行数据
// 还原行数据 $table.revertData(row)
$table.revertData(row) })
}) },
}, deleteRowEvent(row) {
deleteRowEvent(row) { const $table = this.$refs.xTable
const $table = this.$refs.xTable $table.remove(row)
$table.remove(row) },
}, async handleSubmit(isUpdateAttr = false) {
async handleSubmit(isUpdateAttr = false) { const $table = this.$refs.xTable
const $table = this.$refs.xTable const { fullData: _tableData } = $table.getTableData()
const { fullData: _tableData } = $table.getTableData() console.log(_tableData)
console.log(_tableData) const params = {
const params = { ...this.form,
...this.form, type: this.adType,
type: this.adType, is_inner: this.is_inner,
is_inner: this.is_inner, option: { icon: this.customIcon },
option: { icon: this.customIcon }, attributes: this.form.is_plugin
attributes: this.form.is_plugin ? undefined
? undefined : _tableData.map(({ name, alias, desc, type }) => {
: _tableData.map(({ name, alias, desc, type }) => { return { name, alias, desc, type }
return { name, alias, desc, type } }),
}), plugin_script: this.form.is_plugin ? this.plugin_script : undefined,
plugin_script: this.form.is_plugin ? this.plugin_script : undefined, }
} let res
let res if (this.type === 'add') {
if (this.type === 'add') { res = await postDiscovery(params)
res = await postDiscovery(params) } else {
} else { res = await putDiscovery(this.ruleData.id, params)
res = await putDiscovery(this.ruleData.id, params) }
} if (isUpdateAttr) {
if (isUpdateAttr) { this.tableData = res.attributes
this.tableData = res.attributes this.type = 'edit'
this.type = 'edit' this.ruleData = res
this.ruleData = res this.$message.success('更新成功!')
this.$message.success('更新成功!') if (this.is_inner) {
if (this.is_inner) { this.getDiscovery()
this.getDiscovery() }
} return
return }
} this.handleClose()
this.handleClose() console.log(this.is_inner)
console.log(this.is_inner) if (this.is_inner) {
if (this.is_inner) { this.$message.success('保存成功!')
this.$message.success('保存成功!') this.getDiscovery()
this.getDiscovery() } else {
} else { this.$emit('updateNotInner', res)
this.$emit('updateNotInner', res) }
} },
}, changeIsPlugin(e) {
changeIsPlugin(e) { if (e.target.value) {
if (e.target.value) { this.$nextTick(() => {
this.$nextTick(() => { this.$refs.codemirror.initCodeMirror(this.plugin_script)
this.$refs.codemirror.initCodeMirror(this.plugin_script) })
}) }
} },
}, changeCodeContent(value) {
changeCodeContent(value) { this.plugin_script = value && value.replace('\t', ' ')
this.plugin_script = value && value.replace('\t', ' ') },
}, },
}, }
} </script>
</script>
<style></style>
<style></style>

View File

@ -25,7 +25,7 @@
:expandedKeys="expandedKeys" :expandedKeys="expandedKeys"
> >
<a-icon slot="switcherIcon" type="down" /> <a-icon slot="switcherIcon" type="down" />
<template #title="{ key: treeKey, title, isLeaf }"> <template #title="{ key: treeKey, title,isLeaf }">
<ContextMenu <ContextMenu
:title="title" :title="title"
:treeKey="treeKey" :treeKey="treeKey"
@ -135,7 +135,8 @@
{{ col.title }}</span {{ col.title }}</span
> >
</template> </template>
<template v-if="col.is_choice" #edit="{ row }"> <template v-if="col.is_choice || col.is_password" #edit="{ row }">
<vxe-input v-if="col.is_password" v-model="passwordValue[col.field]" />
<a-select <a-select
:getPopupContainer="(trigger) => trigger.parentElement" :getPopupContainer="(trigger) => trigger.parentElement"
:style="{ width: '100%', height: '32px' }" :style="{ width: '100%', height: '32px' }"
@ -177,10 +178,20 @@
#default="{row}" #default="{row}"
> >
<span v-if="col.value_type === '6' && row[col.field]">{{ row[col.field] }}</span> <span v-if="col.value_type === '6' && row[col.field]">{{ row[col.field] }}</span>
<a v-else-if="col.is_link" :href="`${row[col.field]}`" target="_blank">{{ row[col.field] }}</a> <a
v-else-if="col.is_link && row[col.field]"
:href="
row[col.field].startsWith('http') || row[col.field].startsWith('https')
? `${row[col.field]}`
: `http://${row[col.field]}`
"
target="_blank"
>{{ row[col.field] }}</a
>
<PasswordField <PasswordField
v-else-if="col.is_password && row[col.field]" v-else-if="col.is_password && row[col.field]"
:password="row[col.field]" :ci_id="row._id"
:attr_id="col.attr_id"
></PasswordField> ></PasswordField>
<template v-else-if="col.is_choice"> <template v-else-if="col.is_choice">
<template v-if="col.is_list"> <template v-if="col.is_list">
@ -333,7 +344,7 @@ import {
} from '@/modules/cmdb/api/CIRelation' } from '@/modules/cmdb/api/CIRelation'
import { getCITypeAttributesById } from '@/modules/cmdb/api/CITypeAttr' import { getCITypeAttributesById } from '@/modules/cmdb/api/CITypeAttr'
import { searchCI2, updateCI, deleteCI } from '@/modules/cmdb/api/ci' import { searchCI2, updateCI, deleteCI, searchCI } from '@/modules/cmdb/api/ci'
import { getCITypes } from '../../api/CIType' import { getCITypes } from '../../api/CIType'
import { roleHasPermissionToGrant } from '@/modules/acl/api/permission' import { roleHasPermissionToGrant } from '@/modules/acl/api/permission'
import { searchResourceType } from '@/modules/acl/api/resource' import { searchResourceType } from '@/modules/acl/api/resource'
@ -347,6 +358,7 @@ import PasswordField from '../../components/passwordField/index.vue'
import PreferenceSearch from '../../components/preferenceSearch/preferenceSearch.vue' import PreferenceSearch from '../../components/preferenceSearch/preferenceSearch.vue'
import CMDBGrant from '../../components/cmdbGrant' import CMDBGrant from '../../components/cmdbGrant'
import { ops_move_icon as OpsMoveIcon } from '@/core/icons' import { ops_move_icon as OpsMoveIcon } from '@/core/icons'
import { getAttrPassword } from '../../api/CITypeAttr'
export default { export default {
name: 'RelationViews', name: 'RelationViews',
@ -407,6 +419,11 @@ export default {
tableDragClassName: [], tableDragClassName: [],
resource_type: {}, resource_type: {},
initialPasswordValue: {},
passwordValue: {},
lastEditCiId: null,
isContinueCloseEdit: true,
} }
}, },
@ -890,6 +907,12 @@ export default {
calcColumns() { calcColumns() {
const width = document.getElementById('relation-views-right').clientWidth const width = document.getElementById('relation-views-right').clientWidth
this.columns = getCITableColumns(this.instanceList, this.preferenceAttrList, width) this.columns = getCITableColumns(this.instanceList, this.preferenceAttrList, width)
this.columns.forEach((col) => {
if (col.is_password) {
this.initialPasswordValue[col.field] = ''
this.passwordValue[col.field] = ''
}
})
this.$nextTick(() => { this.$nextTick(() => {
this.$refs.xTable.refreshColumn() this.$refs.xTable.refreshColumn()
}) })
@ -1076,15 +1099,47 @@ export default {
} }
return _editRender return _editRender
}, },
handleEditActived() {}, handleEditActived() {
const passwordCol = this.columns.filter((col) => col.is_password)
this.$nextTick(() => {
const editRecord = this.$refs.xTable.getVxetableRef().getEditRecord()
const { row, column } = editRecord
if (passwordCol.length && this.lastEditCiId !== row._id) {
this.$nextTick(async () => {
for (let i = 0; i < passwordCol.length; i++) {
await getAttrPassword(row._id, passwordCol[i].attr_id).then((res) => {
this.initialPasswordValue[passwordCol[i].field] = res.value
this.passwordValue[passwordCol[i].field] = res.value
})
}
this.isContinueCloseEdit = false
await this.$refs.xTable.getVxetableRef().clearEdit()
this.isContinueCloseEdit = true
this.$nextTick(() => {
this.$refs.xTable.getVxetableRef().setEditCell(row, column.field)
})
})
}
this.lastEditCiId = row._id
})
},
handleEditClose({ row, rowIndex, column }) { handleEditClose({ row, rowIndex, column }) {
if (!this.isContinueCloseEdit) {
return
}
const $table = this.$refs['xTable'] const $table = this.$refs['xTable']
const data = {} const data = {}
this.columns.forEach((item) => { this.columns.forEach((item) => {
if (!_.isEqual(row[item.field], this.initialInstanceList[rowIndex][item.field])) { if (!_.isEqual(row[item.field], this.initialInstanceList[rowIndex][item.field])) {
data[item.field] = row[item.field] || null data[item.field] = row[item.field] ?? null
} }
}) })
Object.keys(this.initialPasswordValue).forEach((key) => {
if (this.initialPasswordValue[key] !== this.passwordValue[key]) {
data[key] = this.passwordValue[key]
}
})
this.lastEditCiId = null
if (JSON.stringify(data) !== '{}') { if (JSON.stringify(data) !== '{}') {
updateCI(row.ci_id || row._id, data) updateCI(row.ci_id || row._id, data)
.then(() => { .then(() => {
@ -1102,6 +1157,12 @@ export default {
$table.revertData(row) $table.revertData(row)
}) })
} }
this.columns.forEach((col) => {
if (col.is_password) {
this.initialPasswordValue[col.field] = ''
this.passwordValue[col.field] = ''
}
})
}, },
deleteCI(record) { deleteCI(record) {
const that = this const that = this

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff