This commit is contained in:
2024-10-24 09:23:39 +08:00
parent 641c34b1b3
commit 16c005556f
36 changed files with 7780 additions and 0 deletions

54
SCLP/models/brands.py Normal file
View File

@@ -0,0 +1,54 @@
# -*- coding:utf-8 -*-
"""
@Author : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc : 可视对讲厂家信息表 改&查
"""
from pydantic import BaseModel, field_validator
from utils.database import BaseTable, get_table_handler
from utils.misc import InvalidException
class UpdateBrand(BaseModel):
name: str
@field_validator("name")
def check_name(cls, value):
th = get_table_handler()
if BrandsTable.exists(th, value):
return value
else:
raise InvalidException("请提供正确的可视对讲厂家名")
class BrandsTable(BaseTable):
@staticmethod
def get_checked_factory(table_handler: BaseTable):
"""获取当前启用的可视对讲厂家"""
table_handler.query("SELECT brand_name FROM brands WHERE status = '开启'")
res = table_handler.cursor.fetchall()
if res:
return {"name": res[0][0]}
else:
return {"name": None}
@staticmethod
def update_checked_factory(table_handler: BaseTable, brand_name: str):
"""更新启用的可视对讲厂家"""
sqls = [
"UPDATE brands SET status = '关闭' WHERE status = '开启'",
"UPDATE brands SET status = '开启' WHERE brand_name = ?"
]
table_handler.execute(sqls, [(), (brand_name,)])
return {"status": True}
@staticmethod
def exists(table_handler: BaseTable, brand_name: str):
"""可视对讲厂家是否存在"""
table_handler.query("SELECT brand_name FROM brands WHERE brand_name = ?", (brand_name,))
res = table_handler.cursor.fetchall()
if res:
return True
else:
return False

793
SCLP/models/devices.py Normal file
View File

