From c49acb0ffdc7a872fe892f0587a4ae011845e45b Mon Sep 17 00:00:00 2001 From: apan Date: Tue, 26 Jul 2022 18:06:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=A5=E5=BA=93=EF=BC=8C=E9=A2=86=E7=94=A8?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/drug/views.py | 144 ++++++++++++++++++++++++ apps/drug_template/views.py | 123 ++++++++++++++++++++- apps/home/views.py | 25 ++++- db_logic/medicament.py | 196 ++++++++++++++++++--------------- db_logic/medicament_record.py | 67 +++++------ db_logic/meidcament_variety.py | 78 +++++++------ models/medicament_models.py | 31 +++++- 7 files changed, 500 insertions(+), 164 deletions(-) create mode 100644 apps/drug/views.py diff --git a/apps/drug/views.py b/apps/drug/views.py new file mode 100644 index 0000000..033ab4b --- /dev/null +++ b/apps/drug/views.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- +''' +@Date:2022/07/26 11:19:30 +''' +import datetime +from flask import jsonify, request +from flask import Blueprint +from db_logic.client import BllClient + + +from db_logic.medicament import BllMedicament +from models.medicament_models import EntityMedicament +from db_logic.user import BllUser +from models.user_models import EntityUser +from models.client_models import EntityClient +from common.utils import DrugStatus, PageParam, Utils +drug_router = Blueprint("drug", __name__) + + + + +# 试剂扫码领用 +@drug_router.route("/use", methods=["GET", "POST"]) +def drug_collect(): + # 获取参数 + bar_code = request.values.get("bar_code") + user_id=request.values.get("user_id") + force_use = request.values.get("force_use", "False") + + # 获取条码试剂 + drug_entity = BllMedicament().findEntity(EntityMedicament.bar_code==bar_code) + # 条码实际逻辑判段 + if not drug_entity: + data = Utils.false_return(msg="药剂条码无效") + elif drug_entity.status not in [DrugStatus.Normal, DrugStatus.Empty]: + data = Utils.false_return(msg="药剂未在库") + elif drug_entity.status == DrugStatus.Empty: + data = Utils.false_return(msg="药剂已为空瓶") + else: + customer_id = drug_entity.customer_id + client_id = drug_entity.client_id + + # 获取临期的试剂 + drug_obj = BllMedicament().getDrugNearExpired(drug_entity.variety_id, customer_id) + date_str = lambda x: datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d") + drug_obj_date_str = date_str(drug_obj.expiration_date) + drug_entity_date_str = date_str(drug_entity.expiration_date) + 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: + # 领取试剂 + user_info = BllUser().findEntity(EntityUser.user_id==user_id) + drug_entity.by_user_date = Utils.get_str_datetime() + drug_entity.by_user_id=user_info.user_id + drug_entity.by_user_name=user_info.real_name + drug_entity.status=DrugStatus.Out + # 试剂领用--事务逻辑处理 + BllMedicament().drugUse( + drug_entity, + BllClient().findEntity(EntityClient.client_id==client_id), + user_info + ) + data = Utils.true_return(msg='领用成功',data=Utils.resultAlchemyData(drug_entity)) + return jsonify(data) + + +# 试剂归还 +@drug_router.route("/drug_return", methods=["GET", "POST"]) +def drug_return(): + # 获取参数 + bar_code = request.values.get("bar_code") + place = request.values.get("place") + user_id = request.values.get("user_id") + + + # 根据条码查询试剂信息 + drug_info = BllMedicament().findEntity(EntityMedicament.bar_code==bar_code) + if not drug_info: + data = Utils.false_return(msg="药剂条码无效") + elif drug_info.status != DrugStatus.Out: + data = Utils.false_return(msg="此药剂未被领用") + else: + # 药剂归还,进入归还事务处理 + drug_info.status = DrugStatus.Normal + if place: + drug_info.place = place + user_info = BllUser().findEntity(EntityUser.user_id == user_id) + BllMedicament().drugReturn(drug_info, BllClient().findEntity(drug_info.client_id), user_info) + data = Utils.true_return(msg="药剂归还成功", data=Utils.resultAlchemyData(drug_info)) + return jsonify(data) + + +# 试剂领用/归还,列表展示 +@drug_router.route("/use_or_return_list", methods=["GET", "POST"]) +def drug_use_retur_list(): + status = request.values.get("status") + page = request.values.get("page", 1) + page_size = request.values.get("page_size", 10) + page_param = PageParam(page, page_size) + data = BllMedicament().drug_use_return(status=status, page_param=page_param) + return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": data})) + + +# 试剂称重展示试剂详细信息 +@drug_router.route("/get_drug_info", methods=["GET", "POST"]) +def get_drug_info(): + bar_code = request.values.get("bar_code") + data_list = BllMedicament().get_bar_code_drug_info(bar_code=bar_code) + return jsonify(Utils.true_return(data=Utils.msyql_table_model(data_list)[0])) + + + + +# 试剂管理 +@drug_router.route("/drug_manage", methods=["GET", "POST"]) +def get_drug_info(): + seach_word = request.values.get("seach_word") + client_id = request.values.get("client_id") + data_list = BllMedicament().get_drug_info_distinct_list(seach_word=seach_word, client_id=client_id) + return jsonify(Utils.true_return(data=Utils.msyql_table_model(data_list))) + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/drug_template/views.py b/apps/drug_template/views.py index b450ec0..268f9bc 100644 --- a/apps/drug_template/views.py +++ b/apps/drug_template/views.py @@ -5,15 +5,20 @@ ''' +import datetime +import json from flask import jsonify, request from flask import Blueprint from common.read_excel import ReadExcel from common.utils import Utils from db_logic.client import BllClient +from db_logic.medicament import BllMedicament from db_logic.user import BllUser from db_logic.medicament_template import BllMedicamentTemplate -from models.medicament_models import EntityMedicamentTemplate +from db_logic.meidcament_variety import BllMedicamentVariety +from models.client_models import EntityClient +from models.medicament_models import EntityMedicament, EntityMedicamentTemplate @@ -34,9 +39,123 @@ def show_template(): # 选择药剂入库 +@tmp_router.route("/select_drug", methods=["GET", "POST"]) +def select_drug_info(): + seach_word =request.values.get("seach_word") + data_list = BllMedicament().get_drug_info_distinct_list(seach_word) + return jsonify(Utils.true_return(data=Utils.msyql_table_model(data_list))) + +# 绑定入库 +@tmp_router.route("/bind_tmp_enter_warehouse", methods=["GET", "POST"]) +def bind_tmp_input_db(): + tmp_content = request.values.get("tmplate_content") + customer_id = request.values.get("customer_id", '') + client_id = request.values.get("client_id") + bar_code = request.values.get("bar_code") + user_id = request.values.get("user_id") + if not bar_code: + return jsonify(Utils.false_return(msg="条码不能为空")) + drug_obj = BllMedicament().findEntity(EntityMedicament.bar_code==bar_code) + if drug_obj: + return jsonify(Utils.false_return(msg="该药剂已被锁定")) + else: + drug_info = eval(tmp_content) + user_info = BllUser().findEntity(user_id) + drug_variety = BllMedicamentVariety().createDrugVariety( + customer_id=customer_id, + drug_info=drug_info, user_info=user_info + ) + finds = [ + "name", "cas_number", "english_name", "purity", "manufacturer", "distributor", + "production_date", "shelf_life", "net_weight_unit", "net_weight", "tp", "price", + "place", "expiration_date" + ] + key_dict = {} + for i in finds: + key_dict[i] = drug_info.get(i) + new_dict = { + "medicament_id": Utils.UUID(), + "variety_id": drug_variety.variety_id, + "bar_code": bar_code, + "customer_id": customer_id, + "client_id": client_id, + # "expiration_date": datetime.datetime.strptime(drug_info.get('production_date'), "%Y-%m-%d") + datetime.timedelta( + # days=drug_info.get("shelf_life")).strftime("%Y-%m-%d %H:%M:%S"), + "inventory_warning_value":10, + "shelf_life_warning_value":10, + "use_days_warning_value":10, + "is_supervise":0, + "remain": drug_info.get("net_weight"), + "put_in_date": Utils.get_str_datetime(), + "put_in_user_id": user_info.user_id, + "put_in_user_name": user_info.real_name, + "status":5 + } + new_dict.update(**key_dict) + drug_entity = EntityMedicament(**new_dict) + objs = BllMedicament().drugPutIn( + drug_entity, + BllClient().findEntity(EntityClient.client_id==client_id), + user_info + ) + if objs: + return jsonify(Utils.true_return(msg="药剂入库成功")) + else: + return jsonify(Utils.false_return(msg="数据异常,入库失败")) + -# 编辑试剂信息 +# 新增试剂模板 +@tmp_router.route("/add_tmp", methods=["GET", "POST"]) +def add_tmp_info(): + tmp_name = request.values.get("template_name") + client_id = request.values.get("client_id") + tmp_content = request.values.get("tmplate_content") + user_id = request.values.get("user_id") + user = BllUser().findEntity(user_id) + client = BllClient().findEntity(client_id) + 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) + """ + # 获取最大的条形码和条形码数量 + tmp_obj = BllMedicamentTemplate().execute(sql_all).fetchone() + if tmp_obj: + max_barcode = tmp_obj.start_bar_code + bar_code_count = tmp_obj.bar_code_count + max_barcode = int(max_barcode) + int(bar_code_count) + else: + max_barcode = 100001 + start_bar_code = max_barcode + + try: + if isinstance(tmp_content, str): + tmp_content = eval(tmp_content) + total_count = 0 + for i in tmp_content: + total_count += int(i['export_count']) + + obj = EntityMedicamentTemplate( + customer_id=client.customer_id, + client_id=client.client_id, + client_name=client.client_name, + template_name=tmp_name, + template_content=json.dumps(tmp_content), + is_wait_export=1, + start_bar_code=start_bar_code, + bar_code_count=bar_code_count, + create_date=Utils.get_str_datetime(), + create_user_id=user.user_id, + create_user_name=user.real_name, + + ) + state = BllMedicamentTemplate().insert(obj) + if state: + return jsonify(Utils.true_return(msg="添加模板成功")) + else: + return jsonify(Utils.false_return(msg="导入失败")) + except Exception as error: + return jsonify(Utils.false_return(msg=f"请求有误:{error}")) + diff --git a/apps/home/views.py b/apps/home/views.py index 3ae4d9e..3688ee8 100644 --- a/apps/home/views.py +++ b/apps/home/views.py @@ -4,6 +4,7 @@ @Date:2022/07/18 16:19:33 ''' from flask import jsonify, request +from db_logic.medicament import BllMedicament from models.warning_models import EntityWarning @@ -23,11 +24,11 @@ home_router = Blueprint('home', __name__, url_prefix="/home") @home_router.route('/home_number', methods=["GET", "POST"]) # def getRecordTypeDrugRecordListJson(): def get_record_type_drug_record_json(): - customerId = request.values.get('customerId') - client_id = request.values.get('clientId') + customer_id = request.values.get('customer_id') + client_id = request.values.get('client_id') # 获取药剂记录今日入库 领用 归还Json数据 typ_dic = BllMedicamentRecord().getTodayDrugRecordCount( - customerId=customerId, clientId=client_id) + customerId=customer_id, clientId=client_id) data = { "putin_count": typ_dic.get(1), "use_count": typ_dic.get(2), @@ -37,6 +38,19 @@ def get_record_type_drug_record_json(): return jsonify(Utils.true_return(data=data)) +# 试剂余量 +@home_router.route("/home_drug_remaining", methods=["GET", "POST"]) +def drug_remaining(): + client_id = request.values.get("client_id") + page = request.values.get("page", 1) + page_size = 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) + return jsonify(Utils.true_return(data={"total_count": page_param.totalRecords, "data": Utils.msyql_table_model(data_list)})) + +# 预警信息总览 + + # 获取预警信息列表接口 @home_router.route('/home_warning_list', methods=["GET", "POST"]) def get_warning_list(): @@ -60,10 +74,11 @@ def get_warning_list(): def update_warning_type(): warning_id = request.values.get('warning_id') obj = BllWarning().findEntity(EntityWarning.warning_id == warning_id) - obj.object_type = 2 + # obj.object_type = 2 obj.solve_date= Utils.get_str_datetime() obj.solve_user_id = '' obj.solve_user_name = '' - BllWarning.update(obj) + obj.is_solve=1 + BllWarning().update(obj) return jsonify(Utils.true_return()) \ No newline at end of file diff --git a/db_logic/medicament.py b/db_logic/medicament.py index c34fdab..bbced9a 100644 --- a/db_logic/medicament.py +++ b/db_logic/medicament.py @@ -3,7 +3,6 @@ ''' @Date:2022/07/18 16:54:45 ''' -from re import template import sys sys.path.append('.') import datetime @@ -32,6 +31,41 @@ class BllMedicament(Repository): def __init__(self, entityType=EntityMedicament): return super().__init__(entityType) + # 获取离保质期最近的同类药剂 + def getDrugNearExpired(self, varietyId, customerId): + drugList = self.findList( + and_( + EntityMedicament.status == DrugStatus.Normal, + EntityMedicament.variety_id == varietyId + )).order_by(EntityMedicament.expiration_date).limit(1) + return drugList.first() + + # 根据条码获取试剂详细信息 + 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, net_weight_unit, purity, + sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) surplus_number + from rms_medicament %s GROUP BY `name`, cas_number, purity + """ + where_base = "" + if client_id: + where_base = f" client_id='{client_id}'" + if where_base: + where_base = " where " + where_base + sql_all = sql_all % where_base + data_list = self.execute(sql_all).fetchall() + count_sql = f"SELECT count(*) FROM rms_medicament %s GROUP BY `name`, cas_number, purity" % where_base + page_param.totalRecords = self.execute(count_sql).fetchone()[0] + return data_list + + + + #获取药剂列表 def getDrugList(self, customerId, keyWord, pageParam): keyWord = '%' + keyWord + '%' @@ -46,12 +80,23 @@ class BllMedicament(Repository): ) return self.queryPage(orm_query, pageParam) - # def get_drug_info_distinct_list(self, seach_word): - # sql_all = """ - # sqlect * from - # """ - - + # 选择药剂入库--试剂详情 + def get_drug_info_distinct_list(self, seach_word, client_id=None): + sql_all = """ + select * from rms_medicament %s + """ + group_base = " group by `name`, cas_number, net_weight_unit" + where_base = "" + if client_id: + where_base += f"client_id='{client_id}'" + if 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 = "where" + where_base + sql_all = sql_all % (where_base+group_base, ) + return self.execute(sql_all).fetchall() # 药剂入库 def drugPutIn(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()): @@ -76,8 +121,8 @@ class BllMedicament(Repository): self.beginTrans() self.session.add(entityDrug) self.session.add(entityDrugRecord) - self.commitTrans() - + boolean_ = self.commitTrans() + return boolean_ # 药剂领用 def drugUse(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()): #创建事务 @@ -142,14 +187,24 @@ class BllMedicament(Repository): self.commitTrans() - # 获取信息详情 - def get_medicament_info(self): - # 名称、规格、纯度进行去重展示 并分页 - self.session = self.DBSession() - self.session.query(distinct()).group_by( - self.entityType.name, - self.entityType.net_weight_unit, - self.entityType.purity) + # 获取领用和归还页面列表 + def 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 += ' limit ' + \ + str((page_param.curPage - 1) * page_param.pageRows) + \ + ',' + str(page_param.pageRows) + data_list = self.execute(sql_all).fetchall() + count_sql = f"SELECT count(*) FROM rms_medicament where status={status}" + page_param.totalRecords = self.execute(count_sql).fetchone()[0] + return data_list + # 获取库存信息总览 def get_stock_all_info(self, page_param, name=None): @@ -184,65 +239,33 @@ class BllMedicament(Repository): #获取所有药剂列表 def getAllDrugList(self, search_word, page_param, customer_id=None, client_id=None): # (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord) - """ - [ - 'medicament_id', 'variety_id', 'bar_code', 'client_id', 'client_code', 'customer_id', - 'cas_number', 'name', 'english_name', 'manufacturer', 'distributor', 'production_date', - 'expiration_date', 'shelf_life', 'inventory_warning_value', 'shelf_life_warning_value', - 'use_days_warning_value', 'is_weigh', 'weigh_flag', 'remain', 'total', 'net_weight_unit', - 'net_weight', 'tp', 'purity', 'price', 'flow_position_code', 'cell_position_code', 'place', - 'status', 'is_supervise', 'by_user_date', 'by_user_id', 'by_user_name', 'put_in_date', - 'put_in_user_id', 'put_in_user_name', 'is_add', 'user_auditing'] + sql_all = """ + select `name`, 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 """ - filter_base = [] + filter_base = "" if customer_id: - filter_base.append(self.entityType.customer_id == customer_id) + filter_base = f"customer_id='{customer_id}'" + # filter_base.append(self.entityType.customer_id == customer_id) if client_id: - filter_base.append(self.entityType.client_id == client_id) + if filter_base: + filter_base += " and " + filter_base += f"client_id='{client_id}'" + # filter_base.append(self.entityType.client_id == client_id) if search_word: seach_w = f"%{search_word}%" - filter_base.append( - or_( - self.entityType.name.like(seach_w), - self.entityType.bar_code.like(seach_w), - self.entityType.english_name.like(seach_w), - ) - ) - data = self.session.query( - self.entityType.name, - self.entityType.distributor, - self.entityType.net_weight_unit, - self.entityType.remain, - self.entityType.production_date, - self.entityType.expiration_date, - self.entityType.shelf_life, - self.entityType.put_in_user_name, - self.entityType.put_in_date, - - # 试剂详细信息数据展示 - self.entityType.english_name, - self.entityType.purity, - self.entityType.is_supervise, - self.entityType.by_user_name, - - ).filter(*filter_base) - fields = [ - "name", "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" - ] - data_list = [] + if filter_base: + filter_base += " and " + filter_base += f" `name` like '{seach_w}' or english_name like '{seach_w}' or english_name like '{seach_w}'" + if filter_base: + filter_base = "where " + filter_base + sql_all = sql_all % filter_base + data_list = self.execute(sql_all).fetchall() count_sql = f"SELECT count(medicament_id) FROM rms_medicament" page_param.totalRecords = self.execute(count_sql).fetchone()[0] - page_data = self.queryPage(data, page_param) - for i in page_data: - data_list.append(dict(zip(fields, i))) + data_list = Utils.msyql_table_model(data_list) return data_list # 入库、领用、归还记录 @@ -273,13 +296,6 @@ class BllMedicament(Repository): count_sql = f"SELECT count(*) FROM rms_medicament_record WHERE record_type={record_type} " page_param.totalRecords = self.execute(count_sql).fetchone()[0] return Utils.mysqlfinds_list(data_list, finds) - # # 获取库存消耗 - # def get_comsume_stock(self): - # self.session.query( - # self.entityType.status, - # func.count(self.entityType.medicament_id) - - # ) # #获取指定用户当前领用药剂 @@ -291,18 +307,22 @@ class BllMedicament(Repository): if __name__ == '__main__': from db_logic.medicament import BllMedicament - values= {} - page = values.get("page", 1) - page_size = values.get("page_size", 10) - record_type = values.get("record_type", 1) - put_in_user_name = values.get("put_in_user_name") - name = values.get("name") - start_time = values.get("start_time") - end_time = values.get("end_time") - page_param = PageParam(page, page_size) - typ_dic = BllMedicament().drug_show_type_info(record_type=record_type, put_in_user_name=put_in_user_name, - name=name, start_time=start_time, end_time=end_time, page_param=page_param - ) - print(typ_dic) + from common.utils import PageParam + page_param = PageParam(1, 10) + data = BllMedicament().getAllDrugList(page_param=page_param, search_word='') + print(data) + # values= {} + # page = values.get("page", 1) + # page_size = values.get("page_size", 10) + # record_type = values.get("record_type", 1) + # put_in_user_name = values.get("put_in_user_name") + # name = values.get("name") + # start_time = values.get("start_time") + # end_time = values.get("end_time") + # page_param = PageParam(page, page_size) + # typ_dic = BllMedicament().drug_show_type_info(record_type=record_type, put_in_user_name=put_in_user_name, + # name=name, start_time=start_time, end_time=end_time, page_param=page_param + # ) + # print(typ_dic) diff --git a/db_logic/medicament_record.py b/db_logic/medicament_record.py index 0d822d8..ccfca7b 100644 --- a/db_logic/medicament_record.py +++ b/db_logic/medicament_record.py @@ -31,11 +31,24 @@ class BllMedicamentRecord(Repository): def __init__(self, entityType=EntityMedicamentRecord): return super().__init__(entityType) - def get_today_record_number(self,): - self.entityType.query() + # 获取流转记录 + def get_drug_flow_log(self, page_param): + sql_all = """ + select a.`name`, 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`, 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 order by create_date desc + ) b on b.medicament_id=a.medicament_id + """ + count_sql = "select count(*) from rms_medicament_record" + page_param.totalRecords = self.execute(count_sql).fetchone()[0] + sql_all += ' limit ' + str((page_param.curPage - 1) * page_param.pageRows) + ',' + str(page_param.pageRows) + data = Utils.msyql_table_model(self.execute(sql_all)) + # print(data) + return data + # return self.execute(sql_all) - return # #获取指定用户流转记录 # def getUserDrugRecordList(self, pageParam, customerId, userId=None): # queryStr = 'select * from RMS_MedicamentRecord r left join RMS_Medicament m on m.MedicamentId=r.MedicamentId and m.CustomerId=:customerId ' @@ -79,21 +92,20 @@ class BllMedicamentRecord(Repository): ).select_from(self.entityType).group_by(EntityMedicamentRecord.record_type).all() return data - def default_data_list(self, **kw): - sql_all = kw.get("sql_all") - finds = kw.get("finds") - base_bool = kw.get("base_bool", False) + # 公用方法 + def default_data_list(self, sql_all, finds=None): med_data = self.execute(sql_all).fetchall() data_list = [] base_num = 0 - for med in med_data: - new_med = [] - # for n in med: - # new_med.append(float(n) if isinstance(n, Decimal) else n) - new_med = [n if not isinstance(n, Decimal) else float(n) for n in med] - data_list.append(dict(zip(finds, new_med))) - if base_bool: - base_num += float(new_med[-1]) + data= Utils.msyql_table_model(med_data) + for d in data: + new_dic = {} + for k,v in d.items(): + v = v if not isinstance(v, Decimal) else float(v) + new_dic[k]=v + data_list.append(new_dic) + if finds: + base_num += float(new_dic.get(finds)) return data_list, base_num # 获取库存消耗数据 @@ -128,13 +140,13 @@ class BllMedicamentRecord(Repository): str((page_param.curPage - 1) * page_param.pageRows) + \ ',' + str(page_param.pageRows) - data_list, _ = self.default_data_list(**{"sql_all":sql_all, "finds":finds}) + data_list, _ = self.default_data_list(sql_all) return data_list # 试剂用量消耗 def durg_useing_info(self, seach_word, page_param): sql_all = """ - select c.`name`, c.purity, c.cas_number, c.net_weight_unit, sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) on_in, c.c_two, c.sum_use from ( + select c.`name`, c.purity, c.cas_number, c.net_weight_unit, sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) on_in, c.c_two use_num, c.sum_use use_level from ( select a.*, b.c_two, b.sum_use from( select medicament_id, `name`, cas_number, purity, net_weight_unit, `status` from rms_medicament %s @@ -148,16 +160,13 @@ class BllMedicamentRecord(Repository): sql_all = sql_all % f"where `name` like '{seach_word}' or english_name like '{seach_word}'" else: sql_all = sql_all % "" - finds = [ - "name", "purity", "cas_number", "net_weight_unit", "on_in", "use_num", "use_level", "ratio" - ] count_sql = "select count(medicament_id) from rms_medicament group by `name`, purity, net_weight_unit" page_param.totalRecords = self.execute(count_sql).fetchone()[0] sql_all += ' limit ' + \ str((page_param.curPage - 1) * page_param.pageRows) + \ ',' + str(page_param.pageRows) - data, ratio_all = self.default_data_list(**{"sql_all": sql_all, "finds": finds, "base_bool": True}) + data, ratio_all = self.default_data_list(sql_all, "use_level") for i in data: i["ratio"] = str(round(float(i["use_level"]) / ratio_all, 2) * 100) + "%" @@ -166,7 +175,7 @@ class BllMedicamentRecord(Repository): # 人员用量消耗 def user_use_info(self, page_param, seach_word=None, seach_user=None): sql_all = """ - select c.by_user_name, c.by_user_id, c.sum_use, c.c_two from ( + select c.by_user_name, c.by_user_id, c.sum_use use_number, c.c_two 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( @@ -187,15 +196,12 @@ class BllMedicamentRecord(Repository): sql_all = sql_all % f"where {filter_sql}" else: sql_all = sql_all % "" - finds = [ - "by_user_name", "by_user_id", "use_number", "use_level", "ratio" - ] count_sql = "select count(medicament_id) from rms_medicament_record group by create_user_id" page_param.totalRecords = self.execute(count_sql).fetchone()[0] sql_all += ' limit ' + \ str((page_param.curPage - 1) * page_param.pageRows) + \ ',' + str(page_param.pageRows) - data, ratio_all = self.default_data_list(**{"sql_all": sql_all, "finds": finds, "base_bool": True}) + data, ratio_all = self.default_data_list(sql_all, "use_level") for i in data: i["ratio"] = str( round(float(i["use_level"]) / ratio_all, 2) * 100) + "%" @@ -232,13 +238,10 @@ class BllMedicamentRecord(Repository): sql_all = sql_all % f"where {filter_sql}" else: sql_all = sql_all % "" - finds = [ - "name", "purity", "cas_number", "net_weight_unit", "use_num", "return_num" - ] count_sql = "select count(medicament_id) from rms_medicament group by `name`, purity, net_weight_unit" page_param.totalRecords = self.execute(count_sql).fetchone()[0] sql_all += ' limit ' + str((page_param.curPage - 1) * page_param.pageRows) + ',' + str(page_param.pageRows) - data, _ = self.default_data_list(**{"sql_all": sql_all, "finds":finds}) + data, _ = self.default_data_list(sql_all) return data # #获取药剂最后一次使用余量 @@ -266,5 +269,7 @@ if __name__ == '__main__': from db_logic.medicament_record import BllMedicamentRecord # customerId, clientId = None, '8db7e540-070f-11ed-a286-f47b094925e1' # sql = f"update rms_medicament_record set use_quantity={round(random.uniform(1,10), 1)}" - typ_dic = BllMedicamentRecord().drug_use_f('', '化') + from common.utils import PageParam + page_param = PageParam(1, 10) + typ_dic = BllMedicamentRecord().durg_useing_info(page_param=page_param, seach_word='') print(typ_dic) diff --git a/db_logic/meidcament_variety.py b/db_logic/meidcament_variety.py index 5e2f919..35ca06e 100644 --- a/db_logic/meidcament_variety.py +++ b/db_logic/meidcament_variety.py @@ -3,7 +3,10 @@ ''' @Date:2022/07/19 09:43:08 ''' +import sys +sys.path.append(".") from sqlalchemy import or_, and_ +from common.utils import Utils from db_logic.db_base import Repository from models.medicament_models import EntityMedicamentVariety @@ -22,42 +25,45 @@ class BllMedicamentVariety(Repository): def __init__(self, entityType=EntityMedicamentVariety): return super().__init__(entityType) - # # 创建药剂品种 - # def createDrugVariety(self, customerId, name, englishName, casNumber, purity, unit, speciUnit, speci, entityUser=EntityUser()): - # entity = self.findEntity(and_(EntityMedicamentVariety.Name == name, EntityMedicamentVariety.Purity == purity, - # EntityMedicamentVariety.Unit == unit, EntityMedicamentVariety.SpeciUnit == speciUnit, EntityMedicamentVariety.Speci == speci)) - # print(entity, 6666666666) - # if(entity is None): - # entity = EntityMedicamentVariety() - # entity.VarietyId = Utils.UUID() - # entity.CustomerId = customerId - # entity.InventoryWarningValue = 10 - # entity.ShelfLifeWarningValue = 10 - # entity.UseDaysWarningValue = 10 - # entity.Name = name - # entity.EnglishName = englishName - # entity.CASNumber = casNumber - # entity.Purity = purity - # entity.Unit = unit - # entity.SpeciUnit = speciUnit - # entity.TotalCount = 1 - # entity.InventoryWarningValue = 2 - # entity.NormalCount = 1 - # entity.UseCount = 0 - # entity.EmptyCount = 0 - # entity.IsSupervise = 0 - # entity.Speci = speci - # entity.CreateDate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") - # entity.CreateUserId = entityUser.UserId - # entity.CreateUserName = entityUser.RealName - # self.insert(entity) - # else: - # entity.TotalCount += 1 - # entity.NormalCount += 1 - # self.update(entity) - # entity = self.session.merge(entity) - # return entity - + # 创建药剂品种 + def createDrugVariety(self, customer_id, drug_info, user_info): + entity = self.findEntity( + and_( + EntityMedicamentVariety.name == drug_info.get("name"), + EntityMedicamentVariety.purity == drug_info.get("purity"), + EntityMedicamentVariety.net_weight_unit == drug_info.get("net_weight_unit"), + EntityMedicamentVariety.net_weight == drug_info.get("net_weight") + ) + ) + if not entity: + entity = EntityMedicamentVariety( + customer_id=customer_id, + name=drug_info.get("name"), + english_name=drug_info.get("english_name"), + cas_number=drug_info.get("cas_number"), + purity=drug_info.get("purity"), + tp=drug_info.get("tp", 1), + net_weight_unit=drug_info.get("net_weight_unit"), + net_weight=drug_info.get("net_weight"), + create_date=Utils.get_str_datetime(), + create_user_id=user_info.get("user_id"), + create_user_name=user_info.get("real_name"), + shelf_life_warning_value=10, + inventory_warning_value=10, + use_days_warning_value=10, + total_count=1, + normal_count=1, + use_count=0, + empty_count=0, + is_supervise=0 + ) + self.insert(entity) + else: + entity.total_count += 1 + entity.normal_count += 1 + self.update(entity) + entity = self.session.merge(entity) + return entity # # 获取品种统计 # def getVarietyStatistics(self): # SQL = """ diff --git a/models/medicament_models.py b/models/medicament_models.py index 6467a49..6b2f9d7 100644 --- a/models/medicament_models.py +++ b/models/medicament_models.py @@ -139,6 +139,8 @@ class EntityMedicamentTemplate(Base): @classmethod def get_finds(cls): return inspect(Base.metadata, cls.__tablename__.c.keys()) + + class EntityMedicamentRecord(Base): __tablename__ = "rms_medicament_record" __table_args__ = ( @@ -225,8 +227,33 @@ class EntityMedicamentExtend(Base): field_table_type = Column(Integer, comment="字段所在表") -# if __name__ == '__main__': -# # from db_logic.medicament_record import BllMedicamentRecord +if __name__ == '__main__': + drug_info = {} + user_info = {} + from common.utils import Utils + entity = EntityMedicamentVariety( + customer_id="customer_id", + name=drug_info.get("name"), + english_name=drug_info.get("english_name"), + cas_number=drug_info.get("cas_number"), + purity=drug_info.get("purity"), + tp=drug_info.get("tp", 1), + net_weight_unit=drug_info.get("net_weight_unit"), + net_weight=drug_info.get("net_weight"), + create_date=Utils.get_str_datetime(), + create_user_id=user_info.get("user_id"), + create_user_name=user_info.get("real_name"), + shelf_life_warning_value=10, + inventory_warning_value=10, + use_days_warning_value=10, + total_count=1, + normal_count=1, + use_count=0, + empty_count=0, + is_supervise=0 + ) + print(entity.is_supervise) + # from db_logic.medicament_record import BllMedicamentRecord # # customerId, clientId = None, '8db7e540-070f-11ed-a286-f47b094925e1' # # aaa = BllMedicamentRecord().getTodayDrugRecordCount(customerId, clientId) # # print(aaa)