diff --git a/Common/Utils.py b/Common/Utils.py
index 90a4ee1..cda8045 100644
--- a/Common/Utils.py
+++ b/Common/Utils.py
@@ -25,6 +25,16 @@ class Utils(object):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
+ # 反转bar_code
+ def get_bar_code_reverse(bar_code):
+ if len(bar_code) > 10:
+ new_code = ''
+ for i in range(int(len(bar_code) / 2)):
+ new_code = bar_code[i*2:(i+1)*2] + new_code
+ else:
+ new_code = bar_code
+ return bar_code, new_code
+
#MD5加密78
def MD5(str):
# 创建md5对象
@@ -35,6 +45,9 @@ class Utils(object):
def get_str_datetime():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ def get_file_name_datetime():
+ return datetime.datetime.now().strftime("%Y%m%d%H%M%S")
+
def sql_paging_assemble(sql_all, page_param):
sql_all += ' limit ' + str((page_param.curPage - 1) * page_param.pageRows) + ',' + str(page_param.pageRows)
return sql_all
diff --git a/Common/auth.py b/Common/auth.py
index 8ef0d84..bd1fc2d 100644
--- a/Common/auth.py
+++ b/Common/auth.py
@@ -18,7 +18,6 @@ token_auth = HTTPTokenAuth()
def verify_password(username, password):
'''用于检查用户提供的用户名和密码'''
user = EntityUser.query.filter_by(username=username).first()
- print(username, password)
if user is None:
return False
g.current_user = user
@@ -36,10 +35,6 @@ def verify_token(token):
'''用于检查用户请求是否有token,并且token真实存在,还在有效期内'''
# g.current_user = User.verify_jwt(token) if token else None
g.current_user = BllUser().verify_jwt(token)
- # if g.current_user:
- # 每次认证通过后(即将访问资源API),更新 last_seen 时间
- # g.current_user.update_last_visit_date()
- # BllUser().update(g.current_user)
return g.current_user is not None
diff --git a/Common/create_barcode.py b/Common/create_barcode.py
new file mode 100644
index 0000000..699558c
--- /dev/null
+++ b/Common/create_barcode.py
@@ -0,0 +1,150 @@
+"""
+此文件是用来生成Code128条形码 并实现打印功能
+"""
+import os
+
+from PyQt5.QtGui import *
+from PyQt5.QtCore import *
+from PyQt5.QtWidgets import QApplication
+from PyQt5.QtPrintSupport import QPrinter
+from pystrich.code128 import Code128Encoder
+import uuid
+
+
+class CreateBarcode:
+
+ """
+ Code128Encoder(options={}) options参数
+ * ttf_font:用于呈现标签的truetype字体文件的绝对路径
+ * ttf_fontsize:绘制标签的字体大小
+ * label_border:条形码和标签之间的像素空间数
+ * bottom_border:标签和底部边框之间的像素空间数
+ * height:图像的高度(以像素为单位)
+ * show_label:是否在条形码下面显示标签(默认为True)“”
+ """
+ code_path = os.path.join(os.getcwd(), "img")
+ if not os.path.exists(code_path):
+ os.makedirs(code_path)
+ def __init__(self):
+ pass
+
+
+ def create_Code128_img(self, barcode):
+ a = Code128Encoder(barcode, options={
+ 'ttf_font': os.path.join(os.getcwd(),'arial.ttf'),
+ 'label_border': 0, 'height': 45, 'bottom_border': 0,'ttf_fontsize':13,
+ })
+ # bar_width 条码宽度尺寸
+
+
+ file_name = os.path.join(self.code_path, str(uuid.uuid4()) + '.png')
+ a.save(file_name, bar_width=1)
+ self.printer_code(file_name)
+
+ def printer_code(self, file_name):
+ a = QApplication([])
+ document = QTextDocument()
+ html = """
+
+ Report
+
+
+
+
+
+ """.format(file_name)
+
+ document.setHtml(html)
+ printer = QPrinter()
+ printer.setPageSize(QPagedPaintDevice.Custom)
+ printer.setPaperSize(QSizeF(30.0,18.0),QPrinter.Millimeter)
+ # 设置纸张到条码的边距 左上下右
+ printer.setPageMargins(0, 3, 0, 0, QPrinter.Millimeter)
+
+ #document.setPageSize(QSizeF(printer.pageRect().size()))
+ document.setPageSize(QSizeF(100.0,65.0))
+
+ print('正在打印中。。。。')
+ document.print_(printer)
+ print('打印完成。。')
+ # os.remove(file_name)
+
+ def create_drug_lobel_code(self, **kwargs):
+ a = Code128Encoder(
+ kwargs.get("code_number"),
+ options={
+ 'ttf_font': os.path.join(os.getcwd(),'arial.ttf'),
+ 'label_border': 0, 'height': 15, 'bottom_border': 0,'ttf_fontsize':0,
+ })
+ # bar_width 条码宽度尺寸
+
+
+ file_name = os.path.join(self.code_path, str(uuid.uuid4()) + '.png')
+ a.save(file_name, bar_width=1)
+ kwargs["file_path"] = file_name
+ self.printer_drug_label(**kwargs)
+
+ def printer_drug_label(self, **kwargs):
+ a = QApplication([])
+ document = QTextDocument()
+ #TODO 添加溶剂
+ html = """
+
+ Report
+
+
+
+
+
+ 珠海市食品药品检验所
+ 名称: {}
+ 编号: {}
+ 浓度: {} 溶剂: {}
+ 配置日期: {}
+ 有 效 期:{}
+ 配 置 人:{}
+
+
+
+
+ """.format(
+
+ kwargs.get("name"),
+ kwargs.get("code_number"),
+ kwargs.get("purity"),
+ kwargs.get("solvent"),
+ kwargs.get("start_time")[:10],
+ kwargs.get("end_time")[:10],
+ kwargs.get("user_name"),
+ kwargs.get("file_path"),
+ )
+ document.setHtml(html)
+ printer = QPrinter()
+ printer.setPageSize(QPagedPaintDevice.Custom)
+ printer.setPaperSize(QSizeF(60.0,40.0),QPrinter.Millimeter)
+ # printer.setPaperSize(QSizeF(30.0,50.0),QPrinter.Millimeter)
+ # 设置纸张到条码的边距 左上下右
+ printer.setPageMargins(6, 2, 0, 0, QPrinter.Millimeter)
+
+ document.setPageSize(QSizeF(printer.pageRect().size()))
+ #document.setPageSize(QSizeF(50.0,30.0))
+
+ print('正在打印中。。。。')
+ document.print_(printer)
+ print('打印完成。。')
+ # os.remove(file_name)
+
+
+if __name__ == '__main__':
+ kwS = {
+ "code_number":"200001",
+ "medicament_name":"1111111",
+ "purity":"12",
+ "solvent": "2313",
+ "start_time": "2022-10-15",
+ "end_time": "2022-10-16",
+ "user_name":"测试账户"
+ }
+ CreateBarcode().create_drug_lobel_code(**kwS)
+ # CreateBarcode().create_Code128_img("200000001")
diff --git a/Common/read_excel.py b/Common/read_excel.py
index 66dd769..97fd130 100644
--- a/Common/read_excel.py
+++ b/Common/read_excel.py
@@ -18,14 +18,14 @@ class ReadExcel:
self.ws = self.wb.active
self.template_list = []
- def read(self):
+ def read(self, func_type):
max_lines = self.ws.max_row
if self.ws['C1'].value == 'template_content':
for key in range(2, max_lines + 1):
value = self.ws['{}'.format('C' + str(key))].value
self.template_list.append(value)
return self.template_list
- elif self.ws['A1'].value == '申购单编号' and self.ws['B1'].value == '采购单编号':
+ elif self.ws['A1'].value == '单位编号' and self.ws['B1'].value == '产品编号':
drug_list = []
# lineIndex = 0
try:
@@ -39,12 +39,32 @@ class ReadExcel:
"variety_id": str(uuid.uuid1()),
}
+ # key_list = [
+ # "unit_code", "remark2", "category",
+ # "speci", "name", "english_name",
+ # "purity", "cas_number", "standard_code",
+ # "net_weight", "net_weight_unit", "export_count",
+ # "production_date", "shelf_life", "expiration_date",
+ # "price", "is_supervise", "remain",
+ # "manufacturer", "storage_condition", "remark9"
+ # ]
+ # TODO 添加供应商修改
key_list = [
- "name", "english_name", "purity", "cas_number", "speci", "net_weight_unit", "export_count", "export_unit",
- "production_date", "shelf_life", "expiration_date", "price", "is_supervise", "total", "manufacturer", "remain"
+ "unit_code", "remark2", "category",
+ "speci", "name", "english_name",
+ "purity", "cas_number", "standard_code",
+ "net_weight", "net_weight_unit", "export_count",
+ "production_date", "shelf_life", "expiration_date",
+ "price", "is_supervise", "remain",
+ "manufacturer", "distributor", "storage_condition", "remark9"
]
+ # v_list = list("EFGHJKLMNOPQRSTU")
+ # v_list = list("ABCDEFGHIJKLNOPQRSTUV")
+ # 添加供应商
+ v_list = list("ABCDEFGHIJKLNOPQRSTUVW")
# 采用列表和字母对应的两个列表,进行循环的方式写入字典,简化代码量
- v_list = list("EFGHJKLMNOPQRSTU")
+
+
str_tim = "%Y-%m-%d %H:%M:%S"
def date_func(x): return datetime.datetime.strptime(
x, str_tim)
@@ -53,16 +73,33 @@ class ReadExcel:
key_key = key_list[i]
# 时间格式转换
if key_key == "production_date" or key_key == "expiration_date":
- value = date_func(value_func(
- v_key)).strftime(str_tim)
+ # 计算保质期
+ va = value_func(v_key)
+ if va:
+ if len(va) > 0 and len(va) == 10:
+ va += " 00:00:00"
+ else:
+ va = date_func(va).strftime(str_tim)
+ if key_key == "production_date":
+ if va:
+ value = va
+ else:
+ value = time.strftime(str_tim[:8]) + " 00:00:00"
+ elif key_key == "expiration_date":
+ if va:
+ value = va
+ else:
+ value = (
+ date_func(drug_template_dict.get("production_date")) +
+ datetime.timedelta(days=360)
+ ).strftime(str_tim)
+
elif key_key == "is_supervise":
va = value_func(v_key)
if va == "否":
value = 0
else:
value = 1
- elif key_key == "remain":
- value = drug_template_dict.get("speci")
else:
value = value_func(v_key)
@@ -70,59 +107,16 @@ class ReadExcel:
if key_list[i] == "name" and drug_template_dict.get("name") == "":
self.template_list.append(json.dumps(drug_list))
return self.template_list
-
- # 时间判断逻辑较为凌乱,采用原思路进行重写
-
- # 定义当前时间对象
- # pDate = datetime.datetime.now()
- # 局部性时间字符串,共用
-
- # 定义公共方法,处理时间转换
-
- # 和原逻辑一样,简化写法
- # if not value_func("P"):
- # if value_func("O"):
- # pDate = date_func(value_func("N"))
- # shelf_life = value_func("O", "3650")
- # else:
- # if value_func("N"):
- # pDate = date_func(value_func('N'), str_tim)
- # shelf_life = self.time_long(
- # date_func(pDate.strftime(str_tim)), date_func(value_func("P")))
- # drug_template_dict["production_date"] = pDate.strftime(
- # str_tim)
- # drug_template_dict["shelf_life"] = shelf_life
-
- # if(not self.ws['P{}'.format(str(line))].value):
- # pDate = datetime.datetime.now()
- # if(self.ws['O{}'.format(str(line))].value):
- # pDate = datetime.datetime.strptime(str(self.ws['N{}'.format(str(line))].value), "%Y-%m-%d %H:%M:%S")
- # drug_template_dict['ProductionDate'] = pDate.strftime("%Y-%m-%d")
- # drug_template_dict['ShelfLife'] = str(self.ws['O{}'.format(str(line))].value or '3650')
- # else:
- # pDate = datetime.datetime.now()
- # if(self.ws['N{}'.format(str(line))].value):
- # pDate = datetime.datetime.strptime(str(self.ws['N{}'.format(str(line))].value), "%Y-%m-%d %H:%M:%S")
- # drug_template_dict['ProductionDate'] = pDate.strftime("%Y-%m-%d")
- # drug_template_dict['ShelfLife'] = self.time_long(
- # datetime.datetime.strptime(pDate.strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S"), datetime.datetime.strptime(str(self.ws['P{}'.format(str(line))].value), "%Y-%m-%d %H:%M:%S"))
- # v_list1 = list("QRSTUVW")
- # key_list1 = [
- # "price", "is_supervise", "remain", "manufacturer", "remark8", "remark9", "remark10"
- # ]
- # for x in range(len(key_list1)):
- # ex = ''
- # if key_list1[x] in ["price", "remain"]:
- # ex = "0"
- # val = value_func(v_list1[x], ex)
- # if v_list1[x] == 'R':
- # if val != "是":
- # value = 0
- # else:
- # value = 1
- # else:
- # value = val
- # drug_template_dict[key_list1[x]] = value
+ # 计算保质期
+ shelf_life = drug_template_dict.get("shelf_life")
+ if not shelf_life:
+ shelf_life = (
+ date_func(drug_template_dict.get("expiration_date")) -
+ date_func(drug_template_dict.get("production_date"))).days
+ drug_template_dict["shelf_life"] = shelf_life
+
+ drug_template_dict["func_type"] = func_type
+ drug_template_dict["total"] = drug_template_dict.get("remain")
drug_list.append(drug_template_dict)
self.template_list.append(json.dumps(drug_list))
diff --git a/Common/report_excel.py b/Common/report_excel.py
new file mode 100644
index 0000000..be92080
--- /dev/null
+++ b/Common/report_excel.py
@@ -0,0 +1,307 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+'''
+@Date:2022/08/27 11:05:06
+'''
+import sys
+sys.path.append('.')
+import string
+import os
+import datetime
+from openpyxl.workbook import Workbook
+from openpyxl.styles import Alignment, Side, Border, Font, PatternFill
+
+class ReportData:
+ def __init__(self):
+
+ # 新建一个workbook
+ self.wb = Workbook()
+ # 定义设置样式
+ self.a = 0
+
+ def set_style(self, title='sheet1'):
+ # 如果是第一次调用则删除默认创建的sheet表
+ if self.a == 0:
+ self.wb.remove(self.wb['Sheet'])
+ self.a += 1
+ # 创建第几个sheet
+ self.ws = self.wb.create_sheet()
+ # 设置sheet的标题
+ self.ws.title = title
+ # 设置1 2 3 行固定的高度
+ self.ws.row_dimensions[1].height = 35
+ self.ws.row_dimensions[2].height = 25
+ self.ws.row_dimensions[3].height = 28
+ # 水平对齐, 居中对齐
+ self.alignment_style = Alignment(
+ horizontal='center', vertical='center')
+ # 定义Border边框样式
+ left, right, top, bottom = [Side(style='thin', color='000000')] * 4
+ self.border_style = Border(
+ left=left, right=right, top=top, bottom=bottom)
+ # 设置列宽
+ # 生成前14个大写字母 ascii_uppercase生成所有大写字母
+ self.upper_string = string.ascii_uppercase[:15]
+ # 定义字体
+ self.font_size = Font(size=9)
+ for col in self.upper_string:
+ self.ws.column_dimensions[col].width = 20
+
+ # 创建第一行
+ def create_row1(self, value, length):
+ # 合并第1行1-14列单元格
+ self.ws.merge_cells(start_row=1, end_row=1,
+ start_column=1, end_column=length)
+ # 写入值
+ self.ws.cell(row=1, column=1).value = value
+ self.ws['A1'].alignment = self.alignment_style
+ self.ws['A1'].font = Font(size=16, bold=True)
+ self.create_row2(length)
+
+ def create_row2(self, length):
+ # 第2行写入值
+ now_time = datetime.datetime.now().strftime('%Y%m%d %H%M')
+ # 格式化时间为中文年月日
+ now_time = now_time[:4] + '年' + now_time[4:6] + '月' + \
+ now_time[6:8] + '日' + now_time[8:11] + '时' + now_time[11:13] + '分'
+ self.ws.cell(row=2, column=1).value = '报表导出时间:{}'.format(now_time)
+ self.ws.cell(row=2, column=3).value = '终端系统版本:3.1'
+ self.ws.cell(row=2, column=5).value = ''
+ self.ws.cell(row=2, column=7).value = '报表导出位置:终端'
+ # 合并单元格
+ x = 1
+ while x < 6:
+ self.ws.merge_cells(start_row=2, end_row=2,
+ start_column=x, end_column=x + 1)
+ x += 2
+ self.ws.merge_cells(start_row=2, end_row=2,
+ start_column=7, end_column=length)
+ # 遍历取1, 3, 5, 7为第二行添加样式
+ for x in range(1, 8, 2):
+ self.ws.cell(row=2, column=x).font = Font(size=9)
+ # 水平对齐 垂直对齐
+ self.ws.cell(row=2, column=x).alignment = self.alignment_style
+ if x < 7:
+ # 边框样式
+ self.ws.cell(row=2, column=x).border = self.border_style
+ self.ws.cell(row=2, column=x + 1).border = self.border_style
+ else:
+ # 因为第2行第7-14列是合并的单元格 所以需要循环添加边框样式
+ while x < length + 1:
+ self.ws.cell(row=2, column=x).border = self.border_style
+ x += 1
+
+ # 创建第三行, 需要传入一个列表用来写入单元格的值
+ def create_row3(self, data_list):
+ for data in range(1, len(data_list) + 1):
+ # 第三行写入值
+ self.ws.cell(row=3, column=data).value = data_list[data - 1]
+ # 设置文本水平居中, 垂直居中
+ self.ws.cell(row=3, column=data).alignment = self.alignment_style
+ # 设置字体加粗
+ self.ws.cell(row=3, column=data).font = Font(bold=True, size=9)
+ # 背景颜色
+ self.ws.cell(row=3, column=data).fill = PatternFill(
+ fill_type='solid', fgColor='EE9A49')
+ # 边框样式
+ self.ws.cell(row=3, column=data).border = self.border_style
+
+ # 创建多行固定样式 start_row从第几行开始有规律 传入一个数据库获取的列表对象的值, 传入一个数据对象keys列表
+ def create_multiple_rows(self, start_row, data_list, keys_list):
+ # 从第4行创建
+ for row_number in range(start_row, len(data_list) + start_row):
+ # 设置每一行的行高
+ self.ws.row_dimensions[row_number].height = 18
+ # 遍历每一个对象的长度
+ col_ = 1
+ for key_ in keys_list:
+ # 写入值
+ try:
+ value = data_list[row_number - start_row][key_]
+ except:
+ value = "/"
+ self.ws.cell(
+ row=row_number, column=col_).value = value
+ # 设置文本水平居中, 垂直居中
+ self.ws.cell(row=row_number,
+ column=col_).alignment = self.alignment_style
+ # 设置边框样式
+ self.ws.cell(row=row_number,
+ column=col_).border = self.border_style
+ # 设置字体大小
+ self.ws.cell(row=row_number, column=col_).font = Font(size=9)
+ col_ += 1
+
+ # 保存文件
+ def save(self, file_path):
+ self.wb.save('{}.xlsx'.format(file_path))
+ self.close()
+
+ # 关闭文件
+ def close(self):
+ self.wb.close()
+
+ # 替换空白
+ def replace_space(self, length):
+ self.max_lines = self.ws.max_row
+ upper_letter_str = string.ascii_uppercase[:length]
+ for upper_letter in upper_letter_str:
+ for row_ in range(1, self.max_lines + 1):
+ b = self.ws[upper_letter + str(row_)].value
+ # print(b)
+ if not b:
+ self.ws[upper_letter + str(row_)].value = 'null'
+
+ # 编辑excel表格中列药剂状态1 2 3 替换为在库 出库 空瓶
+ def editor_status(self, col_):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ b = self.ws[col_ + str(row_)].value
+ if b == 1:
+ self.ws[col_ + str(row_)].value = '在库'
+ elif b == 2:
+ self.ws[col_ + str(row_)].value = '出库'
+ elif b == 3:
+ self.ws[col_ + str(row_)].value = '空瓶'
+
+ # 编辑药剂重点监管列为1 0 替换为是 否
+ def editor_isSupervise(self, col_):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ b = self.ws[col_ + str(row_)].value
+ if b == 1:
+ self.ws[col_ + str(row_)].value = '是'
+ elif b == 0:
+ self.ws[col_ + str(row_)].value = '否'
+
+ # 编辑操作类型 1 2 3 入库 领用 归还
+ def editor_RecordType(self, col_):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ b = self.ws[col_ + str(row_)].value
+ if b == 1:
+ self.ws[col_ + str(row_)].value = '入库'
+ elif b == 2:
+ self.ws[col_ + str(row_)].value = '领用'
+ elif b == 3:
+ self.ws[col_ + str(row_)].value = '归还'
+
+ # 替换sqlAlchemy时间格式
+ def editor_time(self, keys_list, params):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ col_ = string.ascii_uppercase[keys_list.index(params)]
+ b = self.ws[col_ + str(row_)].value
+ if b:
+ if len(b) == 19:
+ self.ws[col_ + str(row_)].value = b.replace('T', ' ')
+ else:
+ self.ws[col_ + str(row_)].value = "/"
+
+ # 编辑用户管理列为1 0 替换为正常 禁用
+ def editor_user_status(self, col_):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ b = self.ws[col_ + str(row_)].value
+ if b == 1:
+ self.ws[col_ + str(row_)].value = '正常'
+ elif b == 0:
+ self.ws[col_ + str(row_)].value = '禁用'
+
+ # 构建文件内容
+ def build_file(self,**kwargs):
+ data_list = kwargs.pop("data_list")
+ key_list = kwargs.pop("key_list")
+ finds_name = kwargs.pop("finds_name")
+ self.set_style(title="Sheet")
+ file_name = kwargs.pop("file_name")
+ if len(key_list) < 7:
+ for _ in range(7-len(key_list)):
+ key_list.append("/")
+ finds_name.append("/")
+ self.create_row1(file_name, len(finds_name))
+ self.create_row3(finds_name)
+ self.create_multiple_rows(4, data_list, key_list)
+ for i in key_list:
+ if "date" in i:
+ self.editor_time(key_list, i)
+ if "status" in i:
+ self.editor_status(string.ascii_uppercase[key_list.index(i)])
+ if "is_supervise" in i:
+ self.editor_isSupervise(string.ascii_uppercase[key_list.index(i)])
+ if "record_type" == i:
+ self.editor_RecordType(
+ string.ascii_uppercase[key_list.index(i)])
+ return self
+
+ # 下载文件
+
+ @staticmethod
+ def download_excel(filename, chunk_size=512):
+ try:
+ f = open(filename, 'rb')
+ except:
+ return
+ while True:
+ c = f.read(chunk_size)
+ if c:
+ yield c
+ else:
+ f.close()
+ os.remove(filename)
+ break
+
+
+
+# # 导出用户数据报表接口
+# @dataReport.route('/downloadUserReport', methods=["GET", "POST"])
+# def downloadUserReport():
+# try:
+# uPath = Utils.getUDiskPath()
+# if (uPath == ''):
+# return jsonify(Utils.resultData(1, '未检测到U盘!'))
+# else:
+# data_user_list = BllUser().findList().all()
+# data_user_list = json.loads(
+# Utils.resultAlchemyData(data_user_list))
+
+# # 创建一个报表类实例
+# a = ReportData()
+# a.set_style(title='Sheet')
+# data_list = ['工号', '角色', '姓名', '性别', 'QQ', '手机', '邮箱',
+# '条码', '状态', '最后一次登录时间', ]
+# a.create_row1('用户角色数据统计表', len(data_list))
+# a.create_row3(data_list)
+# keys_list = ['UserCode', 'RoleName', 'RealName', 'Sex', 'QQ', 'Mobile', 'Email',
+# 'BarCode', 'IsEnabled', 'LastVisitDate', ]
+# a.create_multiple_rows(4, data_user_list, keys_list)
+# a.replace_space(len(data_list))
+# a.editor_time(keys_list, 'LastVisitDate')
+# # 判断用户角色
+# for row_ in range(4, a.max_lines + 1):
+# col_ = string.ascii_uppercase[keys_list.index('UserCode')]
+# b = a.ws[col_ + str(row_)].value
+# if b == 'admin':
+# for col_value in range(1, len(keys_list) + 1):
+# a.ws.cell(row=row_, column=col_value).fill = PatternFill(
+# fill_type='solid', fgColor='FF0000')
+# elif b == 'yanyi':
+# for col_value in range(1, len(keys_list) + 1):
+# a.ws.cell(row=row_, column=col_value).fill = PatternFill(
+# fill_type='solid', fgColor='FFFF00')
+
+# # 优化用户性别
+# for row_ in range(4, a.max_lines + 1):
+# col_ = string.ascii_uppercase[keys_list.index('Sex')]
+# b = a.ws[col_ + str(row_)].value
+# if b == 0:
+# a.ws[col_ + str(row_)].value = '女'
+# else:
+# a.ws[col_ + str(row_)].value = '男'
+# a.editor_user_status('I')
+# file_name = '用户角色数据统计表{}'.format(Utils.UUID())
+# a.save(uPath + '/' + file_name)
+# returnData = Utils.resultData(0, '导出成功')
+# return jsonify(returnData)
+# except Exception as e:
+# return jsonify(Utils.resultData(2, str(e)))
diff --git a/Common/report_excel_new.py b/Common/report_excel_new.py
new file mode 100644
index 0000000..cad7e57
--- /dev/null
+++ b/Common/report_excel_new.py
@@ -0,0 +1,324 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+'''
+@Date:2022/08/27 11:05:06
+'''
+import sys
+sys.path.append('.')
+import string
+import os
+import datetime
+from openpyxl.workbook import Workbook
+from openpyxl.styles import Alignment, Side, Border, Font, PatternFill
+
+class ReportData:
+ def __init__(self):
+
+ # 新建一个workbook
+ self.wb = Workbook()
+ # 定义设置样式
+ self.a = 0
+
+ def set_style(self, title='sheet1', ty=1):
+ # 如果是第一次调用则删除默认创建的sheet表
+ if self.a == 0:
+ self.wb.remove(self.wb['Sheet'])
+ self.a += 1
+ # 创建第几个sheet
+ self.ws = self.wb.create_sheet()
+ # 设置sheet的标题
+ self.ws.title = title
+ # 设置1 2 3 行固定的高度
+ self.ws.row_dimensions[1].height = 35
+ self.ws.row_dimensions[2].height = 25
+ self.ws.row_dimensions[3].height = 28
+ # 水平对齐, 居中对齐
+ self.alignment_style2 = Alignment(
+ horizontal='left', vertical='top', wrapText=True)
+ self.alignment_style = Alignment(
+ horizontal='center', vertical='center', wrapText=True)
+ # 定义Border边框样式
+ left, right, top, bottom = [Side(style='thin', color='000000')] * 4
+ self.border_style = Border(
+ left=left, right=right, top=top, bottom=bottom)
+ # 设置列宽
+ # 生成前14个大写字母 ascii_uppercase生成所有大写字母
+ self.upper_string = string.ascii_uppercase[:15]
+ # 定义字体
+ self.font_size = Font(size=9)
+ width_list = [15, 15, 10, 15, 15, 5, 20, 10, 10]
+ for col in self.upper_string:
+ try:
+ width = width_list[self.upper_string.index(col)]
+ except:
+ width = 20
+ self.ws.column_dimensions[col].width = width
+
+ # 创建第一行
+ def create_row1(self, value, length):
+ # 合并第1行1-14列单元格
+ self.ws.merge_cells(start_row=1, end_row=1,
+ start_column=1, end_column=length)
+ # 写入值
+ self.ws.cell(row=1, column=1).value = value
+ self.ws['A1'].alignment = self.alignment_style
+ self.ws['A1'].font = Font(size=16, bold=True)
+ self.create_row2(length)
+
+ def create_row2(self, length):
+ # 第2行写入值
+ now_time = datetime.datetime.now().strftime('%Y%m%d %H%M')
+ # 格式化时间为中文年月日
+ now_time = now_time[:4] + '年' + now_time[4:6] + '月' + \
+ now_time[6:8] + '日' + now_time[8:11] + '时' + now_time[11:13] + '分'
+ self.ws.cell(row=2, column=1).value = '报表导出时间:{}'.format(now_time)
+ self.ws.cell(row=2, column=3).value = '终端系统版本:3.1'
+ self.ws.cell(row=2, column=5).value = ''
+ self.ws.cell(row=2, column=7).value = '报表导出位置:终端'
+ # 合并单元格
+ x = 1
+ while x < 6:
+ self.ws.merge_cells(start_row=2, end_row=2,
+ start_column=x, end_column=x + 1)
+ x += 2
+ self.ws.merge_cells(start_row=2, end_row=2,
+ start_column=7, end_column=length)
+ # 遍历取1, 3, 5, 7为第二行添加样式
+ for x in range(1, 8, 2):
+ self.ws.cell(row=2, column=x).font = Font(size=9)
+ # 水平对齐 垂直对齐
+ self.ws.cell(row=2, column=x).alignment = self.alignment_style
+ if x < 7:
+ # 边框样式
+ self.ws.cell(row=2, column=x).border = self.border_style
+ self.ws.cell(row=2, column=x + 1).border = self.border_style
+ else:
+ # 因为第2行第7-14列是合并的单元格 所以需要循环添加边框样式
+ while x < length + 1:
+ self.ws.cell(row=2, column=x).border = self.border_style
+ x += 1
+
+ # 创建第三行, 需要传入一个列表用来写入单元格的值
+ def create_row3(self, data_list):
+ for data in range(1, len(data_list) + 1):
+ # 第三行写入值
+ self.ws.cell(row=3, column=data).value = data_list[data - 1]
+ # 设置文本水平居中, 垂直居中
+ self.ws.cell(row=3, column=data).alignment = self.alignment_style
+ # 设置字体加粗
+ self.ws.cell(row=3, column=data).font = Font(bold=True, size=9)
+ # 背景颜色
+ # self.ws.cell(row=3, column=data).fill = PatternFill(
+ # fill_type='solid', fgColor='EE9A49')
+ # 边框样式
+ self.ws.cell(row=3, column=data).border = self.border_style
+
+ # 创建多行固定样式 start_row从第几行开始有规律 传入一个数据库获取的列表对象的值, 传入一个数据对象keys列表
+ def create_multiple_rows(self, start_row, data_list, keys_list):
+ # 从第4行创建
+ for row_number in range(start_row, len(data_list) + start_row):
+ # 设置每一行的行高
+ self.ws.row_dimensions[row_number].height = 50
+ # self.ws.row_dimensions[row_number].width = 80
+ # 遍历每一个对象的长度
+ col_ = 1
+ for key_ in keys_list:
+ # 写入值
+ try:
+ value = data_list[row_number - start_row][key_]
+ except:
+ value = "/"
+ self.ws.cell(
+ row=row_number, column=col_).value = value
+ # 设置文本水平居中, 垂直居中
+ if key_ == "acceptace":
+ self.ws.cell(row=row_number,
+ column=col_).alignment = self.alignment_style2
+ else:
+ self.ws.cell(row=row_number,
+ column=col_).alignment = self.alignment_style
+ # 设置边框样式
+ self.ws.cell(row=row_number,
+ column=col_).border = self.border_style
+ # 设置字体大小
+ self.ws.cell(row=row_number, column=col_).font = Font(size=9)
+ # self.ws.row_dimensions[row_number].width = 256*width_list[col_-1]
+ # self.ws.cell(row=row_number, column=col_).width = int(width_list[col_-1])
+ col_ += 1
+
+ # 保存文件
+ def save(self, file_path):
+ self.wb.save('{}.xlsx'.format(file_path))
+ self.close()
+
+ # 关闭文件
+ def close(self):
+ self.wb.close()
+
+ # 替换空白
+ def replace_space(self, length):
+ self.max_lines = self.ws.max_row
+ upper_letter_str = string.ascii_uppercase[:length]
+ for upper_letter in upper_letter_str:
+ for row_ in range(1, self.max_lines + 1):
+ b = self.ws[upper_letter + str(row_)].value
+ # print(b)
+ if not b:
+ self.ws[upper_letter + str(row_)].value = 'null'
+
+ # 编辑excel表格中列药剂状态1 2 3 替换为在库 出库 空瓶
+ def editor_status(self, col_):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ b = self.ws[col_ + str(row_)].value
+ if b == 1:
+ self.ws[col_ + str(row_)].value = '在库'
+ elif b == 2:
+ self.ws[col_ + str(row_)].value = '出库'
+ elif b == 3:
+ self.ws[col_ + str(row_)].value = '空瓶'
+
+ # 编辑药剂重点监管列为1 0 替换为是 否
+ def editor_isSupervise(self, col_):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ b = self.ws[col_ + str(row_)].value
+ if b == 1:
+ self.ws[col_ + str(row_)].value = '是'
+ elif b == 0:
+ self.ws[col_ + str(row_)].value = '否'
+
+ # 编辑操作类型 1 2 3 入库 领用 归还
+ def editor_RecordType(self, col_):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ b = self.ws[col_ + str(row_)].value
+ if b == 1:
+ self.ws[col_ + str(row_)].value = '入库'
+ elif b == 2:
+ self.ws[col_ + str(row_)].value = '领用'
+ elif b == 3:
+ self.ws[col_ + str(row_)].value = '归还'
+
+ # 替换sqlAlchemy时间格式
+ def editor_time(self, keys_list, params):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ col_ = string.ascii_uppercase[keys_list.index(params)]
+ b = self.ws[col_ + str(row_)].value
+ if b:
+ if len(b) == 19:
+ self.ws[col_ + str(row_)].value = b.replace('T', ' ')
+ else:
+ self.ws[col_ + str(row_)].value = "/"
+
+ # 编辑用户管理列为1 0 替换为正常 禁用
+ def editor_user_status(self, col_):
+ self.max_lines = self.ws.max_row
+ for row_ in range(4, self.max_lines + 1):
+ b = self.ws[col_ + str(row_)].value
+ if b == 1:
+ self.ws[col_ + str(row_)].value = '正常'
+ elif b == 0:
+ self.ws[col_ + str(row_)].value = '禁用'
+
+ # 构建文件内容
+ def build_file(self,**kwargs):
+ data_list = kwargs.pop("data_list")
+ key_list = kwargs.pop("key_list")
+ finds_name = kwargs.pop("finds_name")
+ if data_list[0].get("gg_ph"):
+ self.set_style(title="Sheet", ty=2)
+ else:
+ self.set_style(title="Sheet")
+ file_name = kwargs.pop("file_name")
+ if len(key_list) < 7:
+ for _ in range(7-len(key_list)):
+ key_list.append("/")
+ finds_name.append("/")
+ self.create_row1(file_name, len(finds_name))
+ self.create_row3(finds_name)
+ self.create_multiple_rows(4, data_list, key_list)
+ for i in key_list:
+ if "date" in i:
+ self.editor_time(key_list, i)
+ if "status" in i:
+ self.editor_status(string.ascii_uppercase[key_list.index(i)])
+ if "is_supervise" in i:
+ self.editor_isSupervise(string.ascii_uppercase[key_list.index(i)])
+ if "record_type" == i:
+ self.editor_RecordType(
+ string.ascii_uppercase[key_list.index(i)])
+ return self
+
+ # 下载文件
+
+ @staticmethod
+ def download_excel(filename, chunk_size=512):
+ try:
+ f = open(filename, 'rb')
+ except:
+ return
+ while True:
+ c = f.read(chunk_size)
+ if c:
+ yield c
+ else:
+ f.close()
+ os.remove(filename)
+ break
+
+
+
+# # 导出用户数据报表接口
+# @dataReport.route('/downloadUserReport', methods=["GET", "POST"])
+# def downloadUserReport():
+# try:
+# uPath = Utils.getUDiskPath()
+# if (uPath == ''):
+# return jsonify(Utils.resultData(1, '未检测到U盘!'))
+# else:
+# data_user_list = BllUser().findList().all()
+# data_user_list = json.loads(
+# Utils.resultAlchemyData(data_user_list))
+
+# # 创建一个报表类实例
+# a = ReportData()
+# a.set_style(title='Sheet')
+# data_list = ['工号', '角色', '姓名', '性别', 'QQ', '手机', '邮箱',
+# '条码', '状态', '最后一次登录时间', ]
+# a.create_row1('用户角色数据统计表', len(data_list))
+# a.create_row3(data_list)
+# keys_list = ['UserCode', 'RoleName', 'RealName', 'Sex', 'QQ', 'Mobile', 'Email',
+# 'BarCode', 'IsEnabled', 'LastVisitDate', ]
+# a.create_multiple_rows(4, data_user_list, keys_list)
+# a.replace_space(len(data_list))
+# a.editor_time(keys_list, 'LastVisitDate')
+# # 判断用户角色
+# for row_ in range(4, a.max_lines + 1):
+# col_ = string.ascii_uppercase[keys_list.index('UserCode')]
+# b = a.ws[col_ + str(row_)].value
+# if b == 'admin':
+# for col_value in range(1, len(keys_list) + 1):
+# a.ws.cell(row=row_, column=col_value).fill = PatternFill(
+# fill_type='solid', fgColor='FF0000')
+# elif b == 'yanyi':
+# for col_value in range(1, len(keys_list) + 1):
+# a.ws.cell(row=row_, column=col_value).fill = PatternFill(
+# fill_type='solid', fgColor='FFFF00')
+
+# # 优化用户性别
+# for row_ in range(4, a.max_lines + 1):
+# col_ = string.ascii_uppercase[keys_list.index('Sex')]
+# b = a.ws[col_ + str(row_)].value
+# if b == 0:
+# a.ws[col_ + str(row_)].value = '女'
+# else:
+# a.ws[col_ + str(row_)].value = '男'
+# a.editor_user_status('I')
+# file_name = '用户角色数据统计表{}'.format(Utils.UUID())
+# a.save(uPath + '/' + file_name)
+# returnData = Utils.resultData(0, '导出成功')
+# return jsonify(returnData)
+# except Exception as e:
+# return jsonify(Utils.resultData(2, str(e)))
diff --git a/apps/client/views.py b/apps/client/views.py
index 649071c..7157410 100644
--- a/apps/client/views.py
+++ b/apps/client/views.py
@@ -29,7 +29,8 @@ client_router = Blueprint("client", __name__)
@client_router.route("/client_list", methods=["POST"])
@token_auth.login_required
def get_client_list():
- data = BllClient().get_all_client_list()
+ func_type = request.values.get("func_type")
+ data = BllClient().get_all_client_list(func_type=func_type)
data_list = Utils.msyql_table_model(data)
return jsonify(Utils.true_return(data={"data_list": data_list}))
@@ -39,11 +40,12 @@ def get_client_list():
@token_auth.login_required
def getclient_list():
seach_word = request.values.get("seach_word")
+ func_type = request.values.get("func_type")
page = request.values.get("page", 1)
page_size = request.values.get("page_size", 100)
page_param = PageParam(int(page), int(page_size))
data = BllClient().get_client_seach(
- seach_word=seach_word, page_param=page_param
+ seach_word=seach_word, func_type=func_type, page_param=page_param
)
data_list = Utils.msyql_table_model(data)
return jsonify(Utils.true_return(data={"data_list": data_list, "total_count": page_param.totalRecords}))
@@ -53,35 +55,62 @@ def getclient_list():
@client_router.route("/add_or_update", methods=["POST"])
@token_auth.login_required
def client_add_update():
- finds = [
- "client_title", "client_name", "client_code", "client_type", "place", "filter_production_date",
- "filter_shelf_life_warning_value", "contact_people_name", "contact_phone", "description"
- ]
client_id = request.values.get("client_id")
obj = BllClient().findEntity(
EntityClient.client_code == request.values.get("client_code")
)
+ finds_list = dir(EntityClient)
if client_id:
client_obj = BllClient().findEntity(
EntityClient.client_id==client_id
)
if obj:
- if client_obj.client_id != obj.client_id:
- return jsonify(Utils.false_return())
- for i in finds:
- setattr(client_obj, i, request.values.get(i))
- BllClient().update(client_obj)
- return jsonify(Utils.true_return(msg="修改成功"))
+ for i in finds_list:
+ va = request.values.get(i)
+ if va:
+ setattr(client_obj, i, va)
+ BllClient().update(client_obj)
+ return jsonify(Utils.true_return(msg="修改成功"))
+ else:
+ return jsonify(Utils.false_return(msg="柜体信息有误"))
else:
- if obj:
- return jsonify(Utils.false_return(msg="柜体需要不能重复"))
client_obj = EntityClient()
- for i in finds:
- setattr(client_obj, i, request.values.get(i))
-
+ for i in finds_list:
+ va = request.values.get(i)
+ if va:
+ setattr(client_obj, i, va)
BllClient().insert(client_obj)
return jsonify(Utils.true_return(msg="添加成功"))
+ # finds = [
+ # "client_title", "client_name", "client_code", "client_type", "place", "filter_production_date",
+ # "filter_shelf_life_warning_value", "contact_people_name", "contact_phone", "description"
+ # ]
+ # client_id = request.values.get("client_id")
+ # obj = BllClient().findEntity(
+ # EntityClient.client_code == request.values.get("client_code")
+ # )
+ # if client_id:
+ # client_obj = BllClient().findEntity(
+ # EntityClient.client_id==client_id
+ # )
+ # if obj:
+ # if client_obj.client_id != obj.client_id:
+ # return jsonify(Utils.false_return())
+ # for i in finds:
+ # setattr(client_obj, i, request.values.get(i))
+ # BllClient().update(client_obj)
+ # return jsonify(Utils.true_return(msg="修改成功"))
+ # else:
+ # if obj:
+ # return jsonify(Utils.false_return(msg="柜体需要不能重复"))
+ # client_obj = EntityClient()
+ # for i in finds:
+ # setattr(client_obj, i, request.values.get(i))
+
+ # BllClient().insert(client_obj)
+ # return jsonify(Utils.true_return(msg="添加成功"))
+
# 锁定或解锁柜体
@client_router.route("/update_status", methods=["POST"])
@token_auth.login_required
@@ -238,23 +267,39 @@ def client_ban_user_list():
@client_router.route("/user_ban_confirm", methods=["POST"])
@token_auth.login_required
def client_ban_user_confirm():
+ # user_id = request.values.get("user_id")
+ # client_id = request.values.get("client_id")
+ # data = BllClientUser().inster_user_client(user_id, client_id)
+ # if data:
+ # return jsonify(Utils.true_return())
+ # else:
+ # return jsonify(Utils.false_return())
+
user_id = request.values.get("user_id")
client_id = request.values.get("client_id")
- data = BllClientUser().inster_user_client(user_id, client_id)
+ data = BllClientUser().del_user_ban_client(
+ user_id=user_id, client_id=client_id)
if data:
- return jsonify(Utils.true_return())
+ return jsonify(Utils.true_return(msg=""))
else:
- return jsonify(Utils.false_return())
+ return jsonify(Utils.false_return(msg=""))
# 取消禁用试剂
@client_router.route("/user_ban_relieve", methods=["POST"])
@token_auth.login_required
def client_user_ban_relieve():
+ # user_id = request.values.get("user_id")
+ # client_id = request.values.get("client_id")
+ # data = BllClientUser().del_user_ban_client(
+ # user_id=user_id, client_id=client_id)
+ # if data:
+ # return jsonify(Utils.true_return(msg="删除成功"))
+ # else:
+ # return jsonify(Utils.false_return(msg="删除失败"))
user_id = request.values.get("user_id")
client_id = request.values.get("client_id")
- data = BllClientUser().del_user_ban_client(
- user_id=user_id, client_id=client_id)
+ data = BllClientUser().inster_user_client(user_id, client_id)
if data:
- return jsonify(Utils.true_return(msg="删除成功"))
+ return jsonify(Utils.true_return())
else:
- return jsonify(Utils.false_return(msg="删除失败"))
+ return jsonify(Utils.false_return())
\ No newline at end of file
diff --git a/apps/drug/views.py b/apps/drug/views.py
index 9484206..7812a26 100644
--- a/apps/drug/views.py
+++ b/apps/drug/views.py
@@ -30,6 +30,7 @@ drug_router = Blueprint("drug", __name__)
def drug_collect():
# 获取参数
bar_code = request.values.get("bar_code")
+ func_type = request.values.get("func_type")
# user_id=request.values.get("user_id")
# 默认用户id,后续从token 中获取
# user_id = '4cea74ee-0d8b-11ed-943e-f47b094925e1'
@@ -43,10 +44,13 @@ def drug_collect():
if not drug_entity:
data = Utils.false_return(msg="药剂条码无效")
elif drug_entity.status not in [DrugStatus.Normal, DrugStatus.Empty]:
- print(drug_entity.status)
data = Utils.false_return(msg="药剂未在库")
elif drug_entity.status == DrugStatus.Empty:
data = Utils.false_return(msg="药剂已为空瓶")
+ elif str(drug_entity.func_type) != str(func_type):
+ data = Utils.false_return(msg="试剂不属于这里当前管理")
+ elif drug_entity.remain == '' or drug_entity.remain == None or not drug_entity:
+ data = Utils.false_return(msg="试剂未称重,请先称重!")
else:
customer_id = drug_entity.customer_id
client_id = drug_entity.client_id
@@ -55,9 +59,13 @@ def drug_collect():
drug_obj = BllMedicament().getDrugNearExpired(drug_entity.variety_id, customer_id)
# date_str = lambda x: datetime.datetime.strptime('', "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
# drug_obj_date_str = date_str(drug_obj.expiration_date)
- drug_obj_date_str = datetime.datetime.strptime(drug_obj.expiration_date, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
+ drug_obj_date_str = None
+ if drug_obj.expiration_date:
+ drug_obj_date_str = datetime.datetime.strptime(drug_obj.expiration_date, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
# drug_entity_date_str = date_str(drug_entity.expiration_date)
- drug_entity_date_str = datetime.datetime.strptime(drug_entity.expiration_date, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
+ drug_entity_date_str = None
+ if drug_entity.expiration_date:
+ drug_entity_date_str = datetime.datetime.strptime(drug_entity.expiration_date, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
if drug_obj.medicament_id != drug_entity.medicament_id and force_use == "False" and drug_obj_date_str != drug_entity_date_str:
data = Utils.false_return(status=2, msg=f'"{drug_entity.name}({drug_entity.bar_code})"此类药有更接近保质期的实例"{drug_obj.bar_code}", 存在于"{drug_obj.client_code}"号终端')
else:
@@ -87,6 +95,7 @@ def drug_collect():
def drug_return():
# 获取参数
bar_code = request.values.get("bar_code")
+ func_type = request.values.get("func_type")
place = request.values.get("place")
# user_id = request.values.get("user_id")
# 默认用户id,后续从token 中获取
@@ -99,6 +108,8 @@ def drug_return():
data = Utils.false_return(msg="药剂条码无效")
elif drug_info.status != DrugStatus.Out:
data = Utils.false_return(msg="此药剂未被领用")
+ elif drug_info.func_type != func_type:
+ data = Utils.false_return(msg="试剂不属于这里当前管理")
else:
# 药剂归还,进入归还事务处理
drug_info.status = DrugStatus.Normal
@@ -116,10 +127,11 @@ def drug_return():
@token_auth.login_required
def drug_use_retur_list():
status = request.values.get("status")
+ func_type = request.values.get("func_type")
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
- data = BllMedicament().drug_use_return(status=status, page_param=page_param)
+ data = BllMedicament().drug_use_return(status=status, func_type=func_type, page_param=page_param)
return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": Utils.msyql_table_model(data)}))
@@ -128,9 +140,14 @@ def drug_use_retur_list():
@token_auth.login_required
def get_drug_info():
bar_code = request.values.get("bar_code")
- data = BllMedicament().findEntity(EntityMedicament.bar_code == bar_code)
+ func_type = request.values.get("func_type")
+ bar_code, new_code = Utils.get_bar_code_reverse(bar_code)
+ data = BllMedicament().execute(
+ f"select * from rms_medicament where func_type={func_type} and (bar_code like '%{bar_code}%' or bar_code like '%{new_code}%') "
+ ).fetchall()
+ data = Utils.msyql_table_model(data)
if data:
- return jsonify(Utils.true_return(data=Utils.model_to_dict(data)))
+ return jsonify(Utils.true_return(data=data[0]))
else:
return jsonify(Utils.false_return(msg="条码有误"))
@@ -143,12 +160,16 @@ def get_drug_info():
@token_auth.login_required
def get_drug_manage():
seach_word = request.values.get("seach_word")
+ b_code = request.values.get("b_code")
client_id = request.values.get("client_id")
+ func_type = request.values.get("func_type")
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
data_list = BllMedicament().get_drug_list(
- seach_word=seach_word, client_id=client_id, page_param=page_param
+ seach_word=seach_word,
+ b_code=b_code,
+ client_id=client_id, func_type=func_type, page_param=page_param
)
return jsonify(Utils.true_return(data={"data": Utils.msyql_table_model(data_list), "total_count":page_param.totalRecords}))
@@ -159,13 +180,8 @@ def get_drug_manage():
@drug_router.route("/update", methods=["GET", "POST"])
@token_auth.login_required
def drug_update():
- finds_list = [
- "name", "english_name", "bar_code", "cas_number",
- "purity", "shelf_life", "production_date", "expiration_date",
- "use_days_warning_value", "shelf_life_warning_value",
- "inventory_warning_value", "speci", "net_weight_unit", "net_weight",
- "is_supervise", "is_weigh"
- ]
+ finds_list = dir(EntityMedicament)
+
medicament_id = request.values.get("medicament_id")
bar_code = request.values.get("bar_code")
medicament_obj = BllMedicament().findEntity(
@@ -174,7 +190,9 @@ def drug_update():
obj = BllMedicament().findEntity(EntityMedicament.bar_code == bar_code)
if obj.medicament_id == medicament_obj.medicament_id:
for i in finds_list:
- setattr(medicament_obj, i, request.values.get(i))
+ va = request.values.get(i)
+ if va:
+ setattr(medicament_obj, i, request.values.get(i))
BllMedicament().update(medicament_obj)
return jsonify(Utils.true_return(msg="修改成功"))
else:
@@ -182,7 +200,7 @@ def drug_update():
return jsonify(Utils.true_return(msg="试剂id不能为空"))
-# 编辑数据
+# 删除数据
@drug_router.route("/del", methods=["GET", "POST"])
@token_auth.login_required
def drug_del():
@@ -199,11 +217,13 @@ def drug_del():
@token_auth.login_required
def get_durg_record():
medicament_id = request.values.get("medicament_id")
+ func_type = request.values.get("func_type")
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
data_list = BllMedicamentRecord().get_drug_flow_log(
medicament_id=medicament_id,
+ func_type=func_type,
page_param=page_param)
return jsonify(Utils.true_return(data={"data_list": Utils.msyql_table_model(data_list), "total_count":page_param.totalRecords}))
@@ -213,6 +233,7 @@ def get_durg_record():
@token_auth.login_required
def drug_set_empty_bottle():
drug_id = request.values.get("medicament_id")
+ empty_str = request.values.get("empty_str")
obj = BllMedicament()
drug_obj = obj.findEntity(EntityMedicament.medicament_id == drug_id)
if drug_obj:
@@ -220,6 +241,8 @@ def drug_set_empty_bottle():
return jsonify(Utils.false_return(msg="该试剂为空瓶,无需设置"))
else:
drug_obj.status = 3
+ if empty_str:
+ drug_obj.remark11=empty_str
obj.update(drug_obj)
return jsonify(Utils.true_return())
else:
diff --git a/apps/drug_form/views.py b/apps/drug_form/views.py
index 9673cf5..63ec67d 100644
--- a/apps/drug_form/views.py
+++ b/apps/drug_form/views.py
@@ -22,8 +22,9 @@ drug_form_router = Blueprint("drug_form", __name__)
def get_drug_form():
page = request.values.get("page", 1)
page_size = request.values.get("page_size", 10)
+ func_type = request.values.get("func_type")
page_param = PageParam(int(page), int(page_size))
- data_list = BllMedicamentExtend().get_list(page_param=page_param)
+ data_list = BllMedicamentExtend().get_list(func_type=func_type,page_param=page_param)
return jsonify(Utils.true_return(data={"data_list": Utils.msyql_table_model(data_list), "total_count": page_param.totalRecords}))
@@ -31,6 +32,7 @@ def get_drug_form():
@token_auth.login_required
def add_update_drug_form():
drug_form_id = request.values.get("drug_form_id")
+ func_type = request.values.get("func_type")
bll_obj = BllMedicamentExtend()
finds = [
"name", "description", "key_lenth", "is_use"
@@ -51,6 +53,7 @@ def add_update_drug_form():
obj = bll_obj.findEntity(EntityMedicamentExtend.id == del_obj[0])
for i in finds:
setattr(obj, i, request.values.get(i))
+ setattr(obj, "func_type", func_type)
setattr(obj, 'is_del', 0)
bll_obj.update(obj)
else:
@@ -63,6 +66,7 @@ def add_update_drug_form():
sort_index = bll_obj.execute(
"select max(sort_index) sort_index from rms_medicament_extend").fetchone()
setattr(obj, "sort_index", int(sort_index.sort_index or '0') + 1)
+ setattr(obj, "func_type", func_type)
bll_obj.insert(obj)
return jsonify(Utils.true_return())
else:
@@ -84,5 +88,6 @@ def del_drug_form():
@drug_form_router.route("/get_use", methods=["GET"])
@token_auth.login_required
def get_use_drug_form():
- data_list = BllMedicamentExtend().get_use_list()
+ func_type = request.values.get("func_type")
+ data_list = BllMedicamentExtend().get_use_list(func_type=func_type)
return jsonify(Utils.true_return(data=Utils.msyql_table_model(data_list)))
diff --git a/apps/drug_label/views.py b/apps/drug_label/views.py
new file mode 100644
index 0000000..937bf57
--- /dev/null
+++ b/apps/drug_label/views.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+'''
+@Date: 2022/11/28 10:51:52
+'''
+import sys
+sys.path.append('.')
+import json
+from flask import Blueprint, request, jsonify
+
+from db_logic.medicament_label import BllMedicamentLabel
+from db_logic.medicament_relation import BllMedicamentRelation
+
+from models.medicament_models import EntityMedicamentLabel, EntityMedicamentRelation
+
+from Common.Utils import PageParam, Utils
+
+drug_label_app = Blueprint("drug_label", __name__)
+
+
+@drug_label_app.route("/get", methods=["POST"])
+# @token_auth.login_required
+def get_seach_drug_label():
+ seach_word = request.values.get("seach_word")
+ page = request.values.get("page", 1)
+ page_size = request.values.get("page_size", 10)
+ page_param = PageParam(int(page), int(page_size))
+
+ data_list = BllMedicamentLabel().get_seach_list(
+ seach_word=seach_word,
+ page_param=page_param
+ )
+ return jsonify(Utils.true_return(data={
+ "total_count": page_param.totalRecords,
+ "data_list": Utils.msyql_table_model(data_list)
+ }))
+
+
+@drug_label_app.route("/attribute_label_list", methods=["POST"])
+def get_attribute_label_list():
+ data_list = []
+ data = BllMedicamentLabel().get_attribute_label_list_info()
+ for i in data:
+ for j in i[0].split(","):
+ if j not in data_list:
+ data_list.append(j)
+ return jsonify(
+ Utils.true_return(
+ data=data_list
+ )
+ )
+
+@drug_label_app.route("/update_add", methods=["POST"])
+# @token_auth.login_required
+def set_drug_label():
+ variety_id = request.values.get("id")
+ name = request.values.get("name")
+ description = request.values.get("description")
+ obj = BllMedicamentLabel()
+ if variety_id:
+ label_obj = obj.findEntity(
+ EntityMedicamentLabel.variety_id == variety_id)
+ if label_obj:
+ setattr(label_obj, "name", name)
+ setattr(label_obj, "description", description)
+ obj.update(label_obj)
+ return jsonify(Utils.true_return(msg="修改成功"))
+ else:
+ return jsonify(Utils.false_return())
+ else:
+ model_obj = EntityMedicamentLabel(
+ name=name,
+ description=description
+ )
+ obj.insert(model_obj)
+ return jsonify(Utils.true_return(msg="添加成功"))
+
+
+
+
+@drug_label_app.route("/del", methods=["POST"])
+# @token_auth.login_required
+def del_drug_label():
+ label_id = request.values.get("id_list")
+ obj = BllMedicamentLabel()
+ data_list = obj.findList(
+ EntityMedicamentLabel.variety_id.in_(tuple(json.loads(label_id)))).all()
+ for i in data_list:
+ obj.session.delete(i)
+ obj.session.commit()
+ return jsonify(Utils.true_return(msg="删除成功"))
+
+
+@drug_label_app.route("/relation/get", methods=["POST"])
+# @token_auth.login_required
+def get_seach_drug_relation():
+ seach_word = request.values.get("seach_word")
+ page = request.values.get("page", 1)
+ page_size = request.values.get("page_size", 10)
+ page_param = PageParam(int(page), int(page_size))
+
+ data_list = BllMedicamentRelation().get_seach_list(
+ seach_word=seach_word,
+ page_param=page_param
+ )
+ return jsonify(Utils.true_return(data={
+ "total_count": page_param.totalRecords,
+ "data_list": Utils.msyql_table_model(data_list)
+ }))
+
+
+@drug_label_app.route("/relation/update_add", methods=["POST"])
+# @token_auth.login_required
+def set_drug_relation():
+ relation_id = request.values.get("id")
+ name = request.values.get("name1")
+ name2 = request.values.get("name2")
+ relation = request.values.get("relation")
+ description = request.values.get("description")
+ obj = BllMedicamentRelation()
+ if relation_id:
+ relation_obj = obj.findEntity(
+ EntityMedicamentRelation.id == relation_id)
+ if relation_obj:
+ setattr(relation_obj, "name1", name)
+ setattr(relation_obj, "name2", name2)
+ setattr(relation_obj, "relation", relation)
+ setattr(relation_obj, "description", description)
+ obj.update(relation_obj)
+ return jsonify(Utils.true_return(msg="修改成功"))
+ else:
+ return jsonify(Utils.false_return())
+ else:
+ model_obj = EntityMedicamentRelation()
+ setattr(model_obj, "name1", name)
+ setattr(model_obj, "name2", name2)
+ setattr(model_obj, "relation", relation)
+ setattr(model_obj, "description", description)
+ obj.insert(model_obj)
+ return jsonify(Utils.true_return(msg="添加成功"))
+
+
+@drug_label_app.route("/relation/del", methods=["POST"])
+# @token_auth.login_required
+def del_relation():
+ list_id = request.values.get("id_list")
+ obj = BllMedicamentRelation()
+ data_list = obj.findList(
+ EntityMedicamentRelation.id.in_(tuple(json.loads(list_id)))).all()
+ for i in data_list:
+ obj.session.delete(i)
+ obj.session.commit()
+ return jsonify(Utils.true_return(msg="删除成功"))
+
diff --git a/apps/drug_template/views.py b/apps/drug_template/views.py
index a496476..f1e67c6 100644
--- a/apps/drug_template/views.py
+++ b/apps/drug_template/views.py
@@ -6,6 +6,8 @@
import sys
sys.path.append(".")
+import re
+import os
import datetime
import json
from flask import jsonify, request, g
@@ -32,10 +34,15 @@ tmp_router = Blueprint("drug_tmplate", __name__)
@token_auth.login_required
def show_template():
client_id = request.values.get("client_id")
+ func_type = request.values.get("func_type")
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
- data = BllMedicamentTemplate().getAllTemplateList(client_id=client_id, page_param=page_param)
+ data = BllMedicamentTemplate().getAllTemplateList(
+ client_id=client_id,
+ func_type=func_type,
+ page_param=page_param
+ )
data = Utils.msyql_table_model(data)
new_data_list = []
for i in data:
@@ -61,11 +68,14 @@ def show_template():
@token_auth.login_required
def select_drug_info():
seach_word =request.values.get("seach_word")
+ func_type = request.values.get("func_type")
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
data_list = BllMedicament().get_drug_info_distinct_list(
- seach_word=seach_word, page_param=page_param)
+ seach_word=seach_word,
+ func_type=func_type,
+ page_param=page_param)
data_list = Utils.msyql_table_model(data_list)
return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data_list": data_list}))
@@ -74,7 +84,8 @@ def select_drug_info():
@token_auth.login_required
def bind_tmp_input_db():
tmp_content = request.values.get("tmplate_content")
- customer_id = request.values.get("customer_id", '')
+ customer_id = request.values.get("customer_id", '1002437b-debf-46d6-b186-3e16bcf0cc0f')
+ func_type = request.values.get("func_type")
client_id = request.values.get("client_id")
# client_id = '1c39cb24-07f8-11ed-abd4-f47b094925e1'
bar_code = request.values.get("bar_code")
@@ -92,15 +103,14 @@ def bind_tmp_input_db():
continue
else:
drug_info[k] = v
- # user_info = BllUser().findEntity('4cea74ee-0d8b-11ed-943e-f47b094925e1')
user_info = g.current_user
drug_variety = BllMedicamentVariety().createDrugVariety(
customer_id=customer_id,
drug_info=drug_info, user_info=user_info
)
- # 预估质量
- remain_num = drug_info.get("remain")
+
+ remain_num = drug_info.get("remain", 0)
if not remain_num:
remain_num = drug_info.get("total")
new_dict = {
@@ -112,12 +122,13 @@ def bind_tmp_input_db():
"inventory_warning_value":10,
"shelf_life_warning_value":10,
"use_days_warning_value":10,
- "is_supervise":0,
+ # "is_supervise":0,
"put_in_date": Utils.get_str_datetime(),
"put_in_user_id": user_info.user_id,
"put_in_user_name": user_info.real_name,
"status":1,
- "remain":remain_num
+ "remain": remain_num,
+ "func_type": func_type,
}
finds_list = dir(EntityMedicament())
for i in finds_list:
@@ -127,15 +138,15 @@ def bind_tmp_input_db():
if value != None:
new_dict[i] = value
drug_entity = EntityMedicament(**new_dict)
- objs = BllMedicament().drugPutIn(
- drug_entity,
- BllClient().findEntity(EntityClient.client_id==client_id),
- user_info
- )
- if objs:
+ try:
+ BllMedicament().drugPutIn(
+ drug_entity,
+ BllClient().findEntity(EntityClient.client_id==client_id),
+ user_info
+ )
return jsonify(Utils.true_return(msg="药剂入库成功"))
- else:
- return jsonify(Utils.false_return(msg="数据异常,入库失败"))
+ except Exception as error:
+ return jsonify(Utils.false_return(msg="数据异常,入库失败: %s" % error))
@@ -145,6 +156,7 @@ def bind_tmp_input_db():
def add_tmp_info():
tmp_name = request.values.get("template_name")
client_id = request.values.get("client_id")
+ func_type = request.values.get("func_type")
# client_id = '1c39cb24-07f8-11ed-abd4-f47b094925e1'
tmp_content = request.values.get("template_content")
# user_id = '4cea74ee-0d8b-11ed-943e-f47b094925e1'
@@ -180,6 +192,7 @@ def add_tmp_info():
client_id=client.client_id,
client_name=client.client_name,
template_name=tmp_name,
+ func_type=func_type,
template_content=json.dumps(tmp_content),
is_wait_export=1,
start_bar_code=start_bar_code,
@@ -209,12 +222,13 @@ def add_tmp_info():
def import_tmplate():
try:
file_path = Utils.getUDiskPath()
+ # file_path = request.values.get("file_path")
if not file_path:
return jsonify(msg="请插入U盘")
else:
- client_id = request.values.get("cliet_id", '')
+ client_id = request.values.get("client_id", '')
template_name = request.values.get("template_name", '')
- # user_id = request.values.get("user_id")
+ func_type = request.values.get("func_type")
read_excel = ReadExcel(file_path + "/" + template_name)
sql_all = """
select bar_code_count, start_bar_code from rms_medicament_template where start_bar_code=(select max(start_bar_code) max_start from rms_medicament_template)
@@ -228,9 +242,9 @@ def import_tmplate():
max_barcode = 100001
start_bar_code = max_barcode
- result_list = read_excel.read()
- client_obj = BllClient().findEntity(client_id)
- # user_obj = BllUser().findEntity(user_id)
+ result_list = read_excel.read(func_type=str(func_type))
+ client_obj = BllClient().findEntity(
+ EntityClient.client_id==client_id)
user_obj = g.current_user
if result_list:
inster_obj_list = []
@@ -239,7 +253,7 @@ def import_tmplate():
template_content_list = eval(value)
for template_content in template_content_list:
- total_count += int(template_content['export_cout'])
+ total_count += int(template_content['export_count'])
obj = EntityMedicamentTemplate(
customer_id=client_obj.customer_id,
client_id=client_obj.client_id,
@@ -251,7 +265,8 @@ def import_tmplate():
bar_code_count=total_count,
create_date=Utils.get_str_datetime(),
create_user_id=user_obj.user_id,
- create_user_name=user_obj.real_name
+ create_user_name=user_obj.real_name,
+ func_type=func_type
)
inster_obj_list.append(obj)
@@ -281,4 +296,45 @@ def remove_tmp():
return Utils.false_return(msg='删除药剂模板失败')
+# 读取优盘下的文件列表
+@tmp_router.route("/u_file_list", methods=["POST"])
+# @token_auth.login_required
+def get_file_list():
+ # file_path = request.values.get("file_path")
+ file_path = Utils.getUDiskPath()
+ if not file_path:
+ return jsonify(Utils.false_return(msg="请插入U盘"))
+ data_file_list = list(filter(lambda x: re.match(
+ 'tem_.*?.xlsx', x), os.listdir(file_path)))
+ return jsonify(Utils.true_return(data=data_file_list))
+ # return jsonify(Utils.true_return(data=os.listdir(file_path)))
+
+
+# @tmp_router.route("/pring_bar_code", methods=["POST"])
+# @token_auth.login_required
+# def print_code_data():
+# start = request.values.get("start_code")
+# end = request.values.get("end_code")
+# obj = CreateBarcode()
+# for i in range(int(start), int(end)):
+# obj.create_Code128_img(str(i))
+# return jsonify(Utils.true_return(msg="成功"))
+
+# # 获取所有导入模板信息
+# @tmp_router.route("/all_tmp", methods=["GET"])
+# # @token_auth.login_required
+# def get_tmp_all_list():
+# data_list = BllMedicamentTemplate().execute(
+# "select * from rms_medicament_template"
+# )
+# return jsonify(Utils.true_return(data=Utils.msyql_table_model(data_list)))
+
+
+# @tmp_router.route("/getManufacturerList", methods=["POST"])
+# def get_ManufacturerList():
+# data = BllMedicament().execute(
+# "select DISTINCT manufacturer as `value` from rms_medicament where manufacturer is not null and manufacturer != ''"
+# ).fetchall()
+# return jsonify(Utils.true_return(data=Utils.msyql_table_model(data)))
+
diff --git a/apps/home/views.py b/apps/home/views.py
index 613882e..141a2b4 100644
--- a/apps/home/views.py
+++ b/apps/home/views.py
@@ -19,27 +19,12 @@ from flask import Blueprint
home_router = Blueprint('home', __name__, url_prefix="/home")
-# # 获取页面主概览数据 --- 查询条件,缺少柜体id,客户id
-# @home_router.route('/home_number', methods=["GET", "POST"])
-# @token_auth.login_required
-# def get_record_type_drug_record_json():
-# customer_id = request.values.get('customer_id')
-# client_id = request.values.get('client_id')
-# # 获取药剂记录今日入库 领用 归还Json数据
-# typ_dic = BllMedicamentRecord().getTodayDrugRecordCount()
-# 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.route("/home_info", methods=["GET", "POST"])
@token_auth.login_required
def get_home_info():
+ func_type = request.values.get("func_type")
resp_data = {
"new_day_record_number":{},
"warning_list": [],
@@ -47,7 +32,8 @@ def get_home_info():
}
try:
- resp_data["new_day_record_number"] = BllMedicamentRecord().getTodayDrugRecordCount()
+ resp_data["new_day_record_number"] = BllMedicamentRecord(
+ ).getTodayDrugRecordCount(func_type=func_type)
warning_obj = BllWarning()
resp_data["warning_list"] = Utils.msyql_table_model(warning_obj.getWarningList())
warning_data_list, number_all = warning_obj.get_waring_type_classify()
@@ -70,10 +56,15 @@ def get_home_info():
@token_auth.login_required
def drug_remaining():
client_id = request.values.get("client_id")
+ func_type = request.values.get("func_type")
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
- data_list = BllMedicament().get_drug_surplus(client_id=client_id, page_param=page_param)
+ data_list = BllMedicament().get_drug_surplus(
+ client_id=client_id,
+ func_type=func_type,
+ page_param=page_param
+ )
return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": Utils.msyql_table_model(data_list)}))
# 预警信息总览
diff --git a/apps/monitor/views.py b/apps/monitor/views.py
index b4f8313..5e67d55 100644
--- a/apps/monitor/views.py
+++ b/apps/monitor/views.py
@@ -3,10 +3,7 @@
'''
@Date:2022/08/10 16:53:41
'''
-from dataclasses import dataclass
import sys
-
-from db_logic.humiture_record import BllHumitureRecord
sys.path.append('.')
from sqlalchemy import and_, or_
@@ -14,15 +11,16 @@ from sqlalchemy import and_, or_
from Common.auth import token_auth
from flask import Blueprint, jsonify, request, g
from Common.Utils import PageParam, Utils
-
+from apps.report.utils_base import download_file
+from db_logic.humiture_record import BllHumitureRecord
monitor_router = Blueprint('monitor', __name__)
# 每日温度记录
-@monitor_router.route("/day_monitor", methods=["POST"])
-@token_auth.login_required
+@monitor_router.route("/day_monitor", methods=["GET", "POST"])
+# @token_auth.login_required
def get_day_monitor():
client_id = request.values.get("client_id")
start_time = request.values.get("start_time")
@@ -30,15 +28,33 @@ def get_day_monitor():
page = request.values.get("page", 1)
page_size = request.values.get("page_size", 10)
page_param = PageParam(int(page), int(page_size))
+
+ # 报表数据
+ download_tp = request.values.get("download_type", 0)
+ if download_tp:
+ page_param = None
+
data_list = BllHumitureRecord().get_client_day_log(
client_id=client_id, start_time=start_time,
end_time=end_time, page_param=page_param
)
- return jsonify(Utils.true_return(data={"data_list": Utils.msyql_table_model(data_list), "total_count": page_param.totalRecords}))
-
+ if not download_tp:
+ return jsonify(Utils.true_return(data={"data_list": Utils.msyql_table_model(data_list), "total_count": page_param.totalRecords}))
+ else:
+ file_name = request.values.get("file_name", "数据表")
+ rsp = download_file(
+ # file_path=file_path,
+ file_name=file_name,
+ data_list=data_list,
+ tp=download_tp
+ )
+ if rsp:
+ return rsp
+ else:
+ return jsonify(Utils.false_return())
# 获取每日记录详情
-@monitor_router.route("/day_monitor_info", methods=["POST"])
+@monitor_router.route("/day_monitor_info", methods=["GET", "POST"])
@token_auth.login_required
def get_day_monitor_info():
client_id = request.values.get("client_id")
@@ -47,10 +63,28 @@ def get_day_monitor_info():
page = request.values.get("page", 1)
page_size = request.values.get("page_size", 10)
page_param = PageParam(int(page), int(page_size))
+
+ # 报表数据
+ download_tp = request.values.get("download_type", 0)
+ if download_tp:
+ page_param = None
data_list = BllHumitureRecord().get_client_day_log_info(
client_id=client_id,
start_time=start_time,
end_time=end_time,
page_param=page_param
)
- return jsonify(Utils.true_return(data={"data_list": Utils.msyql_table_model(data_list), "total_count": page_param.totalRecords}))
+ if not download_tp:
+ return jsonify(Utils.true_return(data={"data_list": Utils.msyql_table_model(data_list), "total_count": page_param.totalRecords}))
+ else:
+ file_name = request.values.get("file_name", "数据表")
+ rsp = download_file(
+ # file_path=file_path,
+ file_name=file_name,
+ data_list=data_list,
+ tp=download_tp
+ )
+ if rsp:
+ return rsp
+ else:
+ return jsonify(Utils.false_return())
diff --git a/apps/power/views.py b/apps/power/views.py
index a5292b0..201fbe4 100644
--- a/apps/power/views.py
+++ b/apps/power/views.py
@@ -43,21 +43,19 @@ def add_user_power_list():
client_module = request.values.get("client_module_id")
drug_module = request.values.get("drug_module_id")
standard_module = request.values.get("standard_module_id")
- dangerous_module = request.values.get("dangerous_module_id")
- # instrument_modulet = request.values.get("instrument_module_id")
+ consumables_module = request.values.get("consumables_module_id")
+ instrument_module = request.values.get("instrument_module_id")
inster_dic = {
"1": eval(client_module) if client_module else [],
"2": eval(drug_module) if drug_module else [],
"3": eval(standard_module) if standard_module else [],
- "4": eval(dangerous_module) if dangerous_module else [],
- # "5": eval(instrument_modulet) if instrument_modulet else [],
+ "4": eval(consumables_module) if consumables_module else [],
+ "5": eval(instrument_module) if instrument_module else [],
}
# 删除除去柜子权限外的所有权限
BllModuleRelation().delete(
- and_(EntityModuleRelation.object_id == user_id,
- EntityModuleRelation.module_type != "1",
- EntityModuleRelation.object_type == "2")
- )
+ and_(EntityModuleRelation.object_id == user_id)
+ )
inster_module_list = []
for k,v in inster_dic.items():
for i in v:
@@ -133,19 +131,18 @@ def add_role():
role_id = request.values.get("role_id")
role_code = request.values.get("role_code")
role_name = request.values.get("role_name")
- # sys_module_list = request.values.get("sys_module")
- # client_module_list = request.values.get("client_module")
client_module = request.values.get("client_module_id")
drug_module = request.values.get("drug_module_id")
standard_module = request.values.get("standard_module_id")
- dangerous_module = request.values.get("dangerous_module_id")
+ consumables_module = request.values.get("consumables_module_id")
+ instrument_module = request.values.get("instrument_module_id")
# instrument_modulet = request.values.get("instrument_module_id")
inster_dic = {
"1": eval(client_module) if client_module else [],
"2": eval(drug_module) if drug_module else [],
"3": eval(standard_module) if standard_module else [],
- "4": eval(dangerous_module) if dangerous_module else [],
- # "5": eval(instrument_modulet) if instrument_modulet else [],
+ "4": eval(consumables_module) if consumables_module else [],
+ "5": eval(instrument_module) if instrument_module else [],
}
description = request.values.get("description")
# 获取角色代码或者角色名的角色信息
@@ -196,30 +193,6 @@ def add_role():
create_user_name=g.current_user.real_name
)
)
- # if sys_module_list:
- # sys_module_list = eval(sys_module_list)
- # for module_id in sys_module_list:
- # inster_module_list.append(
- # EntityModuleRelation(
- # object_type=1,
- # object_id=role_id,
- # module_id=module_id,
- # module_type=2,
- # create_date=Utils.get_str_datetime()
- # )
- # )
- # if client_module_list:
- # client_module_list = eval(client_module_list)
- # for module_id in client_module_list:
- # inster_module_list.append(
- # EntityModuleRelation(
- # object_type=1,
- # object_id=role_id,
- # module_id=module_id,
- # module_type=1,
- # create_date=Utils.get_str_datetime()
- # )
- # )
BllModuleRelation().insert_many(inster_module_list)
return jsonify(Utils.true_return())
diff --git a/apps/report/dows_utils.py b/apps/report/dows_utils.py
new file mode 100644
index 0000000..636c07f
--- /dev/null
+++ b/apps/report/dows_utils.py
@@ -0,0 +1,17 @@
+import os
+from flask import send_file, Response
+from urllib.parse import quote
+from Common.report_excel import ReportData
+
+def dows_flie(file_path, file_name):
+ file_name = file_name+".xlsx"
+ # response = send_file(os.path.join(file_path, file_name), as_attachment=True, attachment_filename=quote(file_name))
+
+ # response = send_file(ReportData.download_excel(os.path.join(file_path, file_name)), as_attachment=True, attachment_filename=quote(file_name))
+ response = Response(ReportData.download_excel(os.path.join(file_path, file_name)), content_type='application/octet-stream')
+ response.headers["Content-Disposition"] = \
+ "attachment;" \
+ "filename*=UTF-8''{utf_filename}".format(
+ utf_filename=quote(file_name)
+ )
+ return response
\ No newline at end of file
diff --git a/apps/report/utils_base.py b/apps/report/utils_base.py
new file mode 100644
index 0000000..b231057
--- /dev/null
+++ b/apps/report/utils_base.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+'''
+@Date:2022/09/14 11:00:47
+'''
+import sys
+sys.path.append('.')
+
+import os
+from Common.report_excel import ReportData
+from Common.report_excel_new import ReportData as NewReportData
+from Common.Utils import Utils
+from apps.report.dows_utils import dows_flie
+
+def get_finds_list(tp):
+ dic = {
+ "1": ["name", "cas_number", "speci", "purity", "count_number", "sum_remain"],
+ "2": ['name', 'manufacturer', 'distributor', 'purity', 'cas_number', 'speci', 'remain', 'net_weight', 'net_weight_unit', 'price', 'production_date', 'expiration_date', 'shelf_life', 'unit_code', 'remark2', 'category', 'standard_code', 'storage_condition', 'remark9', 'put_in_user_name', 'put_in_date'],
+ "3": ['name', 'unit_code', 'bar_code', 'remark2', 'speci', 'remain', 'purity', 'cas_number', 'production_date', 'expiration_date', 'shelf_life', 'price', 'net_weight', 'net_weight_unit', 'put_in_date', 'manufacturer', 'storage_condition', 'remark9', 'category', 'standard_code', 'put_in_user_name', 'status', 'by_user_name', 'client_name'],
+ "4": ["name", "purity", "cas_number", "enter_stock", "in_stock", "up_stock", "no_stock"],
+ "5": ["name", "purity", "cas_number", "speci", "on_in", "use_num", "use_level", "ratio"],
+ "6": ["create_user_name", "role_name", "use_num", "use_amount", "ratio"],
+ "7": ["name", "purity", "cas_number", "speci", "new_on", "sum_tp2", "sum_tp3"],
+ "8": ["name", "unit_code", "bar_code", "purity", "cas_number", "use_quantity", "status", "create_date", "create_user_name", "client_name"],
+ "9": ["client_name", "place", "day_date", "avg_wd", "avg_sd", "avg_voc"],
+ "10": ["day_date", "wd", "sd", "voc",],
+ "11": ["name","code_number","unit_code","start_time","end_time","purity","capacity","basis","doc_log","user_name"],
+ "12": ["name", "gg_ph", "shelf_life", "manufacturer", "distributor", "num", "acceptace", "put_in_user_name", "put_in_date"]
+ }
+ return dic.get(str(tp))
+
+def get_finds_name_list(tp):
+ dic = {
+ "1": ["试剂名称", "CAS码", "规格", "纯度", "在库剩余数量(瓶)", "在库剩余总质量(g)"],
+ "2": ['试剂名称', '生产厂商', '供应商', '纯度', 'CAS码', '规格', '余量', '净含量', '单位', '价格', '生产日期', '过期日期', '保质期', '单位编号', '产品编号', '类别', '批号', '存储条件', '密度', '入库操作人', '入库时间'],
+ "3": ['试剂名称', '单位编号', '试剂编码', '产品编号', '规格', '余量', '纯度', 'CAS码', '生产日期', '过期日期', '保质期', '价格', '净含量', '单位', '入库日期', '生产厂商', '存储条件', '密度', '类别', '批号', '试剂管理人', '状态', '最后使用人', '所属终端'],
+ "4": ["试剂名称", "纯度", "CAS码", "入库数量", "当前在库数量", "当前借出数量", "消耗数量"],
+ "5": ["试剂名称", "纯度", "CAS码", "规格", "库存量(瓶)", "使用次数", "总用量(g)", "占用百分比"],
+ "6": ["用户名称", "用户身份","使用次数","总用量(g)","占用百分比(%)"],
+ "7": ["用户名称", "纯度", "CAS码", "规格", "当前库存总量", "领用次数", "归还次数"],
+ "8": ["试剂名称", "单位编号", "试剂编码", "纯度", "CAS码", "用量", "状态", "操作时间", "操作人员", "所属终端"],
+
+ "9": ["柜体名称", "所处位置", "日期", "温度(平均值)", "湿度(平均值)", "VOC(平均值)"],
+ "10": ["时间", "温度", "湿度", "VO含量"],
+ "11": ["储备液名称","储备液编号","物质单位编号","配置日期","有效期","配置浓度","配置量","配置依据","配置记录", "配置人"],
+ "12": ["耗材名称", "规格、批号/型号", "有效期", "生产企业", "经销单位", "数量", "验收记录", "验收人", "日期"]
+ }
+ return dic.get(str(tp))
+
+
+def download_file(file_name, data_list, tp):
+ try:
+ file_path = os.path.join(os.getcwd(), "report_file")
+ if not os.path.exists(file_path):
+ os.makedirs(file_path)
+ if tp == "12":
+ obj_report = NewReportData()
+ else:
+ obj_report = ReportData()
+ obj = obj_report.build_file(**{
+ "file_name": file_name,
+ "data_list": data_list,
+ "key_list": get_finds_list(tp),
+ "finds_name": get_finds_name_list(tp),
+ })
+ rsp_file_name = f"{file_name}{Utils.get_file_name_datetime()}"
+ obj.save(os.path.join(file_path, rsp_file_name))
+ rep = dows_flie(file_path, rsp_file_name)
+ return rep
+ # return file_path, rsp_file_name
+ # return True
+ except Exception as error:
+ print(error)
+ return False, False
diff --git a/apps/report/views.py b/apps/report/views.py
index 76f9d2a..fb3a8f0 100644
--- a/apps/report/views.py
+++ b/apps/report/views.py
@@ -3,47 +3,243 @@
'''
@Date:2022/07/19 17:12:23
'''
-from flask import jsonify, request, g
+from flask import jsonify, request, g, Blueprint
from Common.Utils import PageParam, Utils
from config.SystemConfig import SystemConfig
from db_logic.medicament_record import BllMedicamentRecord
from db_logic.medicament import BllMedicament
from Common.auth import token_auth
-from flask import Blueprint
+from apps.report.utils_base import download_file
report_router = Blueprint("report", __name__)
-# 获取报表统计页面展示
-# @report_router.route('/report_home', methods=["GET", "POST"])
-# def report_home_info():
-# # 试剂使用统计
-# data_list = BllMedicamentRecord().get_drug_record_count()
-# return jsonify(Utils.true_return(data=data_list))
+"""
+# # 获取报表统计页面展示
+# # @report_router.route('/report_home', methods=["GET", "POST"])
+# # def report_home_info():
+# # # 试剂使用统计
+# # data_list = BllMedicamentRecord().get_drug_record_count()
+# # return jsonify(Utils.true_return(data=data_list))
+
+# # # 消耗统计
+# # @report_router.route("/drug_stock_use_classify", methods=["GET", "POST"])
+# # def get_drug_stock_use_classify():
+# # data_list, total_number = BllMedicament().get_drug_stock_use_classify()
+# # return jsonify(Utils.true_return(data={"total_count":total_number, "data":data_list}))
+
+
+# # # 试剂用量消耗
+# # @report_router.route("/drug_use_classify", methods=["GET", "POST"])
+# # def get_drug_use_classify():
+# # data_list = BllMedicamentRecord().report_home_drug_useing_classify()
+# # return jsonify(Utils.true_return(data=data_list))
+
+# # # 用户试剂消耗
+# # @report_router.route("/drug_user_use_info", methods=["GET", "POST"])
+# # def get_drug_user_use_number():
+# # data_list = BllMedicamentRecord().report_home_user_use_info()
+# # return jsonify(Utils.true_return(data=data_list))
+
+# # 报表统计主页
+# @report_router.route("/report_home", methods=["GET", "POST"])
+# @token_auth.login_required
+# def report_home_show():
+# resp_data = {
+# "drug_use_type_data": "",
+# "use_avg_info":{},
+# "drug_stock_expend": {"count_number":0, "data":""},
+# "drug_use_expend":"",
+# "user_use_expend": ""
+
+# }
+# try:
+# obj_data = BllMedicamentRecord()
+# # 试剂使用统计
+# drug_use_type_data, avg_use_dic = obj_data.get_drug_record_count()
+# # 消耗统计部分
+# drug_stock_expend, num_all = BllMedicament().get_drug_stock_use_classify()
+# # 试剂用量消耗
+# drug_use_expend = obj_data.report_home_drug_useing_classify()
+# # 用户试剂消耗
+# user_use_expend = obj_data.report_home_user_use_info()
+# resp_data["drug_use_type_data"] = drug_use_type_data
+# resp_data["use_avg_info"] = avg_use_dic
+# resp_data["drug_stock_expend"] = {
+# "count_number": num_all,
+# "data": drug_stock_expend
+# }
+# resp_data["drug_use_expend"] = drug_use_expend
+# resp_data["user_use_expend"] = user_use_expend
+# return jsonify(Utils.true_return(data=resp_data))
+# except Exception as error:
+# return jsonify(Utils.except_return(msg=f"error:{error}", data=resp_data))
+
+
+
+
+
+# # 库存信息总览
+# @report_router.route("/stock_data_info", methods=["GET", "POST"])
+# @token_auth.login_required
+# def get_stock_data_info():
+# name = request.values.get("name", None)
+# page = int(request.values.get('page', 1))
+# page_size = int(request.values.get('page_size', 15))
+# page_param = PageParam(page, page_size)
+# data_list = BllMedicament().get_stock_all_info(
+# name=name,
+# page_param=page_param)
+# data_list = Utils.msyql_table_model(data_list)
+# if data_list:
+# return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))
+# else:
+# return jsonify(Utils.false_return(msg="无效数据"))
+
+
+# # 入库信息查询and 试剂信息查询
+# @report_router.route("/drug_details_info", methods=["GET", "POST"])
+# @token_auth.login_required
+# def drun_input_info():
+# # 获取参数
+# seach_word = request.values.get('seach_word')
+# manufacturer = request.values.get("manufacturer")
+# start_time = request.values.get("start_time")
+# end_time = request.values.get("end_time")
+# # 客户id
+# customer_id = None
+# client_id = request.values.get("client_id")
+# # 分页处理
+# page = int(request.values.get("page", 1))
+# page_size = int(request.values.get("page_size", 10))
+# page_param = PageParam(page, page_size)
+# # 获取数据
+# data = BllMedicament().getAllDrugList(
+# search_word=seach_word,
+# manufacturer=manufacturer,
+# start_time=start_time,
+# end_time=end_time,
+# page_param=page_param,
+# customer_id=customer_id,
+# client_id=client_id
+# )
+# # 数据处理,列表key:value格式
+
+# data_list = Utils.msyql_table_model(data)
+# return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))
+
+
+# # 库存消耗
+# # 试剂名称、纯度、cas码 查询rms_medicament 分组后获取
+# @report_router.route("/stock_loss_info", methods=["GET", "POST"])
+# @token_auth.login_required
+# def stock_loss_info():
+# # 获取参数
+# seach_word = request.values.get('seach_word')
+# start_time = request.values.get('start_time')
+# end_time = request.values.get('end_time')
+# page = int(request.values.get("page", 1))
+# page_size = int(request.values.get("page_size", 10))
+# page_param = PageParam(page, page_size)
+# # 获取数据结果
+# data = BllMedicamentRecord().durg_stock_loss(
+# seach_word=seach_word,
+# 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}))
-# # 消耗统计
-# @report_router.route("/drug_stock_use_classify", methods=["GET", "POST"])
-# def get_drug_stock_use_classify():
-# data_list, total_number = BllMedicament().get_drug_stock_use_classify()
-# return jsonify(Utils.true_return(data={"total_count":total_number, "data":data_list}))
# # 试剂用量消耗
-# @report_router.route("/drug_use_classify", methods=["GET", "POST"])
-# def get_drug_use_classify():
-# data_list = BllMedicamentRecord().report_home_drug_useing_classify()
-# return jsonify(Utils.true_return(data=data_list))
+# @report_router.route("/drug_use_expend", methods=["GET", "POST"])
+# @token_auth.login_required
+# def get_drug_use_expend():
+# # 参数获取
+# seach_word = request.values.get('seach_word')
+# start_time = request.values.get('start_time')
+# end_time = request.values.get('end_time')
+# page = int(request.values.get("page", 1))
+# page_size = int(request.values.get("page_size", 10))
+# page_param = PageParam(page, page_size)
+# # 获取数据
+# data = BllMedicamentRecord().durg_useing_info(
+# seach_word=seach_word,
+# 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}))
+
+
+# # 人员用量消耗
+# @report_router.route("/drug_user_use_expend", methods=["GET", "POST"])
+# @token_auth.login_required
+# def get_drug_user_use_expend():
+# # 参数获取
+# seach_user = request.values.get('seach_user')
+# start_time = request.values.get('start_time')
+# end_time = request.values.get('end_time')
+# page = int(request.values.get("page", 1))
+# page_size = int(request.values.get("page_size", 10))
+# page_param = PageParam(page, page_size)
+# # 获取数据
+# data = BllMedicamentRecord().user_use_info(
+# seach_user=seach_user,
+# 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}))
+
-# # 用户试剂消耗
-# @report_router.route("/drug_user_use_info", methods=["GET", "POST"])
-# def get_drug_user_use_number():
-# data_list = BllMedicamentRecord().report_home_user_use_info()
-# return jsonify(Utils.true_return(data=data_list))
+# # 使用频率
+# @report_router.route("/use_frequency", methods=["GET", "POST"])
+# @token_auth.login_required
+# def drug_use_frequency():
+# seach_word = request.values.get('seach_word')
+# client_id = request.values.get("client_id")
+# start_time = request.values.get('start_time')
+# end_time = request.values.get('end_time')
+# page = int(request.values.get("page", 1))
+# page_size = int(request.values.get("page_size", 10))
+# page_param = PageParam(page, page_size)
+# data = BllMedicamentRecord().use_frequency(
+# seach_word=seach_word,
+# start_time=start_time,
+# end_time=end_time,
+# 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"])
+# @token_auth.login_required
+# def drug_log_type_info():
+# page = int(request.values.get("page", 1))
+# page_size = int(request.values.get("page_size", 10))
+# statue_type = request.values.get("status")
+# record_type = request.values.get("record_type")
+# put_in_user_name = request.values.get("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, statue_type=statue_type,
+# name=name,
+# start_time=start_time, end_time=end_time,
+# page_param=page_param
+# )
+# data_list = Utils.msyql_table_model(data_list)
+# return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))
+"""
# 报表统计主页
@report_router.route("/report_home", methods=["GET", "POST"])
@token_auth.login_required
def report_home_show():
+ func_type = request.values.get("func_type")
resp_data = {
"drug_use_type_data": "",
"use_avg_info":{},
@@ -55,13 +251,20 @@ def report_home_show():
try:
obj_data = BllMedicamentRecord()
# 试剂使用统计
- drug_use_type_data, avg_use_dic = obj_data.get_drug_record_count()
+ drug_use_type_data, avg_use_dic = obj_data.get_drug_record_count(
+ func_type=func_type)
# 消耗统计部分
- drug_stock_expend, num_all = BllMedicament().get_drug_stock_use_classify()
+ drug_stock_expend, num_all = BllMedicament().get_drug_stock_use_classify(
+ func_type=func_type
+ )
# 试剂用量消耗
- drug_use_expend = obj_data.report_home_drug_useing_classify()
+ drug_use_expend = obj_data.report_home_drug_useing_classify(
+ func_type=func_type
+ )
# 用户试剂消耗
- user_use_expend = obj_data.report_home_user_use_info()
+ user_use_expend = obj_data.report_home_user_use_info(
+ func_type=func_type
+ )
resp_data["drug_use_type_data"] = drug_use_type_data
resp_data["use_avg_info"] = avg_use_dic
resp_data["drug_stock_expend"] = {
@@ -76,24 +279,41 @@ def report_home_show():
-
-
# 库存信息总览
@report_router.route("/stock_data_info", methods=["GET", "POST"])
-@token_auth.login_required
+# @token_auth.login_required
def get_stock_data_info():
name = request.values.get("name", None)
+ func_type = request.values.get("func_type")
page = int(request.values.get('page', 1))
page_size = int(request.values.get('page_size', 15))
page_param = PageParam(page, page_size)
+
+ # 导出报表功能
+ download_tp = request.values.get("download_type", 0)
+ if download_tp:
+ page_param = None
data_list = BllMedicament().get_stock_all_info(
name=name,
+ func_type=func_type,
page_param=page_param)
data_list = Utils.msyql_table_model(data_list)
- if data_list:
- return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))
+ if not download_tp:
+ if data_list:
+ return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))
+ else:
+ return jsonify(Utils.true_return(data={"total_count": 0, "data": data_list}))
else:
- return jsonify(Utils.false_return(msg="无效数据"))
+ file_name = request.values.get("file_name", "数据表")
+ res = download_file(
+ file_name=file_name,
+ data_list=data_list,
+ tp=download_tp
+ )
+ if res:
+ return res
+ else:
+ return jsonify(Utils.false_return())
# 入库信息查询and 试剂信息查询
@@ -105,28 +325,49 @@ def drun_input_info():
manufacturer = request.values.get("manufacturer")
start_time = request.values.get("start_time")
end_time = request.values.get("end_time")
- # 客户id
+
+ func_type = request.values.get("func_type")
+
customer_id = None
client_id = request.values.get("client_id")
+ # TODO 添加房间筛选
+ client_place = request.values.get("client_place")
# 分页处理
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
- # 获取数据
+
+ download_tp = request.values.get("download_type", 0)
+ if download_tp:
+ page_param = None
+ # 获取数据
data = BllMedicament().getAllDrugList(
search_word=seach_word,
manufacturer=manufacturer,
+ func_type=func_type,
start_time=start_time,
end_time=end_time,
page_param=page_param,
customer_id=customer_id,
- client_id=client_id
+ client_id=client_id,
+ client_speci=client_place
)
# 数据处理,列表key:value格式
data_list = Utils.msyql_table_model(data)
- return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))
-
+ if not download_tp:
+ return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))
+ else:
+ file_name = request.values.get("file_name", "数据表")
+ rsp = download_file(
+ file_name=file_name,
+ data_list=data_list,
+ tp=download_tp
+ )
+ if rsp:
+ return rsp
+ else:
+ return jsonify(Utils.false_return())
# 库存消耗
# 试剂名称、纯度、cas码 查询rms_medicament 分组后获取
@@ -135,18 +376,38 @@ def drun_input_info():
def stock_loss_info():
# 获取参数
seach_word = request.values.get('seach_word')
- start_time = request.values.get('start_time')
- end_time = request.values.get('end_time')
+
+
+ func_type = request.values.get("func_type")
+
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
+
+ # 报表数据
+ download_tp = request.values.get("download_type", 0)
+ if download_tp:
+ page_param = None
+
# 获取数据结果
data = BllMedicamentRecord().durg_stock_loss(
seach_word=seach_word,
- start_time=start_time,
- end_time=end_time,
+ func_type=func_type,
page_param=page_param)
- return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
+ if not download_tp:
+ return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
+ else:
+ file_name = request.values.get("file_name", "数据表")
+ rsp = download_file(
+ file_name=file_name,
+ data_list=data,
+ tp=download_tp
+ )
+ if rsp:
+ return rsp
+ else:
+ return jsonify(Utils.false_return())
+
@@ -156,19 +417,34 @@ def stock_loss_info():
def get_drug_use_expend():
# 参数获取
seach_word = request.values.get('seach_word')
- start_time = request.values.get('start_time')
- end_time = request.values.get('end_time')
+ func_type = request.values.get("func_type")
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
+
+ # 报表数据
+ download_tp = request.values.get("download_type", 0)
+ if download_tp:
+ page_param = None
# 获取数据
data = BllMedicamentRecord().durg_useing_info(
seach_word=seach_word,
- start_time=start_time,
- end_time=end_time,
+ func_type=func_type,
page_param=page_param)
- return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
-
+ if not download_tp:
+ return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
+ else:
+ file_name = request.values.get("file_name", "数据表")
+ rsp = download_file(
+ # file_path=file_path,
+ file_name=file_name,
+ data_list=data,
+ tp=download_tp
+ )
+ if rsp:
+ return rsp
+ else:
+ return jsonify(Utils.false_return())
# 人员用量消耗
@report_router.route("/drug_user_use_expend", methods=["GET", "POST"])
@@ -178,17 +454,35 @@ def get_drug_user_use_expend():
seach_user = request.values.get('seach_user')
start_time = request.values.get('start_time')
end_time = request.values.get('end_time')
+ func_type = request.values.get("func_type")
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
+
+ # 报表数据
+ download_tp = request.values.get("download_type", 0)
+ if download_tp:
+ page_param = None
# 获取数据
data = BllMedicamentRecord().user_use_info(
seach_user=seach_user,
+ func_type=func_type,
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}))
-
+ if not download_tp:
+ return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
+ else:
+ file_name = request.values.get("file_name", "数据表")
+ rsp = download_file(
+ file_name=file_name,
+ data_list=data,
+ tp=download_tp
+ )
+ if rsp:
+ return rsp
+ else:
+ return jsonify(Utils.false_return())
# 使用频率
@report_router.route("/use_frequency", methods=["GET", "POST"])
@@ -198,37 +492,116 @@ def drug_use_frequency():
client_id = request.values.get("client_id")
start_time = request.values.get('start_time')
end_time = request.values.get('end_time')
+ func_type = request.values.get("func_type")
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
page_param = PageParam(page, page_size)
+
+ # 报表数据
+ download_tp = request.values.get("download_type", 0)
+ if download_tp:
+ page_param = None
+
data = BllMedicamentRecord().use_frequency(
seach_word=seach_word,
start_time=start_time,
end_time=end_time,
+ func_type=func_type,
client_id=client_id,
page_param=page_param)
- return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
-
+ if not download_tp:
+ return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data}))
+ else:
+ file_name = request.values.get("file_name", "数据表")
+ rsp = download_file(
+ # file_path=file_path,
+ file_name=file_name,
+ data_list=data,
+ tp=download_tp
+ )
+ if rsp:
+ return rsp
+ else:
+ return jsonify(Utils.false_return())
# 入库、领用、归还记录
@report_router.route("/drug_log_type_info", methods=["GET", "POST"])
-@token_auth.login_required
+# @token_auth.login_required
def drug_log_type_info():
page = int(request.values.get("page", 1))
page_size = int(request.values.get("page_size", 10))
statue_type = request.values.get("status")
record_type = request.values.get("record_type")
+ func_type = request.values.get("func_type")
+
put_in_user_name = request.values.get("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)
+ # 报表数据
+ download_tp = request.values.get("download_type", 0)
+ if download_tp:
+ page_param = None
data_list = BllMedicament().drug_show_type_info(
- record_type=record_type, put_in_user_name=put_in_user_name, statue_type=statue_type,
+ record_type=record_type,
+ put_in_user_name=put_in_user_name,
+ func_type=func_type,
+ statue_type=statue_type,
name=name,
start_time=start_time, end_time=end_time,
page_param=page_param
)
data_list = Utils.msyql_table_model(data_list)
- return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))
+ if not download_tp:
+ return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data_list}))
+ else:
+ file_name = request.values.get("file_name", "数据表")
+ rsp = download_file(
+ # file_path=file_path,
+ file_name=file_name,
+ data_list=data_list,
+ tp=download_tp
+ )
+ if rsp:
+ return rsp
+ else:
+ return jsonify(Utils.false_return())
+
+
+# 入库验收表导出
+@report_router.route("/putin_acceptance_record", methods=["GET", "POST"])
+# @token_auth.login_required
+def get_putin_acceptance_record():
+ data = BllMedicament().execute(
+ """
+ SELECT
+ `name`, speci, remark5, date_format( expiration_date,'%Y-%m-%d') shelf_life, manufacturer, distributor, count(*) num, put_in_user_name, date_format( put_in_date,'%Y-%m-%d') put_in_date
+ FROM `rms_medicament`
+ GROUP BY `name`, purity, speci, remark5, DATE_FORMAT(put_in_date,"%Y-%m-%d")
+ """
+ ).fetchall()
+ data_list = Utils.msyql_table_model(data)
+ for i in data_list:
+ gg_ph = ''
+ if str(i["speci"]) !='' and str(i["speci"]) !='None':
+ gg_ph += str(i["speci"])
+ if str(i["remark5"]) !='' and str(i["remark5"]) !='None':
+ if gg_ph:
+ gg_ph += ","
+ gg_ph += str(i["remark5"])
+ i["gg_ph"] = gg_ph
+ i["acceptace"] = """□标识清晰\r\n□外观完整、无破损\r\n□形状无明显改变\r\n□符合申购要求"""
+ i["shelf_life"] = str(i["shelf_life"])
+ file_name = "实验耗材入库验收记录表"
+ data = download_file(
+ # file_path=file_path,
+ file_name=file_name,
+ data_list=data_list,
+ tp="12"
+ )
+ if data:
+ return data
+ else:
+ return jsonify(Utils.false_return())
\ No newline at end of file
diff --git a/apps/stock_record/views.py b/apps/stock_record/views.py
new file mode 100644
index 0000000..a58ab5e
--- /dev/null
+++ b/apps/stock_record/views.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+'''
+@Date: 2022/11/28 11:17:55
+'''
+import sys
+sys.path.append('.')
+
+
+from flask import jsonify, request, g, Blueprint
+
+from Common.Utils import PageParam, Utils
+from Common.auth import token_auth
+from db_logic.stock_record import BllStockRecord
+
+stock_router = Blueprint("stock_record", __name__)
+
+
+
+
+# 列表展示
+@stock_router.route("/getlist", methods=["POST"])
+# @token_auth.login_required
+def get_stock_record_list():
+ client_id = request.values.get("client_id")
+ page = request.values.get("page", 1)
+ page_size = request.values.get("page_size", 10)
+ page_param = PageParam(int(page), int(page_size))
+ data_list = BllStockRecord().get_list_info(client_id=client_id, page_param=page_param)
+ data_list = Utils.msyql_table_model(data_list)
+ return jsonify(Utils.true_return(data={"data_list": data_list, "total_count": page_param.totalRecords}))
+
+# 盘点库单
+@stock_router.route("/set_stock", methods=["POST"])
+@token_auth.login_required
+def set_stock_record():
+ client_id = request.values.get("client_id")
+ client_code = request.values.get("client_code")
+ data = BllStockRecord().set_stock_info(
+ client_id=client_id,
+ client_code=client_code,
+ user_info=g.current_user
+ )
+ if data:
+ return jsonify(Utils.true_return())
+ else:
+ return jsonify(Utils.false_return())
+
diff --git a/apps/user/views.py b/apps/user/views.py
index 0da4381..fbdf77f 100644
--- a/apps/user/views.py
+++ b/apps/user/views.py
@@ -24,8 +24,7 @@ def user_login():
# password = body.password
user_obj, user_info = BllUser().login(user_name=user_name, password=password)
if user_obj:
- print(user_obj)
- return jsonify(Utils.true_return(msg="登陆成功", data={"token":user_obj, "user_info": user_info}))
+ return jsonify(Utils.true_return(msg="登陆成功", data={"token":user_obj, "user_info": Utils.to_dict(user_info)}))
else:
return jsonify(Utils.false_return(status=201, msg="登陆失败"))
@@ -124,15 +123,11 @@ def update_user_info():
)
if obj.user_id != new_obj.user_id:
return jsonify(Utils.false_return(msg="工号不能重复"))
- obj.real_name = request.values.get("real_name")
- obj.mobile = request.values.get("mobile")
- obj.sex = request.values.get("sex")
- obj.email = request.values.get("email")
- obj.user_code = request.values.get("user_code")
- obj.qq = request.values.get("qq")
- obj.role_id = request.values.get("role_id")
- obj.role_name = request.values.get("role_name")
- obj.is_enabled = request.values.get("is_enabled")
+ finds_list = dir(EntityUser)
+ for i in finds_list:
+ va = request.values.get(i)
+ if va:
+ setattr(obj, i, va)
obj.update_last_visit_date()
BllUser().update(obj)
return jsonify(Utils.true_return(msg="修改成功"))
diff --git a/config/SystemConfig.py b/config/SystemConfig.py
index 53769d6..3625be0 100644
--- a/config/SystemConfig.py
+++ b/config/SystemConfig.py
@@ -1,21 +1,3 @@
-# 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
diff --git a/db_logic/client.py b/db_logic/client.py
index c3b4692..fd4b32c 100644
--- a/db_logic/client.py
+++ b/db_logic/client.py
@@ -9,7 +9,6 @@ sys.path.append(".")
from Common.Utils import Utils
import os
-print(os.getcwd())
from sqlalchemy import asc
from db_logic.db_base import Repository
from models.client_models import EntityClient
@@ -23,23 +22,28 @@ class BllClient(Repository):
# 获取客户端列表
- def get_all_client_list(self):
+ def get_all_client_list(self, func_type):
# return self.findList().order_by(asc(EntityClient.client_code)).all()
- sql_all = """select * from rms_client order by client_code """
+ sql_all = f"""select * from rms_client where func_type='{func_type}' order by client_code """
return self.execute(sql_all).fetchall()
- def get_client_seach(self, seach_word, page_param):
+ def get_client_seach(self, seach_word, func_type, page_param):
filter_base = ""
if seach_word:
filter_base += f" client_name like '%{seach_word}%' "
+ # 添加类别参数
+ if func_type:
+ if filter_base:
+ filter_base += " and "
+ filter_base += f" func_type='{func_type}' "
if filter_base:
filter_base = f" where {filter_base} "
sql_all = f"""
select * from rms_client {filter_base} order by client_code
"""
try:
- count_number = len(self.execute(sql_all).fetchall())
+ count_number = self.execute(f"select count(*) num from rms_client {filter_base} order by client_code").fetchone().num
except Exception:
count_number = 0
page_param.totalRecords=count_number
diff --git a/db_logic/client_user.py b/db_logic/client_user.py
index 36b2a79..69beb4a 100644
--- a/db_logic/client_user.py
+++ b/db_logic/client_user.py
@@ -31,7 +31,7 @@ class BllClientUser(Repository):
filter_base = f" where {filter_base} "
sql_all = f"""
SELECT a.user_id, a.real_name, a.role_name, a.avatar_url,
- CASE WHEN b.client_user_id is not null THEN 1 else 0 END status_type
+ CASE WHEN b.client_user_id is not null THEN 0 else 1 END status_type
from (select * from rms_user {filter_base}) as a LEFT JOIN(
select * from rms_client_user where client_id='{client_id}'
)as b on a.user_id=b.user_id
@@ -46,12 +46,18 @@ class BllClientUser(Repository):
def inster_user_client(self, user_id, client_id):
try:
- self.insert(
- EntityClientUser(
- client_id=client_id,
- user_id=user_id
+ if not self.findEntity(
+ and_(
+ EntityClientUser.client_id == client_id,
+ EntityClientUser.user_id == user_id,
+ )
+ ):
+ self.insert(
+ EntityClientUser(
+ client_id=client_id,
+ user_id=user_id
+ )
)
- )
return True
except Exception:
return False
diff --git a/db_logic/control_log.py b/db_logic/control_log.py
index 0d9d146..f3ab1b7 100644
--- a/db_logic/control_log.py
+++ b/db_logic/control_log.py
@@ -21,21 +21,29 @@ class BllLog(Repository):
#获取系统日志列表
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))
+ orm_query = self.findList().filter(
+ EntityLog.customer_id == customerId
+ ).filter(
+ or_(
+ EntityLog.operate_user_name.like(keyWord),
+ EntityLog.operate_type.like(keyWord)
+ )
+ ).order_by(desc(EntityLog.operate_date))
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)
+ user_id = currentInfo.get('user_id')
+ client_code = currentInfo.get('client_code')
+ customer_id = currentInfo.get('customer_id')
+ user = BllUser().findEntity(user_id)
+ entity_log = EntityLog(log_id=str(Utils.UUID()), customer_id=customer_id, LogType=1, operate_user_id=user_id,
+ operate_account=user.account, operate_user_name=user.real_name,
+ operate_type_code='通信成功', operate_type='通信成功',
+ execute_result="终端{0}:{1}".format(
+ client_code, ExecuteResult),
+ operate_date=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
+ is_add=1
+ )
self.insert(entity_log)
diff --git a/db_logic/humiture_record.py b/db_logic/humiture_record.py
index 3430a41..1220631 100644
--- a/db_logic/humiture_record.py
+++ b/db_logic/humiture_record.py
@@ -78,9 +78,10 @@ class BllHumitureRecord(Repository):
count_number = len(self.execute(sql_all).fetchall())
except Exception:
count_number = 0
- page_param.totalRecords = count_number
- page_sql = Utils.sql_paging_assemble(sql_all, page_param)
- return self.execute(page_sql).fetchall()
+ if page_param:
+ page_param.totalRecords = count_number
+ sql_all = Utils.sql_paging_assemble(sql_all, page_param)
+ return self.execute(sql_all).fetchall()
# 获取每日记录详情
def get_client_day_log_info(self, client_id, start_time, end_time, page_param):
diff --git a/db_logic/medicament.py b/db_logic/medicament.py
index 37bdc50..7385fd0 100644
--- a/db_logic/medicament.py
+++ b/db_logic/medicament.py
@@ -34,24 +34,25 @@ class BllMedicament(Repository):
# 根据条码获取试剂详细信息
def get_bar_code_drug_info(self, bar_code):
return self.execute(f"select * from rms_medicament where bar_code='{bar_code}'").fetchall()
-
- # 获取库存余量
- def get_drug_surplus(self, client_id, page_param):
- sql_all = """
- select
- `name`, english_name, cas_number, speci, net_weight_unit, purity,
- sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) surplus_number
- from rms_medicament %s GROUP BY `name`, speci, purity
- """
+
+ # 获取库存余量
+ def get_drug_surplus(self, client_id, func_type, page_param):
# 动态添加查询条件
where_base = ""
if client_id:
where_base = f" client_id='{client_id}'"
+ if func_type:
+ if where_base:
+ where_base += " and "
+ where_base += f" func_type='{func_type}'"
if where_base:
- where_base = " where " + where_base
- # 组装sql
- sql_all = sql_all % where_base
-
+ where_base = f" where {where_base} "
+ sql_all = f"""
+ select
+ `name`, english_name, cas_number, speci, net_weight_unit, purity,
+ sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) surplus_number
+ from rms_medicament {where_base} GROUP BY `name`, speci, purity order by put_in_date desc
+ """
# 查询页总数
try:
total_count = len(self.execute(sql_all).fetchall())
@@ -66,26 +67,11 @@ class BllMedicament(Repository):
return data_list
# 获取试剂库存消耗
- def get_drug_stock_use_classify(self):
- sql_all = """
- select count(medicament_id) count_number, `status` from rms_medicament GROUP BY `status`
+ def get_drug_stock_use_classify(self, func_type):
+ sql_all = f"""
+ select count(medicament_id) count_number, `status` from rms_medicament where func_type='{func_type}' GROUP BY `status` order by put_in_date desc
"""
- # # 查看分组数据
- # data = self.execute(sql_all).fetchall()
- # # 计算总数
- # data_number = sum([i[0] for i in data])
- # data_li = Utils.msyql_table_model(data)
- # data_list = []
- # # 计算百分比,组装数据
- # for i in data_li:
- # new_dict = {
- # # "ratio": str(round(i["count_number"] / data_number,2) * 100) + "%"
- # "ratio": Utils.classify(i['count_number'], data_number)
- # }
- # new_dict.update(i)
- # data_list.append(new_dict)
- # return data_list, data_number
- # 查看分组数据
+ # 查看分组数据
data = self.execute(sql_all).fetchall()
# 计算总数
data_number = sum([i[0] for i in data])
@@ -129,7 +115,7 @@ class BllMedicament(Repository):
return self.queryPage(orm_query, pageParam)
# 试剂管理
- def get_drug_list(self, client_id, seach_word, page_param):
+ def get_drug_list(self, client_id, seach_word, b_code, func_type, page_param):
filter_base = ""
if client_id:
filter_base += f" client_id='{client_id}' "
@@ -137,7 +123,35 @@ class BllMedicament(Repository):
seach_word = f"%{seach_word}%"
if filter_base:
filter_base += " and "
- filter_base += f" `name` like '{seach_word}' or english_name like '{seach_word}' "
+ filter_base += f" (`name` like '{seach_word}' or english_name like '{seach_word}') "
+ # 搜索bar_code
+ # if b_code:
+ # if len(b_code) > 10:
+ # new_code = ''
+ # for i in range(int(len(b_code) / 2)):
+ # new_code = b_code[i*2:(i+1)*2] + new_code
+ # else:
+ # new_code = b_code
+ # new_code = f"%{new_code}%"
+ # if filter_base:
+ # filter_base += " and "
+ # filter_base += f" bar_code like '{new_code}' "
+ if filter_base:
+ if len(seach_word) > 10:
+ new_code = ''
+ for i in range(int(len(seach_word) / 2)):
+ new_code = seach_word[i*2:(i+1)*2] + new_code
+ else:
+ new_code = seach_word
+ new_code = f"%{new_code}%"
+ if filter_base:
+ filter_base += " and "
+ filter_base += f" (bar_code like '{new_code}' or bar_code like '{seach_word}' )"
+ if func_type:
+ if filter_base:
+ filter_base += " and "
+ filter_base += f" func_type='{func_type}'"
+
if filter_base:
filter_base = f" where {filter_base}"
sql_all = f"""
@@ -150,37 +164,38 @@ class BllMedicament(Repository):
page_param.totalRecords=count_number
page_sql = Utils.sql_paging_assemble(sql_all, page_param)
return self.execute(page_sql).fetchall()
-
+
# 选择药剂入库--试剂详情
- def get_drug_info_distinct_list(self, seach_word, page_param, client_id=None):
- sql_all = """
- select * from rms_medicament %s
- """
- # 分组查询
- group_base = " group by `name`, purity, speci"
+ def get_drug_info_distinct_list(self, seach_word, func_type, page_param, client_id=None):
# 动态添加查询条件
- where_base = ""
+ filter_base = ""
if client_id:
- where_base += f"client_id='{client_id}'"
+ filter_base += f"client_id='{client_id}'"
if seach_word:
seach_word = f"%{seach_word}%"
- if where_base:
- where_base += " and"
- where_base += f" `name` like '{seach_word}' or english_name like '{seach_word}' "
- if where_base:
- where_base = f"where {where_base} "
- # 组装最终sql
- run_sql = sql_all % where_base+group_base
+ if filter_base:
+ filter_base += " and"
+ filter_base += f" (`name` like '{seach_word}' or english_name like '{seach_word}') "
+ if func_type:
+ if filter_base:
+ filter_base += " and"
+ filter_base += f" func_type='{func_type}' "
+ if filter_base:
+ filter_base = f" where {filter_base}"
+
+ sql_all = f"""
+ select * from rms_medicament {filter_base} group by `name`, purity, speci order by put_in_date desc
+ """
try:
- count_number = len(self.execute(run_sql).fetchall())
+ count_number = len(self.execute(sql_all).fetchall())
except Exception:
count_number = 0
page_param.totalRecords = count_number
# 分页sql
- run_sql = Utils.sql_paging_assemble(run_sql, page_param)
- run_sql_data = self.execute(run_sql).fetchall()
+ page_sql = Utils.sql_paging_assemble(sql_all, page_param)
+
+ return self.execute(page_sql).fetchall()
- return run_sql_data
# 药剂入库
def drugPutIn(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()):
@@ -274,20 +289,9 @@ class BllMedicament(Repository):
self.commitTrans()
# 获取领用和归还页面列表
- def drug_use_return(self, status, page_param):
- # sql_all = """
- # select * from rms_medicament %s
- # """
- # sql_all = sql_all % (f"where status={status}", )
-
- # count_sql = f"SELECT count(*) FROM rms_medicament where status={status}"
- # page_param.totalRecords = self.execute(count_sql).fetchone()[0]
- # sql_all = Utils.sql_paging_assemble(sql_all, page_param)
- # data_list = self.execute(sql_all).fetchall()
- # count_sql = f"SELECT count(*) FROM rms_medicament where status={status}"
- # page_param.totalRecords = self.execute(count_sql).fetchone()[0]
+ def drug_use_return(self, status, func_type, page_param):
sql_all = f"""
- select * from rms_medicament where status={status} order by by_user_date desc
+ select * from rms_medicament where status={status} and func_type='{func_type}' order by by_user_date desc
"""
try:
count_number = len(self.execute(sql_all).fetchall())
@@ -298,45 +302,18 @@ class BllMedicament(Repository):
data_list = self.execute(sql_all).fetchall()
return data_list
-
+
# 获取库存信息总览
- def get_stock_all_info(self, page_param, name=None):
- # sql_all = """
- # select DISTINCT `name`, speci, cas_number,net_weight_unit, purity, client_id,
- # sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) count_number,
- # sum(CASE WHEN `status`=1 THEN remain ELSE 0 END) sum_remain
- # FROM rms_medicament %s
- # """
- # # 拼接查询条件及分组条件
- # filter_base = ""
- # if name:
- # filter_base = f" where `name` LIKE '%{name}%'"
- # filter_base += " GROUP BY `name`, speci, purity"
- # sql_all = sql_all % filter_base
-
- # # 首次查询,判断长度,做分页使用
- # try:
- # count_number = len(self.execute(sql_all).fetchall())
- # except Exception:
- # count_number = 0
- # page_param.totalRecords = count_number
-
- # # 组件分页参数,返回分页后数据
- # sql_all = Utils.sql_paging_assemble(sql_all, page_param)
- # sql_data = self.execute(sql_all).fetchall()
-
- # return sql_data
+ def get_stock_all_info(self, page_param, func_type, name=None):
filter_base = ""
if name:
filter_base = f" `name` LIKE '%{name}%'"
+ if func_type:
+ if filter_base:
+ filter_base += " and "
+ filter_base += f" func_type='{func_type}' "
if filter_base:
filter_base = f" where {filter_base}"
- # sql_all =f"""
- # select DISTINCT `name`, speci, cas_number,net_weight_unit, purity, client_id,
- # sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) count_number,
- # sum(CASE WHEN `status`=1 THEN remain ELSE 0 END) sum_remain
- # FROM rms_medicament {filter_base} GROUP BY `name`, speci, purity order by put_in_date desc
- # """
sql_all =f"""
select DISTINCT
`name`, speci, cas_number,net_weight_unit, purity,
@@ -347,9 +324,6 @@ class BllMedicament(Repository):
sum(CASE WHEN `status`=1 THEN remain ELSE 0 END) sum_remain
FROM rms_medicament {filter_base} GROUP BY `name`, speci, purity order by put_in_date desc
"""
- # 拼接查询条件及分组条件
-
-
# 首次查询,判断长度,做分页使用
try:
count_number = len(self.execute(sql_all).fetchall())
@@ -360,56 +334,10 @@ class BllMedicament(Repository):
page_param.totalRecords = count_number
sql_all = Utils.sql_paging_assemble(sql_all, page_param)
return self.execute(sql_all).fetchall()
- #获取所有药剂列表
- def getAllDrugList(self, search_word, manufacturer, start_time, end_time, page_param, customer_id=None, client_id=None):
- # # (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord)
- # sql_all = """
- # select `name`, bar_code, status, speci, manufacturer, distributor, net_weight_unit, remain, production_date, expiration_date,
- # shelf_life, put_in_user_name, put_in_date, english_name, purity, is_supervise, by_user_name
- # from rms_medicament %s
- # """
- # # manufacturer = manufacturer,
- # # start_time = start_time,
- # # end_time = end_time,
- # # 动态添加查询条件
- # filter_base = ""
- # if customer_id:
- # filter_base = f"customer_id='{customer_id}'"
- # if client_id:
- # if filter_base:
- # filter_base += " and "
- # filter_base += f"client_id='{client_id}'"
- # # 名称搜索
- # if search_word:
- # seach_w = f"%{search_word}%"
- # if filter_base:
- # filter_base += " and "
- # filter_base += f" `name` like '{seach_w}' or english_name like '{seach_w}' or manufacturer like '{seach_w}'"
- # # 厂商搜索
- # if manufacturer:
- # manufacturer = f"%{manufacturer}%"
- # if filter_base:
- # filter_base += " and "
- # filter_base += f"manufacturer like '{manufacturer}'"
- # # 时间范围搜索
- # if start_time and end_time:
- # if filter_base:
- # filter_base += " and "
- # filter_base += f"put_in_date >= '{start_time}' and put_in_date<='{end_time}'"
- # if filter_base:
- # filter_base = "where " + filter_base
- # sql_all = sql_all % filter_base
- # # 获取数量做分页
- # try:
- # count_number= len(self.execute(sql_all).fetchall())
- # except Exception:
- # count_number = 0
- # page_param.totalRecords = count_number
- # # 进行分页sql拼接
- # sql_all = Utils.sql_paging_assemble(sql_all, page_param)
- # return self.execute(sql_all).fetchall()
- # (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord)
+ #获取所有药剂列表
+ def getAllDrugList(self, search_word, manufacturer, start_time, end_time, func_type, page_param, customer_id=None, client_id=None, client_speci=None):
+ # (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord)
filter_base = ""
if customer_id:
filter_base = f"customer_id='{customer_id}'"
@@ -435,15 +363,23 @@ class BllMedicament(Repository):
filter_base += " and "
filter_base += f"put_in_date >= '{start_time}' and put_in_date<='{end_time}'"
# 管理模块区分
+ if func_type:
+ if filter_base:
+ filter_base += " and "
+ filter_base += f" func_type='{func_type}'"
if filter_base:
filter_base = "where " + filter_base
# select * from rms_medicament {filter_base}
+ #TODO 添加房间筛选
+ filter_base1 = ""
+ # if client_speci:
+ # filter_base1 += f"where client_speci='{client_speci}'"
sql_all = f"""
select a.*,b.client_name from (
select * from rms_medicament {filter_base}
) a LEFT JOIN(
- select client_id,client_name from rms_client
+ select client_id,client_name from rms_client {filter_base1}
) b on a.client_id=b.client_id
where client_name is not null
order by put_in_date desc
@@ -466,44 +402,7 @@ class BllMedicament(Repository):
return self.execute(sql_all).fetchall()
# 入库、领用、归还记录
- def drug_show_type_info(self, record_type, start_time, end_time, put_in_user_name, name, statue_type, page_param):
- # sql_all = """
- # SELECT
- # b.`name`, b.english_name, b.bar_code, b.purity, b.cas_number, b.speci, 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, speci, 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}"
-
- # 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}'"
- # filter_sql_1 = ''
- # if statue_type:
- # filter_sql_1 = f" where `status`={statue_type}"
- # if name:
- # name = f"%{name}%"
- # if filter_sql_1:
- # filter_sql_1 += " and"
- # else:
- # filter_sql_1 += " where "
- # filter_sql_1 += f" `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"]
- # try:
- # count_number = len(self.execute(sql_all).fetchall())
- # except Exception:
- # count_number = 0
- # page_param.totalRecords = count_number
- # sql_all_page = Utils.sql_paging_assemble(sql_all, page_param)
- # return self.execute(sql_all_page).fetchall()
+ def drug_show_type_info(self, record_type, start_time, end_time, put_in_user_name, name, func_type, statue_type, page_param):
filter_base1 = f" WHERE record_type={record_type} "
if put_in_user_name:
filter_base1 += f" and create_user_name like '%{put_in_user_name}%'"
@@ -519,6 +418,11 @@ class BllMedicament(Repository):
if filter_base2:
filter_base2 += " and "
filter_base2 = f" `status`={statue_type}"
+
+ if func_type:
+ if filter_base2:
+ filter_base2 += " and "
+ filter_base2 += f" func_type='{func_type}' "
if filter_base2:
filter_base2 = f" where {filter_base2}"
sql_all = f"""
@@ -547,13 +451,20 @@ class BllMedicament(Repository):
sql_all = Utils.sql_paging_assemble(sql_all, page_param)
return self.execute(sql_all).fetchall()
-
- # #获取指定用户当前领用药剂
- # def getUserUseDrugList(self, userId):
-
- # drugList = self.findList(
- # EntityMedicament.ByUserId == userId, EntityMedicament.Status == DrugStatus.Out).all()
- # return drugList
+ def client_room_number(self):
+ sql_all = """
+ select
+ sum(record_num) value, client_speci name
+ from (
+ select medicament_id, client_id from rms_medicament
+ ) as a LEFT JOIN(
+ SELECT count(*) record_num, medicament_id FROM rms_medicament_record WHERE record_type=2 GROUP BY medicament_id
+ ) as b on a.medicament_id=b.medicament_id LEFT JOIN
+ rms_client as c on a.client_id=c.client_id
+ GROUP BY client_speci
+ HAVING client_speci is not null
+ """
+ return self.execute(sql_all).fetchall()
def inster_log_shiji(self):
import random
diff --git a/db_logic/medicament_extend.py b/db_logic/medicament_extend.py
index d87dd8e..664d2b7 100644
--- a/db_logic/medicament_extend.py
+++ b/db_logic/medicament_extend.py
@@ -19,9 +19,9 @@ class BllMedicamentExtend(Repository):
super().__init__(entityType)
- def get_list(self, page_param):
- sql_all = """
- select id, name, description,key_lenth, sort_index, is_use from rms_medicament_extend where is_del=0 order by sort_index
+ def get_list(self, func_type, page_param):
+ sql_all = f"""
+ select id, name, description,key_lenth, sort_index, is_use from rms_medicament_extend where func_type='{func_type}' and is_del=0 order by sort_index
"""
try:
count_number = len(self.execute(sql_all).fetchall())
@@ -32,8 +32,15 @@ class BllMedicamentExtend(Repository):
page_sql = Utils.sql_paging_assemble(sql_all, page_param)
return self.execute(page_sql).fetchall()
- def get_use_list(self):
- sql_all = """
- select id, name, description,key_lenth, sort_index, is_use from rms_medicament_extend where is_del=0 and is_use=1 order by sort_index
+ def get_use_list(self, func_type):
+ sql_all = f"""
+ select id, name, description,key_lenth, sort_index, is_use from rms_medicament_extend where func_type='{func_type}' and is_del=0 and is_use=1 order by sort_index
"""
- return self.execute(sql_all).fetchall()
\ No newline at end of file
+ return self.execute(sql_all).fetchall()
+
+ def random_inster_func_type(self):
+ import random
+ data_list = self.findList().all()
+ for i in data_list:
+ setattr(i, "func_type", random.randint(1,4))
+ self.update(i)
\ No newline at end of file
diff --git a/db_logic/medicament_label.py b/db_logic/medicament_label.py
new file mode 100644
index 0000000..5b0c611
--- /dev/null
+++ b/db_logic/medicament_label.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+'''
+@Date:2022/09/09 16:22:25
+'''
+import sys
+sys.path.append('.')
+
+from db_logic.db_base import Repository
+
+from models.medicament_models import EntityMedicamentLabel
+
+from Common.Utils import Utils
+
+
+class BllMedicamentLabel(Repository):
+ def __init__(self, entityType=EntityMedicamentLabel):
+ return super().__init__(entityType)
+
+ def get_attribute_label_list_info(self):
+ sql_all = """
+ SELECT DISTINCT description FROM `rms_medicament_label`
+ """
+ return self.execute(sql_all).fetchall()
+
+
+ def get_seach_list(self, seach_word, page_param):
+ filter_base = ""
+ if seach_word:
+ seach_word = f"%{seach_word}%"
+ filter_base += f" name like '{seach_word}' "
+
+ if filter_base:
+ filter_base = f" where {filter_base}"
+ sql_all = f"""
+ select * from rms_medicament_label {filter_base}
+ """
+ try:
+ count_number = len(self.execute(sql_all).fetchall())
+
+ except:
+ count_number = 0
+ page_param.totalRecords = count_number
+ page_sql = Utils.sql_paging_assemble(sql_all, page_param)
+ return self.execute(page_sql).fetchall()
diff --git a/db_logic/medicament_record.py b/db_logic/medicament_record.py
index ef185b6..12c0f2f 100644
--- a/db_logic/medicament_record.py
+++ b/db_logic/medicament_record.py
@@ -30,40 +30,25 @@ class BllMedicamentRecord(Repository):
# 获取流转记录
- def get_drug_flow_log(self, medicament_id, page_param):
- # filter_base = ""
- # if medicament_id:
- # filter_base += f" medicament_id='{medicament_id}' "
- # if filter_base:
- # filter_base = f" where {filter_base}"
- # sql_all = f"""
- # select a.`name`, a.speci, a.bar_code, a.cas_number, a.purity, a.client_id, a.`status`, b.create_date, b.create_user_name from(
- # select medicament_id, `name`, speci, bar_code, cas_number, purity, client_id, `status` from rms_medicament
- # ) a RIGHT JOIN(
- # select medicament_id, create_date, create_user_id, create_user_name from rms_medicament_record {filter_base} order by create_date desc
- # ) b on b.medicament_id=a.medicament_id
- # """
- # # count_sql = "select count(*) from rms_medicament_record"
- # try:
- # count_number = len(self.execute(sql_all).fetchall())
- # except Exception:
- # count_number = 0
- # page_param.totalRecords = count_number
- # sql_all = Utils.sql_paging_assemble(sql_all, page_param)
- # return self.execute(sql_all).fetchall()
+ def get_drug_flow_log(self, medicament_id, func_type, page_param):
filter_base = ""
if medicament_id:
filter_base += f" medicament_id='{medicament_id}' "
+ # if func_type:
+ # if filter_base:
+ # filter_base += " and "
+ # filter_base += f" func_type='{func_type}' "
if filter_base:
filter_base = f" where {filter_base}"
sql_all = f"""
- select a.*, b.create_date, b.create_user_name, b.record_type from(
- select medicament_id, create_date, create_user_id, create_user_name, record_type from rms_medicament_record {filter_base}
+ select a.*, b.create_date, b.create_user_name from(
+ select medicament_id, create_date, create_user_id, create_user_name from rms_medicament_record {filter_base}
) b LEFT JOIN(
select * from rms_medicament {filter_base}
) a on b.medicament_id=a.medicament_id order by create_date desc
"""
+ # count_sql = "select count(*) from rms_medicament_record"
try:
count_number = len(self.execute(sql_all).fetchall())
except Exception:
@@ -72,78 +57,19 @@ class BllMedicamentRecord(Repository):
sql_all = Utils.sql_paging_assemble(sql_all, page_param)
return self.execute(sql_all).fetchall()
- # #获取指定用户流转记录
- # 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):
- # sql_all = """
- # SELECT
- # record_type, count(record_id) type_number
- # FROM rms_medicament_record
- # where TO_DAYS(create_date)=TO_DAYS(NOW()) %s
- # GROUP BY record_type
- # """
- # filter_base =""
- # # if customer_id:
- # # filter_base += f" and customer_id='{customer_id}'"
- # # if client_id:
- # # if filter_base:
- # # filter_base += " and "
- # # filter_base += f"client_id='{client_id}'"
- # sql_all = sql_all % filter_base
- # sql_data = self.execute(sql_all).fetchall()
- # n_a, n_b = 0,0
- # data_list = []
- # default_list = [(1,0),(2,0),(3,0)]
- # sql_data = sql_data if sql_data else default_list
- # for i in sql_data:
- # if i[0] == 2:
- # n_a = i[1]
- # if i[0] == 3:
- # n_b = i[1]
- # data_list.append({
- # "record_type":i[0],
- # "type_number":i[1]
- # })
- # data_list.append(
- # {
- # "record_type":100,
- # "type_number": n_a - n_b
- # }
- # )
- # return data_list
+ def getTodayDrugRecordCount(self, func_type):
sql_all = f"""
SELECT
record_type, count(record_id) type_number
FROM rms_medicament_record as a LEFT JOIN rms_medicament as b on a.medicament_id=b.medicament_id
- where TO_DAYS(create_date)=TO_DAYS('{Utils.get_str_datetime()}')
+ where TO_DAYS(create_date)=TO_DAYS('{Utils.get_str_datetime()}') and func_type='{func_type}'
GROUP BY record_type
"""
- # filter_base =""
- # if customer_id:
- # filter_base += f" and customer_id='{customer_id}'"
- # if client_id:
- # if filter_base:
- # filter_base += " and "
- # filter_base += f"client_id='{client_id}'"
- # sql_all = sql_all % filter_base
sql_data = self.execute(sql_all).fetchall()
- n_c = self.execute(f"select count(*) num from rms_medicament where `status`= 2").fetchone().num
+ n_c = self.execute(f"select count(*) num from rms_medicament where `status`= 2 and func_type={func_type}").fetchone().num
data_list = []
default_list = [(1,0),(2,0),(3,0)]
sql_data = sql_data if sql_data else default_list
@@ -166,7 +92,7 @@ class BllMedicamentRecord(Repository):
select `name`, medicament_id from rms_medicament
) a RIGHT JOIN(
select medicament_id, create_date, record_type from rms_medicament_record WHERE record_type=%s ORDER BY create_date desc LIMIT 1
- ) b on a.medicament_id=b.medicament_id
+ ) b on a.medicament_id=b.medicament_id
"""
sql_list = []
for record_type in record_type_list:
@@ -178,28 +104,10 @@ class BllMedicamentRecord(Repository):
return self.execute(sql_all).fetchall()
# 获取报表统计主页,使用频率
- def get_use_avg_number(self):
- # sql_all = """
- # select a.`name`, IFNULL(b.count_number ,0) count_number from (
- # select medicament_id, purity, `name`, speci from rms_medicament
- # ) a LEFT JOIN(
- # select medicament_id, count(record_id) count_number from rms_medicament_record where record_type=2 GROUP BY medicament_id
- # ) b
- # on a.medicament_id=b.medicament_id GROUP BY a.purity, a.`name`, a.speci ORDER BY count_number desc
- # """
- # sql_data = self.execute(sql_all).fetchall()
- # use_number = sum([float(i[1]) for i in sql_data])
- # drug_num = len(sql_data)
-
- # resp_data = {
- # "avg_use_number": round(use_number / drug_num),
- # "max_name": sql_data[0][0],
- # "max_number": sql_data[0][1]
- # }
- # return resp_data
+ def get_use_avg_number(self, func_type):
sql_all = f"""
select a.`name`, IFNULL(b.count_number ,0) count_number from (
- select medicament_id, purity, `name`, speci from rms_medicament
+ select medicament_id, purity, `name`, speci from rms_medicament where func_type='{func_type}'
) a LEFT JOIN(
select medicament_id, count(record_id) count_number from rms_medicament_record where record_type=2 GROUP BY medicament_id
) b
@@ -224,34 +132,13 @@ class BllMedicamentRecord(Repository):
return resp_data
# 获取报表统计主页入库记录信息
- def get_drug_record_count(self):
- # sql_all = """
- # select COUNT(record_id) count_number, record_type from rms_medicament_record GROUP BY record_type
- # """
- # # 获取分类数量
- # data = self.execute(sql_all).fetchall()
- # data_li = Utils.msyql_table_model(data)
- # data_list = []
- # # 获取时间维度最后一条名称及时间
- # name_info_list = self.get_drug_log_time_name([1,2,3])
- # name_info_dict = {}
- # for name in name_info_list:
- # name_info_dict[name[-1]] = name
- # # 组装数据
- # for i in data_li:
- # name_info = name_info_dict.get(i['record_type'])
- # new_dic = {
- # "name": name_info[0],
- # "date_time": name_info[2]
- # }
- # new_dic.update(**i)
- # data_list.append(new_dic)
- # return data_list, self.get_use_avg_number()
+ def get_drug_record_count(self, func_type):
+ # select COUNT(record_id) count_number, record_type from rms_medicament_record GROUP BY record_type
sql_all = f"""
select count(record_id) count_number, record_type from (
select record_id,medicament_id, record_type from rms_medicament_record
) as a LEFT JOIN
- rms_medicament as b on a.medicament_id=b.medicament_id
+ rms_medicament as b on a.medicament_id=b.medicament_id where func_type='{func_type}'
GROUP BY record_type
"""
# 获取分类数量
@@ -283,18 +170,13 @@ class BllMedicamentRecord(Repository):
"date_time":""
}
)
- return data_list, self.get_use_avg_number()
+ return data_list, self.get_use_avg_number(func_type)
# 获取报表统计主页试剂用量消耗
- def report_home_drug_useing_classify(self):
- # select a.count_id count_number, b.`name` from (
- # select count(record_id) count_id, medicament_id from rms_medicament_record GROUP BY medicament_id
- # ) a LEFT JOIN(
- # select `name`, medicament_id from rms_medicament
- # ) b on a.medicament_id=b.medicament_id
- sql_all = """
- select a.`name`, sum(b.count_id) count_num from (
- select `name`, medicament_id, speci, purity from rms_medicament) a LEFT JOIN(
+ def report_home_drug_useing_classify(self, func_type):
+ sql_all = f"""
+ select a.`name`, IFNULL(sum(b.count_id),0) count_num from (
+ select `name`, medicament_id, speci, purity from rms_medicament where func_type='{func_type}') a LEFT JOIN(
select count(record_id) count_id, medicament_id from rms_medicament_record GROUP BY medicament_id
)b on a.medicament_id=b.medicament_id GROUP BY `name`, speci, purity
"""
@@ -310,39 +192,24 @@ class BllMedicamentRecord(Repository):
data_li = Utils.msyql_table_model(data)
data_list = []
for i in data_li:
- if i["count_num"] is None:
- i["count_num"] = 0
if data_number == 0:
- ratio = "0%"
+ ratio = 0
else:
ratio = Utils.classify(i["count_num"], data_number)
new_dic = {
"ratio": ratio
-
}
if i["count_num"] == 0:
- i["count_num"] = ''
+ count_num = ''
else:
- i["count_num"] = int(i["count_num"])
+ count_num = int(i["count_num"])
+ i["count_num"] = count_num
new_dic.update(**i)
data_list.append(new_dic)
return data_list
# 获取报表统计主页人员用量消耗
- def report_home_user_use_info(self):
- # sql_all = """
- # select a.count_id count_number, a.create_user_id, a.create_user_name, b.avatar_url from(
-
- # select count(record_id) count_id, create_user_id,create_user_name from rms_medicament_record GROUP BY create_user_id
- # ) a LEFT JOIN(
-
- # select avatar_url, user_id from rms_user
- # ) b on a.create_user_id= b.user_id
-
- # """
- # data = self.execute(sql_all).fetchall()
- # data_list = Utils.msyql_table_model(data)
- # return data_list
+ def report_home_user_use_info(self, func_type):
sql_all = f"""
select a.count_id count_number, a.create_user_id, a.create_user_name, b.avatar_url from(
select count(record_id) count_id, create_user_id,create_user_name from
@@ -350,11 +217,11 @@ class BllMedicamentRecord(Repository):
LEFT JOIN
rms_medicament as d
on c.medicament_id=d.medicament_id
+ where func_type='{func_type}'
GROUP BY create_user_id
) a LEFT JOIN(
select avatar_url, user_id from rms_user
) b on a.create_user_id= b.user_id
- order by count_number desc
"""
data = self.execute(sql_all).fetchall()
@@ -385,47 +252,15 @@ class BllMedicamentRecord(Repository):
return data_list, base_num
# 获取库存消耗数据
- def durg_stock_loss(self, seach_word, start_time, end_time, page_param):
- # sql_all = """
- # select c.`name`, c.cas_number,c.speci, 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`=2 THEN 1 ELSE 0 END) up_stock,
- # sum(CASE WHEN c.`status`=3 THEN 1 ELSE 0 END) no_stock
- # from (
- # select a.*, b.enter_stock from (
- # select medicament_id, `name`, cas_number, speci, purity, net_weight_unit, `status` from rms_medicament
- # %s
- # ) a LEFT JOIN(
- # SELECT medicament_id, sum(CASE WHEN record_type=1 THEN 1 ELSE 0 END) enter_stock from rms_medicament_record %s GROUP BY medicament_id
- # ) b on b.medicament_id = a.medicament_id
- # ) c GROUP BY `name`, purity, speci
-
- # """
- # # 拼接搜索条件
- # filter_base1 = ""
- # if seach_word:
- # seach_word = f"%{seach_word}%"
- # filter_base1 = f" where `name` like '{seach_word}' or english_name like '{seach_word}'"
- # filter_base2 = ""
- # if start_time and end_time:
- # filter_base2 += f" where create_date >= '{start_time}' and create_date <= '{end_time}'"
-
- # sql_all = sql_all % (filter_base1, filter_base2)
- # # 查询获取数据条目数
- # try:
- # count_number = len(self.execute(sql_all).fetchall())
- # except Exception:
- # count_number = 0
- # page_param.totalRecords = count_number
- # # 数据分页处理
- # sql_all = Utils.sql_paging_assemble(sql_all, page_param)
- # # 获取处理后的数据
- # data_list, _ = self.default_data_list(sql_all)
- # return data_list
+ def durg_stock_loss(self, seach_word, func_type, page_param):
filter_base = ""
if seach_word:
seach_word = f"%{seach_word}%"
filter_base += f" (`name` like '{seach_word}' or english_name like '{seach_word}') "
+ if func_type:
+ if filter_base:
+ filter_base += " and "
+ filter_base += f" func_type='{func_type}'"
if filter_base:
filter_base = f" where {filter_base}"
sql_all = f"""
@@ -457,53 +292,16 @@ class BllMedicamentRecord(Repository):
return data_list
# 试剂用量消耗
- def durg_useing_info(self, seach_word, start_time, end_time, page_param):
+ def durg_useing_info(self, seach_word, func_type, page_param):
# 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 %s GROUP BY medicament_id
-
- # sql_all = """
- # select c.`name`, c.purity, c.speci, c.cas_number, c.net_weight_unit,
- # sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) on_in,
- # IFNULL(c.c_two,0) use_num,
- # IFNULL(c.sum_use,0) use_level from (
- # select a.*, b.c_two, b.sum_use from(
- # select medicament_id, `name`, speci, cas_number, purity, net_weight_unit, `status` from rms_medicament
- # %s
- # ) a LEFT JOIN(
- # select medicament_id, FORMAT(sum(use_quantity),2) sum_use, count(record_id) c_two from rms_medicament_record where record_type=2 %s GROUP BY medicament_id
- # ) b on a.medicament_id=b.medicament_id
- # ) c GROUP BY `name`, purity, speci
- # """
- # # 拼接查询条件
- # filter_base1 = ""
- # if seach_word:
- # seach_word = f"%{seach_word}%"
- # filter_base1 = f"where `name` like '{seach_word}' or english_name like '{seach_word}'"
- # filter_base2 = ""
- # if start_time and end_time:
- # filter_base2 = f" and create_date >= '{start_time}' and create_date <= '{end_time}'"
-
- # sql_all = sql_all %(filter_base1, filter_base2)
-
- # # 获取数量
- # try:
- # count_number = len(self.execute(sql_all).fetchall())
- # except Exception:
- # count_number = 0
- # page_param.totalRecords = count_number
- # page_sql_all = Utils.sql_paging_assemble(sql_all, page_param)
- # # 获取组建后的数据结果
- # data, ratio_all = self.default_data_list(page_sql_all, "use_level")
- # # 拼接百分比数据
- # for i in data:
- # try:
- # i["ratio"] = Utils.classify(i["use_level"], ratio_all)
- # except Exception:
- # i["ratio"] = "0%"
- # return data
filter_base = ""
if seach_word:
seach_word = f"%{seach_word}%"
filter_base += f" (`name` like '{seach_word}' or english_name like '{seach_word}') "
+ if func_type:
+ if filter_base:
+ filter_base += " and "
+ filter_base += f" func_type='{func_type}'"
if filter_base:
filter_base = f" where {filter_base}"
sql_all = f"""
@@ -533,55 +331,9 @@ class BllMedicamentRecord(Repository):
except Exception:
i["ratio"] = "0%"
return data
+
# 人员用量消耗
- def user_use_info(self, page_param, start_time, end_time, seach_user=None):
- # # sql_all = """
- # # select c.by_user_name, c.by_user_id, c.sum_use use_number, IFNULL(c.c_two, 0) use_level 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
- # # """
- # sql_all = """
- # select a.*, b.role_name from (
- # select convert(sum(use_quantity), decimal(10,2)) use_amount,
- # sum( CASE WHEN record_type = 2 THEN 1 ELSE 0 END ) use_num,
- # create_user_id,
- # create_user_name
- # from rms_medicament_record %s GROUP BY create_user_id
- # ) a LEFT JOIN (
- # SELECT role_name, user_id FROM rms_user
- # ) b on a.create_user_id = b.user_id
- # """
- # # 查询条件组合
- # filter_base = ""
- # if seach_user:
- # filter_base += f"by_user_name like '%{seach_user}%'"
- # if start_time and end_time:
- # if filter_base:
- # filter_base += " and "
- # filter_base += f" create_date >= '{start_time}' and create_date <= '{end_time}'"
- # if filter_base:
- # filter_base = " where " + filter_base
- # sql_all = sql_all % filter_base
- # # 分页总数
- # try:
- # count_number = len(self.execute(sql_all).fetchall())
- # except Exception:
- # count_number = 0
- # page_param.totalRecords = count_number
- # # 数据分页
- # sql_all=Utils.sql_paging_assemble(sql_all, page_param)
- # data, ratio_all = self.default_data_list(sql_all, "use_amount")
- # # 数据处理
- # for i in data:
- # try:
- # i["ratio"] = Utils.classify(i["use_amount"], ratio_all)
- # except Exception:
- # i["ratio"] = "0%"
- # return data
+ def user_use_info(self, page_param, start_time, end_time, func_type, seach_user=None):
filter_base = ""
if seach_user:
filter_base += f" create_user_name like '%{seach_user}%'"
@@ -589,6 +341,10 @@ class BllMedicamentRecord(Repository):
if filter_base:
filter_base += " and "
filter_base += f" create_date >= '{start_time}' and create_date <= '{end_time}'"
+ if func_type:
+ if filter_base:
+ filter_base += " and "
+ filter_base += f" func_type='{func_type}'"
if filter_base:
filter_base = f" where {filter_base}"
@@ -624,49 +380,9 @@ class BllMedicamentRecord(Repository):
except Exception:
i["ratio"] = "0%"
return data
+
# 使用频率
- def use_frequency(self, page_param, start_time, end_time,client_id=None, seach_word=None):
- # sql_all = """
- # select c.`name`, c.purity, c.speci, 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`, speci, 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 %s GROUP BY medicament_id
- # )b on a.medicament_id=b.medicament_id
- # ) c GROUP BY `name`, purity, speci
- # """
- # # 查询条件sql组合
- # filter_base1 = ""
- # if client_id:
- # filter_base1 += f" client_id='{client_id}' "
- # if seach_word:
- # if filter_base1:
- # filter_base1 += "and "
- # seach_word = f"%{seach_word}%"
- # filter_base1 += f" `name` like '{seach_word}' or english_name like '{seach_word}'"
- # if filter_base1:
- # filter_base1 = " where " + filter_base1
- # filter_base2 = ""
- # if start_time and end_time:
- # filter_base2 += f" where create_date >= '{start_time}' and create_date <= '{end_time}'"
-
- # sql_all = sql_all % (filter_base1, filter_base2)
- # # 查询数据列表长度
- # try:
- # count_number = len(self.execute(sql_all).fetchall())
- # except Exception:
- # count_number = 0
- # page_param.totalRecords = count_number
- # # 处理数据
- # sql_all = Utils.sql_paging_assemble(sql_all, page_param)
- # data, _ = self.default_data_list(sql_all)
- # return data
+ def use_frequency(self, page_param, start_time, end_time, func_type,client_id=None, seach_word=None):
filter_base1 = ""
if client_id:
filter_base1 += f" client_id='{client_id}' "
@@ -675,6 +391,10 @@ class BllMedicamentRecord(Repository):
filter_base1 += "and "
seach_word = f"%{seach_word}%"
filter_base1 += f" (`name` like '{seach_word}' or english_name like '{seach_word}') "
+ if func_type:
+ if filter_base1:
+ filter_base1 += "and "
+ filter_base1 += f" func_type='{func_type}' "
if filter_base1:
filter_base1 = " where " + filter_base1
filter_base2 = ""
diff --git a/db_logic/medicament_relation.py b/db_logic/medicament_relation.py
new file mode 100644
index 0000000..2eebaf9
--- /dev/null
+++ b/db_logic/medicament_relation.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+'''
+@Date:2022/09/09 16:22:30
+'''
+import sys
+sys.path.append('.')
+
+
+from db_logic.db_base import Repository
+
+from models.medicament_models import EntityMedicamentRelation
+
+from Common.Utils import Utils
+
+
+class BllMedicamentRelation(Repository):
+ def __init__(self, entityType=EntityMedicamentRelation):
+ return super().__init__(entityType)
+
+ def get_seach_list(self, seach_word, page_param):
+ filter_base = ""
+ if seach_word:
+ seach_word = f"%{seach_word}%"
+ filter_base += f" (name1 like '{seach_word}' or name2 like '{seach_word}' or relation like '{seach_word}') "
+
+ if filter_base:
+ filter_base = f" where {filter_base}"
+ sql_all = f"""
+ select * from rms_medicament_relation {filter_base}
+ """
+ try:
+ count_number = len(self.execute(sql_all).fetchall())
+
+ except:
+ count_number = 0
+ page_param.totalRecords = count_number
+ page_sql = Utils.sql_paging_assemble(sql_all, page_param)
+ return self.execute(page_sql).fetchall()
\ No newline at end of file
diff --git a/db_logic/medicament_template.py b/db_logic/medicament_template.py
index 36431e3..318e3a3 100644
--- a/db_logic/medicament_template.py
+++ b/db_logic/medicament_template.py
@@ -21,10 +21,14 @@ class BllMedicamentTemplate(Repository):
return super().__init__(entityType)
# 获取所有模板列表
- def getAllTemplateList(self, client_id, page_param):
+ def getAllTemplateList(self, client_id, func_type, page_param):
filter_base = ""
if client_id:
filter_base += f" client_id='{client_id}' "
+ if func_type:
+ if filter_base:
+ filter_base += " and "
+ filter_base += f" func_type='{func_type}' "
if filter_base:
filter_base = f" where {filter_base} "
sql_all = f"select * from rms_medicament_template {filter_base} order by create_date desc"
@@ -46,6 +50,7 @@ class BllMedicamentTemplate(Repository):
# return self.execute(sql_all)
+
def inster_base_log(self, asss):
import random, json
li_ba = []
diff --git a/db_logic/module.py b/db_logic/module.py
index 3550725..23abbdb 100644
--- a/db_logic/module.py
+++ b/db_logic/module.py
@@ -33,7 +33,7 @@ class BllModule(Repository):
# if i["module_type"] == "1":
# data["client_manage"].append(i)
# elif i["module_type"] == "2":
- # data["sys_manage"].append(i)
+ # data["drug_manage"].append(i)
# elif i["module_type"] == "3":
# data["standard_manage"].append(i)
# elif i["module_type"] == "4":
@@ -46,7 +46,8 @@ class BllModule(Repository):
"client_manage":[],
"drug_manage": [],
"standard_manage": [],
- "dangerous_manage": [],
+ "consumables_manage": [],
+ "instrument_manage": []
}
for i in sql_data:
if i["module_type"] == "1":
@@ -56,28 +57,12 @@ class BllModule(Repository):
elif i["module_type"] == "3":
data_dict["standard_manage"].append(i)
elif i["module_type"] == "4":
- data_dict["dangerous_manage"].append(i)
+ data_dict["consumables_manage"].append(i)
+ elif i["module_type"] == "5":
+ data_dict["instrument_manage"].append(i)
return data_dict
- def inster_info_list(self):
- obj_list = []
- from demo import data_list
- for i in data_list:
- obj = EntityModule(
- module_type=i.get("ModuleType"),
- module_name=i.get("ModuleName"),
- module_code=i.get("ModuleCode"),
- sort_index=i.get("SortIndex"),
- module_weight=i.get("SortIndex"),
- parent_id=0,
- is_enabled=1,
- create_date=Utils.get_str_datetime(),
- create_user_id='4cea74ee-0d8b-11ed-943e-f47b094925e1',
- create_user_name="admin",
- )
- obj_list.append(obj)
- self.insert_many(obj_list)
if __name__ == '__main__':
from Common.Utils import Utils
diff --git a/db_logic/module_relation.py b/db_logic/module_relation.py
index e669f94..3c50173 100644
--- a/db_logic/module_relation.py
+++ b/db_logic/module_relation.py
@@ -74,7 +74,8 @@ class BllModuleRelation(Repository):
"client_manage":[],
"drug_manage": [],
"standard_manage": [],
- "dangerous_manage": [],
+ "consumables_manage": [],
+ "instrument_manage": [],
}
for i in data:
if i["module_type"] == "1":
@@ -84,41 +85,13 @@ class BllModuleRelation(Repository):
elif i["module_type"] == "3":
data_dict["standard_manage"].append(i)
elif i["module_type"] == "4":
- data_dict["dangerous_manage"].append(i)
+ data_dict["consumables_manage"].append(i)
+ elif i["module_type"] == "5":
+ data_dict["instrument_manage"].append(i)
return data_dict
def get_user_module_list(self, user_info):
- # sql_all = f"""
- # select a.module_id, a.module_name, a.module_type, a.module_code, a.sort_index,
- # CASE WHEN b.object_id is NULL THEN 0 ELSE 1 END have, IFNULL(b.object_type,0) object_type
- # from (
- # select * from rms_module) a LEFT JOIN (
- # select * from rms_module_relation where object_id='{user_info.user_id}' or object_id='{user_info.role_id}'
- # ) b on a.module_id = b.module_id
- # """
- # sql_data = self.execute(sql_all).fetchall()
- # data = Utils.msyql_table_model(sql_data)
- # data_dict = {
- # "client_manage": [],
- # "drug_manage":[],
- # "standard_manage":[],
- # "consumables_manage": [],
- # "instrument_manage":[]
- # }
- # for i in data:
- # if i["module_type"] == "1":
- # data_dict["client_manage"].append(i)
- # elif i["module_type"] == "2":
- # data_dict["drug_manage"].append(i)
- # elif i["module_type"] == "3":
- # data_dict["standard_manage"].append(i)
- # elif i["module_type"] == "4":
- # data_dict["consumables_manage"].append(i)
- # elif i["module_type"] == "5":
- # data_dict["instrument_manage"].append(i)
-
- # return data_dict
sql_all = f"""
select a.module_id, a.module_name, a.module_type, a.module_code, a.sort_index,
CASE WHEN b.object_id is NULL THEN 0 ELSE 1 END have, IFNULL(b.object_type,0) object_type
@@ -131,9 +104,10 @@ class BllModuleRelation(Repository):
data = Utils.msyql_table_model(sql_data)
data_dict = {
"client_manage":[],
- "drug_manage":[],
- "standard_manage":[],
- "dangerous_manage": [],
+ "drug_manage": [],
+ "standard_manage": [],
+ "consumables_manage": [],
+ "instrument_manage": [],
}
for i in data:
if i["module_type"] == "1":
@@ -143,8 +117,9 @@ class BllModuleRelation(Repository):
elif i["module_type"] == "3":
data_dict["standard_manage"].append(i)
elif i["module_type"] == "4":
- data_dict["dangerous_manage"].append(i)
-
+ data_dict["consumables_manage"].append(i)
+ elif i["module_type"] == "5":
+ data_dict["instrument_manage"].append(i)
return data_dict
@@ -185,7 +160,7 @@ class BllModuleRelation(Repository):
return self.execute(page_sql_data).fetchall()
def add_inster_user_moduele(self):
- role_id = "68984021-117b-11ed-8c91-f47b094925e5"
+ role_id = "19535c92-8da4-4645-88c5-9a4ee3fdb22e"
obj_list = []
all_module_list = self.execute("select * from rms_module")
all_module_list = Utils.msyql_table_model(all_module_list)
@@ -196,7 +171,7 @@ class BllModuleRelation(Repository):
module_type=i['module_type'],
module_id=i['module_id'],
create_date=Utils.get_str_datetime(),
- create_user_id='4cea74ee-0d8b-11ed-943e-f47b094925e1',
+ create_user_id='',
create_user_name=''
)
obj_list.append(obj)
diff --git a/db_logic/msds.py b/db_logic/msds.py
index a5d2db9..9fe34bf 100644
--- a/db_logic/msds.py
+++ b/db_logic/msds.py
@@ -30,7 +30,7 @@ class BllMsDs(Repository):
select * from rms_msds {filter_base}
"""
try:
- count_number = len(self.execute(sql_all).fetchall())
+ count_number = self.execute(f"select count(*) num from rms_msds {filter_base}").fetchone().num
except Exception:
count_number = 0
page_param.totalRecords=count_number
diff --git a/db_logic/stock_record.py b/db_logic/stock_record.py
new file mode 100644
index 0000000..c4debfa
--- /dev/null
+++ b/db_logic/stock_record.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+'''
+@Date:2022/09/14 09:54:18
+'''
+import sys
+sys.path.append('.')
+
+from models.medicament_models import EntityStockRecord
+from db_logic.medicament import BllMedicament
+from db_logic.db_base import Repository
+from Common.Utils import Utils
+import json
+
+
+class BllStockRecord(Repository):
+
+ def __init__(self, entityType=EntityStockRecord):
+ return super().__init__(entityType)
+
+
+ def get_list_info(self, page_param, client_id):
+ filter_base = ""
+ if client_id:
+ filter_base += f" client_id='{client_id}'"
+ if filter_base:
+ filter_base = f" where {filter_base} "
+
+ sql_all = f"""
+ select * from rms_stock_record {filter_base}
+ """
+ try:
+ count_number = len(self.execute(sql_all).fetchall())
+ except:
+ count_number = 0
+ page_param.totalRecords = count_number
+ page_sql = Utils.sql_paging_assemble(sql_all, page_param)
+ return self.execute(page_sql).fetchall()
+
+ def set_stock_info(self, client_id, client_code, user_info):
+ # 查询当前在库试剂信息
+ sql_base1 = f"""
+ select name,purity,speci,count(*) stock_num
+ from rms_medicament where client_id='{client_id}' and `status`=1 GROUP BY `name`,purity,speci
+
+ """
+ data_list = Utils.msyql_table_model(self.execute(sql_base1).fetchall())
+ try:
+ total_num = 0
+ for i in data_list:
+ total_num += int(i["stock_num"])
+ obj = EntityStockRecord(
+ user_id=user_info.user_id,
+ create_date=Utils.get_str_datetime(),
+ total=total_num,
+ client_code=client_code,
+ client_id=client_id,
+ medicament_info=json.dumps(data_list)
+ )
+ self.insert(obj)
+ return True
+ except Exception as error:
+ print(error)
+ return False
+
+
+
+
+
+
+
diff --git a/demo.py b/demo.py
index 22e18fd..aef43d0 100644
--- a/demo.py
+++ b/demo.py
@@ -5,7 +5,35 @@
'''
import sys
sys.path.append('.')
+from db_logic.module import BllModule
+from models.power_models import EntityModule
+from Common.Utils import Utils
-from werkzeug.security import check_password_hash, generate_password_hash
+data_list = BllModule().execute("select * from rms_module_copy1 where module_type=2 order by sort_index").fetchall()
+data_list = Utils.msyql_table_model(data_list)
+obj_list = []
+a = 65
+for i in data_list:
+ module_code = i["module_code"]
+ if "Drug" in module_code:
+ module_code = str(module_code).replace("Drug", "Instrument")
+ module_name = i["module_name"]
+ if "试剂" in module_name:
+ module_name = str(module_name).replace("试剂", "仪器")
+ obj = EntityModule(
+ module_type=5,
+ module_code=module_code,
+ module_name=module_name,
+ sort_index=a,
+ module_weight=a,
+ parent_id=0,
+ is_enabled=i['is_enabled'],
+ create_date=Utils.get_str_datetime()
-print(generate_password_hash("11111111"))
+ )
+ a += 1
+ obj_list.append(obj)
+BllModule().insert_many(obj_list)
+print(a)
+
+# print(data_list)
diff --git a/models/medicament_models.py b/models/medicament_models.py
index 768f7f6..ea96250 100644
--- a/models/medicament_models.py
+++ b/models/medicament_models.py
@@ -219,6 +219,77 @@ class EntityMedicamentExtend(Base):
is_del = Column(Integer, default=0, comment="是否删除")
+class EntityMedicamentLabel(Base):
+ __tablename__ = "rms_medicament_label"
+ __table_args__ = (
+ {
+ "comment": "扩展字段备注表"
+ }
+ )
+ variety_id = Column(String(50), primary_key=True,
+ comment="ID", default=get_uuid)
+ name = Column(String(1000), comment="名称")
+ description = Column(Text, comment="描述")
+ is_add = Column(Integer, default=0)
+
+
+class EntityMedicamentRelation(Base):
+ __tablename__ = "rms_medicament_relation"
+ __table_args__ = (
+ {
+ "comment": "扩展字段备注表"
+ }
+ )
+ id = Column(String(50), primary_key=True, comment="ID", default=get_uuid)
+ name1 = Column(String(255), comment="模块类型区分")
+ name2 = Column(String(255), comment="模块类型区分")
+ relation = Column(Text, comment="关系")
+ description = Column(Text, comment="描述")
+ is_add = Column(Integer, default=0)
+
+
+class EntityStockRecord(Base):
+ __tablename__ = "rms_stock_record"
+ __table_args__ = (
+ {
+ "comment": "试剂盘点"
+ }
+ )
+ id = Column(String(50), primary_key=True, comment="ID", default=get_uuid)
+ user_id = Column(String(50), comment="用户id")
+ create_date = Column(String(50), comment="时间")
+ total = Column(Integer, comment="总数")
+ client_code = Column(String(50), comment="柜子码")
+ client_id = Column(String(50), comment="柜子id")
+ medicament_info = Column(Text, comment="试剂详情")
+
+ is_add = Column(Integer, default=0)
+
+class EntityMedicamentMotherLiquor(Base):
+ __tablename__ = "rms_medicament_mother_liquor"
+ __table_args__ = (
+ {
+ "comment": "试剂母液配置管理"
+ }
+ )
+ id = Column(String(50), primary_key=True, comment="ID", default=get_uuid)
+ medicament_id = Column(String(50), comment="试剂id")
+ name = Column(String(255), comment="试剂名称")
+ start_time = Column(String(50), comment="配置日期")
+ end_time = Column(String(50), comment="有效期")
+ purity = Column(String(50), comment="浓度")
+ capacity = Column(String(50), comment="配置量")
+ solvent = Column(String(50), comment="溶剂")
+ basis = Column(Text, comment="配置依据")
+ doc_log = Column(Text, comment="配置记录")
+ user_id = Column(String(50), comment="配置用户id")
+ user_name = Column(String(50), comment="配置用户名称")
+ code_number = Column(String(50), comment="条码")
+ mother_liquor_code = Column(String(50), comment="母液编码")
+ unit_code = Column(Text, comment="单位编号")
+
+
+
if __name__ == '__main__':
drug_info = {}
user_info = {}