@@ -0,0 +1,793 @@
# -*- coding:utf-8 -*-
"""
@Author : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc : 设备信息表 增&改&查
"""
import csv
import os
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, field_validator
from device.call import ServicesCall, DelFaceItem, AddFaceItem
from models.houses import HousesTable
from utils import logger
from utils.database import BaseTable, get_table_handler
from utils.misc import InvalidException, now_datetime_second, decrypt_number
class DeviceRegister(BaseModel):
device_mac: str
device_name: str
device_desc: str
third_local_device_id: str
device_status: str = "离线"
device_sct: Optional[str] = None
# 以下需要查询已注册设备信息获取
gateway_id: Optional[int] = None
gateway_name: Optional[str] = None
# 以下需要查询产品信息表获取
product_name: str
node_type: str
class Device(BaseModel):
device_id: int
device_name: str
node_type: str
product_name: str
class AccessDevice(BaseModel):
device_id: int
building_ids: list[str]
@field_validator("device_id")
def check_device_id(cls, value):
th = get_table_handler()
if DevicesTable.bind_exits(th, value):
raise InvalidException(f"设备:{value} 已被添加过关联")
if not DevicesTable.exits(th, value):
raise InvalidException(f"设备:{value} 不存在")
return value
@field_validator("building_ids")
def check_authorized_scope(cls, value):
th = get_table_handler()
for i in value:
if not HousesTable.building_exists(th, i):
raise InvalidException(f"楼栋:{i} 不存在")
return value
class AccessDevicesScope(BaseModel):
device_type: str
info: List[AccessDevice]
@field_validator("device_type")
def check_device_type(cls, value):
if value in ["大门闸机", "大门门禁"]:
return value
else:
raise InvalidException("请提供正确的设备类型:[大门闸机, 大门门禁]")
class BuildingDevice(BaseModel):
device_id: int
bind_unit_id: str
@field_validator("device_id")
def check_device_id(cls, value):
th = get_table_handler()
if DevicesTable.bind_exits(th, value):
raise InvalidException(f"设备:{value} 已被添加过关联")
if not DevicesTable.exits(th, value):
raise InvalidException(f"设备:{value} 不存在")
return value
@field_validator("bind_unit_id")
def check_bind_unit_id(cls, value):
th = get_table_handler()
if not HousesTable.unit_exists(th, value):
raise InvalidException(f"单元:{value} 不存在")
return value
class BuildingDevicesScope(BaseModel):
info: List[BuildingDevice]
class SearchDevicesInfo(BaseModel):
search_type: Optional[str] = None
search_key: Optional[str] = None
@field_validator("search_type")
def check_search_type(cls, value):
types = {
"设备名称": "device_name",
"MAC地址": "device_mac",
"设备ID": "device_id"
}
if value in types:
return types[value]
else:
raise InvalidException(f"请提供正确的类型:{list(types.keys())}")
class DevicesTable(BaseTable):
@staticmethod
def check(table_handler: BaseTable):
"""检测是否存在当前表"""
table_handler.query("SELECT name FROM sqlite_master WHERE type='table' AND name='devices'")
if table_handler.cursor.fetchone() is None:
table_handler.execute(
f"""
CREATE TABLE devices (
device_id INTEGER PRIMARY KEY AUTOINCREMENT,
device_mac TEXT UNIQUE,
device_name TEXT,
device_desc TEXT,
third_local_device_id TEXT,
device_status TEXT,
device_sct TEXT,
gateway_id INTEGER,
gateway_name TEXT,
product_name TEXT,
node_type TEXT,
last_online_datetime TEXT,
register_datetime TEXT
)
"""
)
init_config_path = os.path.join(os.path.dirname(os.path.abspath("__file__")), "data/InitialData/devices.csv")
if os.path.exists(init_config_path):
with open(init_config_path, newline='', encoding='utf8') as csvfile:
csvreader = csv.reader(csvfile)
head = next(csvreader)
data = []
if len(head) == 12:
for row in csvreader:
device_mac = row[0].strip()
device_name = row[1].strip()
device_desc = row[2].strip() if row[2].strip() else None
third_local_device_id = row[3].strip() if row[3].strip() else None
device_status = row[4].strip() if row[4].strip() else "离线"
device_sct = row[5].strip() if row[5].strip() else None
gateway_id = int(row[6].strip()) if row[6].strip() else None
gateway_name = row[7].strip() if row[7].strip() else None
product_name = row[8].strip()
node_type = row[9].strip()
last_online_datetime = row[10].strip() if row[10].strip() else None
register_datetime = row[11].strip() if row[11].strip() else None
data.append((device_mac, device_name, device_desc, third_local_device_id, device_status,
device_sct, gateway_id, gateway_name, product_name, node_type,
last_online_datetime, register_datetime))
table_handler.executemany(
f"""
INSERT INTO devices
(device_mac, device_name, device_desc, third_local_device_id, device_status,
device_sct, gateway_id, gateway_name, product_name, node_type,
last_online_datetime, register_datetime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (device_mac) DO NOTHING
""",
data
)
table_handler.query("SELECT name FROM sqlite_master WHERE type='table' AND name='devices_scope'")
if table_handler.cursor.fetchone() is None:
table_handler.execute(
f"""
CREATE TABLE devices_scope (
device_id INT,
device_type TEXT,
bind_unit_id TEXT,
UNIQUE (device_id, bind_unit_id)
)
"""
)
init_config_path = os.path.join(os.path.dirname(os.path.abspath("__file__")),
"data/InitialData/devices_scope.csv")
if os.path.exists(init_config_path):
with open(init_config_path, newline='', encoding='utf8') as csvfile:
csvreader = csv.reader(csvfile)
head = next(csvreader)
data = []
if len(head) == 3:
for row in csvreader:
device_id = row[0].strip()
device_type = row[1].strip()
bind_unit_id = row[2].strip()
data.append((device_id, device_type, bind_unit_id))
table_handler.executemany(
f"""
INSERT INTO devices_scope
(device_id, device_type, bind_unit_id)
VALUES (?, ?, ?)
ON CONFLICT (device_id, bind_unit_id) DO NOTHING
""", data
)
table_handler.query("SELECT name FROM sqlite_master WHERE type='table' AND name='devices_auth'")
if table_handler.cursor.fetchone() is None:
table_handler.execute(
f"""
CREATE TABLE devices_auth (
device_id INT,
_id TEXT,
record_type TEXT,
start_date TEXT,
expire_date TEXT,
add_datetime TEXT,
update_datetime TEXT,
UNIQUE (device_id, _id, record_type)
)
"""
)
init_config_path = os.path.join(os.path.dirname(os.path.abspath("__file__")),
"data/InitialData/devices_auth.csv")
if os.path.exists(init_config_path):
with open(init_config_path, newline='', encoding='utf8') as csvfile:
csvreader = csv.reader(csvfile)
head = next(csvreader)
data = []
if len(head) == 5:
for row in csvreader:
device_id = row[0].strip()
_id = row[1].strip()
record_type = row[2].strip()
start_date = row[3].strip()
expire_date = row[4].strip()
data.append((device_id, _id, record_type, start_date, expire_date,
now_datetime_second(), now_datetime_second()))
table_handler.executemany(
f"""
INSERT INTO devices_auth
(device_id, _id, record_type, start_date, expire_date, add_datetime, update_datetime)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (device_id, _id, record_type) DO NOTHING
""", data
)
@staticmethod
def insert_by_device_register(table_handler: BaseTable, obj: DeviceRegister):
register_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
table_handler.execute(
"""
INSERT INTO devices
(device_mac, device_name, device_desc, third_local_device_id, device_status, device_sct,
gateway_id, gateway_name, product_name, node_type, register_datetime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (device_mac) DO UPDATE SET
device_name=?, device_desc=?, third_local_device_id=?,
device_status=?, device_sct=?, gateway_id=?, gateway_name=?,
product_name=?, node_type=?, register_datetime=?
""",
(obj.device_mac, obj.device_name, obj.device_desc, obj.third_local_device_id,
obj.device_status, obj.device_sct, obj.gateway_id, obj.gateway_name,
obj.product_name, obj.node_type, register_datetime,
obj.device_name, obj.device_desc, obj.third_local_device_id,
obj.device_status, obj.device_sct, obj.gateway_id, obj.gateway_name,
obj.product_name, obj.node_type, register_datetime)
)
table_handler.query(
"""
SELECT device_id
FROM devices
WHERE device_mac = ?
""",
(obj.device_mac,)
)
res = table_handler.cursor.fetchall()
if res:
return res[0][0]
return None
@staticmethod
def insert_device_auth_record(table_handler: BaseTable, device_id: int, _id: str,
start_date: str, expire_date: str, record_type: str = '人行'):
table_handler.execute(
"""
INSERT INTO devices_auth
(device_id, _id, record_type, start_date, expire_date, add_datetime, update_datetime)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (device_id, _id, record_type) DO UPDATE SET
start_date=?, expire_date=?, update_datetime=?
""",
(device_id, _id, record_type, start_date, expire_date,
now_datetime_second(), now_datetime_second(), start_date, expire_date, now_datetime_second())
)
@staticmethod
def get_devices_info(table_handler: BaseTable):
"""获取对应设备的基本信息"""
table_handler.query(
"""
SELECT device_name, third_local_device_id, device_id, device_status,
gateway_name, product_name, node_type, last_online_datetime, register_datetime
FROM devices
WHERE node_type != '网关设备'
"""
)
res = table_handler.cursor.fetchall()
if res:
devices_info = []
for item in res:
devices_info.append({
"device_name": item[0],
"third_local_device_id": item[1],
"device_id": item[2],
"device_status": item[3],
"gateway_name": item[4] if item[4] else "",
"product_name": item[5],
"node_type": item[6],
"last_online_datetime": item[7] if item[7] else "",
"register_datetime": item[8]
})
return devices_info
return None
@staticmethod
def get_device_info(table_handler: BaseTable, device_id: int):
"""获取对应设备的基本信息"""
table_handler.query(
"""
SELECT device_name, node_type, product_name
FROM devices
WHERE device_id = ?
""",
(device_id,)
)
res = table_handler.cursor.fetchall()
if res:
return Device(device_id=device_id, device_name=res[0][0], node_type=res[0][1], product_name=res[0][2])
return None
@staticmethod
def get_device_name(table_handler: BaseTable, device_id: int):
"""获取对应设备名"""
table_handler.query(
"""
SELECT device_name
FROM devices
WHERE device_id = ?
""",
(device_id,)
)
res = table_handler.cursor.fetchall()
if res:
return res[0][0]
return ""
@staticmethod
def get_device_scope_type(table_handler: BaseTable, device_id: int):
"""获取对应设备门禁类型"""
table_handler.query(
"""
SELECT device_type
FROM devices_scope
WHERE device_id = ?
""",
(device_id,)
)
res = table_handler.cursor.fetchall()
if res:
return res[0][0]
return ""
@staticmethod
def get_device_ids_by_unit_id(table_handler: BaseTable, unit_id: str) -> list:
"""查询对应单元权限内的设备ID"""
table_handler.query(
"""
SELECT GROUP_CONCAT(device_id) AS device_ids
FROM devices_scope
WHERE bind_unit_id = ?
""", (unit_id,)
)
res = table_handler.cursor.fetchall()
if res:
return res[0][0].split(',')
else:
return []
@staticmethod
def get_device_ids(table_handler: BaseTable, filter_name: Optional[str] = None, filter_online: bool = True):
"""获取相关的设备ID"""
sub_sql_list = []
if filter_online:
sub_sql_list.append("device_status = '在线'")
if filter_name is not None:
sub_sql_list.append(f"product_name like '%{filter_name}%'")
if len(sub_sql_list) > 0:
sub_sql = "WHERE " + " AND ".join(sub_sql_list)
else:
sub_sql = ""
table_handler.query(f"SELECT GROUP_CONCAT(device_id) device_ids FROM devices {sub_sql}")
res = table_handler.cursor.fetchall()
if res:
return [i for i in res[0][0].split(',')]
else:
return []
@staticmethod
def get_auth_interval(table_handler: BaseTable, _id: str, device_id: int, record_type: str = '人行'):
"""获取对应ID授权在设备上的有效期"""
table_handler.query(
"""
SELECT start_date, expire_date
FROM devices_auth
WHERE device_id = ? and _id = ? and record_type = ?
""",
(device_id, _id, record_type)
)
res = table_handler.cursor.fetchall()
if res:
return res[0][0], res[0][1]
return "", ""
@staticmethod
def update_device_status(table_handler: BaseTable, device_id: int, device_status: str):
"""更新设备在线状态"""
if device_status == "在线":
last_online_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
set_sql = f"device_status='在线', last_online_datetime='{last_online_datetime}' "
else:
set_sql = f"device_status='离线' "
table_handler.execute(
f"""
UPDATE devices SET {set_sql}
WHERE device_id={device_id}
"""
)
@staticmethod
def offline_gateway(table_handler: BaseTable, device_id: int):
"""用于在网关下线时同时下线网关下的所有设备"""
table_handler.execute(
f"""
UPDATE devices SET device_status='离线'
WHERE device_id={device_id} or gateway_id={device_id}
"""
)
@staticmethod
def get_access_devices_info(table_handler: BaseTable,
is_associated: bool,
device_name: str = None,
product_name: str = None,
device_mac: str = None,
device_id: int = None):
if is_associated:
sub_sql = "WHERE d.node_type != '网关设备' AND product_name not like '%停车场%' AND device_type is not null "
else:
sub_sql = "WHERE d.node_type != '网关设备' AND product_name not like '%停车场%' AND device_type is null "
if device_name:
sub_sql += f"AND device_name = '{device_name}'"
elif product_name:
sub_sql += f"AND product_name = '{product_name}'"
elif device_mac:
sub_sql += f"AND device_mac = '{device_mac}'"
elif device_id:
sub_sql += f"AND d.device_id = {device_id}"
table_handler.query(
f"""
SELECT
d.device_id,
device_name,
device_mac,
device_status,
ds.device_type,
GROUP_CONCAT(t.building_name || '-' || t.unit_name) as scopes,
product_name
FROM devices d
LEFT JOIN devices_scope ds ON ds.device_id = d.device_id
LEFT JOIN (SELECT DISTINCT unit_id, unit_name, building_id, building_name FROM houses) t
ON t.unit_id = ds.bind_unit_id
{sub_sql}
GROUP BY d.device_id, device_name, device_mac, device_status, ds.device_type, product_name
"""
)
res = table_handler.cursor.fetchall()
if res:
devices_info = []
for i in res:
devices_info.append({
"device_id": i[0],
"device_name": i[1],
"device_mac": i[2],
"device_status": i[3],
"device_type": i[4] if i[4] else "",
"authorized_scope": i[5].split(",") if i[5] else [],
"product_name": i[6]
})
return {"devices": devices_info}
return {"devices": []}
@staticmethod
def get_associated_access_devices_info(table_handler: BaseTable,
search_type: Optional[str] = None,
search_key: Optional[str] = None):
if search_type:
if search_type == "device_id":
sub_sql = f"WHERE ds.device_id = {search_key}"
elif search_type == "device_name":
sub_sql = f"WHERE d.device_name like '%{search_key}%'"
else:
sub_sql = f"WHERE d.{search_type} = '{search_key}'"
else:
sub_sql = ""
table_handler.query(
f"""
SELECT ds.device_id as _id,
d.device_name as _name,
d.device_mac as _mac,
d.device_status as _status
FROM (SELECT DISTINCT device_id FROM devices_scope) ds
LEFT JOIN devices d ON ds.device_id = d.device_id
{sub_sql}
"""
)
res = table_handler.cursor.fetchall()
if res:
devices_info = []
for i in res:
devices_info.append({
"device_id": i[0],
"device_name": i[1],
"device_mac": i[2],
"device_status": i[3]
})
return {"devices": devices_info}
return {"devices": []}
@staticmethod
def auto_auth_by_unit_id(table_handler: BaseTable, device_id: int, unit_id: str):
"""查询对应单元下相关住户,对具备人脸的住户授权"""
table_handler.query(
"""
SELECT h.householder_id, name, phone, face_url
FROM householders h
LEFT JOIN householders_type ht ON ht.householder_id=h.householder_id
LEFT JOIN houses ON ht.room_id=houses.room_id
WHERE h.type = '住户' AND (face_url != '' or face_url is not null ) AND houses.unit_id = ?
""", (unit_id,)
)
res = table_handler.cursor.fetchall()
if res:
# 人员人脸下放
for i in res:
sc = ServicesCall()
face_item = AddFaceItem(
user_id=i[0],
name=i[1],
phone_number=decrypt_number(i[2]),
face_url=i[3],
device_ids=str([device_id])
)
_callback, code, msg = sc.add_face(device_id, face_item)
if _callback:
DevicesTable.insert_device_auth_record(table_handler, device_id, face_item.user_id,
face_item.start_date, face_item.expire_date)
@staticmethod
def add_access_devices(table_handler: BaseTable, device_type: str, objs: List[AccessDevice]):
data = []
for obj in objs:
for bind_building_id in obj.building_ids:
unit_ids = HousesTable.get_unit_ids(table_handler, bind_building_id)
for unit_id in unit_ids:
data.append((obj.device_id, device_type, unit_id, device_type))
DevicesTable.auto_auth_by_unit_id(table_handler, obj.device_id, unit_id)
try:
table_handler.executemany(
"""
INSERT INTO devices_scope
(device_id, device_type, bind_unit_id)
VALUES (?, ?, ?)
ON CONFLICT (device_id, bind_unit_id) DO UPDATE
SET device_type = ?
""", data
)
return True
except Exception as e:
logger.Logger.error(f"DevicesTable.add_access_devices: {type(e).__name__}, {e}")
raise InvalidException(f"DevicesTable.add_access_devices: {type(e).__name__}, {e}")
@staticmethod
def add_building_devices(table_handler: BaseTable, device_type: str, objs: List[BuildingDevice]):
data = []
for obj in objs:
data.append((obj.device_id, device_type, obj.bind_unit_id))
DevicesTable.auto_auth_by_unit_id(table_handler, obj.device_id, obj.bind_unit_id)
try:
table_handler.executemany(
"""
INSERT INTO devices_scope
(device_id, device_type, bind_unit_id)
VALUES (?, ?, ?)
ON CONFLICT (device_id, bind_unit_id) DO NOTHING
""", data
)
return True
except Exception as e:
logger.Logger.error(f"DevicesTable.add_building_devices: {type(e).__name__}, {e}")
return False
@staticmethod
def add_update_device_auth(table_handler: BaseTable, device_id, _ids: list[str], record_type: str,
start_date: str, expire_date: str):
"""对应设备批量授权记录增加"""
data = []
for _id in _ids:
_datetime = now_datetime_second()
data.append((device_id, _id, record_type, start_date, expire_date, _datetime, _datetime,
start_date, expire_date, _datetime))
try:
table_handler.executemany(
"""
INSERT INTO devices_auth
(device_id, _id, record_type, start_date, expire_date, add_datetime, update_datetime)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (device_id, _id, record_type)
DO UPDATE SET start_date = ?, expire_date = ?, update_datetime = ?
""", data
)
return True
except Exception as e:
logger.Logger.error(f"DevicesTable.add_device_auth: {type(e).__name__}, {e}")
return False
@staticmethod
def get_auth_device_ids(table_handler: BaseTable, _id: str, record_type: str = '人行'):
"""获取ID的所有授权设备"""
table_handler.query(
"""
SELECT device_id
FROM devices_auth
WHERE _id = ? AND record_type = ?
""", (_id, record_type)
)
res = table_handler.cursor.fetchall()
if res:
return [i[0] for i in res]
else:
return []
@staticmethod
def get_auth_device_info(table_handler: BaseTable, _id: str, record_type: str = '人行'):
"""获取ID当前所有授权设备基础信息"""
table_handler.query(
"""
SELECT devices_auth.device_id, device_name, device_mac, device_status
FROM devices_auth
LEFT JOIN devices ON devices.device_id = devices_auth.device_id
WHERE _id = ? AND record_type = ?
""", (_id, record_type)
)
res = table_handler.cursor.fetchall()
if res:
return [{"device_id": i[0], "device_name": i[1], "device_mac": i[2], "device_status": i[3]} for i in res]
else:
return []
@staticmethod
def get_auth_householders_info(table_handler: BaseTable, device_id: int):
"""获取关联授权下的所有完成下放的人员信息"""
table_handler.query(
"""
SELECT da._id, name, phone, face_url, da.start_date, da.expire_date
FROM devices_auth da
LEFT JOIN householders h ON da._id = h.householder_id
WHERE device_id = ? AND record_type = '人行'
""", (device_id,)
)
res = table_handler.cursor.fetchall()
if res:
return [{"id": i[0], "name": i[1], "phone": i[2], "url": i[3], "sdate": i[4], "edate": i[5]} for i in res]
else:
return []
@staticmethod
def delete_householder_all_auth(table_handler: BaseTable, _id: str):
table_handler.execute(
"""
DELETE FROM devices_auth
WHERE _id = ? AND record_type = '人行'
""", (_id,)
)
@staticmethod
def delete_invalid_auth_record(table_handler: BaseTable, device_id: int, _id: str, record_type: str = '人行'):
table_handler.execute(
"""
DELETE FROM devices_auth
WHERE device_id = ? AND _id = ? AND record_type = ?
""",
(device_id, _id, record_type)
)
@staticmethod
def delete_access_device_info(table_handler: BaseTable, device_id: int):
# 1. 确认设备ID有效
if not DevicesTable.exits(table_handler, device_id):
raise InvalidException(f"设备:{device_id} 不存在")
# 2. 获取关联授权下的所有完成下放的人员信息
householder_infos = DevicesTable.get_auth_householders_info(table_handler, device_id)
if len(householder_infos) > 0:
# 3. 移除对应设备中所有的人员信息
sc = ServicesCall()
success_ids = []
for index, householder_info in enumerate(householder_infos):
_callback, code, _ = sc.del_face(device_id,
DelFaceItem(user_id=str(householder_info["id"]),
device_ids=str([device_id])))
if not _callback:
# 存在异常时,回滚已删除掉的人脸
failed = []
msgs = []
for success_id in success_ids:
_back, code, msg = sc.add_face(device_id, AddFaceItem(
name=householder_infos[success_id]["name"],
user_id=str(householder_infos[success_id]["id"]),
phone_number=householder_infos[success_id]["phone"],
face_url=householder_infos[success_id]["url"],
device_ids=str([device_id]),
start_date=householder_infos[success_id]["sdate"],
expire_date=householder_infos[success_id]["edate"]
))
if not _back:
failed.append(householder_infos[success_id]["id"])
msgs.append(msg)
if len(failed) == 0:
raise InvalidException(
f"住户 - {householder_info['id']} 人脸授权移除失败,错误码{code}, {msgs}, 已完成回滚")
else:
raise InvalidException(
f"住户 - {householder_info['id']} 人脸授权移除失败,错误码{code}, {msgs}, 回滚失败")
success_ids.append(index)
# 4. 移除设备的关联记录
table_handler.execute(
"""
DELETE FROM devices_auth
WHERE device_id = ? AND record_type = '人行'
""", (device_id,)
)
table_handler.execute(
"""
DELETE FROM devices_scope
WHERE device_id = ?
""", (device_id,)
)
return {"status": True}
@staticmethod
def exits(table_handler: BaseTable, device_id: int):
table_handler.query(
"""
SELECT device_id FROM devices
WHERE device_id = ?
""", (device_id,)
)
res = table_handler.cursor.fetchall()
if res:
return True
else:
return False
@staticmethod
def bind_exits(table_handler: BaseTable, device_id: int):
table_handler.query(
"""
SELECT bind_unit_id
FROM devices_scope
WHERE device_id = ?
""", (device_id,)
)
res = table_handler.cursor.fetchall()
if res:
return True
else:
return False

