申购相关接口更新;

注释添加
duizhaopin
13507605001 2 years ago
parent 0f34cfad26
commit 55094f77d4

@ -0,0 +1,216 @@
#!/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
self.key_list = [
"remark7", "remark8", "category", "remark9",
"name", "english_name","purity","cas_number","standard_code",
"unit_code","speci","net_weight_unit", "export_count","remark6",
"production_date", "shelf_life", "expiration_date",
"price", "is_supervise", "remain", "manufacturer",
"storage_condition", "remark10"
]
self.finds_name = [
"申购单编号","采购单编号", "药剂类别", "所属项目", "药剂名称", "英文名称", "纯度等级", "CAS码", "批号", "编号", "规格", "规格单位", "导入数量",
"导入单位", "生产日期", "保质期(天)", "到期日期", "价格(元)", "重点监管", "预估质量(g/ml)", "生产厂商", "储存条件", "包装是否完好、标签是否清晰"
]
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
# 生成ascii_uppercase生成所有大写字母
self.upper_string = string.ascii_uppercase
# 水平对齐, 居中对齐
self.alignment_style = Alignment(
horizontal='center', vertical='center')
# 定义字体
self.font_size = Font(size=9)
for col in self.upper_string:
self.ws.column_dimensions[col].width = 10
# 创建第三行, 需要传入一个列表用来写入单元格的值
def create_row3(self, data_list):
for data in range(1, len(data_list) + 1):
# 第三行写入值
self.ws.cell(row=1, column=data).value = data_list[data - 1]
# 创建多行固定样式 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 = ""
try:
value = int(value)
self.ws.cell(row=row_number, column=col_).number_format = '0'
except:
pass
self.ws.cell(row=row_number, column=col_).value = value
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, data_list):
# data_list = kwargs.pop("data_list")
key_list = self.key_list
finds_name = self.finds_name
self.set_style(title="Sheet")
self.create_row3(finds_name)
self.create_multiple_rows(2, 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
# if __name__ == '__main__':
# obj = ReportData()
# obj.build_file(data_list=[{"name":"测试试剂123", "shelf_life":5}])
# obj.save("测试表1")
# data_dict = {
# "data_list":[
# {"name": "申购单编号", "purity":"11~15%", "export_count":"2", "production_date":"2023/01/01", "shelf_life": '5'}
# ],
# "key_list": [
# "remark7", "remark8", "category", "remark9",
# "name", "english_name","purity","cas_number","standard_code",
# "unit_code","speci","net_weight_unit", "export_count","remark6",
# "production_date", "shelf_life", "expiration_date",
# "price", "is_supervise", "remain", "manufacturer",
# "storage_condition", "remark10"
# ],
# "finds_name": [
# "申购单编号","采购单编号", "药剂类别", "所属项目", "药剂名称", "英文名称", "纯度等级", "CAS码", "批号", "编号", "规格", "规格单位", "导入数量",
# "导入单位", "生产日期", "保质期(天)", "到期日期", "价格(元)", "重点监管", "预估质量(g/ml)", "生产厂商", "储存条件", "包装是否完好、标签是否清晰"
# ],
# }
# obj = obj.build_file(**data_dict)
# obj.save("测试表")

@ -24,3 +24,30 @@ client_id
bar_code
status
返回类型{"data":"", "msg":"修改成功", "status":0}
申购相关接口
http://127.0.0.1:9001/api/shengou
/get_list
page
page_size
/add
use_doc 申请描述
use_content 申请详情
/update
id 申请单id
use_content 申请详情
/solve
id 申请单id
result 驳回
information 驳回原因
# 下载接口,可参考报表下载接口
/dowload
id 申请id

@ -3,6 +3,7 @@
'''
@Date:2022/07/29 09:03:39
'''
import json
from flask import Blueprint, jsonify, request
from sqlalchemy import and_
from Common.Utils import Utils, PageParam
@ -25,7 +26,7 @@ from models.humiture_models import EntityHumitureRecord
client_router = Blueprint("client", __name__)
# 查看client列表
# 查看client列表全部不分页
@client_router.route("/client_list", methods=["POST"])
@token_auth.login_required
def get_client_list():
@ -35,7 +36,7 @@ def get_client_list():
return jsonify(Utils.true_return(data={"data_list": data_list}))
# 查看列表
# 查看列表分页
@client_router.route("/get_list", methods=["GET","POST"])
@token_auth.login_required
def getclient_list():
@ -66,6 +67,8 @@ def client_add_update():
)
if obj:
for i in finds_list:
if i == "layer_num":
continue
va = request.values.get(i)
if va:
setattr(client_obj, i, va)
@ -74,11 +77,17 @@ def client_add_update():
else:
return jsonify(Utils.false_return(msg="柜体信息有误"))
else:
client_id = Utils.UUID()
client_obj = EntityClient()
for i in finds_list:
va = request.values.get(i)
if va:
setattr(client_obj, i, va)
# 添加柜子信息
setattr(client_obj, "client_id", client_id)
# 添加柜子数量
layer_num = request.values.get("layer_num")
BllClientCell().create_cell_layer(client_id, layer_num)
BllClient().insert(client_obj)
return jsonify(Utils.true_return(msg="添加成功"))
@ -150,7 +159,7 @@ def client_del():
# rms_medicament_extend,rms_medicament, rms_humiture_record
# 清空指定柜体需删除
# rms_medicament_template,rms_medicament_record,rms_medicament, rms_humiture_record
# 清空柜体
@client_router.route("/client_empty", methods=["POST"])
@token_auth.login_required
def client_empty():
@ -310,3 +319,36 @@ def client_user_ban_relieve():
return jsonify(Utils.true_return())
else:
return jsonify(Utils.false_return())
# 获取已创建的位置数据
@client_router.route("/get_client_place", methods=["POST"])
@token_auth.login_required
def get_client_place_list():
func_type = request.values.get("func_type")
data = BllMedicament().execute(
f"select DISTINCT place as `value` from rms_client where place is not null and place != '' and func_type='{func_type}'"
).fetchall()
return jsonify(Utils.true_return(data=Utils.msyql_table_model(data)))
# 获取柜子层列表
@client_router.route("/get_client_layer", methods=["POST"])
@token_auth.login_required
def get_client_layer_list():
client_id = request.values.get("client_id")
data = BllClientCell().execute(f"select * from rms_client_cell where client_id='{client_id}'").fetchall()
return jsonify(Utils.true_return(data=Utils.msyql_table_model(data)))
# 修改柜子层存放试剂数量
@client_router.route("/update_client_storage_quantity", methods=["POST"])
@token_auth.login_required
def update_storage_quantity():
data_info = request.values.get("data_info")
data_dict = json.loads(data_info)
obj = BllClientCell()
for k,v in data_dict.items():
obj_find = obj.findEntity(EntityClientCell.id == k)
if obj_find:
obj_find.storage_quantity = int(v)
obj.update(obj_find)
return jsonify(Utils.true_return())

