修改架构;

重新搭建flask相关基础代码架构
duizhaopin
apan 3 years ago
parent b521855947
commit 19ed6c9781

@ -1,33 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 09:44:57
'''
from sqlalchemy import or_, asc
from Business.Repository import Repository
from DataEntity.ClientModels import EntityClient
# 用户操作业务逻辑类
class BllClient(Repository):
# _instance_lock = threading.Lock()
# #实现单例模式
# def __new__(cls, *args, **kwargs):
# if not hasattr(BllClient, "_instance"):
# with BllClient._instance_lock:
# if not hasattr(BllClient, "_instance"):
# BllClient._instance = object.__new__(cls)
# return BllClient._instance
def __init__(self, entityType=EntityClient):
return super().__init__(entityType)
# 模糊查询根据客户端编号和客户端名字
def like_ClientId_or_Name(self, searchValue):
return self.findList(or_(EntityClient.client_code.like('%' + searchValue + '%'),
EntityClient.client_name.like('%' + searchValue + '%'))).all()
def getAllClientList(self):
return self.findList().order_by(asc(EntityClient.client_code)).all()

@ -1,62 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 10:27:10
'''
# from Common.utils import Utils
from DataEntity.HumitureRecordModels import EntityHumitureRecord
from Business.Repository import Repository
# 功能模块
class BllHumitureRecord(Repository):
# _instance_lock = threading.Lock()
# #实现单例模式
# def __new__(cls, *args, **kwargs):
# if not hasattr(BllHumitureRecord, "_instance"):
# with BllHumitureRecord._instance_lock:
# if not hasattr(BllHumitureRecord, "_instance"):
# BllHumitureRecord._instance = object.__new__(cls)
# return BllHumitureRecord._instance
def __init__(self, entityType=EntityHumitureRecord):
return super().__init__(entityType)
# 获取温湿度列表
def getHumitureList(self, customerId, pageParam):
queryStr = 'select * from ((select * from rms_humiture_record where client_id=:client_id) '
queryStr += ' union all (select * from rms_humiture_record where client_id!=:client_id order by client_name ASC ) )t order by t.record_date DESC '
queryCountStr = 'select COUNT(*) from ((select * from rms_humiture_record where client_id=:client_id) '
queryCountStr += ' union all (select * from rms_humiture_record where client_id!=:client_id order by client_name ASC ) )t order by t.record_date DESC '
# queryParams = {"clientId": CurrentInfo.ClientInfo.client_id}
queryParams = {"client_id": customerId}
templateList = self.execute(queryStr + ' limit ' + str((pageParam.curPage-1)
* pageParam.pageRows)+','+str(pageParam.pageRows), queryParams).fetchall()
pageParam.totalRecords = self.execute(
queryCountStr, queryParams).fetchone()[0]
jsonData = Utils.mysqlTable2Model(templateList)
return jsonData
def insert_one(self, entity):
self.insert(entity)
# if __name__ == '__main__':
# for x in range(100000):
# en = EntityHumitureRecord(
# record_id=str(Utils.UUID()),
# device_id='',
# client_id='72e70542-b70d-11e8-aea5-448a5bc6c418',
# client_name='1号终端',
# customer_id='',
# temperature='30',
# humidity='50',
# record_date=datetime.datetime.now(),
# is_add=1)
# BllHumitureRecord().insert_one(en)

@ -1,35 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 11:31:27
'''
from sqlalchemy import and_, or_
from Business.Repository import Repository
from DataEntity.LogInfoModels import EntityLog
# 功能模块
class BllLog(Repository):
# _instance_lock = threading.Lock()
# #实现单例模式
#
# def __new__(cls, *args, **kwargs):
# if not hasattr(BllLog, "_instance"):
# with BllLog._instance_lock:
# if not hasattr(BllLog, "_instance"):
# BllLog._instance = object.__new__(cls)
# return BllLog._instance
def __init__(self, entityType=EntityLog):
return super().__init__(entityType)
# 查询某个时间段的日志数据
def query_LogData_between_time(self, start_time, end_time):
self.findList(and_(EntityLog.operate_date >= start_time,
EntityLog.operate_date <= end_time))
# 获取模糊查询日志数据
def like_Log_data(self, searchValue):
return self.findList(or_(EntityLog.operate_user_name.like('%' + searchValue + '%'),
EntityLog.operate_type.like('%' + searchValue + '%')))

@ -1,141 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/14 08:39:04
'''
import threading
import datetime
from sqlalchemy import and_, or_
from Common.utils import Utils
from Business.Repository import Repository
from DataEntity.MedicamentModels import EntityMedicamentVariety
from DataEntity.UserModels import EntityUser
# 药剂品种业务逻辑类
class BllMedicamentVariety(Repository):
_instance_lock = threading.Lock()
# #实现单例模式
# def __new__(cls, *args, **kwargs):
# if not hasattr(BllMedicamentVariety, "_instance"):
# with BllMedicamentVariety._instance_lock:
# if not hasattr(BllMedicamentVariety, "_instance"):
# BllMedicamentVariety._instance = object.__new__(cls)
# return BllMedicamentVariety._instance
def __init__(self, entityType=EntityMedicamentVariety):
return super().__init__(entityType)
# 创建药剂品种
def createDrugVariety(
self, customerId, name, english, casNumber,
purity, total, net_weight_unit, net_weight, tp, entityUser=EntityUser()
):
entity = self.findEntity(
and_(
EntityMedicamentVariety.name == name,
EntityMedicamentVariety.purity == purity,
# EntityMedicamentVariety.Unit == unit,
# EntityMedicamentVariety.SpeciUnit == speciUnit,
# EntityMedicamentVariety.Speci == speci
EntityMedicamentVariety.total == total,
EntityMedicamentVariety.net_weight_unit == net_weight_unit,
EntityMedicamentVariety.net_weight == net_weight,
EntityMedicamentVariety.tp == tp,
)
)
if(entity is None):
print(entity, 9999999999999999999)
entity = EntityMedicamentVariety()
entity.variety_id = str(Utils.UUID())
entity.customer_id = customerId
entity.inventory_warning_value = 10
entity.shelf_life_warning_value = 10
entity.use_days_warning_value = 10
entity.name = name
entity.english_name = english
entity.cas_number = casNumber
entity.purity = purity
entity.total = total
entity.net_weight_unit = net_weight_unit
entity.net_weight = net_weight
entity.tp = tp
# 库存总数
entity.total_count = 1
# 在库数量
entity.normal_count = 1
# 领用数量
entity.use_count = 0
# 空瓶数量
entity.empty_count = 0
entity.is_supervise = 0
entity.create_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
entity.create_user_id = entityUser.user_id
entity.create_user_name = entityUser.real_name
self.insert(entity)
# else:
# # 库存总数 + 1
# entity.TotalCount += 1
# # 在库数量 + 1
# entity.NormalCount += 1
# self.update(entity)
entity = self.session.merge(entity)
return entity
# 模糊查询根据药剂名称或英文名称查询
def findEnglishOrChinseNameList(self, params):
return self.findList(or_(EntityMedicamentVariety.name.like('%' + params + '%'),
EntityMedicamentVariety.english_name.like('%' + params + '%')))
# #创建药剂品种
# def createDrugVariety(self, customerId, name, english, casNumber, purity, unit, speciUnit, speci, entityUser=EntityUser()):
# entity = self.findEntity(and_(EntityMedicamentVariety.Name == name, EntityMedicamentVariety.Purity == purity,
# EntityMedicamentVariety.Unit == unit, EntityMedicamentVariety.SpeciUnit == speciUnit, EntityMedicamentVariety.Speci == speci))
# if(entity is None):
# print(entity, 9999999999999999999)
# entity = EntityMedicamentVariety()
# entity.VarietyId = str(Utils.UUID())
# entity.CustomerId = customerId
# entity.InventoryWarningValue = 10
# entity.ShelfLifeWarningValue = 10
# entity.UseDaysWarningValue = 10
# entity.Name = name
# entity.EnglishName = english
# entity.CASNumber = casNumber
# entity.Purity = purity
# entity.Unit = unit
# entity.SpeciUnit = speciUnit
# # 库存总数
# entity.TotalCount = 1
# # 在库数量
# entity.NormalCount = 1
# # 领用数量
# entity.UseCount = 0
# # 空瓶数量
# entity.EmptyCount = 0
# entity.IsSupervise = 0
# entity.Speci = speci
# entity.CreateDate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# entity.CreateUserId = entityUser.UserId
# entity.CreateUserName = entityUser.RealName
# self.insert(entity)
# # else:
# # # 库存总数 + 1
# # entity.TotalCount += 1
# # # 在库数量 + 1
# # entity.NormalCount += 1
# # self.update(entity)
# entity = self.session.merge(entity)
# return entity
# # 模糊查询根据药剂名称或英文名称查询
# def findEnglishOrChinseNameList(self, params):
# return self.findList(or_(EntityMedicamentVariety.Name.like('%' + params + '%'),
# EntityMedicamentVariety.EnglishName.like('%' + params + '%')))

@ -1,32 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 08:39:51
'''
from Business.Repository import Repository
from DataEntity.UserModels import EntityUser
from sqlalchemy import and_
# 用户操作业务逻辑
class BllUser(Repository):
# _instance_lock = threading.Lock()
# #实现单例模式
# def __new__(cls, *args, **kwargs):
# if not hasattr(BllUser, "_instance"):
# with BllUser._instance_lock:
# if not hasattr(BllUser, "_instance"):
# BllUser._instance = object.__new__(cls)
# return BllUser._instance
def __init__(self, entityType=EntityUser):
return super().__init__(entityType)
# 用户账号密码登录
def login(self, userAccount, userPwd):
print(userAccount, userPwd,
"++++++++++++++++++++++++++++++++++++++++++++++++++")
print(self.findEntity(and_(EntityUser.account ==
userAccount, EntityUser.password == userPwd)))
return self.findEntity(and_(EntityUser.account == userAccount, EntityUser.password == userPwd))

@ -1,32 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 17:07:42
'''
import threading
from sqlalchemy import or_, desc
from DataEntity.WarningModels import EntityWarning
from Business.Repository import Repository
# 功能模块
class BllWarning(Repository):
_instance_lock = threading.Lock()
# #实现单例模式
# def __new__(cls, *args, **kwargs):
# if not hasattr(BllWarning, "_instance"):
# with BllWarning._instance_lock:
# if not hasattr(BllWarning, "_instance"):
# BllWarning._instance = object.__new__(cls)
# return BllWarning._instance
def __init__(self, entityType=EntityWarning):
return super().__init__(entityType)
# 定义通过搜索预警对象进行模糊查询
def like_warning_list(self, searchValue, page, limi):
if len(str(page)) == 0 and len(str(limi)) == 0:
return self.findList(or_(EntityWarning.object_name.like('%' + searchValue + '%'), EntityWarning.warning_content.like('%' + searchValue + '%'))).order_by(desc(EntityWarning.warning_date), desc(EntityWarning.is_solve)).all()
return self.findList(or_(EntityWarning.object_name.like('%' + searchValue + '%'), EntityWarning.warning_content.like('%' + searchValue + '%'))).order_by(desc(EntityWarning.warning_date), desc(EntityWarning.is_solve)).offset((page-1)*limi).limit(limi).all()