1369
SCLP/models/householders.py Normal file

File diff suppressed because it is too large Load Diff

303
SCLP/models/houses.py Normal file
View File

@@ -0,0 +1,303 @@
# -*- coding:utf-8 -*-
"""
@Author : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc : 房产信息表查&改
"""
import csv
import json
import os
import traceback
from utils import logger
from utils.database import BaseTable
from utils.misc import now_datetime_second, extract_fixed_length_number
class HousesTable(BaseTable):
@staticmethod
def check(table_handler: BaseTable):
"""检测是否存在当前表"""
table_handler.query("SELECT name FROM sqlite_master WHERE type='table' AND name='houses'")
if table_handler.cursor.fetchone() is None:
table_handler.execute(
f"""
CREATE TABLE houses (
room_id TEXT UNIQUE,
house_name TEXT UNIQUE,
project_id TEXT,
project_name TEXT,
area_id TEXT,
area_name TEXT,
building_id TEXT,
building_name TEXT,
unit_id TEXT,
unit_name TEXT,
floor_id TEXT,
floor_name TEXT,
room_name TEXT,
householder_count INTEGER,
update_datetime TEXT
)
"""
)
# 根据导出数据生成内置数据
init_config_path = os.path.join(os.path.dirname(os.path.abspath("__file__")), "data/InitialData/houses.csv")
csv_file = open(init_config_path, "w", encoding="utf8")
csv_file.write(
"房屋ID, 房屋编号, 项目ID, 所属项目, 区域ID, 所属区域, 楼栋ID, 所属楼栋, 单元ID, 所属单元, 楼层ID, 所属楼层, 房间号, 住户数量\n")
room_info_path = os.path.join(os.path.dirname(os.path.abspath("__file__")), "data/ExportData/room.txt")
if os.path.exists(room_info_path):
with open(room_info_path, "r", encoding="utf8") as f:
file_content = f.read()
file_content = file_content.replace("ISODate(", "").replace(")", "").replace("'", "\"")
room_info = json.loads(file_content)
for item in room_info:
room_id = item.get("_id", "")
project_id = item["project_id"]
project = item["project_name"]
area_id = item.get("area_id", "")
area = item.get("area_name", "")
building_id = item.get("build_id", "")
building = item.get("building_name", "")
unit_id = item.get("unit_id", "")
unit = item.get("unit_name", "")
floor_id = item.get("floor_id", "")
floor = item.get("floor_name", "")
room = item.get("num", "")
wait_write = [room_id,
'-'.join([i for i in [project, area, building, unit, floor, room] if i != '']),
project_id, project, area_id, area, building_id, building,
unit_id, unit, floor_id, floor, room, str(len(item.get("households", [])))]
csv_file.write(', '.join(wait_write) + "\n")
csv_file.flush()
csv_file.close()
if os.path.exists(init_config_path):
with open(init_config_path, newline='', encoding='utf8') as csvfile:
csvreader = csv.reader(csvfile)
head = next(csvreader)
data = []
if len(head) == 14:
for row in csvreader:
room_id = row[0].strip()
house_name = row[1].strip()
project_id = row[2].strip()
project_name = row[3].strip()
area_id = row[4].strip() if row[4].strip() else None
area_name = row[5].strip() if row[5].strip() else None
building_id = row[6].strip() if row[6].strip() else None
building_name = row[7].strip() if row[7].strip() else None
unit_id = row[8].strip() if row[8].strip() else None
unit_name = row[9].strip() if row[9].strip() else None
floor_id = row[10].strip() if row[10].strip() else None
floor_name = row[11].strip() if row[11].strip() else None
room_name = row[12].strip()
householder_count = int(row[13].strip())
update_datetime = now_datetime_second()
data.append((room_id, house_name, project_id, project_name, area_id, area_name,
building_id, building_name, unit_id, unit_name, floor_id, floor_name,
room_name, householder_count, update_datetime))
table_handler.executemany(
f"""
INSERT INTO houses
(room_id, house_name, project_id, project_name, area_id, area_name,
building_id, building_name, unit_id, unit_name, floor_id, floor_name,
room_name, householder_count, update_datetime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (room_id) DO NOTHING
""",
data
)
@staticmethod
def get_house_detail_info(table_handler: BaseTable, room_id):
"""根据房屋ID获取房产详细信息"""
table_handler.query(
"""
SELECT room_id, project_id, room_name, project_name
FROM houses
WHERE room_id = ?
""", (room_id,)
)
res = table_handler.cursor.fetchall()
if res:
return {
"id": res[0][0],
"project_id": res[0][1],
"name": res[0][2],
"type": 1,
"subtype": 0,
"project_name": res[0][3]
}
else:
return None
@staticmethod
def get_unit_id_by_room_id(table_handler: BaseTable, room_id):
"""根据房屋ID获取房产详细信息"""
table_handler.query(
"""
SELECT unit_id
FROM houses
WHERE room_id = ?
""", (room_id,)
)
res = table_handler.cursor.fetchall()
if res:
return res[0][0]
else:
return None
@staticmethod
def get_house_ty_info(table_handler: BaseTable, project_id: str, room_id: str) -> dict | None:
"""查询房产真实信息"""
table_handler.query(
"""
SELECT houses.room_id, house_name, project_id, corp_id,
building_name, unit_name, floor_name, room_name
FROM houses
LEFT JOIN subsystem ON houses.room_id = subsystem.room_id
WHERE project_id = ? AND houses.room_id = ?
""", (project_id, room_id)
)
res = table_handler.cursor.fetchall()
if res:
building = extract_fixed_length_number(res[0][4])
unit = extract_fixed_length_number(res[0][5])
floor = extract_fixed_length_number(res[0][6])
room = extract_fixed_length_number(res[0][7])
ty_house_id = f"{building}{unit}{floor}{room}"
return {
"id": res[0][0],
"house_name": res[0][1],
"ty_house_id": ty_house_id,
"project_id": res[0][2],
"corp_id": res[0][3]
}
else:
return None
@staticmethod
def get_items_by_dynamic_item(table_handler: BaseTable, query_target: str, query_item: dict):
sub_sql_list = []
for key, value in query_item.items():
if isinstance(value, int):
sub_sql_list.append(f"{key}_id = {value}")
else:
sub_sql_list.append(f"{key}_id = '{value}'")
sub_sql = "" if len(sub_sql_list) == 0 else "WHERE " + " and ".join(sub_sql_list)
try:
table_handler.query(
f"""
SELECT DISTINCT {query_target}_id, {query_target}_name
FROM houses {sub_sql}
"""
)
res = table_handler.cursor.fetchall()
if res:
item_list = [{"_id": i[0], "_name": i[1]} for i in res if i[0] is not None]
return item_list
else:
return []
except Exception as e:
logger.Logger.error(f"{type(e).__name__}, {e}")
if logger.DEBUG:
traceback.print_exc()
return []
@staticmethod
def get_householder_count(table_handler: BaseTable, room_id: str):
table_handler.query(
"""
SELECT householder_count
FROM houses
WHERE room_id = ?
""",
(room_id,),
)
res = table_handler.cursor.fetchall()
if res:
return res[0][0]
else:
return None
@staticmethod
def update_householder_count(table_handler: BaseTable, room_id: str, householder_count: int):
table_handler.execute(
"""
UPDATE houses SET
householder_count=?,
update_datetime=?
WHERE room_id=?
""",
(
householder_count,
now_datetime_second(),
room_id
),
)
return True
@staticmethod
def get_unit_ids(table_handler: BaseTable, building_id: str):
table_handler.execute(
"""
SELECT DISTINCT unit_id
FROM houses
WHERE building_id = ?
""", (building_id,)
)
res = table_handler.cursor.fetchall()
if res:
return [i[0] for i in res]
else:
return []
@staticmethod
def exists(table_handler: BaseTable, room_id: str):
table_handler.query(
"""
SELECT house_name
FROM houses
WHERE room_id = ?
""",
(room_id,)
)
res = table_handler.cursor.fetchall()
if res:
return True
else:
return False
@staticmethod
def building_exists(table_handler: BaseTable, building_id: str):
table_handler.query(
"""
SELECT DISTINCT building_id
FROM houses
WHERE building_id = ?
""",
(building_id,)
)
res = table_handler.cursor.fetchall()
if res:
return True
else:
return False
@staticmethod
def unit_exists(table_handler: BaseTable, unit_id: str):
table_handler.query(
"""
SELECT DISTINCT unit_id
FROM houses
WHERE unit_id = ?
""",
(unit_id,)
)
res = table_handler.cursor.fetchall()
if res:
return True
else:
return False

