报表相关接口

duizhaopin
apan 3 years ago
parent 19ed6c9781
commit 64de5e4ba8

@ -11,8 +11,12 @@ import platform
import hashlib
import uuid
import psutil
from dateutil import parser, relativedelta
from sqlalchemy import and_
from config.SystemConfig import SystemConfig
from db_logic.client import BllClient
from db_logic.humiture_record import BllHumitureRecord
from models.humiture_models import EntityHumitureRecord
# 判断当前系统是linux还是windows
system_name = platform.system()
@ -31,6 +35,9 @@ class Utils(object):
hl.update(str.encode(encoding='utf-8'))
return hl.hexdigest()
def get_str_datetime():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
#获取唯一识别码
def UUID():
return str(uuid.uuid1())
@ -113,9 +120,119 @@ class Utils(object):
return round(setTem + diffValue/coeValue, 1)
else:
return round(setTem - diffValue/coeValue, 1)
# # 获取最近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_all_client_data(self):
# client_obj_list = BllClient().get_all_client_list()
# client_dic_list = []
# for i in client_obj_list:
# client_dic_list.append(
# {
# "client_id": i.client_id,
# "client_name": i.client_name
# }
# )
# return client_dic_list
# # 获取温湿度数据
# def get_temperature_or_humidity(self, params=None):
# client_id = params.get('client_id')
# customer_id = params.get('customer_id')
# tp = params.get('tp')
# # 获取所有客户端名称及id
# client_all_list = self.get_all_client_data()
# # 根据条件获取该客户端的信息
# client_obj = BllClient().get_filter_client(client_id, customer_id)
# temperature_dict = {}
# temperature_count_dict = {}
# now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# start_time = (
# parser.parser(datetime.datetime.now().strftime()) + relativedelta.relativedelta(hourse=-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, now_time)
# )
# ).all()
# for hum_obj in humiture_obj_list:
# # 获取每个对象的record_date的时间值
# hum_hour = hum_obj.record_date.strftime("%H")
# # 判断不在字典中默认赋值为0
# if hum_hour not in temperature_dict:
# temperature_count_dict[hum_hour] = 0
# temperature_dict[hum_hour] = 0
# # 判断获取温度值,获取不到判定为湿度
# if tp:
# temperature_dict[hum_hour] += hum_obj.humidity
# else:
# temperature_dict[hum_hour] += hum_obj.temperature
# # 每次循环+1
# temperature_count_dict[hum_hour] += 1
# # 求平均值
# for ea in temperature_count_dict.keys():
# if ea in temperature_dict:
# temperature_dict[ea] = round(
# temperature_dict[ea] / temperature_count_dict[ea], 2
# )
# hour_list = self.get_24_hours()
# data_temp = []
# # 求当前时间进24小时的温度值和小时值
# for data_hour in hour_list:
# if len(data_hour) == 4:
# data_hour = '0' + data_hour
# if tp == 1:
# data_temp.append(random.randint(55, 68))
# elif tp ==2:
# data_temp.append(0)
# else:
# if str(data_hour[:-3]) in temperature_dict:
# data_temp.append(temperature_dict[data_hour[:-3]])
# else:
# data_temp.append('0.0')
# # 返回字段
# series_list = [{
# "name": client_obj.client_name,
# "type": "line",
# "data": data_temp,
# "markPoint":{
# "data": [
# {"type": "max", "name": "最大值"},
# {"type": "min", "name": "最小值"}
# ]
# },
# "markLine": {
# "data": [
# {"type": "average", "name": "平均值"}
# ]
# }
# }]
# flag_unit_dic = {
# "1": ["最近24小时湿度变化", "%RH"],
# "2": ["最近24小时VOC含量变化", "ppm"],
# }
# flag_unit_dic.get(str(tp), ["最近24小时温度变化", "°C"])
#接口数据返回
#接口数据返回
def true_return(status=0, msg='请求成功!', data=''):
data = {
"status": status,

@ -27,7 +27,7 @@ class logUtil(object):
os.makedirs(logs_dir)
# 修改log保存位置
timestamp = time.strftime("%Y-%m-%d", time.localtime())
logfilename = '%s.txt' % timestamp
logfilename = '%s.log' % timestamp
logfilepath = os.path.join(logs_dir, logfilename)
rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=logfilepath,
maxBytes=1024 * 1024 * 50,

@ -3,6 +3,62 @@
'''
@Date:2022/07/18 16:19:33
'''
from flask import jsonify, request
from models.warning_models import EntityWarning
from . import home_router
from . import home_router
from db_logic.medicament_record import BllMedicamentRecord
from db_logic.warning import BllWarning
from common.utils import PageParam, Utils
# 获取页面主概览数据 --- 查询条件缺少柜体id客户id
@home_router.route('/home_number', methods=["GET", "POST"])
# def getRecordTypeDrugRecordListJson():
def get_record_type_drug_record_json():
customerId = request.values.get('customerId')
client_id = request.values.get('clientId')
# 获取药剂记录今日入库 领用 归还Json数据
typ_dic = BllMedicamentRecord().getTodayDrugRecordCount(
customerId=customerId, clientId=client_id)
data = {
"putin_count": typ_dic.get(1),
"use_count": typ_dic.get(2),
"return_count": typ_dic.get(3),
"not_return_count": typ_dic[2] - typ_dic[3]
}
return jsonify(Utils.true_return(data=data))
# 获取预警信息列表接口
@home_router.router('/home_warning_list', methods=["GET", "POST"])
def get_warning_list():
customer_id = request.values.get('customer_id', '')
page = request.values.get('page', 1)
page_size = request.values.get('page_size', 15)
page_param = PageParam(page, page_size)
warning_list = BllWarning.getWarningList(customerId=customer_id, pageParam=page_param)
if warning_list:
data = {
"total_count": page_param.totalRecords,
"data_list": warning_list
}
return jsonify(Utils.true_return(data=data))
else:
return jsonify(Utils.false_return(msg='获取预警信息列表失败'))
# 修改预警状态根据预警id进行
@home_router.router("/update_warning_tp", methods=["GET", "POST"])
def update_warning_type():
warning_id = request.values.get('warning_id')
obj = BllWarning().findEntity(EntityWarning.warning_id == warning_id)
obj.object_type = 2
obj.solve_date= Utils.get_str_datetime()
obj.solve_user_id = ''
obj.solve_user_name = ''
BllWarning.update(obj)
return jsonify(Utils.true_return())

@ -0,0 +1,9 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/19 17:12:29
'''
from flask import Blueprint
report_router = Blueprint("report", __name__)

@ -0,0 +1,58 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/19 17:12:23
'''
from flask import jsonify, request
from . import report_router
from common.utils import Utils
from db_logic.medicament_record import BllMedicamentRecord
from db_logic.medicament import BllMedicament
# 获取报表统计页面展示
@report_router.router('/report_home', methods=["GET", "POST"])
def report_home_info():
# 试剂使用统计
base_data = BllMedicamentRecord().get_drug_record_count()
data = []
for i in base_data:
data.append(
{
"tp":i[0],
"number":i[1],
"date_time": i[2]
}
)
return jsonify(Utils.true_return(data=data))
# 库存信息总览
@report_router.router("/stock_data_info", methods=["GET", "POST"])
def get_stock_data_info():
name = request.values.get("name", None)
page = request.values.get('page', 1)
page_size = request.values.get('page_size', 15)
finds = ["name", "cas_number", "net_weight_unit",
"client_id", "count_surplus", "sum_remain"]
data_list = BllMedicament.get_stock_all_info(name=name, page=page, page_size=page_size)
if data_list:
data = []
for i in data_list:
data.append(dict(zip(finds, list(i))))
return jsonify(Utils.true_return(data=data))
else:
return jsonify(Utils.false_return(msg="无效数据"))
# 入库信息查询and 试剂信息查询
@report_router.router("/input_info")
def drun_input_info():
seach_word = request.values.get('seach_word')
page = request.values.get('page', 1)
page_size = request.values.get('page_size', 10)
manufacturer = request.values.get("manufacturer")
customer_id = request.values.get("customer_id")
client_id = request.values.get("client_id")
data = BllMedicament.getAllDrugList(search_word=seach_word, page=page, page_size=page_size, customer_id=customer_id, client_id=client_id)
return jsonify(Utils.true_return(data=data))

@ -0,0 +1,10 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/19 16:34:17
'''
from flask import Blueprint
user_router = Blueprint('user', __name__)

@ -0,0 +1,23 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/19 16:34:34
'''
from flask import jsonify, request, session
from common.utils import Utils
from . import user_router
from db_logic.user import BllUser
@user_router.router("/login", methods=["POST"])
def user_login():
user_name = request.values.get("user_name")
user_pwd = request.values.get('password')
user_obj = BllUser.login(user_name, user_pwd)
if user_obj:
session['user_id'] = user_obj.user_id
session['customer_id'] = user_obj.customer_id
return jsonify(Utils.true_return(msg="登陆成功"))
else:
return jsonify(Utils.false_return(status=201, msg="登陆失败"))

@ -71,6 +71,7 @@ def create_app():
app = Flask(__name__)
CORS(app)
# app.config.from_object('setting')
app.config["SECRET_KEY"] = "wYdilHT~TRw7j{lF+Ee5MR3nFBINONPUcObwjwzge&/(~[C?Yz"
register_blueprints(app)
return app

@ -3,6 +3,7 @@
'''
@Date:2022/07/18 16:32:26
'''
from sqlalchemy import asc
from db_logic.db_base import Repository
from models.client_models import EntityClient
@ -12,3 +13,17 @@ from models.client_models import EntityClient
class BllClient(Repository):
def __init__(self, entityType=EntityClient):
return super().__init__(entityType)
# 获取客户端列表
def get_all_client_list(self):
return self.findList().order_by(asc(EntityClient.client_code)).all()
# 根据条件查询客户端信息
def get_filter_client(self, client_id, customer_id):
where_list = []
if client_id:
where_list.append(EntityClient.client_id == client_id)
if customer_id:
where_list.append(EntityClient.customer_id == customer_id)
return self.findEntity(tuple(where_list))

@ -8,7 +8,7 @@ sys.path.append(".")
from db_logic.db_base import Repository
from models.humiture_models import EntityHumitureRecord
from common.utils import Utils
# from common.utils import Utils
#日志信息业务逻辑类
class BllHumitureRecord(Repository):

@ -3,14 +3,18 @@
'''
@Date:2022/07/18 16:54:45
'''
from re import template
import sys
sys.path.append('.')
import datetime
from sqlalchemy import or_, and_, desc, asc
from sqlalchemy import distinct, 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
from db_logic.meidcament_variety import BllMedicamentVariety
from common.utils import Utils, DrugStatus, DrugRecordType, PageParam
@ -31,28 +35,37 @@ class BllMedicament(Repository):
#获取药剂列表
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))
orm_query = self.findList().filter(
EntityMedicament.customer_id == customerId
).filter(
# or_(EntityMedicament.RFID.like(keyWord), EntityMedicament.name.like(keyWord))
or_(EntityMedicament.RFID.like(keyWord), EntityMedicament.name.like(keyWord))
).order_by(
# desc(EntityMedicament.PutInStorageDate)
desc(EntityMedicament.put_in_date)
)
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
entityDrugRecord = EntityMedicamentRecord(
customer_id=entityClient.customer_id,
client_id=entityClient.client_id,
client_code=entityClient.client_code,
variety_id=entityDrug.variety_id,
medicament_id=entityDrug.medicament_id,
price=entityDrug.price,
record_type=DrugRecordType.PutIn,
record_remain=float(entityDrug.remain),
is_empty=0,
create_date=Utils.get_str_datetime(),
create_user_id=entityUser.user_id,
create_user_name=entityUser.real_name,
)
# 创建事务
self.beginTrans()
self.session.add(entityDrug)
@ -64,32 +77,26 @@ class BllMedicament(Repository):
#创建事务
self.beginTrans()
self.session.merge(entityDrug)
entityDrugRecord = EntityMedicamentRecord(
customer_id=entityClient.customer_id,
client_id=entityClient.client_id,
client_code=entityClient.client_code,
variety_id=entityDrug.variety_id,
medicament_id=entityDrug.medicament_id,
price=entityDrug.price,
record_type=DrugRecordType.Use,
is_empty=0,
record_remain=float(entityDrug.remain),
create_date=Utils.get_str_datetime(),
create_user_id=entityUser.user_id,
create_user_name=entityUser.real_name,
)
#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
entityVariety = BllMedicamentVariety().findEntity(entityDrug.variety_id)
entityVariety.normal_count -= 1
entityVariety.use_count += 1
self.session.merge(entityVariety)
self.commitTrans()
@ -98,79 +105,139 @@ class BllMedicament(Repository):
#创建事务
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
drug = BllMedicament().findEntity(entityDrug.medicament_id)
lastRemain = float(drug.remain)
entityDrugRecord = EntityMedicamentRecord(
customer_id=entityClient.customer_id,
client_id=entityClient.client_id,
client_code=entityClient.client_code,
variety_id=entityDrug.variety_id,
medicament_id=entityDrug.medicament_id,
price=entityDrug.price,
use_quantity=float(lastRemain) - float(entityDrug.remain if entityDrug.remain else 0),
record_type=DrugRecordType.Return,
record_remain=float(entityDrug.remain),
is_empty=1 if(entityDrug.status == DrugStatus.Empty) else 0,
create_date=Utils.get_str_datetime(),
create_user_id=entityUser.user_id,
create_user_name=entityUser.real_name,
)
self.session.add(entityDrugRecord)
entityVariety = BllMedicamentVariety().findEntity(entityDrug.VarietyId)
if(entityDrug.Remain != 0):
entityVariety.NormalCount += 1
entityVariety = BllMedicamentVariety().findEntity(entityDrug.variety_id)
if(entityDrug.remain != 0):
entityVariety.normal_count += 1
else:
entityVariety.EmptyCount += 1
entityVariety.UseCount -= 1
entityVariety.empty_count += 1
entityVariety.use_count -= 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 get_medicament_info(self):
# 名称、规格、纯度进行去重展示 并分页
self.session = self.DBSession()
self.session.query(distinct()).group_by(
self.entityType.name,
self.entityType.net_weight_unit,
self.entityType.purity)
# 获取库存信息总览
def get_stock_all_info(self, page, page_size, name=None):
page_param = PageParam(page, page_size)
base_case = [
self.entityType.name,
self.entityType.cas_number,
self.entityType.net_weight_unit
]
if name:
filt = [self.entityType.name.like(f"%{name}%")]
else:
filt = []
data = self.session.query(
*base_case,
self.entityType.client_id,
func.count(self.entityType.medicament_id),
func.sum(self.entityType.remain)
).select_from(
self.entityType
).distinct(
*base_case
).filter(
*filt
).group_by(
*base_case
)
return self.queryPage(data, page_param)
#获取所有药剂列表
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
def getAllDrugList(self, search_word, page, page_size, customer_id=None, client_id=None):
# (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord)
"""
[
'medicament_id', 'variety_id', 'bar_code', 'client_id', 'client_code', 'customer_id',
'cas_number', 'name', 'english_name', 'manufacturer', 'distributor', 'production_date',
'expiration_date', 'shelf_life', 'inventory_warning_value', 'shelf_life_warning_value',
'use_days_warning_value', 'is_weigh', 'weigh_flag', 'remain', 'total', 'net_weight_unit',
'net_weight', 'tp', 'purity', 'price', 'flow_position_code', 'cell_position_code', 'place',
'status', 'is_supervise', 'by_user_date', 'by_user_id', 'by_user_name', 'put_in_date',
'put_in_user_id', 'put_in_user_name', 'is_add', 'user_auditing']
"""
page_param = PageParam(page, page_size)
filter_base = []
if customer_id:
filter_base.append(self.entityType.customer_id == customer_id)
if client_id:
filter_base.append(self.entityType.client_id == client_id)
if search_word:
seach_w = f"%{search_word}%"
filter_base.append(
or_(
self.entityType.name.like(seach_w),
self.entityType.bar_code.like(seach_w),
self.entityType.english_name.like(seach_w),
)
)
data = self.session.query(
self.entityType.name,
self.entityType.distributor,
self.entityType.net_weight_unit,
self.entityType.remain,
self.entityType.production_date,
self.entityType.expiration_date,
self.entityType.shelf_life,
self.entityType.put_in_user_name,
self.entityType.put_in_date
).filter(*filter_base)
fields = [
"name", "distributor", "net_weight_unit", "remain",
"production_date", "expiration_date", "shelf_life",
"put_in_user_name", "put_in_date"
]
data_list = []
page_data = self.queryPage(data, page_param)
for i in page_data:
data_list.append(dict(zip(fields, i)))
return data_list
# # 获取库存消耗
# def get_comsume_stock(self):
# self.session.query(
# self.entityType.status,
# func.count(self.entityType.medicament_id)
# )
# #获取指定用户当前领用药剂
# def getUserUseDrugList(self, userId):
# drugList = self.findList(
# EntityMedicament.ByUserId == userId, EntityMedicament.Status == DrugStatus.Out).all()
# return drugList

@ -0,0 +1,106 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/19 10:49:15
'''
import sys
sys.path.append('.')
import datetime
from sqlalchemy import or_, and_, asc, desc
from sqlalchemy.sql import func
from db_logic.db_base import Repository
from models.medicament_models import EntityMedicamentRecord
# from common.utils import Utils
#药剂流转记录业务逻辑类
class BllMedicamentRecord(Repository):
#_instance_lock = threading.Lock()
##实现单例模式
#def __new__(cls, *args, **kwargs):
# if not hasattr(BllMedicamentRecord, "_instance"):
# with BllMedicamentRecord._instance_lock:
# if not hasattr(BllMedicamentRecord, "_instance"):
# BllMedicamentRecord._instance = object.__new__(cls)
# return BllMedicamentRecord._instance
def __init__(self, entityType=EntityMedicamentRecord):
return super().__init__(entityType)
def get_today_record_number(self,):
self.entityType.query()
return
# #获取指定用户流转记录
# def getUserDrugRecordList(self, pageParam, customerId, userId=None):
# queryStr = 'select * from RMS_MedicamentRecord r left join RMS_Medicament m on m.MedicamentId=r.MedicamentId and m.CustomerId=:customerId '
# queryParams = {"customerId": customerId}
# if(userId):
# queryStr += ' where CreateUserId=:userId order by CreateDate desc'
# queryParams["userId"] = userId
# else:
# queryStr += ' order by CreateDate desc'
# templateList = self.execute(queryStr + ' limit ' + str((pageParam.curPage - 1)
# * pageParam.pageRows) + ',' + str(pageParam.pageRows), queryParams).fetchall()
# pageParam.totalRecords = self.execute(
# queryStr.replace('*', 'count(*)'), queryParams).fetchone()[0]
# jsonData = Utils.mysqlTable2Model(templateList)
# return jsonData
#获取今日药剂流转信息数量
def getTodayDrugRecordCount(self, customerId, clientId):
todayDate = datetime.datetime.now().strftime("%Y-%m-%d")
# 使用类型进行分组,直接获取入库,领用,归还的数量
recordListNew = self.session.query(
self.entityType.record_type,
func.count('record_id')
).select_from(self.entityType).filter(
EntityMedicamentRecord.customer_id == customerId,
EntityMedicamentRecord.client_id == clientId,
func.date_format(EntityMedicamentRecord.create_date, '%Y-%m-%d') == todayDate
).group_by(EntityMedicamentRecord.record_type).all()
return dict(recordListNew)
# 获取报表统计内入库记录信息
def get_drug_record_count(self):
query_li = [
self.entityType.record_type,
func.count('record_id'),
func.max(self.entityType.create_date)
]
data = self.session.query(
*tuple(query_li)
).select_from(self.entityType).group_by(EntityMedicamentRecord.record_type).all()
return data
# #获取药剂最后一次使用余量
# def getLastRecordRemain(self, drugId):
# SQL = """
# select RecordRemain from rms_medicamentrecord WHERE MedicamentId='""" + drugId + """' ORDER BY CreateDate DESC LIMIT 1
# """
# try:
# result = BllMedicamentRecord().execute(SQL)
# return float(result.fetchone()[0])
# except Exception as e:
# print(e)
# return 0
# #删除药剂最后一次领用记录
# def deleteLastUseRecord(self, drugId):
# SQL = """
# delete from rms_medicamentrecord WHERE MedicamentId='""" + drugId + """' and RecordType=2 ORDER BY CreateDate DESC LIMIT 1
# """
# result = BllMedicamentRecord().executeNoParam(SQL)
# return result
if __name__ == '__main__':
from db_logic.medicament_record import BllMedicamentRecord
customerId, clientId = None, '8db7e540-070f-11ed-a286-f47b094925e1'
typ_dic = BllMedicamentRecord().get_drug_record_count()
# typ_dic[4] = typ_dic[2] - typ_dic[3]
print(typ_dic)

@ -0,0 +1,110 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/19 09:43:08
'''
from sqlalchemy import or_, and_
from db_logic.db_base import Repository
from models.medicament_models import EntityMedicamentVariety
#药剂品种业务逻辑类
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, englishName, 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))
# print(entity, 6666666666)
# if(entity is None):
# entity = EntityMedicamentVariety()
# entity.VarietyId = Utils.UUID()
# entity.CustomerId = customerId
# entity.InventoryWarningValue = 10
# entity.ShelfLifeWarningValue = 10
# entity.UseDaysWarningValue = 10
# entity.Name = name
# entity.EnglishName = englishName
# entity.CASNumber = casNumber
# entity.Purity = purity
# entity.Unit = unit
# entity.SpeciUnit = speciUnit
# entity.TotalCount = 1
# entity.InventoryWarningValue = 2
# 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:
# entity.TotalCount += 1
# entity.NormalCount += 1
# self.update(entity)
# entity = self.session.merge(entity)
# return entity
# # 获取品种统计
# def getVarietyStatistics(self):
# SQL = """
# SELECT b.VarietyId as VarietyId, COUNT(CASE when IsEmpty = 1 then 1 end) as QuarterlyEmptyCount,
# sum(CASE when IsEmpty = 1 then a.price else 0 end) as QuarterlyEmptyPrice, COUNT(CASE when RecordType = 1 then 1 end) as
# QuarterlyPutInCount from RMS_MedicamentVariety as b LEFT JOIN RMS_MedicamentRecord as a on
# b.VarietyId = a.VarietyId and MONTH((a.CreateDate)) = MONTH(now()) and Date_format
# (a.CreateDate, '%Y') = (DATE_FORMAT(now(), '%Y')) GROUP by b.VarietyId
# """
# # 获取季度数据
# quarter_data = BllMedicamentVariety().execute(SQL).fetchall()
# quarter_data = json.loads(Utils.resultAlchemyData(
# Utils.mysqlTable2Model(quarter_data)))
# SQL = """SELECT b.VarietyId as VarietyId, COUNT(CASE when IsEmpty = 1 then a.CreateDate end)
# as YearEmptyCount, sum(CASE when IsEmpty = 1 then a.price else 0 end) as YearEmptyPrice,
# COUNT(CASE when RecordType = 1 then 1 end) as YearPutInCount from RMS_MedicamentVariety as b LEFT JOIN
# RMS_MedicamentRecord as a on b.VarietyId = a.VarietyId and year((a.CreateDate)) =
# year(now()) GROUP by b.VarietyId"""
# # 获取年度数据
# year_data = BllMedicamentVariety().execute(SQL).fetchall()
# year_data = json.loads(Utils.resultAlchemyData(
# Utils.mysqlTable2Model(year_data)))
# SQL = """
# select a.VarietyId as VarietyId, a.Name,a.Purity,a.CASNumber,a.IsSupervise,
# sum(case when b.`Status` = 1 then 1 else 0 end) as NormalCount,
# sum(case when b.`Status` = 1 or b.`Status` = 2 then 1 else 0 end) as TotalCount,
# sum(case when b.`Status` = 2 then 1 else 0 end) as UseCount,
# sum(case when b.`Status` = 1 or b.`Status` = 2 then b.Price else 0 end) as StockPrice
# from RMS_MedicamentVariety as a LEFT JOIN RMS_Medicament
# as b on b.VarietyId = a.VarietyId GROUP BY a.VarietyId
# """
# # 获取药剂数据
# med_data = BllMedicamentVariety().execute(SQL).fetchall()
# med_data = json.loads(Utils.resultAlchemyData(
# Utils.mysqlTable2Model(med_data)))
# data_list = []
# new_data_list = []
# # 便利数据合通过VarietyId相同合并字典
# for quarter in quarter_data:
# for year in year_data:
# if quarter['VarietyId'] == year['VarietyId']:
# new_data = dict(quarter, **year)
# data_list.append(new_data)
# for data_dict in data_list:
# for med in med_data:
# if data_dict['VarietyId'] == med['VarietyId']:
# new_data = dict(data_dict, **med)
# new_data_list.append(new_data)
# return new_data_list

@ -0,0 +1,32 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/19 13:54:49
'''
from sqlalchemy import or_, desc
from db_logic.db_base import Repository
from models.warning_models import EntityWarning
#预警信息业务逻辑类
class BllWarning(Repository):
def __init__(self, entityType=EntityWarning):
return super().__init__(entityType)
#获取预警列表
def getWarningList(self,customerId,pageParam,keyWord=''):
keyWord='%'+keyWord+'%'
orm_query= self.findList().filter(
EntityWarning.customer_id==customerId
).filter(
or_(EntityWarning.object_name.like(keyWord),
EntityWarning.warning_user_name.like(keyWord))
).order_by(desc(EntityWarning.warning_date))
return self.queryPage(orm_query,pageParam)
#获取预警类型数量
def getWarningCount(self):
recordList=self.findList().all()
# 过期预警列表
gqList = [record for record in recordList if record.object_type == '2']
# 余量预警列表
ylList = [record for record in recordList if record.object_type == '3']
return (len(recordList),len(gqList),len(ylList))

@ -48,4 +48,71 @@
展示
"""
报表统计:
库存信息总览: 分组
在库剩余数量count(id)
剩余总量sum(remain)
入库信息查询
默认展示
试剂信息详情
根据名称纯度规格分组展示
余量
库存消耗: rms_medicament rms_medicament_variety
入库数量 查询类型等于书库的数量
当前库存总量
rms_medicament_record record_type=1 count(id)?
当前库存数量 status=1的count(id)?
当前借出数量 status=2的count(id)?
消耗数量
试剂用量消耗
库存量 表rms_medicament count(id) status=1
使用次数 表rms_medicament_record count(record_type=2) 数量
总用量 表rms_medicament_record sum(use_quantity) record_type=3
"""
# Remark1 = Column(String(50)) # 备注1
# Remark2 = Column(String(50)) # 备注2
# Remark3 = Column(String(50)) # 备注3
# Remark4 = Column(String(50))
# Remark5 = Column(String(50))
# Remark6 = Column(String(50))
# Remark7 = Column(String(50))
# Remark8 = Column(String(50))
# Remark9 = Column(String(50))
# Remark10 = Column(String(50))
# for i in range(30):
# print(f"remark{i+1} = Column(String(50), comment='扩展字段{i+1}')")
import random
from string import digits, ascii_letters, punctuation
aaa = digits + ascii_letters+ punctuation
# ccc = 'l4wu&yj@=ed^ybmw&#6m&vh0cglcqwagu8&($r5@qsmf(bb93='
# print(len(ccc))
print(aaa)
a = ''
# while True:
# c = random.choice(aaa)
# if c in ["'", '"', ",", ";", "."]:
# continue
# # print(c)
# a += c
# # print(a)
# if len(a) >= 50:
# break
# print(a)
import random
print(random.choice([1,2,3]))

@ -1,267 +0,0 @@
[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)

@ -3,9 +3,18 @@
'''
@Date:2022/07/18 15:28:11
'''
import uuid
from datetime import datetime
from random import randint
import sys
sys.path.append('.')
# from common.utils import Utils
from sqlalchemy import Column, String, Integer, Text, Float
from models.models_base import Base, get_uuid
from models.models_base import Base, get_uuid, ModelBase
# from sqlalchemy.ext.declarative import declarative_base
# Base = declarative_base()
class EntityMedicament(Base):
@ -62,17 +71,47 @@ class EntityMedicament(Base):
is_add = Column(Integer, comment="")
user_auditing = Column(String(50), comment="用户审计")
remark1 = Column(String(50), comment='扩展字段1')
remark2 = Column(String(50), comment='扩展字段2')
remark3 = Column(String(50), comment='扩展字段3')
remark4 = Column(String(50), comment='扩展字段4')
remark5 = Column(String(50), comment='扩展字段5')
remark6 = Column(String(50), comment='扩展字段6')
remark7 = Column(String(50), comment='扩展字段7')
remark8 = Column(String(50), comment='扩展字段8')
remark9 = Column(String(50), comment='扩展字段9')
remark10 = Column(String(50), comment='扩展字段10')
remark11 = Column(String(50), comment='扩展字段11')
remark12 = Column(String(50), comment='扩展字段12')
remark13 = Column(String(50), comment='扩展字段13')
remark14 = Column(String(50), comment='扩展字段14')
remark15 = Column(String(50), comment='扩展字段15')
remark16 = Column(String(50), comment='扩展字段16')
remark17 = Column(String(50), comment='扩展字段17')
remark18 = Column(String(50), comment='扩展字段18')
remark19 = Column(String(50), comment='扩展字段19')
remark20 = Column(String(50), comment='扩展字段20')
remark21 = Column(String(50), comment='扩展字段21')
remark22 = Column(String(50), comment='扩展字段22')
remark23 = Column(String(50), comment='扩展字段23')
remark24 = Column(String(50), comment='扩展字段24')
remark25 = Column(String(50), comment='扩展字段25')
remark26 = Column(String(50), comment='扩展字段26')
remark27 = Column(String(50), comment='扩展字段27')
remark28 = Column(String(50), comment='扩展字段28')
remark29 = Column(String(50), comment='扩展字段29')
remark30 = Column(String(50), comment='扩展字段30')
def to_dict(self):
li = []
for i in self.__table__.columns:
li.append(i.name)
return li
# return {c.name: getattr(self, c.name) for c in self.__table__.columns}
# Remark1 = Column(String(50)) # 备注1
# Remark2 = Column(String(50)) # 备注2
# Remark3 = Column(String(50)) # 备注3
# Remark4 = Column(String(50))
# Remark5 = Column(String(50))
# Remark6 = Column(String(50))
# Remark7 = Column(String(50))
# Remark8 = Column(String(50))
# Remark9 = Column(String(50))
# Remark10 = Column(String(50))
class EntityMedicamentTemplate(Base):
@ -154,10 +193,76 @@ class EntityMedicamentVariety(Base):
use_count = Column(Integer, comment="当前领用数量")
normal_count = Column(Integer, comment="在库数量")
total_count = Column(Integer, comment="总数量")
# Remark1 = Column(String(50)) # 备注1
# Remark2 = Column(String(50)) # 备注2
# Remark3 = Column(String(50)) # 备注3
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="", default=1)
remark1 = Column(String(50), comment='扩展字段1')
remark2 = Column(String(50), comment='扩展字段2')
remark3 = Column(String(50), comment='扩展字段3')
remark4 = Column(String(50), comment='扩展字段4')
remark5 = Column(String(50), comment='扩展字段5')
remark6 = Column(String(50), comment='扩展字段6')
remark7 = Column(String(50), comment='扩展字段7')
remark8 = Column(String(50), comment='扩展字段8')
remark9 = Column(String(50), comment='扩展字段9')
remark10 = Column(String(50), comment='扩展字段10')
class EntityMedicamentExtend(Base):
__tablename__ = "rms_medicament_extend"
__table_args__ = (
{
"comment": "扩展字段备注表"
}
)
id = Column(String(50), primary_key=True, comment="ID", default=get_uuid)
field_key = Column(String(50), comment="字段名称")
field_value = Column(String(50), comment="字段含义")
field_table_type = Column(Integer, comment="字段所在表")
if __name__ == '__main__':
# from db_logic.medicament_record import BllMedicamentRecord
# customerId, clientId = None, '8db7e540-070f-11ed-a286-f47b094925e1'
# aaa = BllMedicamentRecord().getTodayDrugRecordCount(customerId, clientId)
# print(aaa)
import random
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from config.SystemConfig import SystemConfig
from sqlalchemy.pool import NullPool
engine = create_engine(SystemConfig.getConfig(
'dbconntion'), poolclass=NullPool)
DBSession = sessionmaker(bind=engine, expire_on_commit=False)
# 创建session对象
session = DBSession()
client_id= get_uuid()
variety_id_list = [get_uuid() for i in range(5)]
bar_code_list = [i for i in range(10001, 10110)]
customer_id= get_uuid()
for i in range(100):
db_mo = EntityMedicament(
bar_code=random.choice(bar_code_list),
variety_id=random.choice(variety_id_list),
client_id=client_id,
client_code=6,
customer_id=customer_id,
cas_number='',
name='',
english_name='',
shelf_life=5170,
inventory_warning_value=10,
shelf_life_warning_value=10,
use_days_warning_value=10,
remain=500,
total=500,
purity="国标",
status=random.randint(1,3)
# create_date=Utils.get_str_datetime()
)
session.add(db_mo)
session.commit()
# Base.metadata.create_all(engine)

@ -9,6 +9,23 @@ from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class ModelBase(object):
fields = None
def __init__(self):
if not self.__class__.fields:
self.__class__.fields = [x.key for x in self.__mapper__.attrs]
def __iter__(self):
if not self.__class__.fields:
self.__class__.fields = [x.key for x in self.__mapper__.attrs]
return next(self)
def __next__(self):
for key in self.__class__.fields:
value = getattr(self, key)
def get_uuid():
return str(uuid.uuid1())
@ -19,6 +36,6 @@ def gen_id():
return uuid.uuid4().hex
if __name__ == '__main__':
print(type(gen_id))
print(type(gen_id()))
# if __name__ == '__main__':
# print(type(gen_id))
# print(type(gen_id()))
Loading…
Cancel
Save