@ -261,7 +261,7 @@ def drug_set_empty_bottle():
else:
return jsonify(Utils.false_return(msg="试剂id有误"))
# 修改试剂余量
@drug_router.route("/update_drug_remain", methods=["GET", "POST"])
@token_auth.login_required
def update_drug_remain():

@ -326,7 +326,7 @@ def get_file_list():
return jsonify(Utils.true_return(data=data_file_list))
# return jsonify(Utils.true_return(data=os.listdir(file_path)))
# 根据模板id打印标签
@tmp_router.route("/pring_bar_code", methods=["POST"])
@token_auth.login_required
def print_code_data():

@ -12,10 +12,11 @@ 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 = {
# put_in_user_name,category,expiration_date
"1": ["name", "cas_number", "speci", "purity", "count_number", "sum_remain", "manufacturer", "category", "put_in_user_name", "expiration_date"],
"1": ["name", "cas_number", "speci", "purity", "count_number", "manufacturer", "category", "put_in_user_name", "expiration_date"],
"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'],
# "2": ["name", "bar_code", "purity", "speci", "manufacturer", "count_number", "status", "put_in_date", "put_in_user_name", "client_name"],
"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'],
@ -34,6 +35,7 @@ def get_finds_list(tp):
}
return dic.get(str(tp))
# 报表字段,中文展示字段
def get_finds_name_list(tp):
dic = {
"1": ["试剂名称", "CAS码", "规格", "纯度", "在库剩余数量(瓶)", "生产厂家", "试剂分类(易制毒、易制爆、剧毒品)", "入库人", "过期时间"],
@ -55,6 +57,7 @@ def get_finds_name_list(tp):
return dic.get(str(tp))
# 下载方法
def download_file(file_name, data_list, tp):
try:
file_path = os.path.join(os.getcwd(), "report_file")

@ -0,0 +1,136 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date: 2023/01/05 14:10:45
'''
import sys
sys.path.append('.')
import os
import json
from flask import Blueprint, request, jsonify, g
from sqlalchemy import and_, or_
from db_logic.medicament_shengou import BllMedicamntShenGou
from models.medicament_models import EntityMedicamntShenGou
from Common.report_shen_gou import ReportData
from db_logic.user import BllUser
from Common.Utils import Utils, PageParam
from Common.auth import token_auth
from apps.report.dows_utils import dows_flie
shengou_bp = Blueprint("shengou", __name__)
# 展示列表,根据用户角色是否展示全部
@shengou_bp.route("/get_list", methods=["POST"])
@token_auth.login_required
def get_shengou_list():
user = g.current_user
page = request.values.get("page")
page_size = request.values.get("page_size")
page_param = PageParam(int(page), int(page_size))
data = BllMedicamntShenGou().get_list(user=user, page_param=page_param)
user_list = BllUser().findList()
user_dict = {}
for i in user_list:
user_dict[i.user_id] = i.real_name
data_list = []
for i in data:
i_dict = dict(i._mapping)
i_dict['user_name'] = user_dict.get(i_dict["user_id"])
i_dict["solve_user_name"] = user_dict.get(i_dict["solve_user_id"], '')
i_dict["solve_user_pt_name"] = user_dict.get(i_dict["solve_user_id_pt"], '')
data_list.append(i_dict)
return jsonify(Utils.true_return(data= {"data_list":data_list, "total_count": page_param.totalRecords}))
# 创建申请记录
@shengou_bp.route("/add", methods=["POST"])
@token_auth.login_required
def add_drug_shengou():
func_type = request.values.get("func_type")
use_doc = request.values.get("use_doc")
use_content = request.values.get("use_content")
if not use_content:
return jsonify(Utils.false_return(msg='内容为空,无需提交'))
obj = EntityMedicamntShenGou(
user_id = g.current_user.user_id,
create_date = Utils.get_str_datetime(),
is_solve = 0,
use_content = use_content,
func_type=func_type,
use_doc=use_doc
)
BllMedicamntShenGou().insert(obj)
return jsonify(Utils.true_return())
# 修改个人申请
@shengou_bp.route("/update", methods=["POST"])
@token_auth.login_required
def update_shengou():
shengou_id = request.values.get("id")
use_content = request.values.get("use_content")
if not use_content:
return jsonify(Utils.false_return(msg='内容为空,无需提交'))
user = g.current_user
user_apply_obj = BllMedicamntShenGou().findEntity(
and_(
EntityMedicamntShenGou.id == shengou_id,
EntityMedicamntShenGou.user_id == user.user_id
)
)
if not user_apply_obj:
return jsonify(Utils.false_return(msg="只能修改自己的申请!"))
user_apply_obj.use_content=use_content
BllMedicamntShenGou().update(user_apply_obj)
return jsonify(Utils.true_return())
# 处理消息
@shengou_bp.route("/solve", methods=["POST"])
@token_auth.login_required
def solve_shengou():
shengou_id =request.values.get("id")
user_id = g.current_user.user_id
obj = BllMedicamntShenGou().findEntity(EntityMedicamntShenGou.id == shengou_id)
if obj.is_solve == 1:
return jsonify(Utils.false_return(msg="已受理,无需重复受理"))
if str(request.values.get('result')) == "0":
obj.information = request.values.get("information")
obj.is_solve = 2
else:
if not obj.solve_user_id:
obj.solve_user_id = user_id
else:
if user_id == obj.solve_user_id:
return jsonify(Utils.false_return(msg="不能位同一人审批"))
obj.solve_user_id_pt=user_id
obj.is_solve = 1
obj.solve_date = Utils.get_str_datetime()
BllMedicamntShenGou().update(obj)
return jsonify(Utils.true_return())
# 导出申购单
@shengou_bp.route("/dowload", methods=["GET", "POST"])
@token_auth.login_required
def dowload_shengou():
shengou_id = request.values.get("id")
obj = BllMedicamntShenGou().findEntity(EntityMedicamntShenGou.id == shengou_id)
if obj and obj.is_solve == 1:
try:
file_path = os.path.join(os.getcwd(), "report_file")
if not os.path.exists(file_path):
os.makedirs(file_path)
obj_report = ReportData()
obj = obj_report.build_file(json.loads(obj.use_content))
rsp_file_name = f"tem_申购单_{Utils.get_file_name_datetime()}"
obj.save(os.path.join(file_path, rsp_file_name))
# u_path = Utils.getUDiskPath()
# if u_path:
# obj.save(os.path.join(u_path, rsp_file_name))
rep = dows_flie(file_path, rsp_file_name)
return rep
# return jsonify(Utils.true_return())
except Exception as error:
print(error)
return jsonify(Utils.false_return(msg=f"导出错误:{error}"))
return jsonify(Utils.false_return(msg="申购单导出错误"))

@ -14,7 +14,7 @@ from models.user_models import EntityUser
user_router = Blueprint('user', __name__)
# 登录
@user_router.route("/login", methods=["POST"])
# @token_auth.login_required
def user_login():

@ -74,6 +74,7 @@ def register_blueprints(app: New_flask):
from apps.drug_form.views import drug_form_router
from apps.stock_record.views import stock_router
from apps.temporary_auth.views import temporary_bp
from apps.shengou.views import shengou_bp
# 主概览相关
app.register_blueprint(home_router, url_prefix="/api/home")
@ -101,6 +102,8 @@ def register_blueprints(app: New_flask):
app.register_blueprint(stock_router, url_prefix="/api/stock")
# 申请
app.register_blueprint(temporary_bp, url_prefix="/api/temporary_auth")
# 申购
app.register_blueprint(shengou_bp, url_prefix="/api/shengou")
def create_app():
app = Flask(__name__)

@ -33,6 +33,21 @@ class BllClientCell(Repository):
page_sql = Utils.sql_paging_assemble(sql_all, page_param)
return self.execute(page_sql).fetchall()
def create_cell_layer(self, client_id, layer_num):
obj_list = []
for i in range(1, int(layer_num)+1):
obj_list.append(
EntityClientCell(
cell_code = i,
client_id=client_id,
cell_speci=f"{i}号格子",
storage_quantity=50
)
)
self.insert_many(obj_list)
return True
# 插入测试数据
def inster_test_data(self):
client_id = '1c39cb24-07f8-11ed-abd4-f47b094925e1'

@ -8,10 +8,11 @@ sys.path.append('.')
from sqlalchemy import distinct, or_, and_, desc, asc
from sqlalchemy.sql import func
from db_logic.db_base import Repository
from models.medicament_models import EntityMedicament, EntityMedicamentRecord, EntityMedicamentTemplate
from models.medicament_models import EntityMedicament, EntityMedicamentRecord, EntityMedicamentTemplate, EntityVariety
from models.client_models import EntityClient
from models.user_models import EntityUser
from db_logic.meidcament_variety import BllMedicamentVariety
from db_logic.variety import BllVariety
from Common.Utils import Utils, DrugStatus, DrugRecordType
@ -41,25 +42,42 @@ class BllMedicament(Repository):
# 获取可入库层数据
def get_drug_save_db_info(self, drug_name, func_type):
sql_all = f"""
# sql_all = f"""
select name, IFNULL(num,0) number, c.client_name, c.client_id, cell_code, cell_speci from (
select cell_code, a.client_id, cell_speci, client_name from (
select * from rms_client_cell
) a LEFT JOIN(
select client_id, client_name from rms_client
) b on a.client_id = b.client_id
) c LEFT JOIN(
select name, client_id, flow_position_code, count(*) num
from rms_medicament where `name` like '%{drug_name}%' and status=1 and func_type={func_type}
GROUP BY client_id, flow_position_code
) d on c.client_id=d.client_id and c.cell_code=d.flow_position_code
# select name, IFNULL(num,0) number, c.client_name, c.client_id, cell_code, cell_speci from (
# select cell_code, a.client_id, cell_speci, client_name from (
# select * from rms_client_cell
# ) a LEFT JOIN(
# select client_id, client_name from rms_client
# ) b on a.client_id = b.client_id
# ) c LEFT JOIN(
# select name, client_id, flow_position_code, count(*) num
# from rms_medicament where `name` like '%{drug_name}%' and status=1 and func_type={func_type}
# GROUP BY client_id, flow_position_code
# ) d on c.client_id=d.client_id and c.cell_code=d.flow_position_code
# HAVING number < 40
# """
sql_all = f"""
select c.*, d.client_name
from (
select a.cell_code,a.client_id, a.cell_speci, IFNULL(a.storage_quantity,0) storage_quantity, count(b.name) num, IFNULL(GROUP_CONCAT(b.name),'') name_json
from (select * from rms_client_cell) a
LEFT JOIN (select * from rms_medicament) b on a.client_id=b.client_id and a.cell_speci=b.flow_position_code
GROUP BY a.id
) c LEFT JOIN (select * from rms_client where func_type={func_type}) d on c.client_id=d.client_id
where d.client_name is not null
HAVING number < 40
"""
data = self.execute(sql_all).fetchall()
data_list = []
data_dict = {}
for i in data:
if int(i.num) >= int(i.storage_quantity):
continue
# 处理当前试剂是否与试剂柜内的试剂冲突,当前试剂名称,数据库内当前层的试剂列表
# if drug_name in i.name_json.split(","):
# pass
if i.client_id in data_dict.keys():
data_dict[i.client_id]["client_cell"].append(i.cell_speci)
else:
@ -69,8 +87,22 @@ class BllMedicament(Repository):
"client_cell": [i.cell_speci]
}
data_dict[i.client_id] = client_dict
# data_dict = {}
# for i in data:
# if i.client_id in data_dict.keys():
# data_dict[i.client_id]["client_cell"].append(i.cell_speci)
# else:
# client_dict = {
# "client_id": i.client_id,
# "client_name": i.client_name,
# "client_cell": [i.cell_speci]
# }
# data_dict[i.client_id] = client_dict
data_list = []
for k,v in data_dict.items():
DrugSetPotionStorageIn = self.getDrugSetPotionStorageIn(drug_name, k)
if DrugSetPotionStorageIn[0]:
v["conflict"] = DrugSetPotionStorageIn[1]
data_list.append(v)
return data_list
@ -680,6 +712,33 @@ class BllMedicament(Repository):
sql_all = Utils.sql_paging_assemble(sql_all, page_param)
return self.execute(sql_all).fetchall()
def getDrugSetPotionStorageIn(self,name,clientId=""):
#print('clientId',clientId)
allLabelSqlStr="SELECT group_concat(remark3) AS allLabels FROM( SELECT DISTINCT b.remark3 FROM rms_medicament as a LEFT JOIN rms_variety as b ON a.`name`=b.`name` WHERE b.purity='权限设置' and a.status=1 AND a.client_id='"+clientId+"')T"
allLabels= self.execute(allLabelSqlStr).fetchone()[0]
#print('allLabels:',allLabels)
if allLabels:
allLabelList=allLabels.split(',')
drugVarietyEntity= BllVariety().findEntity(and_(EntityVariety.name==name,EntityVariety.purity=='权限设置'))
#print('drugVarietyEntity.Remark3:',drugVarietyEntity.Remark3)
if drugVarietyEntity:
for sx in drugVarietyEntity.remark3.split(','):
#print('sx:',sx)
drugLabelsSqlstr="SELECT name2 AS reagent,relation FROM rms_medicament_relation a WHERE a.name1='"+sx+"' UNION SELECT name1 AS reagent,relation FROM rms_medicament_relation a WHERE a.name2='"+sx+"'"
drugLabelList=self.execute(drugLabelsSqlstr).fetchall()
#print('drugLabelList:',drugLabelList)
for item in drugLabelList:
if(item[0] in allLabelList):
return(False,item[1])
return(True,'')
else:
return(True,'')
else:
return(True,'')
def inster_log_shiji(self):
import random
name_list = ["", "硫酸", "氧化钠"]
@ -705,7 +764,9 @@ class BllMedicament(Repository):
obj_list.append(obj)
self.insert_many(obj_list)
# if __name__ == '__main__':
if __name__ == '__main__':
data = BllMedicament().getDrugSetPotionStorageIn("2-氨基苯酚", '1c39cb24-07f8-11ed-abd4-f47b094925e1')
print(data)
# from db_logic.medicament import BllMedicament
# from Common.Utils import PageParam
# page_param = PageParam(1, 10)

@ -0,0 +1,37 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date: 2023/01/05 14:09:40
'''
import sys
sys.path.append('.')
from db_logic.db_base import Repository
from Common.Utils import Utils
from models.medicament_models import EntityMedicamntShenGou
class BllMedicamntShenGou(Repository):
def __init__(self, entityType=EntityMedicamntShenGou):
return super().__init__(entityType)
def get_list(self, user, page_param):
filter_base = ""
if "管理员" not in user.role_name:
filter_base += f" user_id='{user.user_id}'"
if filter_base:
filter_base = f" where {filter_base}"
sql_all = f"""
select * from rms_medicamnt_shengou {filter_base}
"""
try:
count_number = self.execute(f"select count(*) num from ({sql_all})a ").fetchone().num
except Exception:
count_number = 0
if page_param:
page_param.totalRecords = count_number
sql_all = Utils.sql_paging_assemble(sql_all, page_param)
return self.execute(sql_all).fetchall()

@ -16,6 +16,7 @@ class BllUserApply(Repository):
def __init__(self, entityType=EntityUserApply):
super().__init__(entityType)
# 根据用户角色进行列表返回
def get_list_info(self, func_type, page_param, user):
fileter_base = ""
# if client_id:
@ -71,7 +72,8 @@ class BllUserApply(Repository):
for j in range(len(use_content)):
con_info = use_content[j]
if con_info["client_id"] == client_id:
if con_info["name"] == drug_info.name and con_info["purity"] == drug_info.purity and con_info["speci"] == drug_info.speci:
# if con_info["name"] == drug_info.name and con_info["purity"] == drug_info.purity and con_info["speci"] == drug_info.speci:
if con_info["medicament_id"] == drug_info.medicament_id:
if not con_info.get("use_num"):
con_info["use_num"] = 0
if int(con_info["use_num"]) < int(con_info["num"]):
@ -81,6 +83,7 @@ class BllUserApply(Repository):
obj.use_content = json.dumps(use_content)
self.update(obj)
# 获取待领用列表
def get_stay_use_list(self, client_id, user):
sql_all = f"""
select * from rms_user_apply
@ -98,9 +101,7 @@ class BllUserApply(Repository):
j = use_content[j_index]
if j["client_id"] != client_id:
continue
if j.get("use_num") != 0:
n = int(j.get("num")) - int(j.get("use_num"))
if n > 0:
j["stay_use_num"] = n
# if j.get("use_num") != 0:
j["stay_use_num"] = j.get("use_num")
data_list.append(j)
return data_list

@ -20,6 +20,7 @@ class BllUserTemporaryAuth(Repository):
def __init__(self, entityType=EntityUserTemporaryAuth):
super().__init__(entityType)
# 创建临时权限
def create_temporary_auth(self, user_ids, auth_type, t=None):
# try:
# client_code = BllClient().findEntity(EntityClient.client_id == client_id).client_code

@ -0,0 +1,16 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/19 09:43:08
'''
import sys
sys.path.append(".")
from db_logic.db_base import Repository
from models.medicament_models import EntityVariety
#药剂品种业务逻辑类
class BllVariety(Repository):
def __init__(self, entityType=EntityVariety):
return super().__init__(entityType)

@ -53,6 +53,7 @@ class EntityClient(Base):
description = Column(String(200), comment='备注') # 备注
is_add = Column(Integer, comment='是否添加', default=0)
func_type = Column(Integer, comment='试剂柜类型', default=0)
layer_num = Column(Integer, comment='柜子层数', default=6)
class EntityClientCellUser(Base):
__tablename__ = "rms_client_cell_user"
@ -113,6 +114,7 @@ class EntityClientCell(Base):
cell_code = Column(String(50), comment="抽屉码")
client_id = Column(String(50), comment="终端id")
cell_speci = Column(String(50), comment="单元格")
storage_quantity = Column(Integer, comment="存放试剂数量", default=50)
if __name__ == '__main__':

@ -328,6 +328,59 @@ class EntityMedicamentRelationImage(Base):
class EntityVariety(Base):
__tablename__ = "rms_variety"
__table_args__ = (
{
"comment": "药剂类型实体类"
}
)
variety_id = Column(
String(50), primary_key=True, comment="类型ID", default=get_uuid)
customer_id = Column(String(50), comment="客户ID")
cas_number = Column(String(50), comment="药剂cas码")
name = Column(String(50), comment="药剂名称")
english_name = Column(String(50), comment="英文名称")
purity = Column(String(50), comment="纯度")
is_supervise = Column(Integer, comment="是否监管", default=0)
inventory_warning_value = Column(Integer, comment="库存预警量")
shelf_life_warning_value = Column(Integer, comment="保质期到期提前预警天数")
use_days_warning_value = Column(Integer, comment="领用超期预警天数")
is_weigh = Column(Integer, comment="是否称重")
empty_count = Column(Integer, comment="空瓶数量")
use_count = Column(Integer, comment="当前领用数量")
normal_count = Column(Integer, comment="在库数量")
total_count = Column(Integer, comment="总数量")
remark1 = Column(String(50), comment='扩展字段1')
remark2 = Column(String(50), comment='扩展字段2')
remark3 = Column(String(50), comment='扩展字段3')
create_date = Column(String(50), comment="创建日期")
create_user_id = Column(String(50), comment="创建用户ID")
create_user_name = Column(String(50), comment="创建用户名称")
modify_date = Column(String(50), comment="修改时间")
modify_user_id = Column(String(50), comment="修改用户ID")
modify_user_name = Column(String(50), comment="修改用户名称")
is_add = Column(Integer, comment="", default=0)
class EntityMedicamntShenGou(Base):
__tablename__ = "rms_medicamnt_shengou"
__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="申请时间")
use_content = Column(Text, comment="领用详情")
is_solve = Column(Integer, comment="是否处理", default=0)
solve_date = Column(String(50), comment="受理时间")
solve_user_id = Column(String(50), comment="受理人")
solve_user_id_pt = Column(String(50), comment="受理人")
func_type = Column(Integer, comment="类型")
use_doc = Column(Text, comment="类型")
information = Column(Text, comment="驳回原因")
if __name__ == '__main__':
drug_info = {}
user_info = {}

@ -0,0 +1,203 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/08/27 11:05:06
'''
import sys
from types import CellType
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
# 生成ascii_uppercase生成所有大写字母
self.upper_string = string.ascii_uppercase
# 水平对齐, 居中对齐
self.alignment_style = Alignment(
horizontal='center', vertical='center')
# 定义字体
self.font_size = Font(size=9)
for col in self.upper_string:
self.ws.column_dimensions[col].width = 10
# 创建第三行, 需要传入一个列表用来写入单元格的值
def create_row3(self, data_list):
for data in range(1, len(data_list) + 1):
# 第三行写入值
self.ws.cell(row=1, column=data).value = data_list[data - 1]
# 创建多行固定样式 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 = ""
try:
value = int(value)
self.ws.cell(row=row_number, column=col_).number_format = '0'
except:
pass
self.ws.cell(row=row_number, column=col_).value = value
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")
self.create_row3(finds_name)
self.create_multiple_rows(2, 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
if __name__ == '__main__':
obj = ReportData()
data_dict = {
"data_list":[
{"name": "申购单编号", "purity":"11~15%", "export_count":"2", "production_date":"2023/01/01", "shelf_life": '5'}
],
"key_list": [
"remark7", "remark8", "category", "remark9",
"name", "english_name","purity","cas_number","standard_code",
"unit_code","speci","net_weight_unit", "export_count","remark6",
"production_date", "shelf_life", "expiration_date",
"price", "is_supervise", "remain", "manufacturer",
"storage_condition", "remark10"
],
"finds_name": [
"申购单编号","采购单编号", "药剂类别", "所属项目", "药剂名称", "英文名称", "纯度等级", "CAS码", "批号", "编号", "规格", "规格单位", "导入数量",
"导入单位", "生产日期", "保质期(天)", "到期日期", "价格(元)", "重点监管", "预估质量(g/ml)", "生产厂商", "储存条件", "包装是否完好、标签是否清晰"
],
}
obj = obj.build_file(**data_dict)
obj.save("测试表")
Loading…
Cancel
Save