功能联调

main
周平 11 months ago
parent bc77bc5ce9
commit 7a4212140f

@ -2,6 +2,7 @@
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DateTime, func
from website.db_mysql import get_session
Base = declarative_base()
@ -15,4 +16,14 @@ class DeviceClassification(Base):
name = Column(String(255), default='', comment='名称')
suid = Column(String(10), default='', comment='short uuid')
delete = Column("del", Integer, default=0)
create_time = Column(DateTime, default=func.now())
create_time = Column(DateTime, default=func.now())
class DeviceClassificationReporitory(object):
def get_row_by_id(self, cid):
with get_session() as session:
return session.query(DeviceClassification).filter_by(id=cid).first()
def get_row_by_suid(self, suid):
with get_session() as session:
return session.query(DeviceClassification).filter_by(suid=suid).first()

@ -63,11 +63,21 @@ class EnterpriseNodeRepository(object):
def select_tree(self, entity_id: int, name: str = "") -> List[Dict[str, Any]]:
roots = []
with get_session() as session:
sql = "select id, name, suid from enterprise_node where entity_id=:entity_id and del=0 and parent=0 "
# sql = "select id, name, suid, parent from enterprise_node where entity_id=:entity_id and del=0 and parent=0 "
sql = (
"""
SELECT
n.id, n.name, n.parent, p.name AS parent_name, n.suid
FROM enterprise_node n
LEFT JOIN enterprise_node p ON n.parent = p.id
WHERE n.entity_id=:entity_id AND n.del=0 and n.parent=0
"""
)
param = {"entity_id": entity_id}
if name:
sql += " and name like :name"
sql += " and n.name like :name"
param["name"] = f"%{name}%"
res = session.execute(text(sql), param)
@ -78,6 +88,8 @@ class EnterpriseNodeRepository(object):
"id": node["id"],
"name": node["name"],
"suid": node["suid"],
"parent": node["parent"],
"parent_name": node["parent_name"],
"children": self.build_tree(session, node, name),
}
roots.append(root)
@ -87,13 +99,24 @@ class EnterpriseNodeRepository(object):
def build_tree(
self, session: Any, node: Dict[str, Any], name: str = ""
) -> List[Any]:
# sql = (
# "select id, name, suid, parent from enterprise_node where del=0 and parent=:parent"
# )
sql = (
"select id, name, suid from enterprise_node where del=0 and parent=:parent"
"""
SELECT
n.id, n.name, n.parent, p.name AS parent_name, n.suid
FROM enterprise_node n
LEFT JOIN enterprise_node p ON n.parent = p.id
WHERE n.parent=:parent AND n.del=0
"""
)
param = {"parent": node["id"]}
if name:
sql += " and name like :name"
sql += " and n.name like :name"
param["name"] = f"%{name}%"
res = session.execute(text(sql), param)
@ -105,6 +128,8 @@ class EnterpriseNodeRepository(object):
"id": node["id"],
"name": node["name"],
"suid": node["suid"],
"parent": node["parent"],
"parent_name": node["parent_name"],
"children": self.build_tree(session, node, name),
}
children.append(child)
@ -113,9 +138,18 @@ class EnterpriseNodeRepository(object):
def select_node(self, node_id: int) -> Dict[str, Any]:
with get_session() as session:
# sql = (
# "select id, name, parent, addr, lola, contact, phone, comment, suid from enterprise_node "
# "where id=:id and del=0"
# )
sql = (
"select id, name, parent, addr, lola, contact, phone, comment, suid from enterprise_node "
"where id=:id and del=0"
"""
SELECT
n.id, n.name, n.parent, p.name AS parent_name, n.addr, n.lola, n.contact, n.phone, n.comment, n.suid
FROM enterprise_node n
LEFT JOIN enterprise_node p ON n.parent = p.id
WHERE n.id=:id AND n.del=0
"""
)
param = {"id": node_id}
res = session.execute(text(sql), param)
@ -128,6 +162,7 @@ class EnterpriseNodeRepository(object):
sql = "update enterprise_node set del=1 where id=:id"
param = {"id": node_id}
session.execute(text(sql), param)
session.commit()
return 0
def get_node_by_id(self, node_id: int) -> dict:

