#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @Date:2022/07/18 16:54:45 ''' import sys import datetime from dateutil.relativedelta import relativedelta 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, EntityVariety, EntityMedicamentVariety 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 client_list=['72e70542-b70d-11e8-aea5-448a5bc6c411','72e70542-b70d-11e8-aea5-448a5bc6c412','72e70542-b70d-11e8-aea5-448a5bc6c413','72e70542-b70d-11e8-aea5-448a5bc6c414','72e70542-b70d-11e8-aea5-448a5bc6c415','72e70542-b70d-11e8-aea5-448a5bc6c416','72e70542-b70d-11e8-aea5-448a5bc6c417'] #药剂流程业务逻辑类 class BllMedicament(Repository): def __init__(self, entityType=EntityMedicament): return super().__init__(entityType) def update(self, entity): entity.remark30 = '0' return super().update(entity) def get_register_list(self, user, page_param): # sql_all = f""" # select * from rms_user_apply # where # user_id='{user.user_id}' and # is_solve=1 and # solve_date > DATE_SUB('{Utils.get_str_datetime()}', INTERVAL 10 hour) # """ # data = self.execute(sql_all).fetchall() # data_list = [] # for i in data: # use_content = json.loads(i.use_content) # for j_index in range(len(use_content)): # j = use_content[j_index] # if not j.get("use_num"): # # j["stay_use_num"] = j.get("use_num") # drugobj =BllMedicament().findEntity(and_(EntityMedicament.status==4,EntityMedicament.medicament_id == j.get("medicament_id"))) # print(drugobj,'889898989898989') # if drugobj: # data_list.append(j) # #所有试剂 sql_all = f""" select * from rms_medicament where status=4 and by_user_id='{user.user_id}' """ try: total_count = self.execute(f"select count(*) num from rms_medicament where status=4 and by_user_id='{user.user_id}'").fetchone().num except Exception: total_count = 0 page_param.totalRecords = total_count # 调用分页组装sql sql_all = Utils.sql_paging_assemble(sql_all, page_param) return self.execute(sql_all).fetchall() # 获取可入库层数据 def get_drug_save_db_info(self, drug_name, func_type): # 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 # 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.place GROUP BY a.id order by a.cell_speci asc ) 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 order by d.client_name asc """ 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: 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_dict[i.client_id]["client_cell"].sort() # 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 # 获取离保质期最近的同类药剂 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, 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 = f" where {where_base} " sql_all = f""" select `name`, english_name, cas_number, speci, net_weight_unit, purity, manufacturer, 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()) except Exception: total_count = 0 # count_sql = f"SELECT count(*) FROM rms_medicament %s GROUP BY `name`, cas_number, purity" % where_base page_param.totalRecords = total_count # 调用分页组装sql sql_all = Utils.sql_paging_assemble(sql_all, page_param) data_list = self.execute(sql_all).fetchall() return data_list # 获取试剂库存消耗 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 = [] # 计算百分比,组装数据 type_num = [] 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) type_num.append(str(i["status"])) data_list.append(new_dict) set_num_li = list(set(["1", "2", "3"]).difference(set(type_num))) for i in set_num_li: data_list.append( { "status": int(i), "rotio": "0%", "count_number": "0" } ) return data_list, data_number #获取药剂列表 def getDrugList(self, customerId, keyWord, pageParam): keyWord = '%' + keyWord + '%' orm_query = self.findList().filter( EntityMedicament.customer_id == customerId ).filter( # or_(EntityMedicament.RFID.like(keyWord), EntityMedicament.name.like(keyWord)) or_(EntityMedicament.RFID.like(keyWord), EntityMedicament.name.like(keyWord)) ).order_by( # desc(EntityMedicament.PutInStorageDate) desc(EntityMedicament.put_in_date) ) return self.queryPage(orm_query, pageParam) # 试剂管理 def get_drug_list(self, client_id, seach_word, b_code, func_type, page_param, search_status): filter_base = "" if client_id: filter_base += f" client_id='{client_id}' " if seach_word: seach_word = f"%{seach_word}%" if filter_base: filter_base += " and " filter_base += f" (`name` like '{seach_word}' or english_name like '{seach_word}') " if search_status and int(search_status): if filter_base: filter_base += " and " filter_base += f" status='{search_status}'" # 搜索bar_code if b_code: if len(b_code) > 10 and str(func_type) == "1": 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}' or remark12 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 # TODO 确认下面这段和上面修改b_code代码作用 # new_code = f"%{new_code}%" # if filter_base: # filter_base += " or " # 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""" select * from rms_medicament {filter_base} and status != 3 order by put_in_date desc """ try: 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() # 选择药剂入库--试剂详情 def get_drug_info_distinct_list(self, seach_word, func_type, page_param, client_id=None): # 动态添加查询条件 filter_base = "" if client_id: filter_base += f"client_id='{client_id}'" if seach_word: seach_word = f"%{seach_word}%" 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(sql_all).fetchall()) except Exception: count_number = 0 page_param.totalRecords = count_number # 分页sql page_sql = Utils.sql_paging_assemble(sql_all, page_param) return self.execute(page_sql).fetchall() # 药剂入库 def drugPutIn(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()): if entityClient.client_id not in client_list: entityDrugRecord = EntityMedicamentRecord( customer_id=entityClient.customer_id, client_id=entityClient.client_id, client_code=entityClient.client_code, variety_id=entityDrug.variety_id, medicament_id=entityDrug.medicament_id, price=entityDrug.price, record_type=DrugRecordType.PutIn, record_remain=float(entityDrug.remain) if entityDrug.remain else 0, is_empty=0, create_date=Utils.get_str_datetime(), create_user_id=entityUser.user_id, create_user_name=entityUser.real_name, ) # 创建事务 self.beginTrans() entityDrug.remark30 = '0' entityDrug.client_code = entityClient.client_code self.session.add(entityDrug) if entityDrug.status == 1 and entityClient.client_id not in client_list: self.session.add(entityDrugRecord) boolean_ = self.commitTrans() if boolean_ is None: return True return boolean_ # 药剂领用 def drugUse(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser(),notes=''): #创建事务 self.beginTrans() entityDrug.remark30 = '0' self.session.merge(entityDrug) if entityClient.client_id not in client_list: entityDrugRecord = EntityMedicamentRecord( customer_id=entityClient.customer_id, client_id=entityClient.client_id, client_code=entityClient.client_code, variety_id=entityDrug.variety_id, medicament_id=entityDrug.medicament_id, price=entityDrug.price, record_type=DrugRecordType.Use, is_empty=0, record_remain=float(entityDrug.remain) if entityDrug.remain else 0, create_date=Utils.get_str_datetime(), create_user_id=entityUser.user_id, create_user_name=entityUser.real_name, notes = notes ) self.session.add(entityDrugRecord) entityVariety = BllMedicamentVariety().findEntity(entityDrug.variety_id) entityVariety.normal_count -= 1 entityVariety.use_count += 1 self.session.merge(entityVariety) self.commitTrans() # 药剂归还 def drugReturn(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()): #创建事务 self.beginTrans() entityDrug.remark30 = '0' self.session.merge(entityDrug) drug = BllMedicament().findEntity(entityDrug.medicament_id) lastRemain = float(drug.remain) if drug.remain else 0 if entityClient.client_id not in client_list: entityDrugRecord = EntityMedicamentRecord( customer_id=entityClient.customer_id, client_id=entityClient.client_id, client_code=entityClient.client_code, variety_id=entityDrug.variety_id, medicament_id=entityDrug.medicament_id, price=float(entityDrug.price) if entityDrug.price else 0, use_quantity=float(lastRemain) - float(entityDrug.remain if entityDrug.remain else 0), record_type=DrugRecordType.Return, record_remain=float(entityDrug.remain) if entityDrug.remain else 0, is_empty=1 if(entityDrug.status == DrugStatus.Empty) else 0, create_date=Utils.get_str_datetime(), create_user_id=entityUser.user_id, create_user_name=entityUser.real_name, ) # 液体用量数据保存 medicament_variety_obj = BllMedicamentVariety().findEntity( EntityMedicamentVariety.variety_id == entityDrug.variety_id) if medicament_variety_obj.net_weight_unit == 'ml' and medicament_variety_obj.density: use_volume = (float(lastRemain) - float( entityDrug.remain if entityDrug.remain else 0)) / medicament_variety_obj.density entityDrugRecord.use_volume = use_volume self.session.add(entityDrugRecord) entityVariety = BllMedicamentVariety().findEntity(entityDrug.variety_id) if(entityDrug.remain != 0): entityVariety.normal_count += 1 else: entityVariety.empty_count += 1 entityVariety.use_count -= 1 self.session.merge(entityVariety) self.commitTrans() remain_result = self.calculate_use_drug(drug, weight_remain=float(entityDrug.remain if entityDrug.remain else 0)) return remain_result # 药剂登记 def drugRegister(self, entityDrug, entityClient=EntityClient(), entityUser=EntityUser()): #创建事务 self.beginTrans() entityDrug.remark30 = '0' self.session.merge(entityDrug) drug = BllMedicament().findEntity(entityDrug.medicament_id) lastRemain = float(drug.remain) entityDrugRecord = EntityMedicamentRecord( customer_id=entityClient.customer_id, client_id=entityClient.client_id, client_code=entityClient.client_code, variety_id=entityDrug.variety_id, medicament_id=entityDrug.medicament_id, price=entityDrug.price, use_quantity=float(lastRemain) - float(entityDrug.remain if entityDrug.remain else 0), record_type=DrugRecordType.Register, record_remain=float(entityDrug.remain), is_empty=1 if(entityDrug.status == DrugStatus.Empty) else 0, create_date=Utils.get_str_datetime(), create_user_id=entityUser.user_id, create_user_name=entityUser.real_name, ) self.session.add(entityDrugRecord) self.commitTrans() # 获取领用和归还页面列表 管理员要能看到所有领用/归还列表数据 def drug_use_return(self, status, func_type, user, page_param, is_admin): filter_base = f" status={status} and func_type='{func_type}' " if not is_admin: filter_base += f"and by_user_id='{user.user_id}' " sql_all = f""" select * from rms_medicament where status={status} and func_type='{func_type}' and by_user_id='{user.user_id}' order by by_user_date desc """ print(sql_all,'00909') try: count_number = len(self.execute(sql_all).fetchall()) except: count_number = 0 page_param.totalRecords = count_number sql_all = Utils.sql_paging_assemble(sql_all, page_param) data_list = self.execute(sql_all).fetchall() return data_list # 获取库存信息总览 def get_stock_all_info(self, page_param, func_type,client_id, name=None, client_place=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 client_id: if filter_base: filter_base += " and " filter_base += f" client_id='{client_id}' " if filter_base: filter_base = f" where {filter_base}" #TODO 添加房间筛选 filter_base1 = "" if client_place: filter_base1 += f"where place='{client_place}'" # sql_all =f""" # select DISTINCT # `name`, speci, cas_number,net_weight_unit, purity, # manufacturer, distributor, net_weight, net_weight_unit, # client_id, put_in_user_name,category,expiration_date # 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 a.*, b.client_name from ( select DISTINCT `name`, speci, cas_number, purity, manufacturer, distributor, net_weight, net_weight_unit, client_id, put_in_user_name,category,expiration_date,put_in_date, 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 )a LEFT JOIN ( select * from rms_client {filter_base1} ) b on a.client_id=b.client_id where b.client_name is not null order by a.put_in_date desc """ # 首次查询,判断长度,做分页使用 try: count_number = len(self.execute(sql_all).fetchall()) 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() #获取所有药剂列表 def getAllDrugList(self, search_word, manufacturer, start_time, end_time, func_type, page_param, seach_user, 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}'" 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 " bar_code, new_code = Utils.get_bar_code_reverse(search_word) filter_base += f" `name` like '{seach_w}' or english_name like '{seach_w}' or manufacturer like '{seach_w}' " filter_base += f" or bar_code='{bar_code}' or bar_code='{new_code}' " # 厂商搜索 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 func_type: if filter_base: filter_base += " and " filter_base += f" func_type={func_type}" if seach_user: if filter_base: filter_base += " and " filter_base += f" put_in_user_name like '%{seach_user}%'" if filter_base: filter_base = "where " + filter_base # select * from rms_medicament {filter_base} #TODO 添加房间筛选 filter_base1 = "" if client_speci: filter_base1 += f"where place='{client_speci}'" sql_all = f""" select a.*,b.client_name from ( select name, english_name,bar_code,manufacturer,speci,remain,purity,production_date,shelf_life,expiration_date,put_in_date,put_in_user_name, status,by_user_name,client_id, is_packing, is_label, is_aspect from rms_medicament {filter_base} ) a LEFT JOIN( 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 """ # manufacturer = manufacturer, # start_time = start_time, # end_time = end_time, # 动态添加查询条件 # 获取数量做分页 try: count_number= len(self.execute(sql_all).fetchall()) except Exception: count_number = 0 # 进行分页sql拼接 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 drug_show_type_info(self, record_type, start_time, end_time, put_in_user_name, name, func_type, client_id, statue_type, page_param, client_place): filter_base1 = '' if record_type: 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}%'" if start_time and end_time: filter_base1 += f" and create_date >= '{start_time}' and create_date <= '{end_time}'" if client_id: filter_base1 += f" and client_id='{client_id}'" filter_base2 = '' if name: name = f"%{name}%" filter_base2 += f" (`name` like '{name}' or english_name like '{name}') " if statue_type and statue_type != '100': 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}" #TODO 添加房间筛选 filter_base = "" if client_place: filter_base += f"where place='{client_place}'" sql_all = f""" select record_type, `name`, english_name, bar_code, purity, cas_number, speci, use_quantity, use_volume, `status`, create_date, create_user_name, a.client_id, client_code, client_name, unit_code from (select * from rms_medicament_record {filter_base1} ) as 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, unit_code FROM rms_medicament {filter_base2} ) as b on a.medicament_id=b.medicament_id LEFT JOIN(select client_id,client_name from rms_client {filter_base}) c on a.client_id=c.client_id where name is not null and client_name is not null ORDER BY create_date desc """ try: count_number = len(self.execute(sql_all).fetchall()) 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() def drug_show_un_warehoused_type_info(self, **kwargs): """ 未入库记录(未归还) :param kwargs: record_type, start_time, end_time, put_in_user_name, name, func_type, client_id, statue_type, page_param, client_place :return: """ filter_base1 = " where record_type=2 " if kwargs.get("put_in_user_name"): filter_base1 += f" and create_user_name like '%{kwargs.get('put_in_user_name')}%'" if kwargs.get("start_time") and kwargs.get("end_time"): filter_base1 += f" and create_date >= '{kwargs.get('start_time')}' and create_date <= '{kwargs.get('end_time')}'" if kwargs.get("client_id"): filter_base1 += f" and client_id='{kwargs.get('client_id')}'" filter_base2 = " `status` = 2 " if kwargs.get("func_type"): if filter_base2: filter_base2 += " and " filter_base2 += f" func_type='{kwargs.get('func_type')}' " if filter_base2: filter_base2 = f" where {filter_base2}" filter_base = "" if kwargs.get("client_place"): filter_base += f"where place='{kwargs.get('client_place')}'" sql_all = f""" select `name`, english_name, bar_code, purity, cas_number, speci, use_quantity, use_volume, `status`, create_date, create_user_name, a.client_id, client_code, client_name, unit_code from (select * from rms_medicament_record {filter_base1} ) as 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, unit_code FROM rms_medicament {filter_base2} ) as b on a.medicament_id=b.medicament_id LEFT JOIN(select client_id,client_name from rms_client {filter_base}) c on a.client_id=c.client_id where name is not null and client_name is not null GROUP BY b.medicament_id ORDER BY create_date desc """ try: count_number = len(self.execute(sql_all).fetchall()) except Exception: count_number = 0 if kwargs["page_param"]: kwargs["page_param"].totalRecords = count_number sql_all = Utils.sql_paging_assemble(sql_all, kwargs["page_param"]) return self.execute(sql_all).fetchall(), count_number 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 drug_group_info_list(self): sql_all = f""" select medicament_id, name as value, english_name, cas_number, purity, production_date, expiration_date, manufacturer,distributor,speci, net_weight_unit, total from rms_medicament group by `name`, speci, purity """ return self.execute(sql_all).fetchall() # 库存盘点获取分组后的试剂信息数据 def get_drug_stock_info(self, client_id): sql_all = f""" select count(*) stock_num, `name`, speci, purity from rms_medicament where client_id= '{client_id}' group by `name`, speci, purity """ return self.execute(sql_all).fetchall() # 可领用试剂列表 def use_drug_info_list(self, client_id, seach_word, page_param): filter_base = "" if client_id: filter_base += f"client_id='{client_id}'" if seach_word: if filter_base: filter_base += " and " name = f"%{seach_word}%" filter_base += f" (`name` like '{name}' or english_name like '{name}') " if filter_base: filter_base = f" and {filter_base}" # sql_all = f""" # select a.*,b.client_name from ( # select # `name`, speci, purity, count(*) drug_num, manufacturer, distributor,client_id,medicament_id # from # rms_medicament WHERE `status`=1 {filter_base} # GROUP BY # `name`, speci, purity, client_id # ) a LEFT JOIN ( # select * from rms_client # ) b on a.client_id = b.client_id # """ sql_all = f""" select a.*,b.client_name from ( select * from rms_medicament WHERE rms_medicament.func_type=1 and `status`=1 {filter_base} ) a LEFT JOIN ( select * from rms_client WHERE rms_client.place =10 ) b on a.client_id = b.client_id """ 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() # 获取待入库and待归还试剂数据 def get_drug_type_list(self, status, client_id, page_param, user_id): filter_base = "" if status: filter_base += f" status={status} " if filter_base: filter_base += " and " if status == 5: filter_base += f" put_in_user_id='{user_id}'" else: filter_base += f" by_user_id='{user_id}'" if client_id =='72e70542-b70d-11e8-aea5-448a5bc6c411': if filter_base: filter_base += " and " filter_base += f" client_id in ('72e70542-b70d-11e8-aea5-448a5bc6c411','72e70542-b70d-11e8-aea5-448a5bc6c412','72e70542-b70d-11e8-aea5-448a5bc6c413','72e70542-b70d-11e8-aea5-448a5bc6c414') " if client_id =='72e70542-b70d-11e8-aea5-448a5bc6c415': if filter_base: filter_base += " and " filter_base += f" client_id in ('72e70542-b70d-11e8-aea5-448a5bc6c415','72e70542-b70d-11e8-aea5-448a5bc6c416') " if client_id =='72e70542-b70d-11e8-aea5-448a5bc6c417': if filter_base: filter_base += " and " filter_base += f" client_id in ('72e70542-b70d-11e8-aea5-448a5bc6c417') " if filter_base: filter_base = f" where {filter_base}" sql_all = f""" select * from rms_medicament {filter_base} """ print(sql_all) try: count_number = self.execute(f"select count(*) num from rms_medicament {filter_base} ").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() # 获取待入库and待归还试剂数据 def get_drug_type_list2(self, user_id): sql_all = f""" select * from rms_medicament where client_id in ('72e70542-b70d-11e8-aea5-448a5bc6c411','72e70542-b70d-11e8-aea5-448a5bc6c412','72e70542-b70d-11e8-aea5-448a5bc6c413','72e70542-b70d-11e8-aea5-448a5bc6c414','72e70542-b70d-11e8-aea5-448a5bc6c415','72e70542-b70d-11e8-aea5-448a5bc6c416','72e70542-b70d-11e8-aea5-448a5bc6c417') and ((status=5 and put_in_user_id='{user_id}') or (status=2 and by_user_id='{user_id}')) """ data =self.execute(sql_all).fetchall() if data: return True else: return False 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 = ["砷", "硫酸", "氧化钠"] obj_list = [] for i in range(100): obj = EntityMedicament( bar_code= 10000 + i, client_id='1c39cb24-07f8-11ed-abd4-f47b094925e1', client_code="12345", name=random.choice(name_list), production_date=Utils.get_str_datetime(), shelf_life=10, remain=100, total=500, net_weight_unit="g", net_weight=100, purity="国标", put_in_date=Utils.get_str_datetime(), put_in_user_id='4cea74ee-0d8b-11ed-943e-f47b094925e1', put_in_user_name="admin", status=random.randint(1,3) ) obj_list.append(obj) self.insert_many(obj_list) def get_last_drug(self, client_id, drug_name, put_in_date, func_type): """ 判断获取最早入库试剂信息 """ filter_base = "" if func_type: filter_base += f"func_type='{func_type}'" if client_id: if filter_base: filter_base += " and " filter_base += f"client_id='{client_id}'" if drug_name: if filter_base: filter_base += " and " filter_base += f" `name`='{drug_name}' " if filter_base: filter_base = f" and {filter_base}" sql_all = f""" select a.*,b.client_name from ( select * from rms_medicament WHERE `status`=1 {filter_base} ) a LEFT JOIN ( select * from rms_client ) b on a.client_id = b.client_id order by a.put_in_date asc """ medicament_obj = self.execute(sql_all).fetchone() return medicament_obj def get_drug_total_num(self, filter_base): """ 获取药剂总数 :param filter_base: :return: """ if filter_base: filter_base = f" and {filter_base}" sql_all = f""" select count(medicament_id) count_number from rms_medicament where `status` != 3 {filter_base} """ # 查看分组数据 data = self.execute(sql_all).fetchone() return data.count_number if data.count_number else 0 def get_chemicals_total_num(self): """ 获取化学品总数量 :return: """ num = self.get_drug_total_num('') return num def get_chemicals_total_weight(self): """ 获取化学品总重量 :return: """ sql_all = f""" select sum(remain) total_weight from rms_medicament where `status` != 3 """ # 查看分组数据 data = self.execute(sql_all).fetchone() return data.total_weight if data.total_weight else 0 def get_chemicals_other_total_num(self): """ 获取其他化学品总数量 :return: standard_num 普通危化总数 2 reagent_num 易制毒易制爆总数 1 consumables_num 对照品数量 3 """ standard_num = self.get_drug_total_num("func_type=2") reagent_num = self.get_drug_total_num("func_type=1") consumables_num = self.get_drug_total_num("func_type=3") return standard_num, reagent_num, consumables_num def update_expiration_date(self, drug_entry): """ 更改试剂有效期 液体1年 ,普通固体5年, 易潮解固体2年 :param drug_entry: :return: """ # 从分类表中获取时间年份 medicament_variety_obj = BllMedicamentVariety().findEntity( EntityMedicamentVariety.variety_id == drug_entry.variety_id) if not medicament_variety_obj: return add_year = int(medicament_variety_obj.remark5) if medicament_variety_obj.remark5 else 1 date_now = datetime.datetime.now() add_expiration_date = (date_now + relativedelta(years=add_year)).strftime("%Y-%m-%d %H:%M:%S") if not drug_entry.expiration_date or add_expiration_date > str(drug_entry.expiration_date): return else: drug_entry.expiration_date = add_expiration_date self.beginTrans() self.session.merge(drug_entry) self.commitTrans() @staticmethod def calculate_use_drug(drug, weight_remain=0.0): """ 计算用量 :return: {"is_liquid": 是否为液体, "use_volume": 液体用量, "use_quality": 固体用量, "net_weight_unit": 单位} """ if not drug.remain: return medicament_variety_obj = BllMedicamentVariety().findEntity( EntityMedicamentVariety.variety_id == drug.variety_id) remain_result = { "is_liquid": False, "use_volume": 0, "use_quality": float(drug.remain) - float(weight_remain), "net_weight_unit": medicament_variety_obj.net_weight_unit } # 液体 if medicament_variety_obj.net_weight_unit == 'ml' and medicament_variety_obj.density: use_volume = remain_result["use_quality"] / medicament_variety_obj.density remain_result["is_liquid"] = True remain_result["use_volume"] = Utils.reserve_decimal(use_volume, 2) return remain_result 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) # data = BllMedicament().inster_log_shiji() # 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)