1019
SCLP/models/parkinglots.py Normal file

File diff suppressed because it is too large Load Diff

113
SCLP/models/products.py Normal file
View File

@@ -0,0 +1,113 @@
# -*- coding:utf-8 -*-
"""
@Author : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc : 内置的产品信息表在初始化时会初始化csv进行覆盖
"""
import csv
import os
from datetime import datetime
from pydantic import BaseModel
from utils import logger
from utils.database import BaseTable
from utils.misc import now_datetime_second
class Product(BaseModel):
product_id: str
product_name: str
node_type: str
class ProductsTable(BaseTable):
@staticmethod
def check(table_handler: BaseTable):
"""检测是否存在当前表"""
init_config_path = os.path.join(os.path.dirname(os.path.abspath("__file__")), "data/InitialData/products.csv")
if os.path.exists(init_config_path):
table_handler.execute("DROP TABLE IF EXISTS products;")
table_handler.execute(
f"""
CREATE TABLE products (
product_id TEXT,
product_name TEXT,
node_type TEXT,
update_datetime TEXT,
PRIMARY KEY (product_id)
)
"""
)
if os.path.exists(init_config_path):
with open(init_config_path, newline='', encoding='utf8') as csvfile:
csvreader = csv.reader(csvfile)
head = next(csvreader)
data = []
if len(head) == 3:
for row in csvreader:
product_id = row[0].strip()
product_name = row[1].strip()
node_type = row[2].strip()
update_datetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
data.append((product_id, product_name, node_type, update_datetime))
table_handler.executemany(
f"""
INSERT INTO products
(product_id, product_name, node_type, update_datetime)
VALUES (?, ?, ?, ?)
""",
data
)
table_handler.query("SELECT name FROM sqlite_master WHERE type='table' AND name='brands'")
if table_handler.cursor.fetchone() is None:
table_handler.execute(
f"""
CREATE TABLE brands (
brand_id INT,
brand_name TEXT,
status TEXT,
add_datetime TEXT,
update_datetime TEXT,
PRIMARY KEY (brand_id)
)
"""
)
init_config_path = os.path.join(os.path.dirname(os.path.abspath("__file__")), "data/InitialData/brands.csv")
if os.path.exists(init_config_path):
with open(init_config_path, newline='', encoding='utf8') as csvfile:
csvreader = csv.reader(csvfile)
head = next(csvreader)
data = []
if len(head) == 3:
for row in csvreader:
brand_id = row[0].strip()
brand_name = row[1].strip()
status = row[2].strip()
data.append((brand_id, brand_name, status, now_datetime_second(), now_datetime_second()))
table_handler.executemany(
f"""
INSERT INTO brands
(brand_id, brand_name, status, add_datetime, update_datetime)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT (brand_id) DO NOTHING
""",
data
)
@staticmethod
def get_product_info(table_handler: BaseTable, product_id: str):
table_handler.query(
"""
SELECT product_name, node_type
FROM products
WHERE product_id = ?
""",
(product_id,)
)
res = table_handler.cursor.fetchall()
if res:
return Product(product_id=product_id, product_name=res[0][0], node_type=res[0][1])
else:
return None

113
SCLP/models/sessions.py Normal file
View File

@@ -0,0 +1,113 @@
# -*- coding:utf-8 -*-
"""
@Author : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc : 记录一些会话数据
"""
import time
from utils.database import BaseTable
class SessionsTable(BaseTable):
@staticmethod
def check(table_handler: BaseTable):
"""检测是否存在当前表"""
table_handler.query("SELECT name FROM sqlite_master WHERE type='table' AND name='sessions'")
if table_handler.cursor.fetchone() is None:
table_handler.execute(
f"""
CREATE TABLE sessions (
session_id TEXT,
username TEXT,
token TEXT,
captcha TEXT,
last_timestamp TEXT,
PRIMARY KEY (session_id)
)
"""
)
table_handler.execute(
f"""
CREATE INDEX idx_sessions_token ON sessions(token);
"""
)
# 去除冗余的验证会话信息
table_handler.execute(
f"""
DELETE FROM sessions WHERE last_timestamp < {int(time.time() * 1000) - 3 * 24 * 60 * 60 * 1000}
"""
)
@staticmethod
def get_captcha(table_handler: BaseTable, session_id: str):
table_handler.query(
"""
SELECT captcha
FROM sessions
WHERE session_id = ?
""",
(session_id,),
)
res = table_handler.cursor.fetchall()
if res:
return res[0][0]
else:
return None
@staticmethod
def insert(table_handler: BaseTable, session_id, captcha):
timestamp = str(int(time.time() * 1000))
table_handler.execute(
"""
INSERT INTO sessions
(session_id, captcha, last_timestamp)
VALUES (?, ?, ?)
ON CONFLICT (session_id)
DO UPDATE SET captcha=?, last_timestamp=?
""",
(
session_id,
captcha,
timestamp,
captcha,
timestamp,
),
)
return True
@staticmethod
def update(table_handler: BaseTable, session_id: str, username: str, token: str):
timestamp = str(int(time.time() * 1000))
table_handler.execute(
"""
UPDATE sessions SET
username=?,
token=?,
last_timestamp=?
WHERE session_id=?
""",
(
username,
token,
timestamp,
session_id
),
)
return True
@staticmethod
def check_token(table_handler: BaseTable, timestamp: str, token: str):
table_handler.query(
"""
SELECT captcha
FROM sessions
WHERE last_timestamp > ? and token = ?
""",
(timestamp, token),
)
res = table_handler.cursor.fetchall()
if res:
return True
else:
return False