@ -1,52 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 09:42:59
'''
import json
import datetime
import decimal
from sqlalchemy.ext.declarative import DeclarativeMeta
# sqlalchemy对象编码转换类
class AlchemyEncoder(json.JSONEncoder):
# def _iterencode(self, o, markers=None):
# if isinstance(o, decimal.Decimal):
# return str(o)
# return super(AlchemyEncoder, self)._iterencode(o, markers)
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return str(obj)
elif isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, datetime.date):
return obj.isoformat()
if isinstance(obj.__class__, DeclarativeMeta):
# SQLAlchemy类
fields = {}
for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
data = obj.__getattribute__(field)
try:
json.dumps(data) # 序列化对象
fields[field] = data
if data is None:
fields[field] = ''
except TypeError: # 添加了对datetime的处理
if data is None:
fields[field] = ''
if isinstance(data, datetime.datetime):
fields[field] = data.isoformat()
elif isinstance(data, datetime.date):
fields[field] = data.isoformat()
elif isinstance(data, datetime.timedelta):
fields[field] = (
datetime.datetime.min + data).time().isoformat()
elif isinstance(data, decimal.Decimal):
fields[field] = str(data)
else:
fields[field] = None
# Json编码字典
return fields
return json.JSONEncoder.default(self, obj)

File diff suppressed because it is too large Load Diff

@ -1,228 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/14 08:36:50
'''
import threading
import time
from Business.Warning import BllWarning
from Business.MedicamentVariety import BllMedicamentVariety, Utils, datetime
from DataEntity.WarningModels import EntityWarning
class SupervisionWarning:
def __init__(self):
# 删除视频事件
self.deleteVideoDatetime = None
def supervision_start(self):
p = threading.Thread(target=self.supervision_start_thread)
p.start()
def insert_warning_default(self, customer_id, object_type, object_id, object_name, warning_content):
try:
warning_obj = EntityWarning(
warning_id=str(Utils.UUID()),
customer_id=customer_id,
object_type=object_type,
object_id=object_id,
object_name=object_name,
warning_content=warning_content,
warning_date=datetime.datetime.now(),
warning_user_name='系统',
is_solve=0,
is_add=1
)
bool_ = BllWarning().insert(warning_obj)
if bool_:
print('插入成功!')
except Exception as error:
print(error)
return
def warning_content_type(self, tp):
# 根据object_type俩进行消息区分
content_dict = {
"2": "药剂过期预警:过期药剂[%s](%s), 当前时间: %s; 超出设定过期时间%s; 位置:%s; 号柜%s",
"3": "药剂种类余量预警:药剂种类%s, 当前种类药剂余量%s瓶,小于设定余量%s瓶;",
"1": "药剂保质期预警:药剂 %s(%s) 超过保质期预警线, 当前时间:%s; 设定警戒线:%s天; 位置:%s号柜 %s",
"5": "%s 药柜滤芯保质期预警:药柜滤芯提前预警时间%s天,生产日期%s,当前时间:%s,保质期:%s天; 已达到提前预警时间;",
"6": "出库超期预警:用户[%s]已领用: %s(%s) %s天,超过预警线:%s"
}
return content_dict.get(tp, "")
def supervision_start_thread(self):
while True:
try:
BllWarning().executeNoParam("delete from rms_warning where object_type not in('7') ")
# 查询预警数量和某一类型当前在库数量
SQL = """
SELECT b.variety_id as variety_id, b.customer_id, b.Name, sum(case when a.status = 1 then 1 else 0 end) as normal_count, b.inventory_warning_value
from rms_medicament_variety as b LEFT JOIN rms_medicament as a on b.variety_id = a.variety_id GROUP by b.variety_id
"""
data_obj_list = BllMedicamentVariety().execute(SQL).fetchall()
for data_obj in data_obj_list:
if data_obj.inventory_warning_value:
if data_obj.inventory_warning_value > data_obj.normal_count:
# 封装conent统一化管理
# 封装创建warning方法统一化管理
# 药剂种类余量预警
object_type = 3
content_info = self.warning_content_type(
object_type)
self.insert_warning_default(
customer_id=data_obj.customer_id,
object_type=object_type,
object_id=data_obj.variety_id,
object_name=data_obj.name,
warning_content=content_info % (
data_obj.name,
str(data_obj.normal_count),
str(data_obj.inventory_warning_value)
)
)
time.sleep(1)
# SQL查询过期预警数量
SQL = """
select * from rms_medicament a where a.expiration_date < now();
"""
expire_obj_list = BllWarning().execute(SQL).fetchall()
if expire_obj_list:
for expire_obj in expire_obj_list:
if expire_obj.status != 3:
# 封装conent统一化管理
# 封装创建warning方法统一化管理
# 药剂过期预警
object_type = 2
conent = self.warning_content_type(object_type)
self.insert_warning_default(
customer_id=expire_obj.customer_id,
object_type=object_type,
object_id=expire_obj.medicament_id,
object_name=expire_obj.name,
warning_content=conent % (
expire_obj.name,
expire_obj.bar_code,
str(datetime.datetime.now().strftime(
'%Y-%m-%d %H:%M:%S')),
str(expire_obj.expiration_date or ''),
str(expire_obj.client_code or ''),
str(expire_obj.place or '')
),
)
time.sleep(1)
# SQL查询保质期预警数量
SQL = """
select * from rms_medicament a where a.expiration_date < DATE_ADD(now(), INTERVAL a.shelf_life_warning_value DAY);
"""
expireIdList = [x.medicament_id for x in expire_obj_list]
shelflife_obj_list = BllWarning().execute(SQL).fetchall()
if shelflife_obj_list:
for expire_obj in shelflife_obj_list:
if (expire_obj.status != 3 and expire_obj.medicament_id not in expireIdList):
# 封装conent统一化管理
# 封装创建warning方法统一化管理
# 药剂保质期预警
object_type = 1
conent = self.warning_content_type(object_type)
self.insert_warning_default(
customer_id=expire_obj.customer_id,
object_type=object_type,
object_id=expire_obj.medicament_id,
object_name=expire_obj.name,
warning_content=conent % (
expire_obj.name,
expire_obj.bar_code,
str(datetime.datetime.now().strftime(
'%Y-%m-%d %H:%M:%S')),
str(expire_obj.shelf_life_warning_value),
expire_obj.client_code,
(expire_obj.place if expire_obj.place else '')
)
)
time.sleep(1)
# SQL查询领用超期预警数量
todayDate = datetime.datetime.now().strftime("%Y-%m-%d")
SQL = """
SELECT DATEDIFF('"""+todayDate+"""',STR_TO_DATE(by_user_date,'%Y-%m-%d')) as user_days,
b.use_days_warning_value,a.by_user_name,a.`name`,a.bar_code,a.medicament_id,a.customer_id
FROM rms_medicament a LEFT JOIN rms_medicamentvariety b ON a.variety_id=b.variety_id
WHERE DATEDIFF('"""+todayDate+"""',STR_TO_DATE(by_user_date,'%Y-%m-%d'))>b.use_days_warning_value AND a.`status`=2;
"""
shelflife_obj_list = BllWarning().execute(SQL).fetchall()
if shelflife_obj_list:
for expire_obj in shelflife_obj_list:
# 封装conent统一化管理
# 封装创建warning方法统一化管理
# 出库超期预警
object_type = 6
conent = self.warning_content_type(object_type)
self.insert_warning_default(
customer_id=expire_obj.customer_id,
object_type=object_type,
object_id=expire_obj.medicament_id,
object_name=expire_obj.name,
warning_content=conent % (
expire_obj.by_user_name,
expire_obj.name,
expire_obj.bar_code,
str(expire_obj.user_days),
str(expire_obj.use_days_warning_value)
)
)
time.sleep(1)
# SQL查询药柜滤芯保质期预警
SQL = """
SELECT * FROM `rms_client`;
"""
filter_obj_list = BllWarning().execute(SQL).fetchall()
if filter_obj_list is not None:
for filter_obj in filter_obj_list:
if filter_obj.filter_production_date:
# 滤芯过期提前预警时间 生产日期 + 保质期 - 提前预警天数
filter_expire_date = filter_obj.filter_production_date + datetime.timedelta(days=(
filter_obj.filter_shelf_life - filter_obj.filter_shelf_life_warning_value))
if filter_expire_date <= datetime.datetime.now():
BllWarning_obj = BllWarning().findList(
EntityWarning.object_id == filter_obj.client_id).all()
if not BllWarning_obj:
# 封装conent统一化管理
# 封装创建warning方法统一化管理
# 药柜滤芯保质期预警
object_type = 5
conent = self.warning_content_type(
object_type)
self.insert_warning_default(
customer_id=filter_obj.customer_id,
object_type=object_type,
object_id=filter_obj.client_id,
object_name=filter_obj.client_name,
warning_content=conent % (
filter_obj.client_name,
str(filter_obj.filter_shelf_life_warning_value),
filter_obj.filter_production_date.strftime(
'%Y-%m-%d %H:%M:%S'),
str(datetime.datetime.now().strftime(
'%Y-%m-%d %H:%M:%S')),
str(filter_obj.filter_shelf_life),)
)
time.sleep(1)
except Exception as e:
print(str(e))
# logUtil().debug('预警监测:'+traceback.format_exc())
time.sleep(3600)

@ -1,80 +1,60 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 09:37:21
@Date:2022/07/18 15:59:52
'''
import datetime
import functools
import hashlib
import json
import datetime
import random
import os
import platform
import random
import sys
import hashlib
import uuid
from logging import getLogger as get_logger
from logging.config import dictConfig as log_dict_config
import psutil
from Business.Client import BllClient
from Business.HumitureRecord import BllHumitureRecord
from DataEntity.HumitureRecordModels import EntityHumitureRecord
from dateutil import parser, relativedelta
from django.conf import settings
from django.core.cache import cache
from sqlalchemy import and_
from Common.AlchemyUtils import AlchemyEncoder
sys.path.append('.')
from config.SystemConfig import SystemConfig
# 判断当前系统是linux还是windows
system_name = platform.system()
# 加载settings里面的配置项
log_dict_config(settings.LOGGING)
logger = get_logger('default')
"""通用工具类"""
class Utils(object):
# MD5加密
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
#MD5加密78
def MD5(str):
# 创建md5对象
hl = hashlib.md5()
hl.update(str.encode(encoding='utf-8'))
return hl.hexdigest()
# 获取唯一识别码
@staticmethod
#获取唯一识别码
def UUID():
return str(uuid.uuid1())
@staticmethod
def getMacAddress():
mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
return ":".join([mac[e:e+2] for e in range(0, 11, 2)])
#获取当前设置服务器IP地址
def get_server_ip_address():
ip = ''
try:
ip = SystemConfig.getConfig('serverip')
except:
ip = ''
return ip
# 将sqlAlchemy Sql执行数据对象列表转换为实体列表
@staticmethod
#将sqlAlchemy Sql执行数据对象列表转换为实体列表
def mysqlTable2Model(dataList):
# mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
#return [dict(zip(result.keys(), result.values())) for result in dataList]
return [dict(zip(result.keys(), [(x if x is not None else '') for x in result.values()])) for result in dataList]
# 生成统一格式接口数据
@staticmethod
#生成统一格式接口数据
def resultData(status, message, data=""):
return {"status": status, "message": message, "data": data}
# 生成统一格式接口数据
@staticmethod
def resultAlchemyData(data):
return json.dumps(data, cls=AlchemyEncoder)
return json.dumps({"status": status, "message": message, "data": data}, ensure_ascii=False)
# 按时间生成随机文件名
@staticmethod
#按时间生成随机文件名
def getFileName():
nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # 生成当前的时间
randomNum = random.randint(0, 100) # 生成随机数n,其中0<=n<=100
@ -83,255 +63,136 @@ class Utils(object):
uniqueNum = str(nowTime) + str(randomNum)
return uniqueNum
# 创建文件夹
#获取当前插入U盘路径
@staticmethod
def getUDiskPath():
if system_name == 'Windows':
disk_list = psutil.disk_partitions()
# 获取U盘路径
u_path = [
disk.device for disk in disk_list if disk.opts == 'rw,removable']
if u_path:
return u_path[0]
elif system_name == 'Linux':
r = os.popen('ls -a /media/yanyi')
text = r.read()
r.close()
udisklist = text.splitlines()
if(len(udisklist) >= 3):
return '/media/yanyi/' + udisklist[2]
return ""
#创建文件夹
def mkdir(path):
folder = os.path.exists(path)
if not folder:
os.makedirs(path)
# 随机生成一段sha256加密
# 生成统一格式接口数据
@staticmethod
def sha256_secret():
sha256 = hashlib.sha256()
sha256.update(str(random.random()).encode('utf-8'))
res = sha256.hexdigest()
return res
# 读取redis缓存装饰器
def resultAlchemyData(data):
return json.dumps(data)
'''
@currentTem:当前温度值
@setTem设定温度值
'''
def getStableTemValue(cuerrentTem, setTem):
# 差值
diffValue = 0
# 系数
coeValue = 1
diffValue = abs(cuerrentTem - setTem)
if(diffValue > 6):
coeValue = 1
else:
coeValue = 7 - diffValue
@staticmethod
def redis_cache(key, timeout):
def _redis_cache(func):
def warpper(*args, **kwargs):
# 判断缓存是否存在
if cache.has_key(key):
print('get cache')
data = cache.get(key)
else:
print('没有获取到缓存')
data = func(*args, **kwargs)
cache.set(key, json.loads(
Utils.resultAlchemyData(data)), timeout)
return data
return warpper
return _redis_cache
# 获取最近24小时的值
def get_24_hours(self):
# 获取当前的小时值
data_hour_list = []
curtime_hour = datetime.datetime.now().strftime('%H')
y = int(curtime_hour)
for x in range(24):
data_hour_list.append(str(y) + ':00')
if y == 0:
y = 23
continue
y -= 1
return data_hour_list
# 获取温湿度的数据
def get_temperature_or_humidity(self, params=None):
# params 传参则代表湿度, 不传参就代表温度
# 前段echarts展示series 字段的所有数据
series_list = []
# 获取最近24小时的值
data_hour_list = list(reversed(self.get_24_hours()))
# 获取所有客户端
client_list = BllClient().getAllClientList()
# 客户端名字列表
client_name_list = []
for client_obj in client_list:
client_name_list.append(client_obj.client_name)
# 定义两个字典, 键相同, 一个字典保存次数, 一个字典保存温度总数
temperature_dict = {}
temperature_dict_count = {}
# 获取当前时间
curtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 当前时间减去24小时
start_time = (parser.parse(datetime.datetime.now().strftime(
'%Y-%m-%d %H')) + relativedelta.relativedelta(hours=-23)).strftime('%Y-%m-%d %H:%M:%S')
# 获取温湿度的所有对象
humiture_obj_list = BllHumitureRecord().findList(and_(EntityHumitureRecord.client_id == client_obj.client_id,
EntityHumitureRecord.record_date.between(start_time,
curtime))).all()
# 遍历求出每一个对象
for humiture_obj in humiture_obj_list:
# 获取每一个对象的RecordDate的时间值
hum_hour = humiture_obj.record_date.strftime('%H')
# 判断当前hum_hour是否在定义的字典中, 如果没有,hum_hour作为键
# 1作为当前时间共有几个数值, humiture_obj.Temperature的温度作为值
if hum_hour not in temperature_dict:
temperature_dict_count[hum_hour] = 1
if params:
temperature_dict[hum_hour] = humiture_obj.humidity
else:
temperature_dict[hum_hour] = humiture_obj.temperature
# 如果存在, 数值+1, 温度值叠加
else:
if params:
temperature_dict[hum_hour] += humiture_obj.humidity
else:
temperature_dict[hum_hour] += humiture_obj.temperature
temperature_dict_count[hum_hour] += 1
# 求温度的平均值
for each_count in temperature_dict_count.keys():
if each_count in temperature_dict:
temperature_dict[each_count] = round(temperature_dict[each_count]
/ temperature_dict_count[each_count], 2)
# 求出当前时间近24小时的温度值和小时值
data_temperate = []
for data_hour in data_hour_list:
if len(data_hour) == 4:
data_hour = '0' + str(data_hour)
if str(data_hour[:-3]) in temperature_dict:
# data_temperate.append(temperature_dict[data_hour[:-3]])
if params == 1:
data_temperate.append(random.randint(55, 68))
elif params == 2:
data_temperate.append(random.randint(0, 0))
else:
data_temperate.append(temperature_dict[data_hour[:-3]])
else:
# data_temperate.append('0.0')
if params == 1:
data_temperate.append(random.randint(55, 68))
elif params == 2:
data_temperate.append(random.randint(0, 0))
else:
data_temperate.append('0.0')
series_list.append({"name": client_obj.client_name, "type": "line",
"data": data_temperate,
"markPoint":
{"data": [{"type": "max", "name": "最大值"}, {
"type": "min", "name": "最小值"}]},
"markLine": {"data": [{"type": "average", "name": "平均值"}]}})
flag = "最近24小时湿度变化" if params == 1 else "最近24小时温度变化"
if(params == 1):
flag = "最近24小时湿度变化"
unit = '%RH'
elif(params == 2):
flag = "最近24小时VOC含量变化"
unit = 'ppm'
if(cuerrentTem > setTem):
return round(setTem + diffValue/coeValue, 1)
else:
flag = "最近24小时温度变化"
unit = '°C'
data = {"title": {"text": flag},
"tooltip": {"trigger": "axis"},
# 下载为图片
'toolbox': {
'show': 'true',
'feature': {
'saveAsImage': {
'show': 'true',
'type': 'jpeg',
'name': '温湿度监控折线图',
'excludeComponents': "['toolbox']",
'pixelRatio': '2',
'icon': 'image:///static/img/download.png/'
},
'magicType': {'show': 'true', 'type': ['line', 'bar']},
'restore': {
'show': 'true',
}
}
},
"legend": {"data": client_name_list},
"grid": {"x": 55, "x2": 55, "y2": 24},
"calculable": True,
"xAxis": [{"type": "category",
"boundaryGap": False,
"data": data_hour_list}],
"yAxis": [{"type": "value", "axisLabel": {"formatter": "{value} "+unit}}],
"series": series_list}
return round(setTem - diffValue/coeValue, 1)
#接口数据返回
def true_return(status=0, msg='请求成功!', data=''):
data = {
"status": status,
"msg": msg,
"data": data
}
return data
@staticmethod
def log_exception(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
return func(*args, **kwargs)
except Exception as e:
logger.exception(
"[Error in {}] msg: {}".format(__name__, str(e)))
raise
return wrapper
# # 获取当前用户桌面路径 import winreg
# @staticmethod
# def get_desktop():
# key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
# r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
# return winreg.QueryValueEx(key, "Desktop")[0]
def false_return(status=1, msg='请求失败!', data=''):
data = {
"status": status,
"msg": msg,
"data": data
}
return data
@staticmethod
def get_user_ip(request):
if 'HTTP_X_FORWARDED_FOR' in request.META:
return request.META['HTTP_X_FORWARDED_FOR']
else:
return request.META['REMOTE_ADDR']
def except_return(status=2, msg='', data=''):
data = {
"status": status,
"msg": msg,
"data": data
}
return data
# 发送邮件
@staticmethod
def send_email(email):
from django.core.mail import EmailMultiAlternatives
#分页参数模型
class PageParam(object):
def __init__(self, curPage, pageRows, totalRecords=None, orderType=None, orderField=None,):
self.orderType = orderType # 排序类型 asc=正序 desc=倒序
self.orderField = orderField # 排序字段
self.pageRows = pageRows # 单页行数
self.curPage = curPage # 当前页码
self.totalRecords = totalRecords
#获取总页数
#def getTotalPagesCount(self):
# if(self.totalRecords > 0):
# return self.totalRecords % self.pageRows if self.totalRecords % self.pageRows == 0 else self.totalRecords % self.pageRows + 1
# else:
# return 1
subject = '来自www.1117.link的注册确认邮件'
#药剂操作类型
text_content = '''欢迎注册www.1117.link这里是大鱼的论坛站点专注于Python和Django技术的分享\
如果你看到这条消息说明你的邮箱服务器不提供HTML链接功能请联系管理员'''
html_content = '''
<p>感谢注册 target=blank>www.1117.link</a>\
这里是大鱼的博客和教程站点专注于Python和Django技术的分享</p>
<p>请点击站点链接完成注册确认</p>
<p>此链接有效期为{}</p>
'''.format('127.0.0.1:80', settings.CONFIRM_DAYS)
msg = EmailMultiAlternatives(
subject, text_content, settings.EMAIL_HOST_USER, [email])
msg.attach_alternative(html_content, "text/html")
msg.send()
class DrugRecordType(object):
#入库操作
PutIn = 1
# 获取当前插入U盘路径
#领用操作
Use = 2
@staticmethod
def getUDiskPath():
if system_name == 'Windows':
disk_list = psutil.disk_partitions()
# 获取U盘路径
u_path = [
disk.device for disk in disk_list if disk.opts == 'rw,removable']
if u_path:
return u_path[0]
elif system_name == 'Linux':
r = os.popen('ls -a /media/yanyi')
text = r.read()
r.close()
udisklist = text.splitlines()
if(len(udisklist) >= 3):
return '/media/yanyi/' + udisklist[2]
return ""
#归还操作
Return = 3
#药剂状态类型
class DrugStatus(object):
#在库
Normal = 1
#出库
Out = 2
#空瓶
Empty = 3
# 药剂柜状态类
print(Utils.MD5("123456789"))
class CabinetStatus(object):
Tem = None # 温度
Hum = None # 湿度
FanOn = None # 风机是否开启
LightOn = None # 照明是否亮
LockIsLock = None # 电锁是否上
DoorIsClose = None # 门是否关上
RunLigthStatus = None # 运行状态是否正常
SignalLightStatus = None # 通信状态是否正常
FilterLifeLightStatus = None # 滤芯寿命是否正常
AbnormalLightStatus = None # 异常灯是否亮

@ -0,0 +1,34 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 15:14:51
'''
import json
from werkzeug.exceptions import HTTPException
class APIException(HTTPException):
code = -1
msg = "请求错误"
data = []
def __init__(self, code=None, msg=None, data=None, headers=None):
if code:
self.code = code
if msg:
self.msg = msg
if data:
self.data = data
super(APIException, self).__init__(msg, None)
def get_body(self, environ=None, scope=None):
body = dict(
code=self.code,
msg=self.msg,
data=self.data
)
text = json.dumps(body)
return text
def get_headers(self, environ=None, scope=None):
return [('Content-Type', 'application/json')]

@ -0,0 +1,61 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:10:20
'''
import os
import time
import logging
import logging.handlers
class logUtil(object):
def __init__(self):
self.logger = logging.getLogger("")
# 设置输出的等级
LEVELS = {'NOSET': logging.NOTSET,
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL}
# 创建文件目录
logs_dir = "logs/{0}".format(time.strftime("%Y-%m", time.localtime()))
if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
pass
else:
os.makedirs(logs_dir)
# 修改log保存位置
timestamp = time.strftime("%Y-%m-%d", time.localtime())
logfilename = '%s.txt' % timestamp
logfilepath = os.path.join(logs_dir, logfilename)
rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=logfilepath,
maxBytes=1024 * 1024 * 50,
backupCount=5)
# 设置输出格式
formatter = logging.Formatter(
'[%(asctime)s] %(filename)s->%(funcName)s line:%(lineno)d [%(levelname)s]%(message)s')
rotatingFileHandler.setFormatter(formatter)
# 控制台句柄
console = logging.StreamHandler()
console.setLevel(logging.NOTSET)
console.setFormatter(formatter)
# 添加内容到日志句柄中
self.logger.addHandler(rotatingFileHandler)
self.logger.addHandler(console)
self.logger.setLevel(logging.NOTSET)
def info(self, message):
self.logger.info(message)
def debug(self, message):
self.logger.debug(message)
def warning(self, message):
self.logger.warning(message)
def error(self, message):
self.logger.error(message)
logger = logUtil()

@ -1,49 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/14 13:59:09
'''
import json
import time
import os
class GetDrugTypeData:
# 初始化只打开一次
data = None
@classmethod
def init(cls):
cls.data = cls.open_text()
# 打开json文件
@classmethod
def open_text(cls):
with open(os.path.abspath('.')+'/Common/ReagentDB.json', 'r', encoding='utf-8') as f:
content = json.loads(f.read())
return content
# 模糊搜索
@classmethod
def search_data(cls, search_word):
data_list = []
for drug_dict in cls.data:
if drug_dict['ChineseName'].find(search_word) != -1 or drug_dict['EnglishName'].find(search_word) != -1:
new_dict = {}
new_dict['id'] = drug_dict['CASNumber']
new_dict['value'] = drug_dict['ChineseName']
new_dict['subvalue'] = drug_dict['AliasName']
new_dict['EnglishName'] = drug_dict['EnglishName']
data_list.append(new_dict)
# 根据列表的字典的key的长度进行排序
data_list.sort(key=lambda i: len(i['value']))
return data_list[:5]
if __name__ == '__main__':
GetDrugTypeData.init()
print(GetDrugTypeData().search_data('甲醛'))

@ -1,30 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 15:00:46
'''
# 已同步本地数据库
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
# #终端模块权限实体类
class EntityModuleRelation(declarative_base()):
__tablename__ = "rms_module_relation"
__table_args__ = (
{
"comment": "终端模块权限实体类"
}
)
module_relation_id = Column(String(50), primary_key=True, comment="关系ID")
customer_id = Column(String(50), comment="客户ID")
object_type = Column(String(50), comment="对象类型1角色2用户")
object_id = Column(String(50), comment="对象ID")
module_type = Column(String(50), comment="模块类型")
module_id = Column(String(50), comment="模块ID")
create_date = Column(String(50), comment="创建日期")
create_user_id = Column(String(50), comment="创建用户ID")
create_user_name = Column(String(50), comment="创建用户名")
is_add = Column(Integer, comment="")

@ -1,39 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 14:37:18
'''
def model_name_loer(db_model):
for i in db_model.split("\n"):
base = i.split(" = ")
if len(base) < 2:
continue
# print(base)
name = ""
base_name = base[0].replace(" ", '')
for k, v in enumerate(base_name):
if k != 0 and name and v.isupper():
name += '_'
if v.isupper():
name += v.lower()
else:
name += v
base_d = base[1].replace(" ", '')
comment = base_d.split("#")
try:
db_comment = comment[1]
except IndexError:
db_comment = ''
comment_name = comment[0][:-1] + f', comment="{db_comment}")'
print(f"{name} = {comment_name}")
def create_table(Base):
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqldb://root:123456@localhost:3306/local_rms_db',
pool_recycle=10600, pool_size=100, max_overflow=20)
Base.metadata.create_all(engine)

@ -1 +1 @@
### RMS后台管理系统4.0
# RMS后台管理系统4.0

@ -1,2 +0,0 @@
import pymysql
pymysql.install_as_MySQLdb()