@ -5,6 +5,7 @@ from sqlalchemy import text
from website import db_mysql, errors
from website.db.enterprise_device import enterprise_device as DB_Device
from website.db.device_classification import device_classification as DB_DeviceClassification
from website.handler import APIHandler, authenticated
from website.util import shortuuid
@ -29,7 +30,7 @@ class DeviceClassificationAddHandler(APIHandler):
name = self.get_escaped_argument("name", "")
with self.app_mysql.connect() as conn:
cur = conn.execute(
text("SELECT id FROM device_classification WHERE name=:name"),
text("SELECT id FROM device_classification WHERE name=:name and del=0"),
{"name": name},
)
row = cur.fetchone()
@ -95,7 +96,20 @@ class DeviceClassificationDeleteHandler(APIHandler):
@authenticated
def post(self):
did = self.get_int_argument("id")
with self.app_mysql.connect() as conn:
cur = conn.execute(
text("""
select d.id from enterprise_device d, device_classification c
where d.classification=c.suid and c.id=:id and c.del=0
"""), {"id": did}
)
rows = cur.fetchall()
if rows:
raise errors.HTTPAPIError(
errors.ERROR_BAD_REQUEST, "该分类使用中,无法删除"
)
conn.execute(
text("update device_classification set del=1 WHERE id=:id"), {"id": did}
)
@ -138,6 +152,14 @@ class DeviceAddHandler(APIHandler):
if not entity_id or not node_id:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "企业节点不能为空")
# 判断设备分类是否存在
db_classification = DB_DeviceClassification.DeviceClassificationReporitory()
row = db_classification.get_row_by_suid(classification)
if not row:
raise errors.HTTPAPIError(
errors.ERROR_BAD_REQUEST, "设备分类不存在"
)
device_data = {
"entity_id": entity_id,
"node_id": node_id,
@ -148,7 +170,6 @@ class DeviceAddHandler(APIHandler):
"param": param,
"comment": comment,
}
db_device = DB_Device.EnterpriseDeviceRepository()
db_device.add_device(device_data)

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
import asyncio
import json
import logging
from sqlalchemy import text
@ -303,6 +304,50 @@ class EntityInfoHandler(APIHandler):
self.finish(data)
class ModelsHandler(APIHandler):
"""企业模型"""
@authenticated
def post(self):
eid = self.get_int_argument("id")
model_ids = []
with self.app_mysql.connect() as conn:
cur = conn.execute(
text("select base_models from enterprise_busi_model where entity_id=:eid"), {"eid": eid}
)
rows = db_mysql.to_json_list(cur)
for row in rows:
base_models = json.loads(row["base_models"])
model_ids.extend([item["id"] for item in base_models])
cur.close()
model_ids = list(set(model_ids))
cur = conn.execute(text(
"""
select m.name, m.model_type, mc.name as classification_name, m.default_version
from model m, model_classification mc
where m.classification=mc.id and m.id in :model_ids
"""
), {"model_ids": model_ids})
rows = db_mysql.to_json_list(cur)
cur.close()
data = []
for row in rows:
data.append({
"name": row["name"],
"model_type": consts.model_type_map[row["model_type"]],
"classification_name": row["classification_name"],
"default_version": row["default_version"]
})
self.finish({"count": len(model_ids), "data": data})
class EntityDeleteHandler(APIHandler):
"""删除企业"""

@ -7,6 +7,7 @@ handlers = [
("/enterprise/entity/add", handler.EntityAddHandler),
("/enterprise/entity/edit", handler.EntityEditHandler),
("/enterprise/entity/info", handler.EntityInfoHandler),
("/enterprise/entity/models", handler.ModelsHandler),
("/enterprise/entity/delete", handler.EntityDeleteHandler),
("/enterprise/entity/pwdcheck", handler.EntityPwdcheckHandler),
("/enterprise/industrymap", handler.IndustryMapHandler),

@ -32,7 +32,7 @@ class AddHandler(APIHandler):
# @authenticated
def post(self):
entity_id = self.get_int_argument("entity_suid")
entity_id = self.get_int_argument("entity_id")
entity_suid = self.get_escaped_argument("entity_suid", "")
name = self.get_escaped_argument("name", "")
parent = self.get_int_argument("parent", 0)
@ -100,7 +100,7 @@ class EditHandler(APIHandler):
db_node = DB_Node.EnterpriseNodeRepository()
db_node.update_node(
{
"node_id": node_id,
"id": node_id,
"name": name,
"parent": parent,
"addr": addr,

@ -1,17 +1,19 @@
# -*- coding: utf-8 -*-
import logging
import hashlib
import re
import logging
import os
import re
import aiofiles
from sqlalchemy import text
from website import errors
from website import db_mysql
from website import errors
from website import settings
from website.handler import APIHandler, authenticated
class UploadHandler(APIHandler):
@authenticated
async def post(self):
@ -42,7 +44,7 @@ class UploadHandler(APIHandler):
sql = text("select id from files where md5_str=:md5_str")
cur = conn.execute(sql, {"md5_str": md5_str})
row = cur.fetchone()
if not row:
filepath = os.path.join(settings.file_upload_dir, md5_str + '_' + filename)
if not os.path.exists(filepath):
@ -50,9 +52,14 @@ class UploadHandler(APIHandler):
# filename = meta['filename']
async with open(filepath, 'wb') as f:
await f.write(meta['body'])
sql_insert = text("insert into files(filename, filepath, md5_str, filesize, filetype, user) values(:filename, :filepath, :md5_str, :file_size, :filetype, :user)")
conn.execute(sql_insert, {"filename": filename, "filepath": filepath, "md5_str": md5_str, "file_size": int(file_size/1024/1024), "filetype": filetype, "user": self.current_user.id})
sql_insert = text(
"""insert into files(filename, filepath, md5_str, filesize, filetype, user)
values(:filename, :filepath, :md5_str, :file_size, :filetype, :user)"""
)
conn.execute(sql_insert, {"filename": filename, "filepath": filepath, "md5_str": md5_str,
"file_size": int(file_size / 1024 / 1024), "filetype": filetype,
"user": self.current_user.id})
conn.commit()
self.finish({"result": md5_str})
@ -70,10 +77,10 @@ class DeleteHandler(APIHandler):
sql = text("select filepath from files where md5_str=:md5_str")
cur = conn.execute(sql, {"md5_str": md5_str})
row = db_mysql.to_json(cur)
if not row:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "file not found")
filepath = row["filepath"]
if os.path.exists(filepath):
os.remove(filepath)
@ -109,7 +116,7 @@ class BigFileUploadHandler(APIHandler):
# md5_str = hashlib.md5(file_metas[0].body).hexdigest()
filepath = os.path.join(settings.file_upload_dir, filename)
filepath = os.path.join(settings.file_upload_dir, filename)
if not os.path.exists(filepath):
for meta in file_metas:
# filename = meta['filename']
@ -120,4 +127,3 @@ class BigFileUploadHandler(APIHandler):
await f.write(meta['body'])
self.finish()

Loading…
Cancel
Save