Unverified Commit 3a8fad7c authored by 老广's avatar 老广 Committed by GitHub

[Update] 修复页面bug和popover的问题 (#3219)

* [Update] 修复页面bug和popover的问题

* [Update] 修改asset modal table

* [Update] 修改翻译

* [Update] 修改id cache api mixin

* [Update] 去掉asset permission中不用的代码
parents 6ef06869 df9ef230
......@@ -33,11 +33,16 @@ class AssetCreateForm(OrgModelForm):
return
nodes_field = self.fields['nodes']
if self.instance:
nodes_field.choices = ((n.id, n.full_value) for n in
self.instance.nodes.all())
nodes_field.choices = [(n.id, n.full_value) for n in
self.instance.nodes.all()]
else:
nodes_field.choices = []
def add_nodes_initial(self, node):
nodes_field = self.fields['nodes']
nodes_field.choices.append((node.id, node.full_value))
nodes_field.initial = [node]
class Meta:
model = Asset
fields = [
......
......@@ -37,19 +37,22 @@ class TreeMixin:
def tree(cls):
from ..utils import TreeService
tree_updated_time = cache.get(cls.tree_updated_time_cache_key, 0)
now = time.time()
# 什么时候重新初始化 _tree_service
if not cls.tree_created_time or \
tree_updated_time > cls.tree_created_time:
logger.debug("Create node tree")
tree = TreeService.new()
cls.tree_created_time = time.time()
cls.tree_assets_created_time = time.time()
cls.tree_created_time = now
cls.tree_assets_created_time = now
cls._tree_service = tree
return tree
# 是否要重新初始化节点资产
node_assets_updated_time = cache.get(cls.tree_assets_cache_key, 0)
if not cls.tree_assets_created_time or \
node_assets_updated_time > cls.tree_assets_created_time:
cls._tree_service.init_assets_async()
cls.tree_assets_created_time = time.time()
cls._tree_service.init_assets()
cls.tree_assets_created_time = now
logger.debug("Refresh node tree assets")
return cls._tree_service
......
......@@ -15,11 +15,11 @@
text-align: center;
}
#assetTree2.ztree * {
background-color: #f8fafb;
#asset_modal_tree.ztree * {
background-color: white;
}
#assetTree2.ztree {
background-color: #f8fafb;
#asset_modal_tree.ztree {
background-color: white;
}
</style>
......@@ -29,7 +29,8 @@
<div class="ibox float-e-margins">
<div class="ibox-content mailbox-content" style="padding-top: 0;padding-left: 1px">
<div class="file-manager ">
<div id="assetTree2" class="ztree">
<div id="asset_modal_tree" class="ztree">
{% trans 'Loading' %} ...
</div>
<div class="clearfix"></div>
</div>
......@@ -55,12 +56,77 @@
</div>
<script>
var zTree2, asset_table2 = 0;
function initTable2() {
if(asset_table2){
return
function syncTableSelectedAssetToSelect2(table) {
var assets = table.selected;
var options = [];
var select2Id = assetModalOption.select2Id;
$(select2Id + ' option').each(function (i, v) {
options.push(v.value)
});
table.selected_rows.forEach(function (i) {
var name = i.hostname + '(' + i.ip + ')';
var option = new Option(name, i.id, false, true);
if (options.indexOf(i.id) === -1) {
$(select2Id).append(option).trigger('change');
}
});
$(select2Id).val(assets).trigger('change');
}
// 解决input框中的资产和弹出表格中资产的显示不一致
function syncSelectedAssetsToModalTable(assetModalTable) {
var select2Id = assetModalOption.select2Id;
var inputAssets = $(select2Id).val();
var selectedAssets = assetModalTable.selected.concat();
// input assets无,table assets选中,则取消勾选(再次click)
if (selectedAssets.length !== 0) {
$.each(selectedAssets, function (index, assetId) {
if ($.inArray(assetId, inputAssets) === -1) {
$('#' + assetId).trigger('click'); // 取消勾选
}
});
}
// input assets有,table assets没选,则选中(click)
if (inputAssets !== null) {
assetModalTable.selected = inputAssets;
$.each(inputAssets, function (index, assetId) {
var dom = document.getElementById(assetId);
if (dom !== null) {
var selected = dom.parentElement.parentElement.className.indexOf('selected')
}
if (selected === -1) {
$('#' + assetId).trigger('click');
}
});
}
}
defaultOnAssetModalConfirm = syncTableSelectedAssetToSelect2;
defaultOnModalTableDone = syncSelectedAssetsToModalTable;
var assetModalOption = {
selectStyle: 'multi',
select2Id: '#id_assets',
onModalTableDone: defaultOnModalTableDone,
onModalTreeDone: null,
onModalConfirm: defaultOnAssetModalConfirm,
};
var assetModalTable, assetModalTree = null;
function initAssetModalTable() {
if(assetModalTable){
return
}
if (assetModalOption.selectStyle === 'single') {
$('.ipt_check_all').addClass('hidden')
}
var options = {
ele: $('#asset_list_modal_table'),
ajax_url: '{% url "api-assets:asset-list" %}?show_current_asset=1',
......@@ -68,22 +134,26 @@ function initTable2() {
{data: "id"}, {data: "hostname" }, {data: "ip" }
],
lengthMenu: [[10, 25, 50], [10, 25, 50]],
pageLength: 10
pageLength: 10,
select_style: assetModalOption.selectStyle
};
asset_table2 = jumpserver.initServerSideDataTable(options);
return asset_table2
assetModalTable = jumpserver.initServerSideDataTable(options);
if (assetModalOption.onModalTableDone) {
assetModalOption.onModalTableDone(assetModalTable);
}
return assetModalTable
}
function onNodeSelected2(event, treeNode) {
var url = asset_table2.ajax.url();
function onModalTreeNodeSelected(event, treeNode) {
var url = assetModalTable.ajax.url();
url = setUrlParam(url, "node_id", treeNode.meta.node.id);
url = setUrlParam(url, "show_current_asset", "");
asset_table2.ajax.url(url);
asset_table2.ajax.reload();
assetModalTable.ajax.url(url);
assetModalTable.ajax.reload();
}
function initTree2() {
function initModalTree() {
var url = '{% url 'api-assets:node-children-tree' %}?assets=0';
var setting = {
view: {
......@@ -102,17 +172,34 @@ function initTree2() {
type: 'get'
},
callback: {
onSelected: onNodeSelected2
onSelected: onModalTreeNodeSelected
}
};
zTree2 = $.fn.zTree.init($("#assetTree2"), setting);
$.get(url, function(data, status){
$.fn.zTree.init($("#asset_modal_tree"), setting);
assetModalTree = $.fn.zTree.getZTreeObj("assetTree2");
if (assetModalOption.onModalTreeDone) {
assetModalOption.onModalTreeDone(assetModalTree);
}
return assetModalTree;
});
}
function setAssetModalOptions(options) {
assetModalOption = options;
}
$(document).ready(function(){
}).on('show.bs.modal', function () {
initTable2();
initTree2();
initAssetModalTable();
initModalTree();
}).on('click', '#btn_asset_modal_confirm', function () {
if (assetModalOption.onModalConfirm) {
assetModalOption.onModalConfirm(assetModalTable, assetModalTree);
}
$("#asset_list_modal").modal('hide');
})
</script>
{% endblock %}
......
......@@ -226,6 +226,33 @@ function onNodeSelected(event, treeNode) {
asset_table.ajax.reload();
}
function onAssetModalConfirmAddAssetToNode(table) {
var assets_selected = table.selected;
if (!current_node_id) {
return
}
var data = {'assets': assets_selected};
var success = function () {
table.selected = [];
table.ajax.reload()
};
var url = '';
if (update_node_action === "move") {
url = "{% url 'api-assets:node-replace-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node_id);
} else {
url = "{% url 'api-assets:node-add-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node_id);
}
requestApi({
'url': url,
'method': 'PUT',
'body': JSON.stringify(data),
'success': success
})
}
$(document).ready(function(){
initTable();
initTree();
......@@ -236,6 +263,12 @@ $(document).ready(function(){
else{
$('#show_current_asset').css('display', 'inline-block');
}
var modalOption = {
onModalConfirm: onAssetModalConfirmAddAssetToNode,
onModalTableDone: null
};
setAssetModalOptions(modalOption);
})
.on('click', '.labels li', function () {
var val = $(this).text();
......@@ -429,7 +462,6 @@ $(document).ready(function(){
}
function doRemove() {
var nodes = zTree.getSelectedNodes();
if (!current_node_id) {
return
}
......@@ -472,32 +504,7 @@ $(document).ready(function(){
}
$(".ipt_check_all").prop("checked", false)
})
.on('click', '#btn_asset_modal_confirm', function () {
var assets_selected = asset_table2.selected;
if (!current_node_id) {
return
}
var data = {'assets': assets_selected};
var success = function () {
asset_table2.selected = [];
asset_table2.ajax.reload()
};
var url = '';
if (update_node_action === "move") {
url = "{% url 'api-assets:node-replace-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node_id);
} else {
url = "{% url 'api-assets:node-add-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node_id);
}
requestApi({
'url': url,
'method': 'PUT',
'body': JSON.stringify(data),
'success': success
})
}).on('hidden.bs.modal', '#asset_list_modal', function () {
.on('hidden.bs.modal', '#asset_list_modal', function () {
window.location.reload();
}).on('click', '#menu_asset_add', function () {
update_node_action = "add"
......
......@@ -28,25 +28,6 @@ $(document).ready(function () {
}).on('click', '.select2-selection__rendered', function (e) {
e.preventDefault();
$("#asset_list_modal").modal();
initSelectedAssets2Table();
})
.on('click', '#btn_asset_modal_confirm', function () {
var assets = asset_table2.selected;
var options = [];
$('#id_assets option').each(function (i, v) {
options.push(v.value)
});
asset_table2.selected_rows.forEach(function (i) {
var name = i.hostname + '(' + i.ip + ')';
var option = new Option(name, i.id, false, true);
if (options.indexOf(i.id) === -1) {
$('#id_assets').append(option).trigger('change');
}
});
$('.select2').val(assets).trigger('change');
$("#asset_list_modal").modal('hide');
})
.on("submit", "form", function (evt) {
evt.preventDefault();
......
......@@ -32,24 +32,6 @@ $(document).ready(function () {
}).on('click', '.select2-selection__rendered', function (e) {
e.preventDefault();
$("#asset_list_modal").modal();
initSelectedAssets2Table();
})
.on('click', '#btn_asset_modal_confirm', function () {
var assets = asset_table2.selected;
var options = [];
$('#id_assets option').each(function (i, v) {
options.push(v.value)
});
asset_table2.selected_rows.forEach(function (i) {
var name = i.hostname + '(' + i.ip + ')';
var option = new Option(name, i.id, false, true);
if (options.indexOf(i.id) === -1) {
$('#id_assets').append(option).trigger('change');
}
});
$('#id_assets').val(assets).trigger('change');
$("#asset_list_modal").modal('hide');
})
.on("submit", "form", function (evt) {
evt.preventDefault();
......
......@@ -86,7 +86,7 @@ class AssetCreateView(PermissionsMixin, FormMixin, TemplateView):
node = get_object_or_none(Node, id=node_id)
else:
node = Node.org_root()
form["nodes"].initial = node
form.add_nodes_initial(node)
return form
def get_protocol_formset(self):
......
......@@ -11,6 +11,9 @@
#search_btn {
margin-bottom: 0;
}
.form-control {
height: 30px;
}
</style>
{% endblock %}
......
......@@ -8,6 +8,12 @@
#search_btn {
margin-bottom: 0;
}
.form-control {
height: 30px;
}
.select2-selection__rendered span.select2-selection, .select2-container .select2-selection--single {
height: 30px !important;
}
</style>
{% endblock %}
......
......@@ -11,6 +11,12 @@
#search_btn {
margin-bottom: 0;
}
.form-control {
height: 30px;
}
.select2-selection__rendered span.select2-selection, .select2-container .select2-selection--single {
height: 30px !important;
}
</style>
{% endblock %}
......
......@@ -11,6 +11,12 @@
#search_btn {
margin-bottom: 0;
}
.form-control {
height: 30px;
}
.select2-selection__rendered span.select2-selection, .select2-container .select2-selection--single {
height: 30px !important;
}
</style>
{% endblock %}
......
......@@ -44,8 +44,10 @@ class IDInCacheFilterMixin(object):
return queryset
cache_key = KEY_CACHE_RESOURCES_ID.format(spm)
resources_id = cache.get(cache_key)
if resources_id and isinstance(resources_id, list):
queryset = queryset.filter(id__in=resources_id)
if not resources_id or not isinstance(resources_id, list):
queryset = queryset.none()
return queryset
queryset = queryset.filter(id__in=resources_id)
return queryset
......
......@@ -14,7 +14,7 @@ from .local import thread_local
pattern = re.compile(r'FROM `(\w+)`')
logger = get_logger(__name__)
DEBUG_DB_QUERY = os.environ.get('DEBUG_DB_QUERY', '0') == '1'
DEBUG_DB = os.environ.get('DEBUG_DB', '0') == '1'
class Counter:
......@@ -58,7 +58,7 @@ def on_request_finished_release_local(sender, **kwargs):
thread_local.__release_local__()
if settings.DEBUG and DEBUG_DB_QUERY:
if settings.DEBUG and DEBUG_DB:
request_finished.connect(on_request_finished_logging_db_query)
......
......@@ -609,6 +609,7 @@ SWAGGER_SETTINGS = {
},
}
# Default email suffix
EMAIL_SUFFIX = CONFIG.EMAIL_SUFFIX
LOGIN_LOG_KEEP_DAYS = CONFIG.LOGIN_LOG_KEEP_DAYS
......
This diff is collapsed.
......@@ -40,7 +40,7 @@ def run_ansible_task(tid, callback=None, **kwargs):
logger.error("No task found")
@shared_task(soft_time_limit=60)
@shared_task(soft_time_limit=60, queue="ansible")
def run_command_execution(cid, **kwargs):
execution = get_object_or_none(CommandExecution, id=cid)
if execution:
......
......@@ -9,6 +9,9 @@
<link href="{% static 'css/plugins/select2/select2.min.css' %}" rel="stylesheet">
<script src="{% static 'js/plugins/select2/select2.full.min.js' %}"></script>
<style>
.form-control {
height: 30px;
}
#search_btn {
margin-bottom: 0;
......@@ -88,13 +91,6 @@
<script src="{% static "js/plugins/footable/footable.all.min.js" %}"></script>
<script>
$(document).ready(function() {
{#$('table').DataTable({#}
{# "searching": false,#}
{# "paging": false,#}
{# "bInfo" : false,#}
{# "order": []#}
{# });#}
{#$('.footable').footable();#}
$('.select2').select2({
dropdownAutoWidth : true,
width: 'auto'
......@@ -116,7 +112,14 @@ $(document).ready(function() {
var html = createPopover(data_list);
$(this).html(html);
});
$('[data-toggle="popover"]').popover();
$('[data-toggle="popover"]').popover({
html: true,
placement: 'bottom',
trigger: 'click',
container: 'body'
}).on('click', function (e) {
$('[data-toggle="popover"]').not(this).popover('hide');
});
})
</script>
{% endblock %}
......
......@@ -35,6 +35,10 @@ class OrgBulkModelViewSet(IDInCacheFilterMixin, BulkModelViewSet):
return queryset
def allow_bulk_destroy(self, qs, filtered):
if qs.count() <= filtered.count():
return False
if self.request.query_params.get('spm', ''):
return True
return False
......
......@@ -97,6 +97,8 @@ class AssetPermissionViewSet(viewsets.ModelViewSet):
inherit_nodes_keys = assets.all().values_list('nodes__key', flat=True)
for key in inherit_nodes_keys:
if key is None:
continue
ancestor_keys = Node.get_nodes_ancestor_keys_by_key(key, with_self=True)
inherit_all_nodes.update(ancestor_keys)
queryset = queryset.filter(
......
......@@ -53,6 +53,16 @@ class AssetPermissionForm(OrgModelForm):
assets_field.queryset = Asset.objects.none()
nodes_field.queryset = Node.objects.none()
def set_nodes_initial(self, nodes):
field = self.fields['nodes']
field.choices = [(n.id, n.full_value) for n in nodes]
field.initial = nodes
def set_assets_initial(self, assets):
field = self.fields['assets']
field.choices = [(a.id, a.hostname) for a in assets]
field.initial = assets
class Meta:
model = AssetPermission
exclude = (
......
......@@ -47,7 +47,7 @@ def on_permission_nodes_changed(sender, instance=None, action='', **kwargs):
if isinstance(instance, AssetPermission):
logger.debug("Asset permission nodes change signal received")
nodes = kwargs['model'].objects.filter(pk__in=kwargs['pk_set'])
system_users = instance.system_users.all().values_list('id', flat=True)
system_users = instance.system_users.all()
for system_user in system_users:
system_user.nodes.add(*tuple(nodes))
......@@ -59,7 +59,7 @@ def on_permission_assets_changed(sender, instance=None, action='', **kwargs):
if isinstance(instance, AssetPermission):
logger.debug("Asset permission assets change signal received")
assets = kwargs['model'].objects.filter(pk__in=kwargs['pk_set'])
system_users = instance.system_users.all().values_list('id', flat=True)
system_users = instance.system_users.all()
for system_user in system_users:
system_user.assets.add(*tuple(assets))
......
......@@ -100,10 +100,7 @@
<form>
<tr>
<td colspan="2" class="no-borders">
<select data-placeholder="{% trans 'Select nodes' %}" class="select2" id="node_select2" style="width: 100%" multiple="" tabindex="4">
{% for node in nodes_remain %}
<option value="{{ node.id }}" id="opt_{{ node.id }}">{{ node.full_value }}</option>
{% endfor %}
<select data-placeholder="{% trans 'Select nodes' %}" class="nodes-select2" id="nodes_select2" style="width: 100%" multiple="" tabindex="4">
</select>
</td>
</tr>
......@@ -202,35 +199,22 @@ function initAssetTable() {
return table
}
$(document).ready(function () {
$('.select2').select2();
table = initAssetTable();
var nodeListUrl = "{% url 'api-assets:node-list' %}";
nodesSelect2Init(".nodes-select2", nodeListUrl);
$("#asset_select2").parent().find(".select2-selection").on('click', function (e) {
if ($(e.target).attr('class') !== 'select2-selection__choice__remove'){
e.preventDefault();
e.stopPropagation();
$("#asset_list_modal").modal();
initSelectedAssets2Table('#asset_select2');
}
})
})
.on('click', '#btn_asset_modal_confirm', function () {
var assets = asset_table2.selected;
var options = [];
$('#asset_select2 option').each(function (i, v) {
options.push(v.value)
});
asset_table2.selected_rows.forEach(function (i) {
var name = i.hostname + '(' + i.ip + ')';
var option = new Option(name, i.id, false, true);
if (options.indexOf(i.id) === -1) {
$('#asset_select2').append(option).trigger('change');
}
});
$('#asset_select2').val(assets).trigger('change');
$("#asset_list_modal").modal('hide');
})
.on('click', '.btn-add-assets', function () {
var assets_selected = $("#asset_select2 option:selected").map(function () {
return $(this).attr('value');
......@@ -250,7 +234,7 @@ $(document).ready(function () {
})
.on('click', '#btn-add-node', function () {
var nodes_selected = {};
$("#node_select2 option:selected").each(function (i, data) {
$("#nodes_select2 option:selected").each(function (i, data) {
nodes_selected[$(data).attr('value')] = $(data).text();
});
if (Object.keys(nodes_selected).length === 0) {
......
......@@ -111,42 +111,25 @@ var dateOptions = {
}
};
var api_action = "{{ api_action }}";
$(document).ready(function () {
$('.select2').select2({
closeOnSelect: false
});
var url = "{% url 'api-assets:node-list' %}";
nodesSelect2Init(".nodes-select2", url);
$('#date_start').daterangepicker(dateOptions);
$('#date_expired').daterangepicker(dateOptions);
$("#id_assets").parent().find(".select2-selection").on('click', function (e) {
if ($(e.target).attr('class') !== 'select2-selection__choice__remove'){
e.preventDefault();
e.stopPropagation();
$("#asset_list_modal").modal();
initSelectedAssets2Table();
}
})
})
.on('click', '#btn_asset_modal_confirm', function () {
var assets = asset_table2.selected;
var options = [];
$('#id_assets option').each(function (i, v) {
options.push(v.value)
});
asset_table2.selected_rows.forEach(function (i) {
var name = i.hostname + '(' + i.ip + ')';
var option = new Option(name, i.id, false, true);
if (options.indexOf(i.id) === -1) {
$('#id_assets').append(option).trigger('change');
}
});
$('#id_assets').val(assets).trigger('change');
$("#asset_list_modal").modal('hide');
})
.on("submit", "form", function (evt) {
evt.preventDefault();
var the_url = '{% url 'api-perms:asset-permission-list' %}';
......
......@@ -227,7 +227,6 @@ function toggle() {
$(document).ready(function(){
initTable();
initTree();
})
.on('click', '.btn-del', function () {
var $this = $(this);
......@@ -247,17 +246,19 @@ $(document).ready(function(){
})
.on('click', '.btn-create-permission', function () {
var url = "{% url 'perms:asset-permission-create' %}";
var nodes = zTree.getSelectedNodes();
var _nodes = [];
var _assets = [];
$.each(nodes, function (id, node) {
if (node.meta.type === 'node') {
_nodes.push(node.meta.node.id)
} else {
_assets.push(node.meta.asset.id)
}
});
url += "?assets=" + _assets.join(",") + "&nodes=" + _nodes.join(",");
if (zTree) {
var nodes = zTree.getSelectedNodes();
var _nodes = [];
var _assets = [];
$.each(nodes, function (id, node) {
if (node.meta.type === 'node') {
_nodes.push(node.meta.node.id)
} else {
_assets.push(node.meta.asset.id)
}
});
url += "?assets=" + _assets.join(",") + "&nodes=" + _nodes.join(",");
}
window.open(url, '_self');
}).on('click', '.toggle', function (e) {
e.preventDefault();
......@@ -283,7 +284,6 @@ $(document).ready(function(){
detailRows.push(tr.attr('id'));
}
}
}).on('click', '#permission_list_table_filter input', function (e) {
e.preventDefault();
e.stopPropagation();
......
......@@ -53,11 +53,11 @@ class AssetPermissionCreateView(PermissionsMixin, CreateView):
nodes_id = nodes_id.split(",")
nodes = Node.objects.filter(id__in=nodes_id)\
.exclude(id=Node.org_root().id)
form['nodes'].initial = nodes
form.set_nodes_initial(nodes)
if assets_id:
assets_id = assets_id.split(",")
assets = Asset.objects.filter(id__in=assets_id)
form['assets'].initial = assets
form.set_assets_initial(assets)
return form
def get_context_data(self, **kwargs):
......
......@@ -17,13 +17,6 @@
padding: 10px 10px;
text-align: center;
}
#assetTree2.ztree * {
background-color: #f8fafb;
}
#assetTree2.ztree {
background-color: #f8fafb;
}
</style>
<div class="wrapper wrapper-content">
......
......@@ -76,10 +76,9 @@ $(document).ready(function () {
if(!$("body").hasClass('body-small')) {
fix_height();
}
})
});
$("[data-toggle=popover]")
.popover();
$("[data-toggle=popover]").popover();
});
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment