数据报表相关接口完善

duizhaopin
apan 3 years ago
parent d870c0d9cf
commit 6826648699

@ -57,6 +57,10 @@ class Utils(object):
#return [dict(zip(result.keys(), result.values())) for result in dataList] #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] return [dict(zip(result.keys(), [(x if x is not None else '') for x in result.values()])) for result in dataList]
# 根据自定义字段及数据顺序进行返回
def mysqlfinds_list(data, finds):
return [dict(zip(finds, i)) for i in data]
#生成统一格式接口数据 #生成统一格式接口数据
def resultData(status, message, data=""): def resultData(status, message, data=""):
return json.dumps({"status": status, "message": message, "data": data}, ensure_ascii=False) return json.dumps({"status": status, "message": message, "data": data}, ensure_ascii=False)

@ -5,7 +5,7 @@
''' '''
from flask import jsonify, request from flask import jsonify, request
from common.utils import Utils from common.utils import PageParam, Utils
from db_logic.medicament_record import BllMedicamentRecord from db_logic.medicament_record import BllMedicamentRecord
from db_logic.medicament import BllMedicament from db_logic.medicament import BllMedicament
@ -39,12 +39,14 @@ def get_stock_data_info():
page_size = request.values.get('page_size', 15) page_size = request.values.get('page_size', 15)
finds = ["name", "cas_number", "net_weight_unit", finds = ["name", "cas_number", "net_weight_unit",
"client_id", "count_surplus", "sum_remain"] "client_id", "count_surplus", "sum_remain"]
data_list = BllMedicament.get_stock_all_info(name=name, page=page, page_size=page_size) page_param = PageParam(page, page_size)
data_list = BllMedicament.get_stock_all_info(
name=name, page_param=page_param)
if data_list: if data_list:
data = [] data = []
for i in data_list: for i in data_list:
data.append(dict(zip(finds, list(i)))) data.append(dict(zip(finds, list(i))))
return jsonify(Utils.true_return(data=data)) return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
else: else:
return jsonify(Utils.false_return(msg="无效数据")) return jsonify(Utils.false_return(msg="无效数据"))
@ -53,13 +55,19 @@ def get_stock_data_info():
@report_router.route("/drug_details_info", methods=["GET", "POST"]) @report_router.route("/drug_details_info", methods=["GET", "POST"])
def drun_input_info(): def drun_input_info():
seach_word = request.values.get('seach_word') 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") # manufacturer = request.values.get("manufacturer")
customer_id = request.values.get("customer_id") customer_id = request.values.get("customer_id")
client_id = request.values.get("client_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) page = request.values.get("page", 1)
return jsonify(Utils.true_return(data=data)) page_size = request.values.get("page_size", 10)
page_param = PageParam(page, page_size)
data = BllMedicament.getAllDrugList(
search_word=seach_word,
page_param=page_param,
customer_id=customer_id,
client_id=client_id
)
return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
# 库存消耗 # 库存消耗
@ -72,9 +80,62 @@ def drun_input_info():
@report_router.route("/stock_loss_info", methods=["GET", "POST"]) @report_router.route("/stock_loss_info", methods=["GET", "POST"])
def stock_loss_info(): def stock_loss_info():
seach_word = request.values.get('seach_word') seach_word = request.values.get('seach_word')
data = BllMedicamentRecord().durg_stock_loss(seach_word) page = request.values.get("page", 1)
return jsonify(Utils.true_return(data=data)) page_size = request.values.get("page_size", 10)
page_param = PageParam(page, page_size)
data = BllMedicamentRecord().durg_stock_loss(seach_word, page_param=page_param)
return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
# 试剂用量消耗 # 试剂用量消耗
@report_router.route("/drug_use_expend", methods=["GET", "POST"])
def drug_use_expend():
seach_word = request.values.get('seach_word')
page = request.values.get("page", 1)
page_size = request.values.get("page_size", 10)
page_param = PageParam(page, page_size)
data = BllMedicamentRecord().durg_useing_info(seach_word, page_param=page_param)
return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
# 人员用量消耗
@report_router.route("/drug_user_use_expend", methods=["GET", "POST"])
def drug_use_expend():
seach_word = request.values.get('seach_word')
page = request.values.get("page", 1)
page_size = request.values.get("page_size", 10)
page_param = PageParam(page, page_size)
data = BllMedicamentRecord().user_use_info(seach_word, page_param=page_param)
return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
# 使用频率
@report_router.route("/use_frequency", methods=["GET", "POST"])
def drug_use_frequency():
seach_word = request.values.get('seach_word', None)
client_id = request.values.get("client_id", None)
page = request.values.get("page", 1)
page_size = request.values.get("page_size", 10)
page_param = PageParam(page, page_size)
data = BllMedicamentRecord().use_frequency(seach_word=seach_word, client_id=client_id, page_param=page_param)
return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
# 入库、领用、归还记录
@report_router.route("/drug_log_type_info", methods=["GET", "POST"])
def drug_log_type_info():
page = request.values.get("page", 1)
page_size = request.values.get("page_size", 10)
record_type = request.values.get("record_type")
put_in_user_name = request.values.get("put_in_user_name")
name = request.values.get("name")
start_time = request.values.get("start_time")
end_time = request.values.get("end_time")
page_param = PageParam(page, page_size)
data_list = BllMedicament().drug_show_type_info(
record_type=record_type, put_in_user_name=put_in_user_name,
name=name, start_time=start_time, end_time=end_time, page_param=page_param
)
return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))

@ -146,8 +146,7 @@ class BllMedicament(Repository):
self.entityType.purity) self.entityType.purity)
# 获取库存信息总览 # 获取库存信息总览
def get_stock_all_info(self, page, page_size, name=None): def get_stock_all_info(self, page_param, name=None):
page_param = PageParam(page, page_size)
base_case = [ base_case = [
self.entityType.name, self.entityType.name,
self.entityType.cas_number, self.entityType.cas_number,
@ -171,11 +170,13 @@ class BllMedicament(Repository):
).group_by( ).group_by(
*base_case *base_case
) )
count_sql = f"SELECT count(medicament_id) FROM rms_medicament "
page_param.totalRecords = self.execute(count_sql).fetchone()[0]
return self.queryPage(data, page_param) return self.queryPage(data, page_param)
#获取所有药剂列表 #获取所有药剂列表
def getAllDrugList(self, search_word, page, page_size, customer_id=None, client_id=None): def getAllDrugList(self, search_word, page_param, customer_id=None, client_id=None):
# (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord) # (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord)
""" """
[ [
@ -188,7 +189,6 @@ class BllMedicament(Repository):
'put_in_user_id', 'put_in_user_name', 'is_add', 'user_auditing'] 'put_in_user_id', 'put_in_user_name', 'is_add', 'user_auditing']
""" """
page_param = PageParam(page, page_size)
filter_base = [] filter_base = []
if customer_id: if customer_id:
filter_base.append(self.entityType.customer_id == customer_id) filter_base.append(self.entityType.customer_id == customer_id)
@ -232,13 +232,42 @@ class BllMedicament(Repository):
"by_user_name" "by_user_name"
] ]
data_list = [] data_list = []
count_sql = f"SELECT count(medicament_id) FROM rms_medicament"
page_param.totalRecords = self.execute(count_sql).fetchone()[0]
page_data = self.queryPage(data, page_param) page_data = self.queryPage(data, page_param)
for i in page_data: for i in page_data:
data_list.append(dict(zip(fields, i))) data_list.append(dict(zip(fields, i)))
return data_list return data_list
# 入库、领用、归还记录
# # 获取库存消耗 def drug_show_type_info(self, record_type, put_in_user_name, name, start_time, end_time, page_param):
sql_all = """
SELECT
b.`name`, b.english_name, b.bar_code, b.purity, b.cas_number, a.use_quantity, b.`status`, a.create_date, a.create_user_name, b.client_id
FROM (
SELECT medicament_id, use_quantity, create_user_name, create_date FROM rms_medicament_record %s
) a LEFT JOIN (
SELECT medicament_id, `name`, english_name, bar_code, purity, cas_number, net_weight, remain, `status`, by_user_date, by_user_name, client_id
FROM rms_medicament %s
) b on b.medicament_id = a.medicament_id
"""
filter_sql = f"WHERE record_type={record_type}"
filter_sql_1 = ''
if put_in_user_name:
filter_sql += f" and create_user_name like {put_in_user_name}"
if start_time and end_time:
filter_sql += f"and create_date >= {start_time} and create_date <= {end_time}"
if name:
filter_sql_1 += f" where `name` like '{name}' or english_name like '{name}'"
sql_all = sql_all % (filter_sql, filter_sql_1)
finds = ["name", "english_name", "bar_code",
"purity", "cas_number", "use_quantity", "status", "create_date", "create_user_name", "client_id"]
sql_all += ' limit ' + str((page_param.curPage - 1) * page_param.pageRows) + ',' + str(page_param.pageRows)
data_list = self.execute(sql_all).fetchall()
count_sql = f"SELECT count(*) FROM rms_medicament_record WHERE record_type={record_type} "
page_param.totalRecords = self.execute(count_sql).fetchone()[0]
return Utils.mysqlfinds_list(data_list, finds)
# # 获取库存消耗
# def get_comsume_stock(self): # def get_comsume_stock(self):
# self.session.query( # self.session.query(
# self.entityType.status, # self.entityType.status,
@ -253,3 +282,21 @@ class BllMedicament(Repository):
# drugList = self.findList( # drugList = self.findList(
# EntityMedicament.ByUserId == userId, EntityMedicament.Status == DrugStatus.Out).all() # EntityMedicament.ByUserId == userId, EntityMedicament.Status == DrugStatus.Out).all()
# return drugList # return drugList
if __name__ == '__main__':
from db_logic.medicament import BllMedicament
values= {}
page = values.get("page", 1)
page_size = values.get("page_size", 10)
record_type = values.get("record_type", 1)
put_in_user_name = values.get("put_in_user_name")
name = values.get("name")
start_time = values.get("start_time")
end_time = values.get("end_time")
page_param = PageParam(page, page_size)
typ_dic = BllMedicament().drug_show_type_info(record_type=record_type, put_in_user_name=put_in_user_name,
name=name, start_time=start_time, end_time=end_time, page_param=page_param
)
print(typ_dic)

@ -79,53 +79,167 @@ class BllMedicamentRecord(Repository):
).select_from(self.entityType).group_by(EntityMedicamentRecord.record_type).all() ).select_from(self.entityType).group_by(EntityMedicamentRecord.record_type).all()
return data return data
def default_data_list(self, **kw):
sql_all = kw.get("sql_all")
finds = kw.get("finds")
base_bool = kw.get("base_bool", False)
med_data = self.execute(sql_all).fetchall()
data_list = []
base_num = 0
for med in med_data:
new_med = []
# for n in med:
# new_med.append(float(n) if isinstance(n, Decimal) else n)
new_med = [n if not isinstance(n, Decimal) else float(n) for n in med]
data_list.append(dict(zip(finds, new_med)))
if base_bool:
base_num += float(new_med[-1])
return data_list, base_num
# 获取库存消耗数据 # 获取库存消耗数据
def durg_stock_loss(self, seach_word): def durg_stock_loss(self, seach_word, page_param):
sql_all = """ sql_all = """
select c.`name`, c.cas_number, c.net_weight_unit, c.purity, c.enter_stock, select c.`name`, c.cas_number, c.net_weight_unit, c.purity, c.enter_stock,
sum(CASE WHEN c.`status`=1 THEN 1 ELSE 0 END) in_stock, sum(CASE WHEN c.`status`=1 THEN 1 ELSE 0 END) in_stock,
sum(CASE WHEN c.`status`=2 THEN 1 ELSE 0 END) up_stock, sum(CASE WHEN c.`status`=2 THEN 1 ELSE 0 END) up_stock,
sum(CASE WHEN c.`status`=3 THEN 1 ELSE 0 END) no_stock sum(CASE WHEN c.`status`=3 THEN 1 ELSE 0 END) no_stock
from ( from (
select a.*, b.enter_stock from ( select a.*, b.enter_stock from (
select medicament_id, `name`, cas_number, purity, net_weight_unit, `status` from rms_medicament
select medicament_id, `name`, cas_number, purity, net_weight_unit, `status` from rms_medicament %s
%s ) a LEFT JOIN(
) a LEFT JOIN( SELECT medicament_id, sum(CASE WHEN record_type=1 THEN 1 ELSE 0 END) enter_stock from rms_medicament_record GROUP BY medicament_id
) b on b.medicament_id = a.medicament_id
SELECT medicament_id, sum(CASE WHEN record_type=1 THEN 1 ELSE 0 END) enter_stock from rms_medicament_record GROUP BY medicament_id ) c GROUP BY `name`, purity, net_weight_unit
) b on b.medicament_id = a.medicament_id) c GROUP BY `name`, purity, net_weight_unit
""" """
if seach_word: if seach_word:
sql_all = sql_all % f"where name link {seach_word} or english_name link {seach_word}" seach_word = f"%{seach_word}%"
sql_all = sql_all % f"where `name` like '{seach_word}' or english_name like '{seach_word}'"
else: else:
sql_all = sql_all % '' sql_all = sql_all % ""
finds = [ finds = [
"name", "cas_number", "net_weight_unit", "purity", "enter_stock", "in_stock", "up_stock", "no_stock" "name", "cas_number", "net_weight_unit", "purity", "enter_stock", "in_stock", "up_stock", "no_stock"
] ]
count_sql = "select count(medicament_id) from rms_medicament group by `name`, purity, net_weight_unit"
page_param.totalRecords = self.execute(count_sql).fetchone()[0]
sql_all += ' limit ' + \
str((page_param.curPage - 1) * page_param.pageRows) + \
',' + str(page_param.pageRows)
med_data = self.execute(sql_all).fetchall() data_list, _ = self.default_data_list(**{"sql_all":sql_all, "finds":finds})
data_list = []
for med in med_data:
new_med = []
for n in med:
if isinstance(n, Decimal):
n = float(n)
new_med.append(n)
data_list.append(dict(zip(finds, new_med)))
return data_list return data_list
# 试剂用量消耗 # 试剂用量消耗
def durg_useing_info(self, seach_word, page_param):
sql_all = """
select c.`name`, c.purity, c.cas_number, c.net_weight_unit, sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) on_in, c.c_two, c.sum_use from (
select a.*, b.c_two, b.sum_use from(
select medicament_id, `name`, cas_number, purity, net_weight_unit, `status` from rms_medicament
%s
) a LEFT JOIN(
select medicament_id, FORMAT(sum(use_quantity), 2) sum_use, sum(CASE WHEN record_type=2 THEN 1 ELSE 0 END) c_two from rms_medicament_record GROUP BY medicament_id
) b on a.medicament_id=b.medicament_id
) c GROUP BY `name`, purity, net_weight_unit
"""
if seach_word:
seach_word = f"%{seach_word}%"
sql_all = sql_all % f"where `name` like '{seach_word}' or english_name like '{seach_word}'"
else:
sql_all = sql_all % ""
finds = [
"name", "purity", "cas_number", "net_weight_unit", "on_in", "use_num", "use_level", "ratio"
]
count_sql = "select count(medicament_id) from rms_medicament group by `name`, purity, net_weight_unit"
page_param.totalRecords = self.execute(count_sql).fetchone()[0]
sql_all += ' limit ' + \
str((page_param.curPage - 1) * page_param.pageRows) + \
',' + str(page_param.pageRows)
def update_db(self): data, ratio_all = self.default_data_list(**{"sql_all": sql_all, "finds": finds, "base_bool": True})
import random for i in data:
typ_dic = BllMedicamentRecord().findList().all() i["ratio"] = str(round(float(i["use_level"]) / ratio_all, 2) * 100) + "%"
for a in typ_dic:
a.use_quantity = round(random.uniform(1, 10), 2) return data
self.session.merge(a)
self.session.commit() # 人员用量消耗
def user_use_info(self, page_param, seach_word=None, seach_user=None):
sql_all = """
select c.by_user_name, c.by_user_id, c.sum_use, c.c_two from (
select a.*, b.c_two, b.sum_use from(
select medicament_id, by_user_name, by_user_id from rms_medicament %s
) a LEFT JOIN(
select medicament_id, FORMAT(sum(use_quantity), 2) sum_use, sum(CASE WHEN record_type=2 THEN 1 ELSE 0 END) c_two from rms_medicament_record GROUP BY medicament_id
) b on a.medicament_id=b.medicament_id
) c GROUP BY by_user_name, by_user_id
"""
filter_sql = ""
if seach_word:
seach_word = f"%{seach_word}%"
filter_sql = f"`name` like '{seach_word}' or english_name like '{seach_word}'"
if seach_user:
if filter_sql:
filter_sql += " and "
seach_user = f"%{seach_user}%"
filter_sql += f"by_user_name like '{seach_user}'"
if filter_sql:
sql_all = sql_all % f"where {filter_sql}"
else:
sql_all = sql_all % ""
finds = [
"by_user_name", "by_user_id", "use_number", "use_level", "ratio"
]
count_sql = "select count(medicament_id) from rms_medicament_record group by create_user_id"
page_param.totalRecords = self.execute(count_sql).fetchone()[0]
sql_all += ' limit ' + \
str((page_param.curPage - 1) * page_param.pageRows) + \
',' + str(page_param.pageRows)
data, ratio_all = self.default_data_list(**{"sql_all": sql_all, "finds": finds, "base_bool": True})
for i in data:
i["ratio"] = str(
round(float(i["use_level"]) / ratio_all, 2) * 100) + "%"
print(i)
return data
# 使用频率
def use_frequency(self, page_param, client_id=None, seach_word=None):
sql_all = """
select c.`name`, c.purity, c.cas_number, c.net_weight_unit,
sum( CASE WHEN c.`status` = 1 THEN 1 ELSE 0 END ) new_on,
c.client_id, sum(c.tp_2) sum_tp2, sum(c.tp_3) sum_tp3 from (
select a.*, IFNULL(b.two_type,0) tp_2, IFNULL(b.three_type,0) tp_3 from (
select medicament_id, `name`, purity, cas_number, net_weight_unit, `status`, client_id from rms_medicament
%s
) a LEFT JOIN(
select medicament_id,
sum( CASE WHEN record_type = 2 THEN 1 ELSE 0 END ) two_type,
sum( CASE WHEN record_type = 3 THEN 1 ELSE 0 END ) three_type
from rms_medicament_record GROUP BY medicament_id
)b on a.medicament_id=b.medicament_id
) c GROUP BY `name`, purity, net_weight_unit
"""
filter_sql = ""
if client_id:
filter_sql += f" client_id='{client_id}' "
if seach_word:
if filter_sql:
filter_sql += "and "
seach_word = f"%{seach_word}%"
filter_sql += f" `name` like '{seach_word}' or english_name like '{seach_word}'"
if filter_sql:
sql_all = sql_all % f"where {filter_sql}"
else:
sql_all = sql_all % ""
finds = [
"name", "purity", "cas_number", "net_weight_unit", "use_num", "return_num"
]
count_sql = "select count(medicament_id) from rms_medicament group by `name`, purity, net_weight_unit"
page_param.totalRecords = self.execute(count_sql).fetchone()[0]
sql_all += ' limit ' + str((page_param.curPage - 1) * page_param.pageRows) + ',' + str(page_param.pageRows)
data, _ = self.default_data_list(**{"sql_all": sql_all, "finds":finds})
return data
# #获取药剂最后一次使用余量 # #获取药剂最后一次使用余量
# def getLastRecordRemain(self, drugId): # def getLastRecordRemain(self, drugId):
@ -150,7 +264,7 @@ class BllMedicamentRecord(Repository):
if __name__ == '__main__': if __name__ == '__main__':
import random import random
from db_logic.medicament_record import BllMedicamentRecord from db_logic.medicament_record import BllMedicamentRecord
customerId, clientId = None, '8db7e540-070f-11ed-a286-f47b094925e1' # customerId, clientId = None, '8db7e540-070f-11ed-a286-f47b094925e1'
sql = f"update rms_medicament_record set use_quantity={round(random.uniform(1,10), 1)}" # sql = f"update rms_medicament_record set use_quantity={round(random.uniform(1,10), 1)}"
typ_dic = BllMedicamentRecord().update_db() typ_dic = BllMedicamentRecord().drug_use_f('', '')
print(typ_dic) print(typ_dic)

@ -120,11 +120,21 @@
# # print(random.choice([1,2,3])) # # print(random.choice([1,2,3]))
a = """12342525436 %s freqwrqwercqwe""" # a = """12342525436 %s freqwrqwercqwe"""
b = '' # b = ''
if b: # if b:
a = a % f"ccccc{b}ccccccc" # a = a % f"ccccc{b}ccccccc"
else: # else:
a = a % '' # a = a % ''
print(a) # print(a)
def mysqlfinds_list(data, finds):
return [dict(zip(finds, i)) for i in data]
fin = ["id", "name", "age"]
da = [(1, "a", 10), (2, "b", 11),(3, "c", 12)]
print(mysqlfinds_list(da, fin))
Loading…
Cancel
Save