95
SCLP/models/spaces.py Normal file
View File

@@ -0,0 +1,95 @@
# -*- coding:utf-8 -*-
"""
@Author : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc : 子系统映射表 增&改&查
"""
import csv
import os
from models.houses import HousesTable
from utils.database import BaseTable
from utils.misc import now_datetime_second, sql_export_xls
class SpacesTable(BaseTable):
@staticmethod
def get_sub_system_name_by_room_id(table_handler: BaseTable, room_id: str):
table_handler.query(
"""
SELECT sub_space_name
FROM subsystem
WHERE room_id = ?
""", (room_id,)
)
res = table_handler.cursor.fetchall()
if res:
return res[0][0]
else:
return None
@staticmethod
def get_space_info_by_sub_space_name(table_handler: BaseTable, sub_space_name: str):
"""根据第三方ID获取对应的房产信息"""
table_handler.query(
"""
SELECT subsystem.room_id, house_name, project_id, sub_system_id
FROM subsystem
LEFT JOIN houses ON subsystem.room_id = houses.room_id
WHERE sub_space_name = ?
""", (sub_space_name,)
)
res = table_handler.cursor.fetchall()
if res:
return {
"room_id": res[0][0],
"house_name": res[0][1],
"project_id": res[0][2],
"sub_system_id": res[0][3]
}
else:
return None
@staticmethod
def get_aiot_platform_data(table_handler: BaseTable):
query = """
SELECT project_id, houses.room_id, house_name, COALESCE(subsystem_id, ''), COALESCE(sub_space_name, '')
FROM houses
LEFT JOIN subsystem ON subsystem.room_id = houses.room_id
"""
file_path = os.path.join(f"data/AIOT平台空间数据{now_datetime_second().replace(':', '_')}.xls")
sql_export_xls(query, table_handler.connection, file_path,
"房屋子系统映射数据表",
["项目id", "房屋id", "房屋名称", "子系统id", "子系统空间名称"])
return file_path
@staticmethod
def get_sub_system_data(table_handler: BaseTable):
query = "SELECT subsystem_id, sub_space_name FROM subsystem"
file_path = os.path.join(f"data/子系统空间数据{now_datetime_second().replace(':', '_')}.xls")
sql_export_xls(query, table_handler.connection, file_path,
"子系统数据表",
["子系统id", "子系统空间名称"])
return file_path
@staticmethod
def update(table_handler: BaseTable, objs: list):
data = []
for obj in objs:
data.append((obj[0], now_datetime_second(), obj[1], obj[2]))
table_handler.executemany(
f"""
UPDATE subsystem
SET room_id = ?, update_datetime = ?
WHERE subsystem_id = ? and sub_space_name = ?
""", data
)
@staticmethod
def exits_room_id(table_handler: BaseTable, room_id: str):
table_handler.query("SELECT room_id FROM spaces WHERE room_id = ?", (room_id,))
if table_handler.cursor.fetchone() is not None:
return True
else:
return False

