Commit 7c814080 authored by ibuler's avatar ibuler

[Update] 优化一些api

parent b0aa9f19
...@@ -20,6 +20,7 @@ from rest_framework.response import Response ...@@ -20,6 +20,7 @@ from rest_framework.response import Response
from rest_framework_bulk import BulkModelViewSet from rest_framework_bulk import BulkModelViewSet
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.shortcuts import get_object_or_404 from django.shortcuts import get_object_or_404
from django.db.models import Count
from common.utils import get_logger, get_object_or_none from common.utils import get_logger, get_object_or_none
from ..hands import IsOrgAdmin from ..hands import IsOrgAdmin
...@@ -42,40 +43,16 @@ class NodeViewSet(viewsets.ModelViewSet): ...@@ -42,40 +43,16 @@ class NodeViewSet(viewsets.ModelViewSet):
permission_classes = (IsOrgAdmin,) permission_classes = (IsOrgAdmin,)
serializer_class = serializers.NodeSerializer serializer_class = serializers.NodeSerializer
def get_queryset(self):
queryset = super().get_queryset().annotate(Count('assets'))
return queryset
def perform_create(self, serializer): def perform_create(self, serializer):
child_key = Node.root().get_next_child_key() child_key = Node.root().get_next_child_key()
serializer.validated_data["key"] = child_key serializer.validated_data["key"] = child_key
serializer.save() serializer.save()
# class NodeWithAssetsApi(generics.ListAPIView):
# permission_classes = (IsOrgAdmin,)
# serializers = serializers.NodeSerializer
#
# def get_node(self):
# pk = self.kwargs.get('pk') or self.request.query_params.get('node')
# if not pk:
# node = Node.root()
# else:
# node = get_object_or_404(Node, pk)
# return node
#
# def get_queryset(self):
# queryset = []
# node = self.get_node()
# children = node.get_children()
# assets = node.get_assets()
# queryset.extend(list(children))
#
# for asset in assets:
# node = Node()
# node.id = asset.id
# node.parent = node.id
# node.value = asset.hostname
# queryset.append(node)
# return queryset
class NodeChildrenApi(mixins.ListModelMixin, generics.CreateAPIView): class NodeChildrenApi(mixins.ListModelMixin, generics.CreateAPIView):
queryset = Node.objects.all() queryset = Node.objects.all()
permission_classes = (IsOrgAdmin,) permission_classes = (IsOrgAdmin,)
...@@ -124,22 +101,26 @@ class NodeChildrenApi(mixins.ListModelMixin, generics.CreateAPIView): ...@@ -124,22 +101,26 @@ class NodeChildrenApi(mixins.ListModelMixin, generics.CreateAPIView):
query_all = self.request.query_params.get("all") query_all = self.request.query_params.get("all")
query_assets = self.request.query_params.get('assets') query_assets = self.request.query_params.get('assets')
node = self.get_object() node = self.get_object()
if node is None: if node is None:
node = Node.root() node = Node.root()
node.assets__count = node.get_all_assets().count()
queryset.append(node) queryset.append(node)
if query_all: if query_all:
children = node.get_all_children() children = node.get_all_children().annotate(Count("assets"))
else: else:
children = node.get_children() children = node.get_children().annotate(Count("assets"))
queryset.extend(list(children)) queryset.extend(list(children))
if query_assets: if query_assets:
assets = node.get_assets() assets = node.get_assets()
for asset in assets: for asset in assets:
node_fake = Node() node_fake = Node()
node_fake.assets__count = 0
node_fake.id = asset.id node_fake.id = asset.id
node_fake.is_node = False node_fake.is_node = False
node_fake.parent_id = node.id node_fake.key = node.key + ':0'
node_fake.value = asset.hostname node_fake.value = asset.hostname
queryset.append(node_fake) queryset.append(node_fake)
queryset = sorted(queryset, key=lambda x: x.is_node, reverse=True) queryset = sorted(queryset, key=lambda x: x.is_node, reverse=True)
......
...@@ -97,12 +97,10 @@ class Node(OrgModelMixin): ...@@ -97,12 +97,10 @@ class Node(OrgModelMixin):
def get_assets(self): def get_assets(self):
from .asset import Asset from .asset import Asset
if self.is_root(): if self.is_default_node():
assets = Asset.objects.filter( assets = Asset.objects.filter(nodes__isnull=True)
Q(nodes__id=self.id) | Q(nodes__isnull=True)
)
else: else:
assets = self.assets.all() assets = Asset.objects.filter(nodes__id=self.id)
return assets return assets
def get_valid_assets(self): def get_valid_assets(self):
...@@ -132,13 +130,17 @@ class Node(OrgModelMixin): ...@@ -132,13 +130,17 @@ class Node(OrgModelMixin):
else: else:
return False return False
@property
def parent_key(self):
parent_key = ":".join(self.key.split(":")[:-1])
return parent_key
@property @property
def parent(self): def parent(self):
if self.is_root(): if self.is_root():
return self return self
parent_key = ":".join(self.key.split(":")[:-1])
try: try:
parent = self.__class__.objects.get(key=parent_key) parent = self.__class__.objects.get(key=self.parent_key)
return parent return parent
except Node.DoesNotExist: except Node.DoesNotExist:
return self.__class__.root() return self.__class__.root()
...@@ -197,5 +199,12 @@ class Node(OrgModelMixin): ...@@ -197,5 +199,12 @@ class Node(OrgModelMixin):
else: else:
return cls.create_root_node() return cls.create_root_node()
@classmethod
def generate_fake(cls, count=100):
import random
for i in range(count):
node = random.choice(cls.objects.all())
node.create_child('Node {}'.format(i))
...@@ -43,14 +43,15 @@ class NodeGrantedSerializer(BulkSerializerMixin, serializers.ModelSerializer): ...@@ -43,14 +43,15 @@ class NodeGrantedSerializer(BulkSerializerMixin, serializers.ModelSerializer):
class NodeSerializer(serializers.ModelSerializer): class NodeSerializer(serializers.ModelSerializer):
parent = serializers.SerializerMethodField()
assets_amount = serializers.SerializerMethodField() assets_amount = serializers.SerializerMethodField()
tree_id = serializers.SerializerMethodField()
tree_parent = serializers.SerializerMethodField()
class Meta: class Meta:
model = Node model = Node
fields = [ fields = [
'id', 'key', 'value', 'parent', 'assets_amount', 'id', 'key', 'value', 'assets_amount',
'is_node', 'org_id', 'is_node', 'org_id', 'tree_id', 'tree_parent',
] ]
list_serializer_class = BulkListSerializer list_serializer_class = BulkListSerializer
...@@ -66,12 +67,16 @@ class NodeSerializer(serializers.ModelSerializer): ...@@ -66,12 +67,16 @@ class NodeSerializer(serializers.ModelSerializer):
return data return data
@staticmethod @staticmethod
def get_parent(obj): def get_assets_amount(obj):
return obj.parent.id if obj.is_node else obj.parent_id return obj.assets__count if hasattr(obj, 'assets__count') else 0
@staticmethod @staticmethod
def get_assets_amount(obj): def get_tree_id(obj):
return obj.get_all_assets().count() if obj.is_node else 0 return obj.key
@staticmethod
def get_tree_parent(obj):
return obj.parent_key
def get_fields(self): def get_fields(self):
fields = super().get_fields() fields = super().get_fields()
......
...@@ -71,7 +71,7 @@ function initTable2() { ...@@ -71,7 +71,7 @@ function initTable2() {
function onSelected2(event, treeNode) { function onSelected2(event, treeNode) {
var url = asset_table2.ajax.url(); var url = asset_table2.ajax.url();
url = setUrlParam(url, "node_id", treeNode.id); url = setUrlParam(url, "node_id", treeNode.node_id);
setCookie('node_selected', treeNode.id); setCookie('node_selected', treeNode.id);
asset_table2.ajax.url(url); asset_table2.ajax.url(url);
asset_table2.ajax.reload(); asset_table2.ajax.reload();
...@@ -97,17 +97,20 @@ function initTree2() { ...@@ -97,17 +97,20 @@ function initTree2() {
var zNodes = []; var zNodes = [];
$.get("{% url 'api-assets:node-list' %}", function(data, status){ $.get("{% url 'api-assets:node-list' %}", function(data, status){
$.each(data, function (index, value) { $.each(data, function (index, value) {
value["pId"] = value["parent"]; value["node_id"] = value["id"];
value["id"] = value["tree_id"];
value["pId"] = value["tree_parent"];
{#value["open"] = true;#} {#value["open"] = true;#}
if (value["key"] === "0") { if (value["key"] === "0") {
value["open"] = true; value["open"] = true;
} }
value["name"] = value["value"] + ' (' + value['assets_amount'] + ')'; value["name"] = value["value"] + ' (' + value['assets_amount'] + ')';
value['value'] = value['value'];
}); });
zNodes = data; zNodes = data;
$.fn.zTree.init($("#assetTree2"), setting, zNodes); $.fn.zTree.init($("#assetTree2"), setting, zNodes);
zTree2 = $.fn.zTree.getZTreeObj("assetTree2"); zTree2 = $.fn.zTree.getZTreeObj("assetTree2");
var root = zTree2.getNodes()[0];
zTree2.expandNode(root);
}); });
} }
......
...@@ -166,16 +166,6 @@ function initTable() { ...@@ -166,16 +166,6 @@ function initTable() {
} }
}}, }},
{#{targets: 5, createdCell: function (td, cellData) {#}
{# if (cellData === 'Unknown'){#}
{# $(td).html('<i class="fa fa-circle text-warning"></i>')#}
{# } else if (!cellData) {#}
{# $(td).html('<i class="fa fa-circle text-danger"></i>')#}
{# } else {#}
{# $(td).html('<i class="fa fa-circle text-navy"></i>')#}
{# }#}
{# }},#}
{targets: 5, createdCell: function (td, cellData, rowData) { {targets: 5, createdCell: function (td, cellData, rowData) {
var update_btn = '<a href="{% url "assets:asset-update" pk=DEFAULT_PK %}" class="btn btn-xs btn-info">{% trans "Update" %}</a>'.replace("{{ DEFAULT_PK }}", cellData); var update_btn = '<a href="{% url "assets:asset-update" pk=DEFAULT_PK %}" class="btn btn-xs btn-info">{% trans "Update" %}</a>'.replace("{{ DEFAULT_PK }}", cellData);
var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn_asset_delete" data-uid="{{ DEFAULT_PK }}">{% trans "Delete" %}</a>'.replace('{{ DEFAULT_PK }}', cellData); var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn_asset_delete" data-uid="{{ DEFAULT_PK }}">{% trans "Delete" %}</a>'.replace('{{ DEFAULT_PK }}', cellData);
...@@ -183,13 +173,6 @@ function initTable() { ...@@ -183,13 +173,6 @@ function initTable() {
}} }}
], ],
ajax_url: '{% url "api-assets:asset-list" %}', ajax_url: '{% url "api-assets:asset-list" %}',
{#columns: [#}
{# {data: "id"}, {data: "hostname" }, {data: "ip" },#}
{# {data: "cpu_cores"}, {data: "is_active", orderable: false },#}
{# {data: "is_connective", orderable: false}, {data: "id", orderable: false }#}
{#],#}
columns: [ columns: [
{data: "id"}, {data: "hostname" }, {data: "ip" }, {data: "id"}, {data: "hostname" }, {data: "ip" },
{data: "cpu_cores"}, {data: "is_active", orderable: false }, {data: "cpu_cores"}, {data: "is_active", orderable: false },
...@@ -207,17 +190,17 @@ function addTreeNode() { ...@@ -207,17 +190,17 @@ function addTreeNode() {
if (!parentNode){ if (!parentNode){
return return
} }
var url = "{% url 'api-assets:node-children' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", parentNode.id ); var url = "{% url 'api-assets:node-children' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", parentNode.node_id );
$.post(url, {}, function (data, status){ $.post(url, {}, function (data, status){
if (status === "success") { if (status === "success") {
var newNode = { var newNode = {
name: data["value"], name: data["value"],
id: data["id"], id: data["id"],
pId: parentNode.id pId: parentNode.node_id
}; };
newNode.checked = zTree.getSelectedNodes()[0].checked; newNode.checked = zTree.getSelectedNodes()[0].checked;
zTree.addNodes(parentNode, 0, newNode); zTree.addNodes(parentNode, 0, newNode);
var node = zTree.getNodeByParam('id', newNode.id, parentNode) var node = zTree.getNodeByParam('id', newNode.node_id, parentNode);
zTree.editName(node); zTree.editName(node);
} else { } else {
alert("{% trans 'Create node failed' %}") alert("{% trans 'Create node failed' %}")
...@@ -236,7 +219,7 @@ function removeTreeNode() { ...@@ -236,7 +219,7 @@ function removeTreeNode() {
} else if (current_node.assets_amount !== 0) { } else if (current_node.assets_amount !== 0) {
toastr.error("{% trans 'Have assets, cancel' %}"); toastr.error("{% trans 'Have assets, cancel' %}");
} else { } else {
var url = "{% url 'api-assets:node-detail' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node.id ); var url = "{% url 'api-assets:node-detail' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node.node_id );
$.ajax({ $.ajax({
url: url, url: url,
method: "DELETE", method: "DELETE",
...@@ -296,7 +279,7 @@ function onBodyMouseDown(event){ ...@@ -296,7 +279,7 @@ function onBodyMouseDown(event){
function onRename(event, treeId, treeNode, isCancel){ function onRename(event, treeId, treeNode, isCancel){
var url = "{% url 'api-assets:node-detail' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", treeNode.id); var url = "{% url 'api-assets:node-detail' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", treeNode.node_id);
var data = {"value": treeNode.name}; var data = {"value": treeNode.name};
if (isCancel){ if (isCancel){
return return
...@@ -310,9 +293,9 @@ function onRename(event, treeId, treeNode, isCancel){ ...@@ -310,9 +293,9 @@ function onRename(event, treeId, treeNode, isCancel){
function onSelected(event, treeNode) { function onSelected(event, treeNode) {
var url = asset_table.ajax.url(); var url = asset_table.ajax.url();
url = setUrlParam(url, "node_id", treeNode.id); url = setUrlParam(url, "node_id", treeNode.node_id);
url = setUrlParam(url, "show_current_asset", getCookie('show_current_asset')); url = setUrlParam(url, "show_current_asset", getCookie('show_current_asset'));
setCookie('node_selected', treeNode.id); setCookie('node_selected', treeNode.node_id);
asset_table.ajax.url(url); asset_table.ajax.url(url);
asset_table.ajax.reload(); asset_table.ajax.reload();
} }
...@@ -329,7 +312,7 @@ function selectQueryNode() { ...@@ -329,7 +312,7 @@ function selectQueryNode() {
node_id = cookie_node_id; node_id = cookie_node_id;
} }
node = zTree.getNodesByParam("id", node_id, null); node = zTree.getNodesByParam("node_id", node_id, null);
if (node){ if (node){
zTree.selectNode(node[0]); zTree.selectNode(node[0]);
} }
...@@ -346,11 +329,7 @@ function beforeDrop(treeId, treeNodes, targetNode, moveType) { ...@@ -346,11 +329,7 @@ function beforeDrop(treeId, treeNodes, targetNode, moveType) {
}); });
var msg = "你想移动节点: `" + treeNodesNames.join(",") + "` 到 `" + targetNode.value + "` 下吗?"; var msg = "你想移动节点: `" + treeNodesNames.join(",") + "` 到 `" + targetNode.value + "` 下吗?";
if (confirm(msg)){ return confirm(msg);
return true
} else {
return false
}
} }
function onDrag(event, treeId, treeNodes) { function onDrag(event, treeId, treeNodes) {
...@@ -359,10 +338,10 @@ function onDrag(event, treeId, treeNodes) { ...@@ -359,10 +338,10 @@ function onDrag(event, treeId, treeNodes) {
function onDrop(event, treeId, treeNodes, targetNode, moveType) { function onDrop(event, treeId, treeNodes, targetNode, moveType) {
var treeNodesIds = []; var treeNodesIds = [];
$.each(treeNodes, function (index, value) { $.each(treeNodes, function (index, value) {
treeNodesIds.push(value.id); treeNodesIds.push(value.node_id);
}); });
var the_url = "{% url 'api-assets:node-add-children' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", targetNode.id); var the_url = "{% url 'api-assets:node-add-children' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", targetNode.node_id);
var body = {nodes: treeNodesIds}; var body = {nodes: treeNodesIds};
APIUpdateAttr({ APIUpdateAttr({
url: the_url, url: the_url,
...@@ -406,8 +385,10 @@ function initTree() { ...@@ -406,8 +385,10 @@ function initTree() {
var zNodes = []; var zNodes = [];
$.get("{% url 'api-assets:node-list' %}", function(data, status){ $.get("{% url 'api-assets:node-list' %}", function(data, status){
$.each(data, function (index, value) { $.each(data, function (index, value) {
if (value["parent"] !== value["id"]){ value["node_id"] = value["id"];
value["pId"] = value["parent"]; value["id"] = value["tree_id"];
if (value["tree_id"] !== value["tree_parent"]){
value["pId"] = value["tree_parent"];
} else { } else {
value["isParent"] = true; value["isParent"] = true;
} }
...@@ -470,7 +451,7 @@ $(document).ready(function(){ ...@@ -470,7 +451,7 @@ $(document).ready(function(){
$.ajax({ $.ajax({
url: "{% url "assets:asset-export" %}", url: "{% url "assets:asset-export" %}",
method: 'POST', method: 'POST',
data: JSON.stringify({assets_id: assets, node_id: current_node.id}), data: JSON.stringify({assets_id: assets, node_id: current_node.node_id}),
dataType: "json", dataType: "json",
success: function (data, textStatus) { success: function (data, textStatus) {
window.open(data.redirect) window.open(data.redirect)
...@@ -487,8 +468,8 @@ $(document).ready(function(){ ...@@ -487,8 +468,8 @@ $(document).ready(function(){
var current_node; var current_node;
if (nodes && nodes.length ===1 ){ if (nodes && nodes.length ===1 ){
current_node = nodes[0]; current_node = nodes[0];
action = setUrlParam(action, 'node_id', current_node.id); action = setUrlParam(action, 'node_id', current_node.node_id);
{#action += "?node_id=" + current_node.id;#} {#action += "?node_id=" + current_node.node_id;#}
$form.attr("action", action) $form.attr("action", action)
} }
$form.find('.help-block').remove(); $form.find('.help-block').remove();
...@@ -514,7 +495,7 @@ $(document).ready(function(){ ...@@ -514,7 +495,7 @@ $(document).ready(function(){
var current_node; var current_node;
if (nodes && nodes.length ===1 ){ if (nodes && nodes.length ===1 ){
current_node = nodes[0]; current_node = nodes[0];
url += "?node_id=" + current_node.id; url += "?node_id=" + current_node.node_id;
} }
window.open(url, '_self'); window.open(url, '_self');
}) })
...@@ -528,7 +509,7 @@ $(document).ready(function(){ ...@@ -528,7 +509,7 @@ $(document).ready(function(){
return null; return null;
} }
var the_url = url.replace("{{ DEFAULT_PK }}", current_node.id); var the_url = url.replace("{{ DEFAULT_PK }}", current_node.node_id);
function success(data) { function success(data) {
rMenu.css({"visibility" : "hidden"}); rMenu.css({"visibility" : "hidden"});
var task_id = data.task; var task_id = data.task;
...@@ -553,7 +534,7 @@ $(document).ready(function(){ ...@@ -553,7 +534,7 @@ $(document).ready(function(){
return null; return null;
} }
var the_url = url.replace("{{ DEFAULT_PK }}", current_node.id); var the_url = url.replace("{{ DEFAULT_PK }}", current_node.node_id);
function success(data) { function success(data) {
rMenu.css({"visibility" : "hidden"}); rMenu.css({"visibility" : "hidden"});
var task_id = data.task; var task_id = data.task;
...@@ -690,7 +671,7 @@ $(document).ready(function(){ ...@@ -690,7 +671,7 @@ $(document).ready(function(){
}; };
APIUpdateAttr({ APIUpdateAttr({
'url': '/api/assets/v1/nodes/' + current_node.id + '/assets/remove/', 'url': '/api/assets/v1/nodes/' + current_node.node_id + '/assets/remove/',
'method': 'PUT', 'method': 'PUT',
'body': JSON.stringify(data), 'body': JSON.stringify(data),
'success': success 'success': success
...@@ -735,9 +716,9 @@ $(document).ready(function(){ ...@@ -735,9 +716,9 @@ $(document).ready(function(){
var url = ''; var url = '';
if (update_node_action === "move") { if (update_node_action === "move") {
url = "{% url 'api-assets:node-replace-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node.id); url = "{% url 'api-assets:node-replace-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node.node_id);
} else { } else {
url = "{% url 'api-assets:node-add-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node.id); url = "{% url 'api-assets:node-add-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node.node_id);
} }
APIUpdateAttr({ APIUpdateAttr({
......
...@@ -261,10 +261,10 @@ LOGGING = { ...@@ -261,10 +261,10 @@ LOGGING = {
'handlers': ['console', 'file'], 'handlers': ['console', 'file'],
'level': "INFO", 'level': "INFO",
}, },
# 'django.db': { 'django.db': {
# 'handlers': ['console', 'file'], 'handlers': ['console', 'file'],
# 'level': 'DEBUG' 'level': 'DEBUG'
# } }
} }
} }
......
...@@ -29,8 +29,7 @@ class OrgManager(models.Manager): ...@@ -29,8 +29,7 @@ class OrgManager(models.Manager):
kwargs = {} kwargs = {}
if not hasattr(tl, 'times'): if not hasattr(tl, 'times'):
tl.times = 0 tl.times = 0
print("[{}]>>>>>>>>>> Get query set".format(tl.times)) # logger.debug("[{}]>>>>>>>>>> Get query set".format(tl.times))
print(current_org)
if not current_org: if not current_org:
kwargs['id'] = None kwargs['id'] = None
elif current_org.is_real(): elif current_org.is_real():
......
...@@ -80,12 +80,12 @@ function onSelected(event, treeNode) { ...@@ -80,12 +80,12 @@ function onSelected(event, treeNode) {
var url = table.ajax.url(); var url = table.ajax.url();
if (treeNode.is_node) { if (treeNode.is_node) {
url = setUrlParam(url, 'asset', ""); url = setUrlParam(url, 'asset', "");
url = setUrlParam(url, 'node', treeNode.id) url = setUrlParam(url, 'node', treeNode.node_id)
} else { } else {
url = setUrlParam(url, 'node', ""); url = setUrlParam(url, 'node', "");
url = setUrlParam(url, 'asset', treeNode.id) url = setUrlParam(url, 'asset', treeNode.node_id)
} }
setCookie('node_selected', treeNode.id); setCookie('node_selected', treeNode.node_id);
table.ajax.url(url); table.ajax.url(url);
table.ajax.reload(); table.ajax.reload();
} }
...@@ -111,10 +111,19 @@ function selectQueryNode() { ...@@ -111,10 +111,19 @@ function selectQueryNode() {
function filter(treeId, parentNode, childNodes) { function filter(treeId, parentNode, childNodes) {
$.each(childNodes, function (index, value) { $.each(childNodes, function (index, value) {
value["pId"] = value["parent"]; value["node_id"] = value["id"];
value["name"] = value["value"]; value["id"] = value["tree_id"];
value["isParent"] = value["is_node"]; if (value["tree_id"] !== value["tree_parent"]) {
value["pId"] = value["tree_parent"];
} else {
value["isParent"] = true;
}
value['name'] = value['value'];
value["iconSkin"] = value["is_node"] ? null : 'file'; value["iconSkin"] = value["is_node"] ? null : 'file';
{#value["pId"] = value["parent"];#}
{#value["name"] = value["value"];#}
value["isParent"] = value["is_node"];
}); });
return childNodes; return childNodes;
} }
...@@ -227,7 +236,7 @@ function initTree() { ...@@ -227,7 +236,7 @@ function initTree() {
async: { async: {
enable: true, enable: true,
url: "{% url 'api-assets:node-children-2' %}?assets=1&all=", url: "{% url 'api-assets:node-children-2' %}?assets=1&all=",
autoParam:["id", "name=n", "level=lv"], autoParam:["node_id=id", "name=n", "level=lv"],
dataFilter: filter, dataFilter: filter,
type: 'get' type: 'get'
}, },
...@@ -238,15 +247,15 @@ function initTree() { ...@@ -238,15 +247,15 @@ function initTree() {
}; };
var zNodes = []; var zNodes = [];
$.get("{% url 'api-assets:node-children-2' %}?assets=1&all=", function(data, status){ $.get("{% url 'api-assets:node-children-2' %}?assets=1", function(data, status){
$.each(data, function (index, value) { $.each(data, function (index, value) {
if (value["parent"] !== value["id"]){ value["node_id"] = value["id"];
value["pId"] = value["parent"]; value["id"] = value["tree_id"];
} else { if (value["tree_id"] !== value["tree_parent"]) {
value["isParent"] = true; value["pId"] = value["tree_parent"];
} }
value["name"] = value["value"];
value["isParent"] = value["is_node"]; value["isParent"] = value["is_node"];
value['name'] = value['value'];
value["iconSkin"] = value["is_node"] ? null : 'file'; value["iconSkin"] = value["is_node"] ? null : 'file';
}); });
zNodes = data; zNodes = data;
...@@ -291,9 +300,9 @@ $(document).ready(function(){ ...@@ -291,9 +300,9 @@ $(document).ready(function(){
var _assets = []; var _assets = [];
$.each(nodes, function (id, node) { $.each(nodes, function (id, node) {
if (node.is_node) { if (node.is_node) {
_nodes.push(node.id) _nodes.push(node.node_id)
} else { } else {
_assets.push(node.id) _assets.push(node.node_id)
} }
}); });
url += "?assets=" + _assets.join(",") + "&nodes=" + _nodes.join(","); url += "?assets=" + _assets.join(",") + "&nodes=" + _nodes.join(",");
......
...@@ -13,7 +13,7 @@ logger = get_logger(__file__) ...@@ -13,7 +13,7 @@ logger = get_logger(__file__)
class Tree: class Tree:
def __init__(self): def __init__(self):
self.__all_nodes = list(Node.objects.all().prefetch_related('assets')) self.__all_nodes = Node.objects.all().prefetch_related('assets')
self.__node_asset_map = defaultdict(set) self.__node_asset_map = defaultdict(set)
self.nodes = defaultdict(dict) self.nodes = defaultdict(dict)
self.root = Node.root() self.root = Node.root()
...@@ -21,7 +21,7 @@ class Tree: ...@@ -21,7 +21,7 @@ class Tree:
def init_node_asset_map(self): def init_node_asset_map(self):
for node in self.__all_nodes: for node in self.__all_nodes:
assets = node.get_assets().values_list('id', flat=True) assets = [a.id for a in node.assets.all()]
for asset in assets: for asset in assets:
self.__node_asset_map[str(asset)].add(node) self.__node_asset_map[str(asset)].add(node)
......
...@@ -107,31 +107,14 @@ function initTable() { ...@@ -107,31 +107,14 @@ function initTable() {
function onSelected(event, treeNode) { function onSelected(event, treeNode) {
url = '{% url "api-perms:user-node-assets" pk=object.id node_id=DEFAULT_PK %}'; url = '{% url "api-perms:user-node-assets" pk=object.id node_id=DEFAULT_PK %}';
url = url.replace("{{ DEFAULT_PK }}", treeNode.id); console.log(">>>>>>>>>>>>>>>>>>>>>>>", treeNode.node_id, treeNode.id, treeNode);
setCookie('node_selected', treeNode.id); url = url.replace("{{ DEFAULT_PK }}", treeNode.node_id);
setCookie('node_selected', treeNode.node_id);
asset_table = initTable(); asset_table = initTable();
asset_table.ajax.url(url); asset_table.ajax.url(url);
asset_table.ajax.reload(); asset_table.ajax.reload();
} }
function selectQueryNode() {
var query_node_id = $.getUrlParam("node");
var cookie_node_id = getCookie('node_selected');
var node;
var node_id;
if (query_node_id !== null) {
node_id = query_node_id
} else if (cookie_node_id !== null) {
node_id = cookie_node_id;
}
node = zTree.getNodesByParam("id", node_id, null);
if (node){
zTree.selectNode(node[0]);
}
}
function initTree() { function initTree() {
var setting = { var setting = {
view: { view: {
...@@ -149,19 +132,22 @@ function initTree() { ...@@ -149,19 +132,22 @@ function initTree() {
}; };
var zNodes = []; var zNodes = [];
$.get("{% url 'api-perms:user-nodes' pk=object.id %}", function(data, status){ $.get("{% url 'api-perms:user-nodes' pk=object.id %}", function(data, status) {
$.each(data, function (index, value) { $.each(data, function (index, value) {
value["pId"] = value["parent"]; value["node_id"] = value["id"];
if (value["key"] === "0") { value["id"] = value["tree_id"];
value["open"] = true; if (value["tree_id"] !== value["tree_parent"]) {
value["pId"] = value["tree_parent"];
} }
value["name"] = value["value"] value["isParent"] = value["is_node"];
value['name'] = value['value'];
value["iconSkin"] = value["is_node"] ? null : 'file';
}); });
zNodes = data; zNodes = data;
$.fn.zTree.init($("#assetTree"), setting, zNodes); $.fn.zTree.init($("#assetTree"), setting, zNodes);
zTree = $.fn.zTree.getZTreeObj("assetTree"); zTree = $.fn.zTree.getZTreeObj("assetTree");
rMenu = $("#rMenu"); var root = zTree.getNodes()[0];
selectQueryNode(); zTree.expandNode(root);
}); });
} }
......
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