@ -1,261 +0,0 @@
"""
Django settings for YY_RMS_Multiple_Manage project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import logging
import os
import time
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%xoxlv+gx&4$^t8a2nyj56g93ayt-_xl_zl^dy3oru8o)3-r1k'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account',
'user',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', # 默认
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'user.login_required.LoginRequiredMiddleware',
]
# 跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
ROOT_URLCONF = 'YY_RMS_Multiple_Manage.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'YY_RMS_Multiple_Manage.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
X_FRAME_OPTIONS = 'ALLOWALL url'
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS = {
'host': 'localhost',
'port': 6379,
'db': 0,
'password': '123456',
'prefix': 'session',
'socket_timeout': 1
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# 部署路径
STATIC_ROOT = '../YY_RMS_Multiple_Manage/static_files'
# 程序运行时加载 只加载一次
from Common.searchDrug import GetDrugTypeData
GetDrugTypeData.init()
flag_ = True
# 日志管理器
# 给过滤器使用的判断
class RequireDebugTrue(logging.Filter):
# 实现filter方法
def filter(self, record):
return DEBUG
log_file_path = os.path.join(BASE_DIR, 'runserver_log')
if not os.path.exists(log_file_path):
os.makedirs(log_file_path)
print("日志文件夹创建成功~~~~~~~~~~~~~~~~~~~")
LOGGING = {
# 基本设置
'version': 1, # 日志级别
'disable_existing_loggers': False, # 是否禁用现有的记录器
# 日志格式集合
'formatters': {
# 标准输出格式
'standard': {
# [具体时间][日志名字:日志级别名称(日志级别ID)] [输出的模块:输出的函数]:调用日志输出函数的语句所在的代码行-日志内容
'format': '具体时间:[%(asctime)s][%(name)s:%(levelname)s(%(lineno)d)]\n当前文件位置:[%(pathname)s]'
'模块名:[%(module)s:]函数名:[%(funcName)s]:\n[第%(lineno)d行]-%(message)s\n'
}
},
# 过滤器
'filters': {
'require_debug_true': {
'()': RequireDebugTrue,
}
},
# 处理器集合
'handlers': {
# 输出到控制台
'console': {
'level': 'DEBUG', # 输出信息的最低级别
'class': 'logging.StreamHandler',
'formatter': 'standard', # 使用standard格式
'filters': ['require_debug_true', ], # 仅当 DEBUG = True 该处理器才生效
},
# 输出到文件
'log': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'standard',
# 输出位置
# 'filename': os.path.join(BASE_DIR, 'runserver_log/%s.log' % time.strftime('%Y_%m_%d')),
'filename': os.path.join(log_file_path, '%s.log' % time.strftime('%Y_%m_%d')),
'maxBytes': 1024*1024*5, # 文件大小 5M
'backupCount': 5, # 备份份数
'encoding': 'utf8', # 文件编码
},
},
# 日志管理器集合
'loggers': {
# 管理器
'default': {
'handlers': ['console', 'log'],
'level': 'DEBUG',
'propagate': True, # 是否传递给父记录器
},
}
}
from Common.SupervisionWarning import SupervisionWarning
SupervisionWarning().supervision_start()

@ -1,33 +0,0 @@
"""YY_RMS_Multiple_Manage URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = [
# path('admin/', admin.site.urls),
path("^$", view=views.home, name="home"),
# 登录相关接口
re_path('^account/', include("account.urls")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
handler404 = 'YY_RMS_Multiple_Manage.views.page_not_found'

@ -1,76 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 17:03:20
'''
from django.views.decorators.http import require_http_methods
from django.shortcuts import HttpResponse, render, redirect
from Business.Warning import BllWarning
from Common.utils import Utils, logger
from Business.User import BllUser
@Utils.log_exception
@require_http_methods(['GET'])
def home(request):
# 获取预警数量
visitType = ''
try:
user_ = request.session['login_user']
user_id = user_["UserId"]
user = BllUser().findEntity(user_id)
role_id = user.RoleId
SQL = """
SELECT c.module_id, c.module_code, c.sort_index, c.module_name from(SELECT a.module_id, b.module_code,
b.sort_index, b.module_name FROM `rms_module_relation` as a LEFT JOIN rms_module as b on a.module_id =
b.module_id WHERE object_id = :user_id and object_type = 2 and a.module_type=2 UNION
SELECT a.module_id, b.module_code, b.sort_index, b.module_name FROM `rms_module_relation` as a
LEFT JOIN rms_module as b on a.module_id = b.module_id WHERE object_id = :role_id and object_type = 1 and a.module_type=2)
as c ORDER BY c.sort_index asc;
"""
module_relation_obj_list = BllUser().execute(
SQL, {'user_id': user_id, 'role_id': role_id}).fetchall()
module_relation_obj_list = Utils.mysqlTable2Model(
module_relation_obj_list)
# 用列表推导式生成一个ModuleCode列表
object_id_list = [x['module_code']
for x in module_relation_obj_list]
print(object_id_list)
#SQL = 'SELECT count(*) as number_ FROM `RMS_Warning` WHERE IsSolve = 0 and now() > WarningDate;'
SQL = 'SELECT count(*) as number_ FROM `rms_warning` WHERE is_solve = 0'
warning_obj = BllWarning().execute(SQL).fetchone()
warning_nb = warning_obj.number_
try:
user = request.session['login_user']
roleName = user['RoleName']
visitType = request.GET.get('visitType')
request.session['visitType'] = visitType
# if(((visitType=='1') or (visitType=='2'))):
# request.session['visitType']='1'
# else:
# request.session['visitType']=''
request.session.set_expiry(0)
except Exception as e:
print(e)
roleName = ''
return render(request, 'home.html', locals())
except Exception as e:
BllWarning().session.rollback()
logger.debug('数据为空', e)
return render(request, 'home.html', locals())
finally:
BllWarning().session.close()
# 404页面处理方案
def page_not_found(request, exception):
logger.debug('页面没有找到')
return HttpResponse('地址错误')

@ -1,16 +0,0 @@
"""
WSGI config for YY_RMS_Multiple_Manage project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YY_RMS_Multiple_Manage.settings')
application = get_wsgi_application()

@ -1,3 +0,0 @@
from django.contrib import admin
# Register your models here.

@ -1,5 +0,0 @@
from django.apps import AppConfig
class AccountConfig(AppConfig):
name = 'account'

@ -1,3 +0,0 @@
from django.db import models
# Create your models here.

@ -1,3 +0,0 @@
from django.test import TestCase
# Create your tests here.

@ -1,23 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 11:04:24
'''
from django.urls import path, re_path
from django.conf.urls import include
from django.conf.urls.static import static
from django.conf import settings
from . import views
app_name = 'account'
urlpatterns = [
# 登录
re_path(r'login/$', views.account_login, name='account_login'),
re_path(r'barcode/$', views.account_barcode, name='account_barcode'),
# 退出系统
re_path(r'logout/$', views.account_logout, name='account_logout'),
]

@ -1,108 +0,0 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 09:32:40
'''
import datetime
import json
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from Common.utils import Utils, logger
from Business.User import BllUser
from Business.Log import BllLog
from DataEntity.UserModels import EntityUser
from DataEntity.LogInfoModels import EntityLog
def get_user_ip(request):
"""
获取访问用户ip
:param request:
:return:
"""
if 'HTTP_X_FORWARDED_FOR' in request.META:
return request.META['HTTP_X_FORWARDED_FOR']
else:
return request.META['REMOTE_ADDR']
@require_http_methods(['GET', 'POST'])
@csrf_exempt
def account_login(request):
if request.method == 'GET':
try:
del request.session['login_user']
except Exception as e:
pass
return render(request, 'account/login.html', locals())
elif request.method == 'POST':
# try:
userAccount = request.POST['userAccount']
userPassword = Utils.MD5(request.POST['userPassword'])
print(userAccount, '-'+userPassword)
user = BllUser().login(userAccount, userPassword)
print(user, "0000000000000000000000000000000000")
if not user:
logger.info('账号或密码不正确, 登录失败')
return JsonResponse(Utils.resultData(0, '账号或密码不正确, 登录失败'))
else:
if user.is_enabled == 1:
request.session['login_user'] = json.loads(
Utils.resultAlchemyData(user))
visitType = request.GET.get('visitType')
request.session['visitType'] = visitType
request.session.set_expiry(0)
logger.info('登录成功')
user.last_visit_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
BllUser().update(user)
ip_ = get_user_ip(request)
if ip_ is None:
ip_ = ''
log_obj = EntityLog(log_id=str(Utils.UUID()), customer_id=user.customer_id, log_type=1,
operate_user_id=user.user_id, operate_account=user.account, operate_user_name=user.real_name,
operate_type_code='登录后台成功', operate_type='登录成功', ip_address=ip_,
execute_result='用户登录后台成功', operate_date=datetime.datetime.now(),
is_add=1)
BllLog().insert(log_obj)
return JsonResponse(Utils.resultData(1, '登录成功', json.loads(Utils.resultAlchemyData(user))))
else:
logger.info(user.role_name + '正在尝试登陆后台管理')
return JsonResponse(Utils.resultData(0, '您不是管理员或该账户已被禁用, 暂时无法登陆, 请联系管理员'))
@require_http_methods(['GET'])
def account_logout(request):
# path = request.META.get('HTTP_REFERER', '/')
del request.session['login_user']
visitType = request.session.get('visitType')
# if(((visitType=='1') or (visitType=='2'))):
# return redirect('/account/login?visitType=1')
# else:
# return redirect('/account/login')
if(visitType):
return redirect('/account/login?visitType='+visitType)
else:
return redirect('/account/login')
# 条码登录
@require_http_methods(['GET'])
def account_barcode(request):
barcode = request.GET.get('barCode')
user_obj = BllUser().findEntity(EntityUser.bar_code == barcode)
if user_obj:
if user_obj.IsEnabled == 1:
request.session['login_user'] = json.loads(
Utils.resultAlchemyData(user_obj))
return JsonResponse(Utils.resultData(1, '登录成功'))
else:
logger.info(user_obj.role_name + '正在尝试登陆后台管理')
return JsonResponse(Utils.resultData(0, '该账户已被禁用, 暂时无法登陆, 请联系管理员'))
else:
return JsonResponse(Utils.resultData(0, '该条码用户不存在!'))

@ -0,0 +1,11 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:28:44
'''
from flask import Blueprint
from apps.home import home_router
all_router = Blueprint('all_router', __name__)
all_router.register_blueprint(home_router, url_prefix="/home")

@ -0,0 +1,4 @@
from flask import Blueprint
home_router = Blueprint('home', __name__)

@ -0,0 +1,8 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:19:33
'''
from . import home_router

@ -0,0 +1,36 @@
# import configparser
# import os
# from PyQt5.QtCore import *
# class SystemConfig(QObject):
# """系统配置参数"""
# config = configparser.ConfigParser()
# configPath=os.getcwd()+'/Config/system.conf'
# config.read(configPath)
# #获取配置文件值
# @classmethod
# def getConfig(cls,key):
# return cls.config.get('System',key)
# #设置配置文件值
# @classmethod
# def setConfig(cls,key,value):
# cls.config.set('System',key,value)
# cls.config.write(open(cls.configPath,'w'))
import os
import configparser
class SystemConfig:
config = configparser.ConfigParser()
configPath = os.getcwd() + '/Config/system.conf'
config.read(configPath)
@classmethod
def getConfig(cls, key):
return cls.config.get('system', key)
@classmethod
def setConfig(cls, key, value):
cls.config.set('system', key, value)
cls.config.write(open(cls.configPath, 'w'))

@ -0,0 +1,77 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 15:02:28
'''
import json
import datetime
import decimal
from flask import Flask as New_flask
from flask.json import JSONEncoder as _JSONEncoder
from flask_cors import CORS
from sqlalchemy.ext.declarative import DeclarativeMeta
#继承JSONEncoder处理sqlalchemy对象编码转换类
class JSONEncoder(_JSONEncoder):
def default(self, obj):
# if isinstance(obj, decimal.Decimal):
# return str(obj)
# elif isinstance(obj, datetime.datetime):
# return obj.isoformat()
# elif isinstance(obj, datetime.date):
# return obj.isoformat()
if isinstance(obj, decimal.Decimal):
return str(obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
if isinstance(obj.__class__, DeclarativeMeta):
#SQLAlchemy类
fields = {}
for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
data = obj.__getattribute__(field)
try:
json.dumps(data) # 序列化对象
fields[field] = data
if data is None:
fields[field] = ''
except TypeError: # 添加了对datetime的处理
# if isinstance(data, datetime.datetime):
# fields[field] = data.isoformat()
# elif isinstance(data, datetime.date):
# fields[field] = data.isoformat()
if isinstance(data, (datetime.datetime, datetime.date)):
fields[field] = data.isoformat()
elif isinstance(data, datetime.timedelta):
fields[field] = (
datetime.datetime.min + data).time().isoformat()
elif isinstance(data, decimal.Decimal):
fields[field] = float(data)
else:
fields[field] = None
# Json编码字典
return fields
return json.JSONEncoder.default(self, obj)
class Flask(New_flask):
json_encoder = JSONEncoder
def register_blueprints(app):
"""
"""
from apps import all_router
app.register_blueprint(all_router, url_prefix="/api")
def create_app():
app = Flask(__name__)
CORS(app)
# app.config.from_object('setting')
register_blueprints(app)
return app

@ -0,0 +1,6 @@
[system]
clientid = 000
serverip = 127.0.0.1
port = 9001
dbconntion = mysql+pymysql://root:123456@127.0.0.1/local_rms_db?charset=utf8

@ -0,0 +1,14 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:32:26
'''
from db_logic.db_base import Repository
from models.client_models import EntityClient
#用户操作业务逻辑类
class BllClient(Repository):
def __init__(self, entityType=EntityClient):
return super().__init__(entityType)

@ -0,0 +1,23 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:34:13
'''
from sqlalchemy import and_
from db_logic.db_base import Repository
from models.client_models import EntityClient, EntityClientUser
#用户操作业务逻辑类
class BllClientUser(Repository):
def __init__(self, entityType=EntityClient):
return super().__init__(entityType)
def isJInZhiUser(self, userId, clientId):
entity = self.findEntity(
and_(EntityClientUser.user_id == userId, EntityClientUser.client_id == clientId))
if(entity is None):
return False
else:
return True

@ -0,0 +1,39 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:41:18
'''
import json
import datetime
from sqlalchemy import or_, desc
from db_logic.db_base import Repository
from models.log_models import EntityLog
from common.utils import Utils
from db_logic.user import BllUser
#日志信息业务逻辑类
class BllLog(Repository):
def __init__(self, entityType=EntityLog):
return super().__init__(entityType)
#获取系统日志列表
def getLogList(self, customerId, pageParam, keyWord=''):
keyWord = '%' + keyWord + '%'
orm_query = self.findList().filter(EntityLog.CustomerId == customerId
).filter(or_(EntityLog.OperateUserName.like(keyWord), EntityLog.OperateType.like(keyWord))).order_by(desc(EntityLog.OperateDate))
return self.queryPage(orm_query, pageParam)
# 插入日志记录函数
def insert_log_record(self, currentInfo_json, ExecuteResult):
currentInfo = json.loads(currentInfo_json)
UserId = currentInfo.get('UserId')
ClientCode = currentInfo.get('ClientCode')
CustomerId = currentInfo.get('CustomerId')
user = BllUser().findEntity(UserId)
entity_log = EntityLog(LogId=str(Utils.UUID()), CustomerId=CustomerId, LogType=1, OperateUserId=UserId,
OperateAccount=user.Account, OperateUserName=user.RealName,
OperateTypeCode='通信成功', OperateType='通信成功',
ExecuteResult="终端{0}{1}".format(
ClientCode, ExecuteResult),
OperateDate=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), IsAdd=1)
self.insert(entity_log)

@ -1,28 +1,32 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 08:42:44
@Date:2022/07/18 15:37:28
'''
"""数据仓储类"""
import traceback
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database
from sqlalchemy.sql.elements import BinaryExpression, BooleanClauseList
from sqlalchemy.pool import NullPool
from sqlalchemy.sql import func
import paginate_sqlalchemy
from config.SystemConfig import SystemConfig
from models.models_base import Base
from common.log_utlis import logger
"""数据仓储类"""
class Repository(object):
# 初始化数据库连接
# engine = create_engine('mysql+pymysql://root:123456@127.0.0.1/TY_RMS_Multiple?charset=utf8',
# engine = create_engine('mysql+mysqldb://root:123456@localhost:3306/ty_rms_multiple_control',
engine = create_engine('mysql+mysqldb://root:123456@localhost:3306/local_rms_db',
pool_recycle=10600, pool_size=100, max_overflow=20)
#engine = create_engine(SystemConfig.getConfig('DBConntion'),pool_size=100,max_overflow=3,pool_timeout=10,pool_recycle=3600)
engine = create_engine(SystemConfig.getConfig(
'dbconntion'), poolclass=NullPool)
if not database_exists(engine.url):
create_database(engine.url)
# 创建session工厂
DBSession = sessionmaker(bind=engine)
DBSession = sessionmaker(bind=engine, expire_on_commit=False)
# 创建session对象
session = DBSession()
# 事务标识
@ -33,6 +37,10 @@ class Repository(object):
# 对象类型
self.entityType = entityType
@classmethod
def createTables(cls):
Base.metadata.create_all(cls.engine)
# 开始事务
def beginTrans(self):
self.session = self.DBSession()
@ -43,27 +51,25 @@ class Repository(object):
try:
self.transFlag = False
self.session.commit()
return True
except Exception as e:
print(e)
logger.debug(traceback.format_exc())
self.session.rollback()
return False
raise e
finally:
self.session.close()
# 新增数据
def insert(self, entity):
try:
if (not self.transFlag):
if(not self.transFlag):
self.session = self.DBSession()
self.session.add(entity)
if(not self.transFlag):
self.session.commit()
return True
except Exception as e:
print(e, 88888888888)
logger.debug(traceback.format_exc())
self.session.rollback()
return False
raise e
finally:
self.session.close()
@ -77,37 +83,39 @@ class Repository(object):
self.session.commit()
return True
except Exception as e:
flag_ = False
logger.debug(traceback.format_exc())
self.session.rollback()
return flag_
raise e
finally:
self.session.close()
# 更新数据
def update(self, entity):
try:
self.session = self.DBSession()
if(not self.transFlag):
self.session = self.DBSession()
self.session.merge(entity)
if(not self.transFlag):
self.session.commit()
return True
except Exception as e:
print(e, 88888888888)
logger.debug(traceback.format_exc())
self.session.rollback()
return False
raise e
finally:
self.session.close()
# 删除操作
def delete(self, where):
try:
if (not self.transFlag):
if(not self.transFlag):
self.session = self.DBSession()
self.session.query(self.entityType).filter(where).delete()
if(not self.transFlag):
self.session.commit()
except Exception as e:
logger.debug(traceback.format_exc())
self.session.rollback()
raise e
finally:
self.session.close()
@ -120,8 +128,9 @@ class Repository(object):
else:
return self.session.query(self.entityType).get(where)
except Exception as e:
print(e, 555555555555)
logger.debug(traceback.format_exc())
self.session.rollback()
raise e
finally:
self.session.close()
@ -130,31 +139,33 @@ class Repository(object):
try:
self.session = self.DBSession()
return self.session.query(self.entityType).filter(*where)
except:
except Exception as e:
logger.debug(traceback.format_exc())
self.session.rollback()
raise e
finally:
self.session.close()
# 查询分页
def queryPage(self, orm_query, pageParam):
# orm_query: SQLalchemy对象
# pageParam pageParam类
try:
page = paginate_sqlalchemy.SqlalchemyOrmPage(
orm_query, page=pageParam.curPage, items_per_page=pageParam.pageRows, db_session=self.DBSession)
pageParam.totalRecords = page.item_count
return page.items
except:
raise
except Exception as e:
logger.debug(traceback.format_exc())
raise e
# 查询数量
def findCount(self, *where):
try:
self.session = self.DBSession()
return self.session.query(func.count('*')).select_from(self.entityType).filter(*where).scalar()
except:
except Exception as e:
logger.debug(traceback.format_exc())
self.session.rollback()
raise e
finally:
self.session.close()
@ -163,8 +174,10 @@ class Repository(object):
try:
self.session = self.DBSession()
return self.session.query(func.max(prop)).select_from(self.entityType).filter(*where).scalar()
except:
except Exception as e:
logger.debug(traceback.format_exc())
self.session.rollback()
raise e
finally:
self.session.close()
@ -173,8 +186,10 @@ class Repository(object):
try:
self.session = self.DBSession()
return self.session.execute(sql, *agrs)
except:
except Exception as e:
logger.debug(traceback.format_exc())
self.session.rollback()
raise e
finally:
self.session.close()
@ -185,7 +200,9 @@ class Repository(object):
self.session.execute(sql)
if(not self.transFlag):
self.session.commit()
except:
except Exception as e:
logger.debug(traceback.format_exc())
self.session.rollback()
raise e
finally:
self.session.close()

@ -0,0 +1,45 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:51:28
'''
import sys
sys.path.append(".")
from db_logic.db_base import Repository
from models.humiture_models import EntityHumitureRecord
from common.utils import Utils
#日志信息业务逻辑类
class BllHumitureRecord(Repository):
#_instance_lock = threading.Lock()
##实现单例模式
#def __new__(cls, *args, **kwargs):
# if not hasattr(BllHumitureRecord, "_instance"):
# with BllHumitureRecord._instance_lock:
# if not hasattr(BllHumitureRecord, "_instance"):
# BllHumitureRecord._instance = object.__new__(cls)
# return BllHumitureRecord._instance
def __init__(self, entityType=EntityHumitureRecord):
return super().__init__(entityType)
# 获取温湿度列表
def getHumitureList(self, customerId, pageParam):
queryStr = 'select * from ((select * from rms_humiture_record where client_id=:client_id) '
queryStr += ' union all (select * from rms_humiture_record where client_id!=:client_id order by client_name ASC ) )t order by t.record_date DESC '
queryCountStr = 'select COUNT(*) from ((select * from rms_humiture_record where client_id=:client_id) '
queryCountStr += ' union all (select * from rms_humiture_record where client_id!=:client_id order by client_name ASC ) )t order by t.record_date DESC '
# queryParams = {"clientId": CurrentInfo.ClientInfo.client_id}
queryParams = {"client_id": customerId}
templateList = self.execute(queryStr + ' limit ' + str((pageParam.curPage - 1)
* pageParam.pageRows) + ',' + str(pageParam.pageRows), queryParams).fetchall()
pageParam.totalRecords = self.execute(
queryCountStr, queryParams).fetchone()[0]
jsonData = Utils.mysqlTable2Model(templateList)
return jsonData
def insert_one(self, entity):
self.insert(entity)

@ -0,0 +1,176 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:54:45
'''
import datetime
from sqlalchemy import or_, and_, desc, asc
from sqlalchemy.sql import func
from db_logic.db_base import Repository
from models.medicament_models import EntityMedicament, EntityMedicamentRecord, EntityMedicamentTemplate
from models.client_models import EntityClient
from models.user_models import EntityUser
from common.utils import Utils, DrugStatus, DrugRecordType
#药剂流程业务逻辑类
class BllMedicament(Repository):
#_instance_lock = threading.Lock()
##实现单例模式
#def __new__(cls, *args, **kwargs):
# if not hasattr(BllMedicament, "_instance"):
# with BllMedicament._instance_lock:
# if not hasattr(BllMedicament, "_instance"):
# BllMedicament._instance = object.__new__(cls)
# return BllMedicament._instance
def __init__(self, entityType=EntityMedicament):
return super().__init__(entityType)
#获取药剂列表
def getDrugList(self, customerId, keyWord, pageParam):
keyWord = '%' + keyWord + '%'
orm_query = self.findList().filter(EntityMedicament.CustomerId == customerId
).filter(or_(EntityMedicament.RFID.like(keyWord), EntityMedicament.Name.like(keyWord))).order_by(desc(EntityMedicament.PutInStorageDate))
return self.queryPage(orm_query, pageParam)
# 药剂入库
def drugPutIn(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()):
entityDrugRecord = EntityMedicamentRecord()
entityDrugRecord.RecordId = Utils.UUID()
entityDrugRecord.CustomerId = entityClient.CustomerId
entityDrugRecord.ClientId = entityClient.ClientId
entityDrugRecord.ClientCode = entityClient.ClientCode
entityDrugRecord.VarietyId = entityDrug.VarietyId
entityDrugRecord.MedicamentId = entityDrug.MedicamentId
entityDrugRecord.Price = entityDrug.Price
entityDrugRecord.RecordType = DrugRecordType.PutIn
entityDrugRecord.RecordRemain = float(entityDrug.Remain)
entityDrugRecord.IsEmpty = 0
entityDrugRecord.CreateDate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
entityDrugRecord.CreateUserId = entityUser.UserId
entityDrugRecord.CreateUserName = entityUser.RealName
# 创建事务
self.beginTrans()
self.session.add(entityDrug)
self.session.add(entityDrugRecord)
self.commitTrans()
# 药剂领用
def drugUse(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()):
#创建事务
self.beginTrans()
self.session.merge(entityDrug)
#if(BllUserMedicament().isJInZhiUser(entityUser.UserId,entityDrug.MedicamentId)):
# warning_obj = EntityWarning(WarningId=str(Utils.UUID()), CustomerId=entityDrug.CustomerId,
# ObjectType=7, ObjectId=entityDrug.MedicamentId, ObjectName=entityDrug.Name,
# WarningContent= entityUser.RealName+'违规领用了药剂“'+entityDrug.Name+'”('+entityDrug.BarCode+'',WarningDate=datetime.datetime.now(),
# WarningUserName=entityUser.RealName, IsSolve=0, IsAdd=1)
# BllWarning().insert(warning_obj)
entityDrugRecord = EntityMedicamentRecord()
entityDrugRecord.RecordId = Utils.UUID()
entityDrugRecord.CustomerId = entityClient.CustomerId
entityDrugRecord.ClientId = entityClient.ClientId
entityDrugRecord.ClientCode = entityClient.ClientCode
entityDrugRecord.VarietyId = entityDrug.VarietyId
entityDrugRecord.MedicamentId = entityDrug.MedicamentId
entityDrugRecord.Price = entityDrug.Price
entityDrugRecord.RecordType = DrugRecordType.Use
entityDrugRecord.IsEmpty = 0
entityDrugRecord.RecordRemain = float(entityDrug.Remain)
entityDrugRecord.CreateDate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
entityDrugRecord.CreateUserId = entityUser.UserId
entityDrugRecord.CreateUserName = entityUser.RealName
self.session.add(entityDrugRecord)
entityVariety = BllMedicamentVariety().findEntity(entityDrug.VarietyId)
entityVariety.NormalCount -= 1
entityVariety.UseCount += 1
self.session.merge(entityVariety)
self.commitTrans()
# 药剂归还
def drugReturn(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()):
#创建事务
self.beginTrans()
self.session.merge(entityDrug)
entityDrugRecord = EntityMedicamentRecord()
entityDrugRecord.RecordId = Utils.UUID()
entityDrugRecord.CustomerId = entityClient.CustomerId
entityDrugRecord.ClientId = entityClient.ClientId
entityDrugRecord.ClientCode = entityClient.ClientCode
entityDrugRecord.VarietyId = entityDrug.VarietyId
entityDrugRecord.MedicamentId = entityDrug.MedicamentId
entityDrugRecord.Price = entityDrug.Price
drug = BllMedicament().findEntity(entityDrug.MedicamentId)
lastRemain = float(drug.Remain)
entityDrugRecord.UseQuantity = float(
lastRemain) - float(entityDrug.Remain if entityDrug.Remain else 0)
entityDrugRecord.RecordType = DrugRecordType.Return
entityDrugRecord.RecordRemain = float(entityDrug.Remain)
entityDrugRecord.IsEmpty = 1 if(
entityDrug.Status == DrugStatus.Empty) else 0
entityDrugRecord.CreateDate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
entityDrugRecord.CreateUserId = entityUser.UserId
entityDrugRecord.CreateUserName = entityUser.RealName
self.session.add(entityDrugRecord)
entityVariety = BllMedicamentVariety().findEntity(entityDrug.VarietyId)
if(entityDrug.Remain != 0):
entityVariety.NormalCount += 1
else:
entityVariety.EmptyCount += 1
entityVariety.UseCount -= 1
self.session.merge(entityVariety)
self.commitTrans()
#获取离保质期最近的同类药剂
def getDrugNearExpired(self, varietyId, customerId):
drugList = self.findList(and_(EntityMedicament.Status == DrugStatus.Normal, EntityMedicament.VarietyId == varietyId)).order_by(
asc(EntityMedicament.ExpirationDate)).limit(1)
return drugList.first()
#获过期药剂列表
def getExpiredDrugList(self, customerId):
todayDate = datetime.datetime.now().strftime("%Y-%m-%d")
drugList = self.findList(and_(func.date_format(
EntityMedicament.ExpirationDate, '%Y-%m-%d') <= todayDate, EntityMedicament.Status != 3)).all()
return drugList
#获取待归还药剂列表
def getWaitReturnDrugList(self, customerId):
drugList = self.findList(and_(EntityMedicament.CustomerId ==
customerId, EntityMedicament.Status == DrugStatus.Out)).all()
return drugList
#获取待入库药剂模板
def getWaitPutInDrugTemplateList(self, customerId, clientId):
templateList = BllMedicamentTemplate().findList(and_(EntityMedicamentTemplate.CustomerId == customerId, EntityMedicamentTemplate.ClientId ==
clientId, EntityMedicamentTemplate.IsWaitExport == 1)).order_by(EntityMedicamentTemplate.CreateDate.desc()).limit(1).all()
return templateList
#获取所有药剂列表
def getAllDrugList(self, searchWord, pageParam, customerId):
queryStr = '(select * from RMS_Medicament where CustomerId=:customerId and ClientId=:clientId and (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord)) '
queryStr += ' union all (select * from RMS_Medicament where CustomerId=:customerId and ClientId!=:clientId and (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord) order by ClientCode ASC ) '
queryParams = {"searchWord": '%' + searchWord + '%',
"customerId": customerId, "clientId": CurrentInfo.ClientInfo.ClientId}
templateList = self.execute(queryStr + ' limit ' + str((pageParam.curPage - 1)
* pageParam.pageRows) + ',' + str(pageParam.pageRows), queryParams).fetchall()
countQuery = "select count(*) from RMS_Medicament where CustomerId=:customerId and (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord)"
pageParam.totalRecords = self.execute(
countQuery, queryParams).fetchone()[0]
jsonData = Utils.mysqlTable2Model(templateList)
return jsonData
#获取指定用户当前领用药剂
def getUserUseDrugList(self, userId):
drugList = self.findList(
EntityMedicament.ByUserId == userId, EntityMedicament.Status == DrugStatus.Out).all()
return drugList

@ -0,0 +1,45 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:44:57
'''
from sqlalchemy import and_, or_, desc
from db_logic.db_base import Repository
from models.user_models import EntityUser
from common.utils import Utils
#用户操作业务逻辑类
class BllUser(Repository):
#_instance_lock = threading.Lock()
##实现单例模式
#def __new__(cls, *args, **kwargs):
# if not hasattr(BllUser, "_instance"):
# with BllUser._instance_lock:
# if not hasattr(BllUser, "_instance"):
# BllUser._instance = object.__new__(cls)
# return BllUser._instance
def __init__(self, entityType=EntityUser):
return super().__init__(entityType)
#用户账号密码登录
def login(self, userAccount, userPwd):
d = Utils.MD5(userPwd)
print(d)
return self.findEntity(and_(EntityUser.Account == userAccount, EntityUser.Password == Utils.MD5(userPwd)))
#根据条码获取用户
def getUserByBarCode(self, barCode):
return self.findEntity(EntityUser.BarCode == barCode)
#获取用户列表
def getUserList(self, customerId, pageParam, keyWord=''):
keyWord = '%' + keyWord + '%'
orm_query = self.findList().filter(EntityUser.CustomerId == customerId
).filter(or_(EntityUser.UserCode.like(keyWord), EntityUser.RealName.like(keyWord))).order_by(desc(EntityUser.CreateDate))
return self.queryPage(orm_query, pageParam)
#获取用户详情信息
def getUserInfo(self, userId):
return self.findEntity(userId)

@ -0,0 +1,51 @@
"""
# 试剂进行入库时已绑定柜体id不考虑相同试剂多柜体的情况
试剂id柜体id
## 主概览
根据试剂记录展示入库/领用/归还/未归还
预警信息
## 报表统计---库存信息--总库存减去已绑定柜体的试剂数
库存信息总览 展示库存内试剂信息 根据所属终端分组去重
入库信息 展示入库试剂信息
试剂信息 根据试剂名称规格纯度进行去重展示 并分页
试剂使用统计 根据试剂记录展示信息
## 实际入库---未对试剂和柜体进行绑定
展示上传excle表格数据/新增模板实际数据
选择试剂入库 展示已入库试剂信息---选择按钮进行编辑试剂信息
绑定入库绑定操作根据前端传递参数进行入库操作
新增模板保存模板基本信息和模板内试剂json字符串信息入库
打印条码
导入入库模板根据柜体模板名称进行解析模板内试剂json字符串进行柜体试剂绑定
删除模板
试剂归还根据前端传递参数进行记录数据入库展示待归还数据列表
试剂称重 ...
## 库存盘点
库存盘点展示试剂库存信息
录入库存添加试剂数量根据管理人员确定展示校验结果
历史记录,
## 试剂管理
展示
"""

@ -0,0 +1,267 @@
[2022-07-18 17:36:02,221] log_utlis.py->debug line:52 [DEBUG]Traceback (most recent call last):
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
self.dialect.do_execute(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
cursor.execute(statement, parameters)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.DataError: (1265, "Data truncated for column 'temperature' at row 1")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File ".\db_logic\db_base.py", line 68, in insert
self.session.commit()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1451, in commit
self._transaction.commit(_to_root=self.future)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
self._prepare_impl()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
self.session.flush()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3383, in flush
self._flush(objects)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3523, in _flush
transaction.rollback(_capture_exception=True)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
raise exception
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3483, in _flush
flush_context.execute()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
rec.execute(self)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
util.preloaded.orm_persistence.save_obj(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
_emit_insert_statements(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1238, in _emit_insert_statements
result = connection._execute_20(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1631, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 332, in _execute_on_connection
return connection._execute_clauseelement(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1498, in _execute_clauseelement
ret = self._execute_context(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1862, in _execute_context
self._handle_dbapi_exception(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2043, in _handle_dbapi_exception
util.raise_(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
raise exception
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
self.dialect.do_execute(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
cursor.execute(statement, parameters)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
sqlalchemy.exc.DataError: (pymysql.err.DataError) (1265, "Data truncated for column 'temperature' at row 1")
[SQL: INSERT INTO rms_humiture_record (device_id, client_id, client_name, customer_id, temperature, humidity, record_date, is_add) VALUES (%(device_id)s, %(client_id)s, %(client_name)s, %(customer_id)s, %(temperature)s, %(humidity)s, %(record_date)s, %(is_add)s)]
[parameters: {'device_id': '', 'client_id': '', 'client_name': '', 'customer_id': '', 'temperature': '', 'humidity': '', 'record_date': '', 'is_add': 1}]
(Background on this error at: https://sqlalche.me/e/14/9h9h)
[2022-07-18 17:38:46,709] log_utlis.py->debug line:52 [DEBUG]Traceback (most recent call last):
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
self.dialect.do_execute(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
cursor.execute(statement, parameters)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.DataError: (1265, "Data truncated for column 'temperature' at row 1")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File ".\db_logic\db_base.py", line 68, in insert
self.session.commit()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1451, in commit
self._transaction.commit(_to_root=self.future)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
self._prepare_impl()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
self.session.flush()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3383, in flush
self._flush(objects)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3523, in _flush
transaction.rollback(_capture_exception=True)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
raise exception
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3483, in _flush
flush_context.execute()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
rec.execute(self)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
util.preloaded.orm_persistence.save_obj(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
_emit_insert_statements(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1238, in _emit_insert_statements
result = connection._execute_20(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1631, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 332, in _execute_on_connection
return connection._execute_clauseelement(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1498, in _execute_clauseelement
ret = self._execute_context(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1862, in _execute_context
self._handle_dbapi_exception(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2043, in _handle_dbapi_exception
util.raise_(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
raise exception
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
self.dialect.do_execute(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
cursor.execute(statement, parameters)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
sqlalchemy.exc.DataError: (pymysql.err.DataError) (1265, "Data truncated for column 'temperature' at row 1")
[SQL: INSERT INTO rms_humiture_record (record_id, device_id, client_id, client_name, customer_id, temperature, humidity, record_date, is_add) VALUES (%(record_id)s, %(device_id)s, %(client_id)s, %(client_name)s, %(customer_id)s, %(temperature)s, %(humidity)s, %(record_date)s, %(is_add)s)]
[parameters: {'record_id': '6bc0c3f0-067d-11ed-83be-f47b094925e1', 'device_id': '', 'client_id': '', 'client_name': '', 'customer_id': '', 'temperature': '', 'humidity': '', 'record_date': '', 'is_add': 1}]
(Background on this error at: https://sqlalche.me/e/14/9h9h)
[2022-07-18 17:40:56,208] log_utlis.py->debug line:52 [DEBUG]Traceback (most recent call last):
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
self.dialect.do_execute(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
cursor.execute(statement, parameters)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.DataError: (1265, "Data truncated for column 'humidity' at row 1")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File ".\db_logic\db_base.py", line 68, in insert
self.session.commit()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1451, in commit
self._transaction.commit(_to_root=self.future)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
self._prepare_impl()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
self.session.flush()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3383, in flush
self._flush(objects)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3523, in _flush
transaction.rollback(_capture_exception=True)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
raise exception
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3483, in _flush
flush_context.execute()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
rec.execute(self)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
util.preloaded.orm_persistence.save_obj(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
_emit_insert_statements(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1238, in _emit_insert_statements
result = connection._execute_20(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1631, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 332, in _execute_on_connection
return connection._execute_clauseelement(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1498, in _execute_clauseelement
ret = self._execute_context(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1862, in _execute_context
self._handle_dbapi_exception(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2043, in _handle_dbapi_exception
util.raise_(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
raise exception
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1819, in _execute_context
self.dialect.do_execute(
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\sqlalchemy\engine\default.py", line 732, in do_execute
cursor.execute(statement, parameters)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\local_project\YY_RMS_Multiple_Manage\venv\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
sqlalchemy.exc.DataError: (pymysql.err.DataError) (1265, "Data truncated for column 'humidity' at row 1")
[SQL: INSERT INTO rms_humiture_record (record_id, device_id, client_id, client_name, customer_id, temperature, humidity, record_date, is_add) VALUES (%(record_id)s, %(device_id)s, %(client_id)s, %(client_name)s, %(customer_id)s, %(temperature)s, %(humidity)s, %(record_date)s, %(is_add)s)]
[parameters: {'record_id': 'b8ed0b2c-067d-11ed-ba8f-f47b094925e1', 'device_id': '', 'client_id': '', 'client_name': '', 'customer_id': '', 'temperature': '0.2', 'humidity': '', 'record_date': '', 'is_add': 1}]
(Background on this error at: https://sqlalche.me/e/14/9h9h)

@ -0,0 +1,43 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 15:00:54
'''
from config.server import create_app
from common.exception_base import APIException
from config.SystemConfig import SystemConfig
app = create_app()
@app.errorhandler(Exception)
def framework_error(e):
# 1、APIException
# 2、Exception
if isinstance(e, APIException):
return e
else:
if not app.config['DEBUG']:
return APIException(msg="系统异常错误: {}".format(e))
else:
return e
def main():
HOST = SystemConfig.getConfig("serverip")
PORT = int(SystemConfig.getConfig("port"))
# CORS(app)
# HOST = '127.0.0.1'
# PORT = 8080
app.run(host=HOST, port=PORT, debug=True)
if __name__ == '__main__':
try:
import sys
sys.exit(main())
except Exception as error:
import traceback
traceback.print_exc()

@ -1,21 +0,0 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YY_RMS_Multiple_Manage.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

@ -1,20 +1,22 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 15:11:59
@Date:2022/07/18 15:24:43
'''
# 已同步本地数据库
from sqlalchemy.ext.declarative import declarative_base
from models.models_base import Base, get_uuid
from sqlalchemy import Column, String, Integer, Float
class EntityClient(declarative_base()):
class EntityClient(Base):
__tablename__ = "rms_client"
__table_args__ = ({
"comment": "终端实体类"
})
client_id = Column(String(50), primary_key=True, comment='终端ID') # 终端ID
client_id = Column(String(50), primary_key=True, comment='终端ID', default=get_uuid) # 终端ID
client_code = Column(String(50), comment='终端编号') # 终端编号
client_name = Column(String(50), comment='终端名称') # 终端名称
customer_id = Column(String(50), comment='客户ID') # 客户ID
@ -29,7 +31,7 @@ class EntityClient(declarative_base()):
total_run_time = Column(Integer, comment='总运行时长') # 总运行时长
temperature_control_swich = Column(Integer, comment='温控开关')
light_control_swich = Column(Integer, comment='照明灯控制开关')
fan_control_swich = Column(Integer, comment='风扇控制开关')
fan_control_swich = Column(Integer, comment='风扇控制开关')
temperature_set_value = Column(Float, comment='温度设定值') # 温度设定控温值
temperature_max_value = Column(Float, comment='温度上限值') # 温度预警上限
temperature_min_value = Column(Float, comment='温度下限值') # 温度预警下限
@ -43,10 +45,10 @@ class EntityClient(declarative_base()):
sort_index = Column(Integer, comment='排序序号') # 排序序号
parent_id = Column(Integer, comment='父级Id') # 父级ID
description = Column(String(200), comment='备注') # 备注
is_add = Column(Integer, comment='是否添加')
is_add = Column(Integer, comment='是否添加', default=1)
class EntityClientCellUser(declarative_base()):
class EntityClientCellUser(Base):
__tablename__ = "rms_client_cell_user"
__table_args__ = (
{
@ -54,7 +56,7 @@ class EntityClientCellUser(declarative_base()):
}
)
id = Column(String(50), primary_key=True, comment="ID")
id = Column(String(50), primary_key=True, comment="ID", default=get_uuid)
client_cell_id = Column(String(50), comment="抽屉ID")
client_cell_code = Column(String(50), comment="抽屉编号")
client_id = Column(String(50), comment="终端ID")
@ -62,7 +64,7 @@ class EntityClientCellUser(declarative_base()):
user_id = Column(String(50), comment="用户ID")
class EntityClientUser(declarative_base()):
class EntityClientUser(Base):
__tablename__ = "rms_client_user"
__table_args__ = (
{
@ -70,12 +72,12 @@ class EntityClientUser(declarative_base()):
}
)
client_user_id = Column(String(50), primary_key=True, comment="用户ID")
client_user_id = Column(String(50), primary_key=True, comment="用户ID", default=get_uuid)
client_id = Column(String(50), comment="终端ID")
user_id = Column(String(50), comment="用户ID")
class EntityClientVersion(declarative_base()):
class EntityClientVersion(Base):
__tablename__ = "rms_client_version"
__table_args__ = (
{
@ -83,7 +85,7 @@ class EntityClientVersion(declarative_base()):
}
)
version_id = Column(String(50), primary_key=True, comment="版本ID")
version_id = Column(String(50), primary_key=True, comment="版本ID", default=get_uuid)
version_name = Column(String(50), comment="版本名称")
version_code = Column(String(50), comment="版本编号")
down_link = Column(String(50), comment="下载链接")
@ -91,4 +93,4 @@ class EntityClientVersion(declarative_base()):
create_date = Column(String(50), comment="创建时间")
create_user_id = Column(Integer, comment="创建用户ID")
create_user_name = Column(String(50), comment="创建用户名")
is_add = Column(Integer, comment="")
is_add = Column(Integer, comment="", default=1)

@ -1,22 +1,21 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 16:01:44
@Date:2022/07/18 15:26:19
'''
# 已同步本地数据库
from sqlalchemy import Column, String, Float, Integer
from sqlalchemy.ext.declarative import declarative_base
from models.models_base import Base, get_uuid
class EntityHumitureRecord(declarative_base()):
class EntityHumitureRecord(Base):
__tablename__ = "rms_humiture_record"
__table_args__ = (
{
"comment": "温湿度记录实体类"
}
)
record_id = Column(String(50), primary_key=True, comment="记录ID") # 记录ID
record_id = Column(String(50), primary_key=True, comment="记录ID", default=get_uuid) # 记录ID
device_id = Column(String(50), comment='设备Id') # 设备ID
client_id = Column(String(50), comment='终端id') # 终端ID
client_name = Column(String(50), comment='终端名称') # 终端名称
@ -24,4 +23,4 @@ class EntityHumitureRecord(declarative_base()):
temperature = Column(Float, comment='温度值') # 温度值
humidity = Column(Float, comment='湿度值') # 湿度值
record_date = Column(String(50), comment='记录日期') # 记录日期
is_add = Column(Integer, comment='是否添加')
is_add = Column(Integer, comment='是否添加', default=1)

@ -1,14 +1,15 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 11:24:26
@Date:2022/07/18 15:30:14
'''
# 已同步本地数据库
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from models.models_base import Base, get_uuid
class EntityLog(declarative_base()):
class EntityLog(Base):
__tablename__ = "rms_log"
__table_args__ = (
{
@ -16,7 +17,7 @@ class EntityLog(declarative_base()):
}
)
log_id = Column(String(50), primary_key=True, comment='日志ID') # 日志ID
log_id = Column(String(50), primary_key=True, comment='日志ID', default=get_uuid) # 日志ID
customer_id = Column(String(50), comment='客户ID') # 客户ID
log_type = Column(String(50), comment='日志类型') # 日志类型
operate_user_id = Column(String(50), comment='操作用户ID') # 操作用户ID
@ -28,4 +29,4 @@ class EntityLog(declarative_base()):
execute_result_code = Column(String(50), comment='执行结果代码') # 执行结果代码
execute_result = Column(String(50), comment='执行结果') # 执行结果
operate_date = Column(String(50), comment='操作日期') # 操作日期
is_add = Column(Integer, comment='是否添加')
is_add = Column(Integer, comment='是否添加', default=1)

@ -1,13 +1,14 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 15:16:50
@Date:2022/07/18 15:28:11
'''
import uuid
from sqlalchemy import Column, String, Integer, Text, Float
from sqlalchemy.ext.declarative import declarative_base
from models.models_base import Base, get_uuid
class EntityMedicament(declarative_base()):
class EntityMedicament(Base):
__tablename__ = "rms_medicament"
__table_args__ = (
{
@ -15,7 +16,7 @@ class EntityMedicament(declarative_base()):
}
)
medicament_id = Column(String(50), primary_key=True, comment="药剂ID")
medicament_id = Column(String(50), primary_key=True, comment="药剂ID", default=get_uuid)
variety_id = Column(String(50), comment="药剂类型ID")
bar_code = Column(String(50), comment="条码")
client_id = Column(String(50), comment="终端ID")
@ -74,14 +75,14 @@ class EntityMedicament(declarative_base()):
# Remark10 = Column(String(50))
class EntityMedicamentTemplate(declarative_base()):
class EntityMedicamentTemplate(Base):
__tablename__ = "rms_medicament_template"
__table_args__ = (
{
"comment": " 药剂入库模板实体类"
}
)
template_id = Column(String(50), primary_key=True, comment="模板ID")
template_id = Column(String(50), primary_key=True, comment="模板ID", default=get_uuid)
customer_id = Column(String(50), comment="客户ID")
client_id = Column(String(50), comment="终端ID")
client_name = Column(String(50), comment="终端名称")
@ -94,17 +95,18 @@ class EntityMedicamentTemplate(declarative_base()):
create_date = Column(String(50), comment="创建日期")
create_user_id = Column(String(50), comment="创建用户ID")
create_user_name = Column(String(50), comment="创建用户名")
is_add = Column(Integer, comment="")
is_add = Column(Integer, comment="", default=1)
class EntityMedicamentRecord(declarative_base()):
class EntityMedicamentRecord(Base):
__tablename__ = "rms_medicament_record"
__table_args__ = (
{
"comment": "药剂流转记录实体类"
}
)
record_id = Column(String(50), primary_key=True, comment="流转记录ID")
record_id = Column(
String(50), primary_key=True, comment="流转记录ID", default=get_uuid)
client_id = Column(String(50), comment="终端ID")
client_code = Column(String(50), comment="终端编号")
customer_id = Column(String(50), comment="客户ID")
@ -118,17 +120,18 @@ class EntityMedicamentRecord(declarative_base()):
create_date = Column(String(50), comment="创建日期")
create_user_id = Column(String(50), comment="创建人ID")
create_user_name = Column(String(50), comment="创建人名称")
is_add = Column(Integer, comment="")
is_add = Column(Integer, comment="", default=1)
class EntityMedicamentVariety(declarative_base()):
class EntityMedicamentVariety(Base):
__tablename__ = "rms_medicament_variety"
__table_args__ = (
{
"comment": "药剂类型实体类"
}
)
variety_id = Column(String(50), primary_key=True, comment="类型ID")
variety_id = Column(
String(50), primary_key=True, comment="类型ID", default=get_uuid)
customer_id = Column(String(50), comment="客户ID")
cas_number = Column(String(50), comment="药剂cas码")
name = Column(String(50), comment="药剂名称")
@ -157,4 +160,4 @@ class EntityMedicamentVariety(declarative_base()):
create_date = Column(String(50), comment="创建日期")
create_user_id = Column(String(50), comment="创建用户ID")
create_user_name = Column(String(50), comment="创建用户名称")
is_add = Column(Integer, comment="")
is_add = Column(Integer, comment="", default=1)

@ -0,0 +1,24 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 15:21:25
'''
import uuid
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def get_uuid():
return str(uuid.uuid1())
def gen_id():
return uuid.uuid4().hex
if __name__ == '__main__':
print(type(gen_id))
print(type(gen_id()))

@ -1,15 +1,15 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 15:14:17
@Date:2022/07/18 15:29:38
'''
# 已同步本地数据库
# 已同步本地数据库
from sqlalchemy import Column, String, Text, Integer
from sqlalchemy.ext.declarative import declarative_base
from models.models_base import Base, get_uuid
class EntityUser(declarative_base()):
class EntityUser(Base):
__tablename__ = "rms_user"
__table_args__ = (
{
@ -17,7 +17,7 @@ class EntityUser(declarative_base()):
}
)
user_id = Column(String(50), primary_key=True, comment='用户ID') # 用户ID
user_id = Column(String(50), primary_key=True, comment='用户ID', default=get_uuid) # 用户ID
customer_id = Column(String(50), comment='客户ID') # 客户ID
role_id = Column(String(50), comment='角色ID') # 角色ID
role_name = Column(String(50), comment='角色名称') # 角色名称
@ -40,10 +40,10 @@ class EntityUser(declarative_base()):
create_date = Column(String(50), comment='创建日期') # 创建日期
create_user_id = Column(String(50), comment='创建用户ID') # 创建用户ID
create_user_name = Column(String(50), comment='创建用户名称') # 创建用户名称
is_add = Column(Integer, comment='是否添加')
is_add = Column(Integer, comment='是否添加', default=1)
class EntityRole(declarative_base()):
class EntityRole(Base):
__tablename__ = "rms_role"
__table_args__ = (
{
@ -51,11 +51,12 @@ class EntityRole(declarative_base()):
}
)
role_id = Column(String(50), primary_key=True, comment="角色ID")
role_id = Column(
String(50), primary_key=True, comment="角色ID", default=get_uuid)
role_code = Column(String(50), comment="角色编号")
role_name = Column(String(50), comment="角色名")
role_level = Column(Integer, comment="角色级别")
sort_index = Column(Integer, comment="排序序号")
is_enabled = Column(Integer, comment="是否启用")
is_enabled = Column(Integer, comment="是否启用", default=1)
description = Column(String(50), comment="备注")
is_add = Column(Integer, comment="")
is_add = Column(Integer, comment="", default=1)

@ -1,22 +1,22 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/13 14:55:55
@Date:2022/07/18 15:27:14
'''
# 已同步本地数据库
from sqlalchemy import Column, String, Integer, Text
from sqlalchemy.ext.declarative import declarative_base
from models.models_base import Base, get_uuid
class EntityWarning(declarative_base()):
class EntityWarning(Base):
__tablename__ = "rms_warning"
__table_args__ = (
{
"comment": "预警信息实体类"
}
)
warning_id = Column(String(50), primary_key=True, comment="预警ID")
warning_id = Column(String(50), primary_key=True, comment="预警ID", default=get_uuid)
customer_id = Column(String(50), comment="客户ID")
object_type = Column(String(50), comment="预警对象类型")
object_id = Column(String(50), comment="预警对象")
@ -24,10 +24,10 @@ class EntityWarning(declarative_base()):
warning_content = Column(String(50), comment="预警内容")
warning_date = Column(String(50), comment="预警日期")
warning_user_id = Column(String(50), comment="预警用户ID")
warning_user_name = Column(String(50), comment="预警用户名")
is_solve = Column(Integer, comment="是否解决")
warning_user_name = Column(String(50), comment="预警用户名", default="系统")
is_solve = Column(Integer, comment="是否解决", default=0)
solve_user_id = Column(String(50), comment="解决用户ID")
solve_user_name = Column(String(50), comment="解决用户名")
solve_date = Column(String(50), comment="解决日期")
solve_content = Column(Text, comment="解决内容")
is_add = Column(Integer, comment="")
is_add = Column(Integer, comment="", default=1)

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -1,429 +0,0 @@
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
/*!
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */
(function ($) {
var $jQval = $.validator,
adapters,
data_validation = "unobtrusiveValidation";
function setValidationValues(options, ruleName, value) {
options.rules[ruleName] = value;
if (options.message) {
options.messages[ruleName] = options.message;
}
}
function splitAndTrim(value) {
return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
}
function escapeAttributeValue(value) {
// As mentioned on http://api.jquery.com/category/selectors/
return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
}
function getModelPrefix(fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
}
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
}
function onErrors(event, validator) { // 'this' is the form element
var container = $(this).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length && validator.errorList.length) {
list.empty();
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
$.each(validator.errorList, function () {
$("<li />").html(this.message).appendTo(list);
});
}
}
function onSuccess(error) { // 'this' is the form element
var container = error.data("unobtrusiveContainer"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;
if (container) {
container.addClass("field-validation-valid").removeClass("field-validation-error");
error.removeData("unobtrusiveContainer");
if (replace) {
container.empty();
}
}
}
function onReset(event) { // 'this' is the form element
var $form = $(this),
key = '__jquery_unobtrusive_validation_form_reset';
if ($form.data(key)) {
return;
}
// Set a flag that indicates we're currently resetting the form.
$form.data(key, true);
try {
$form.data("validator").resetForm();
} finally {
$form.removeData(key);
}
$form.find(".validation-summary-errors")
.addClass("validation-summary-valid")
.removeClass("validation-summary-errors");
$form.find(".field-validation-error")
.addClass("field-validation-valid")
.removeClass("field-validation-error")
.removeData("unobtrusiveContainer")
.find(">*") // If we were using valmsg-replace, get the underlying error
.removeData("unobtrusiveContainer");
}
function validationInfo(form) {
var $form = $(form),
result = $form.data(data_validation),
onResetProxy = $.proxy(onReset, form),
defaultOptions = $jQval.unobtrusive.options || {},
execInContext = function (name, args) {
var func = defaultOptions[name];
func && $.isFunction(func) && func.apply(form, args);
}
if (!result) {
result = {
options: { // options structure passed to jQuery Validate's validate() method
errorClass: defaultOptions.errorClass || "input-validation-error",
errorElement: defaultOptions.errorElement || "span",
errorPlacement: function () {
onError.apply(form, arguments);
execInContext("errorPlacement", arguments);
},
invalidHandler: function () {
onErrors.apply(form, arguments);
execInContext("invalidHandler", arguments);
},
messages: {},
rules: {},
success: function () {
onSuccess.apply(form, arguments);
execInContext("success", arguments);
}
},
attachValidation: function () {
$form
.off("reset." + data_validation, onResetProxy)
.on("reset." + data_validation, onResetProxy)
.validate(this.options);
},
validate: function () { // a validation function that is called by unobtrusive Ajax
$form.validate();
return $form.valid();
}
};
$form.data(data_validation, result);
}
return result;
}
$jQval.unobtrusive = {
adapters: [],
parseElement: function (element, skipAttach) {
/// <summary>
/// Parses a single HTML element for unobtrusive validation attributes.
/// </summary>
/// <param name="element" domElement="true">The HTML element to be parsed.</param>
/// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
/// validation to the form. If parsing just this single element, you should specify true.
/// If parsing several elements, you should specify false, and manually attach the validation
/// to the form when you are finished. The default is false.</param>
var $element = $(element),
form = $element.parents("form")[0],
valInfo, rules, messages;
if (!form) { // Cannot do client-side validation without a form
return;
}
valInfo = validationInfo(form);
valInfo.options.rules[element.name] = rules = {};
valInfo.options.messages[element.name] = messages = {};
$.each(this.adapters, function () {
var prefix = "data-val-" + this.name,
message = $element.attr(prefix),
paramValues = {};
if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
prefix += "-";
$.each(this.params, function () {
paramValues[this] = $element.attr(prefix + this);
});
this.adapt({
element: element,
form: form,
message: message,
params: paramValues,
rules: rules,
messages: messages
});
}
});
$.extend(rules, { "__dummy__": true });
if (!skipAttach) {
valInfo.attachValidation();
}
},
parse: function (selector) {
/// <summary>
/// Parses all the HTML elements in the specified selector. It looks for input elements decorated
/// with the [data-val=true] attribute value and enables validation according to the data-val-*
/// attribute values.
/// </summary>
/// <param name="selector" type="String">Any valid jQuery selector.</param>
// $forms includes all forms in selector's DOM hierarchy (parent, children and self) that have at least one
// element with data-val=true
var $selector = $(selector),
$forms = $selector.parents()
.addBack()
.filter("form")
.add($selector.find("form"))
.has("[data-val=true]");
$selector.find("[data-val=true]").each(function () {
$jQval.unobtrusive.parseElement(this, true);
});
$forms.each(function () {
var info = validationInfo(this);
if (info) {
info.attachValidation();
}
});
}
};
adapters = $jQval.unobtrusive.adapters;
adapters.add = function (adapterName, params, fn) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
/// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
/// mmmm is the parameter name).</param>
/// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
/// attributes into jQuery Validate rules and/or messages.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
if (!fn) { // Called with no params, just a function
fn = params;
params = [];
}
this.push({ name: adapterName, params: params, adapt: fn });
return this;
};
adapters.addBool = function (adapterName, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has no parameter values.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, function (options) {
setValidationValues(options, ruleName || adapterName, true);
});
};
adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
/// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a minimum value.</param>
/// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a maximum value.</param>
/// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
/// have both a minimum and maximum value.</param>
/// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the minimum value. The default is "min".</param>
/// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the maximum value. The default is "max".</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
var min = options.params.min,
max = options.params.max;
if (min && max) {
setValidationValues(options, minMaxRuleName, [min, max]);
}
else if (min) {
setValidationValues(options, minRuleName, min);
}
else if (max) {
setValidationValues(options, maxRuleName, max);
}
});
};
adapters.addSingleVal = function (adapterName, attribute, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has a single value.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
/// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
/// The default is "val".</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [attribute || "val"], function (options) {
setValidationValues(options, ruleName || adapterName, options.params[attribute]);
});
};
$jQval.addMethod("__dummy__", function (value, element, params) {
return true;
});
$jQval.addMethod("regex", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
match = new RegExp(params).exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
$jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
var match;
if (nonalphamin) {
match = value.match(/\W/g);
match = match && match.length >= nonalphamin;
}
return match;
});
if ($jQval.methods.extension) {
adapters.addSingleVal("accept", "mimtype");
adapters.addSingleVal("extension", "extension");
} else {
// for backward compatibility, when the 'extension' validation method does not exist, such as with versions
// of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
// validating the extension, and ignore mime-type validations as they are not supported.
adapters.addSingleVal("extension", "extension", "accept");
}
adapters.addSingleVal("regex", "pattern");
adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
adapters.add("equalto", ["other"], function (options) {
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
setValidationValues(options, "equalTo", element);
});
adapters.add("required", function (options) {
// jQuery Validate equates "required" with "mandatory" for checkbox elements
if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
setValidationValues(options, "required", true);
}
});
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {}
},
prefix = getModelPrefix(options.element.name);
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
var paramName = appendModelPrefix(fieldName, prefix);
value.data[paramName] = function () {
var field = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']");
// For checkboxes and radio buttons, only pick up values from checked fields.
if (field.is(":checkbox")) {
return field.filter(":checked").val() || field.filter(":hidden").val() || '';
}
else if (field.is(":radio")) {
return field.filter(":checked").val() || '';
}
return field.val();
};
});
setValidationValues(options, "remote", value);
});
adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
if (options.params.min) {
setValidationValues(options, "minlength", options.params.min);
}
if (options.params.nonalphamin) {
setValidationValues(options, "nonalphamin", options.params.nonalphamin);
}
if (options.params.regex) {
setValidationValues(options, "regex", options.params.regex);
}
});
$(function () {
$jQval.unobtrusive.parse(document);
});
}(jQuery));

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

@ -1,340 +0,0 @@
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia = window.matchMedia || (function(doc, undefined){
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = '&shy;<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
return { matches: bool, media: q };
};
})(document);
/*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function( win ){
//exposed namespace
win.respond = {};
//define update even in native-mq-supporting browsers, to avoid errors
respond.update = function(){};
//expose media query support flag for external use
respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches;
//if media queries are supported, exit here
if( respond.mediaQueriesSupported ){ return; }
//define vars
var doc = win.document,
docElem = doc.documentElement,
mediastyles = [],
rules = [],
appendedEls = [],
parsedSheets = {},
resizeThrottle = 30,
head = doc.getElementsByTagName( "head" )[0] || docElem,
base = doc.getElementsByTagName( "base" )[0],
links = head.getElementsByTagName( "link" ),
requestQueue = [],
//loop stylesheets, send text content to translate
ripCSS = function(){
var sheets = links,
sl = sheets.length,
i = 0,
//vars for loop:
sheet, href, media, isCSS;
for( ; i < sl; i++ ){
sheet = sheets[ i ],
href = sheet.href,
media = sheet.media,
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
//only links plz and prevent re-parsing
if( !!href && isCSS && !parsedSheets[ href ] ){
// selectivizr exposes css through the rawCssText expando
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate( sheet.styleSheet.rawCssText, href, media );
parsedSheets[ href ] = true;
} else {
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base)
|| href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
requestQueue.push( {
href: href,
media: media
} );
}
}
}
}
makeRequests();
},
//recurse through request queue, get css text
makeRequests = function(){
if( requestQueue.length ){
var thisRequest = requestQueue.shift();
ajax( thisRequest.href, function( styles ){
translate( styles, thisRequest.href, thisRequest.media );
parsedSheets[ thisRequest.href ] = true;
makeRequests();
} );
}
},
//find media blocks in css text, convert to style blocks
translate = function( styles, href, media ){
var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
ql = qs && qs.length || 0,
//try to get CSS path
href = href.substring( 0, href.lastIndexOf( "/" )),
repUrls = function( css ){
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
},
useMedia = !ql && media,
//vars used in loop
i = 0,
j, fullq, thisq, eachq, eql;
//if path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In those cases, the media attribute will currently be ignored.
if( useMedia ){
ql = 1;
}
for( ; i < ql; i++ ){
j = 0;
//media attr
if( useMedia ){
fullq = media;
rules.push( repUrls( styles ) );
}
//parse for styles
else{
fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
}
eachq = fullq.split( "," );
eql = eachq.length;
for( ; j < eql; j++ ){
thisq = eachq[ j ];
mediastyles.push( {
media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
rules : rules.length - 1,
hasquery: thisq.indexOf("(") > -1,
minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
} );
}
}
applyMedia();
},
lastCall,
resizeDefer,
// returns the value of 1em in pixels
getEmValue = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body );
}
else {
body.removeChild( div );
}
//also update eminpx before returning
ret = eminpx = parseFloat(ret);
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminpx,
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docElem[ name ],
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
styleBlocks = {},
lastLink = links[ links.length-1 ],
now = (new Date()).getTime();
//throttle resize calls
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
clearTimeout( resizeDefer );
resizeDefer = setTimeout( applyMedia, resizeThrottle );
return;
}
else {
lastCall = now;
}
for( var i in mediastyles ){
var thisstyle = mediastyles[ i ],
min = thisstyle.minw,
max = thisstyle.maxw,
minnull = min === null,
maxnull = max === null,
em = "em";
if( !!min ){
min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
if( !!max ){
max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
if( !styleBlocks[ thisstyle.media ] ){
styleBlocks[ thisstyle.media ] = [];
}
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
}
}
//remove any existing respond style element(s)
for( var i in appendedEls ){
if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){
head.removeChild( appendedEls[ i ] );
}
}
//inject active styles, grouped by media type
for( var i in styleBlocks ){
var ss = doc.createElement( "style" ),
css = styleBlocks[ i ].join( "\n" );
ss.type = "text/css";
ss.media = i;
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
head.insertBefore( ss, lastLink.nextSibling );
if ( ss.styleSheet ){
ss.styleSheet.cssText = css;
}
else {
ss.appendChild( doc.createTextNode( css ) );
}
//push to appendedEls to track for later removal
appendedEls.push( ss );
}
},
//tweaked Ajax functions from Quirksmode
ajax = function( url, callback ) {
var req = xmlHttp();
if (!req){
return;
}
req.open( "GET", url, true );
req.onreadystatechange = function () {
if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){
return;
}
callback( req.responseText );
}
if ( req.readyState == 4 ){
return;
}
req.send( null );
},
//define ajax obj
xmlHttp = (function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new XMLHttpRequest();
}
catch( e ){
xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" );
}
return function(){
return xmlhttpmethod;
};
})();
//translate CSS
ripCSS();
//expose update for re-running respond later on
respond.update = ripCSS;
//adjust on resize
function callMedia(){
applyMedia( true );
}
if( win.addEventListener ){
win.addEventListener( "resize", callMedia, false );
}
else if( win.attachEvent ){
win.attachEvent( "onresize", callMedia );
}
})(this);

@ -1,20 +0,0 @@
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='&shy;<style media="'+h+'"> #mq-test-1 { width: 42px; }</style>';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document);
/*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B<y;B++){A=D[B],z=A.href,C=A.media,x=A.rel&&A.rel.toLowerCase()==="stylesheet";if(!!z&&x&&!o[z]){if(A.styleSheet&&A.styleSheet.rawCssText){m(A.styleSheet.rawCssText,z,C);o[z]=true}else{if((!/^([a-zA-Z:]*\/\/)/.test(z)&&!g)||z.replace(RegExp.$1,"").split("/")[0]===e.location.host){d.push({href:z,media:C})}}}}u()},u=function(){if(d.length){var x=d.shift();n(x.href,function(y){m(y,x.href,x.media);o[x.href]=true;u()})}},m=function(I,x,z){var G=I.match(/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi),J=G&&G.length||0,x=x.substring(0,x.lastIndexOf("/")),y=function(K){return K.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+x+"$2$3")},A=!J&&z,D=0,C,E,F,B,H;if(x.length){x+="/"}if(A){J=1}for(;D<J;D++){C=0;if(A){E=z;k.push(y(I))}else{E=G[D].match(/@media *([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1;k.push(RegExp.$2&&y(RegExp.$2))}B=E.split(",");H=B.length;for(;C<H;C++){F=B[C];i.push({media:F.split("(")[0].match(/(only\s+)?([a-zA-Z]+)\s?/)&&RegExp.$2||"all",rules:k.length-1,hasquery:F.indexOf("(")>-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l<h){clearTimeout(r);r=setTimeout(j,h);return}else{l=z}for(var E in i){var K=i[E],C=K.minw,J=K.maxw,A=C===null,L=J===null,y="em";if(!!C){C=parseFloat(C)*(C.indexOf(y)>-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -1,65 +0,0 @@
/* Style For Suggestions */
/*
For creating side border like this
| item 1 |
| item 2 |
*/
.suggestions .suggest_item{
padding-bottom: 2px;
padding-top: 2px;
background-color:#EEEEEE;
border-left:1px solid #CCCCCC;
border-right:1px solid #CCCCCC;
}
/*
For creating top border like this
------------
item 1
...
*/
.suggestions .suggest_item.first{
border-top:1px solid #CCCCCC;
}
/*
For creating bottom border like this
...
item 2
------------
*/
.suggestions .suggest_item.last{
border-bottom:1px solid #CCCCCC;
}
/*
For coloring the selected item
*/
.suggestions .suggest_item.selected, .suggestions .suggest_item.selected .description{
background-color:#999999;
color:#FFFFFF;
cursor:pointer;
}
/*
Image thumbnail
*/
.suggestions .suggest_item .thumbnail{
background-color: transparent;
background-position: top center;
background-repeat: no-repeat;
margin: 1px 2px 1px 2px;
float: left;
width: 50px;
height: 50px;
}
/*
Description
*/
.suggestions .suggest_item .description{
font-style: italic;
font-size: 11px;
color: #777;
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -1,2 +0,0 @@
/** layui-v2.5.6 MIT License By https://www.layui.com */
html #layuicss-skincodecss{display:none;position:absolute;width:1989px}.layui-code-h3,.layui-code-view{position:relative;font-size:12px}.layui-code-view{display:block;margin:10px 0;padding:0;border:1px solid #e2e2e2;border-left-width:6px;background-color:#F2F2F2;color:#333;font-family:Courier New}.layui-code-h3{padding:0 10px;height:32px;line-height:32px;border-bottom:1px solid #e2e2e2}.layui-code-h3 a{position:absolute;right:10px;top:0;color:#999}.layui-code-view .layui-code-ol{position:relative;overflow:auto}.layui-code-view .layui-code-ol li{position:relative;margin-left:45px;line-height:20px;padding:0 5px;border-left:1px solid #e2e2e2;list-style-type:decimal-leading-zero;*list-style-type:decimal;background-color:#fff}.layui-code-view pre{margin:0}.layui-code-notepad{border:1px solid #0C0C0C;border-left-color:#3F3F3F;background-color:#0C0C0C;color:#C2BE9E}.layui-code-notepad .layui-code-h3{border-bottom:none}.layui-code-notepad .layui-code-ol li{background-color:#3F3F3F;border-left:none}

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 701 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 299 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save