200
SCLP/models/subsystem.py Normal file
View File

@@ -0,0 +1,200 @@
# -*- coding:utf-8 -*-
"""
@Author : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc : 子系统房产信息表
"""
import csv
import json
import os
import time
from typing import Optional
from pydantic import BaseModel, Field, field_validator
from models.spaces import SpacesTable
from utils.database import BaseTable, get_table_handler
from utils.misc import now_datetime_second, InvalidException, generate_captcha_text
class HouseDetailInfo(BaseModel):
project_id: str
subsystem_id: str
subsystem_name: str
subsystem_data: str
createby_id: str
subsystem_extend: dict
create_time: Optional[int]
corp_id: Optional[str]
message_id: Optional[str] = Field(alias="_id")
action: str = "insert"
house_id: Optional[str] = None
house_name: Optional[str] = None
@field_validator("subsystem_extend")
def check_subsystem_extend(cls, value):
if value.get("label", None) is None:
raise InvalidException("subsystem_extend 中 label 值缺失")
return value
# @field_validator("house_id")
# def check_house_id(cls, value, values):
# th = get_table_handler()
# if value is None or value == "":
# label = values.data.get("subsystem_extend")["label"]
# space_info = SpacesTable.get_space_info_by_sub_space_name(th, label)
# if space_info is None:
# raise InvalidException(f"subsystem_extend - label:{label} 不在映射表中")
# if SubsystemTable.exits_room_id(th, space_info["room_id"]):
# raise InvalidException(f"house_id:{space_info['room_id']} 记录已存在,禁止插入操作")
# return space_info["room_id"]
# if not SpacesTable.exits_room_id(th, value):
# raise InvalidException("映射表中不存在对应的 house_id")
# else:
# return value
# @field_validator("house_name")
# def check_house_name(cls, value, values):
# th = get_table_handler()
# if value is None:
# label = values.data.get("subsystem_extend")["label"]
# space_info = SpacesTable.get_space_info_by_sub_space_name(th, label)
# if space_info is None:
# raise InvalidException(f"subsystem_extend - label:{label} 不在映射表中")
# if SubsystemTable.exits_room_id(th, space_info["room_id"]):
# raise InvalidException(f"house_id:{space_info['room_id']} 记录已存在,禁止插入操作")
# return space_info["house_name"]
# return value
class SubsystemTable(BaseTable):
@staticmethod
def check(table_handler: BaseTable):
"""检测是否存在当前表"""
table_handler.query("SELECT name FROM sqlite_master WHERE type='table' AND name='subsystem'")
if table_handler.cursor.fetchone() is None:
table_handler.execute(
f"""
CREATE TABLE subsystem (
room_id TEXT UNIQUE,
subsystem_id TEXT,
subsystem_project_id TEXT,
sub_space_name TEXT,
subsystem_name TEXT,
subsystem_data TEXT,
subsystem_extend TEXT,
createby_id TEXT,
corp_id TEXT,
_id TEXT,
create_time INTEGER,
update_time INTEGER,
update_datetime TEXT,
PRIMARY KEY (subsystem_id, subsystem_project_id, sub_space_name)
)
"""
)
init_config_path = os.path.join(os.path.dirname(os.path.abspath("__file__")), "data/InitialData/subsystem.csv")
if os.path.exists(init_config_path):
with open(init_config_path, newline='', encoding='utf8') as csvfile:
csvreader = csv.reader(csvfile)
head = next(csvreader)
if len(head) == 10:
data = []
for row in csvreader:
room_id = row[0].strip()
subsystem_project_id = row[1].strip()
sub_space_name = row[2].strip()
subsystem_name = row[3].strip()
subsystem_data = row[4].strip()
subsystem_extend = row[5].strip()
createby_id = row[6].strip()
corp_id = row[7].strip()
_id = row[8].strip()
create_time = int(row[9].strip())
update_datetime = now_datetime_second()
data.append((room_id, subsystem_project_id, sub_space_name, subsystem_name, subsystem_data, subsystem_extend,
createby_id, corp_id, _id, create_time, int(time.time() * 1000), update_datetime))
table_handler.executemany(
f"""
INSERT INTO subsystem
(room_id, subsystem_project_id, sub_space_name, subsystem_name, subsystem_data, subsystem_extend,
createby_id, corp_id, _id, create_time, update_time, update_datetime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (room_id) DO NOTHING
""", data
)
@staticmethod
def get_house_detail_info_by_project_id(table_handler: BaseTable, project_id: str) -> list:
"""根据项目ID获取查找子系统空间结构中的房间信息"""
table_handler.query(
"""
SELECT subsystem.room_id, sub_space_name, house_name, subsystem_project_id,
subsystem_id, subsystem_name, subsystem_data, subsystem_extend,
createby_id, corp_id, _id, create_time, update_time
FROM subsystem
LEFT JOIN houses ON subsystem.room_id = houses.room_id
WHERE subsystem_project_id = ?
ORDER BY create_time DESC
""", (project_id,)
)
res = table_handler.cursor.fetchall()
house_detail_info_list = []
if res:
for info in res:
subsystem_extend = json.loads(info[7].replace("'", '"').replace("None", "null"))
subsystem_extend["label"] = info[1]
house_detail_info_list.append({
"house_id": info[0] if info[0] else "",
"house_name": info[2] if info[0] else "",
"project_id": info[3],
"subsystem_id": info[4],
"subsystem_name": info[5],
"subsystem_data": info[6],
"subsystem_extend": subsystem_extend,
"createby_id": info[8],
"corp_id": info[9],
"_id": generate_captcha_text(16).lower(),
"create_time": info[11],
"update_time": info[12],
"is_stop": False,
"valid": True,
"ids": None
})
return house_detail_info_list
@staticmethod
def add_sub_system_house_info(table_handler: BaseTable, obj: HouseDetailInfo):
"""添加房产信息"""
nt = now_datetime_second()
if obj.action == "insert":
table_handler.execute(
"""
INSERT OR IGNORE INTO subsystem
(subsystem_id, subsystem_project_id, sub_space_name, subsystem_name, subsystem_data, subsystem_extend,
createby_id, corp_id, _id, create_time, update_time, update_datetime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (obj.subsystem_id, obj.project_id, obj.subsystem_extend["label"], obj.subsystem_name, obj.subsystem_data, str(obj.subsystem_extend),
obj.createby_id, obj.corp_id, obj.message_id, obj.create_time, int(time.time() * 1000), nt)
)
else:
table_handler.execute(
"""
UPDATE subsystem
SET subsystem_id = ?, subsystem_project_id = ?, sub_space_name = ?, subsystem_name = ?,
subsystem_data = ?, subsystem_extend = ?,
createby_id = ?, corp_id = ?, _id = ?, create_time = ?, update_time = ?, update_datetime = ?
WHERE room_id = ?
""", (obj.subsystem_id, obj.project_id, obj.subsystem_extend["label"], obj.subsystem_name,
obj.subsystem_data, str(obj.subsystem_extend),
obj.createby_id, obj.corp_id, obj.message_id,
obj.create_time, int(time.time() * 1000), nt, obj.house_id)
)
@staticmethod
def exits_room_id(table_handler: BaseTable, room_id: str):
table_handler.query("SELECT room_id FROM subsystem WHERE room_id = ?", (room_id,))
if table_handler.cursor.fetchone() is not None:
return True
else:
return False