#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @Date:2022/07/18 16:54:45 ''' import sys import sqlalchemy sys.path.append('.') import datetime 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.client_models import EntityClient from models.user_models import EntityUser from db_logic.meidcament_variety import BllMedicamentVariety from Common.Utils import Utils, DrugStatus, DrugRecordType #药剂流程业务逻辑类 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 sql_all = sql_all % where_base # 调用分页组装sql sql_all = Utils.sql_paging_assemble(sql_all, page_param) data_list = self.execute(sql_all).fetchall() # 查询页总数 count_sql = f"SELECT count(*) FROM rms_medicament %s GROUP BY `name`, cas_number, purity" % where_base page_param.totalRecords = self.execute(count_sql).fetchone()[0] return data_list # 获取试剂库存消耗 def get_drug_stock_use_classify(self): sql_all = """ select count(medicament_id) count_number, `status` from rms_medicament GROUP BY `status` """ data = self.execute(sql_all).fetchall() data_number = sum([i[0] for i in data]) data_li = Utils.msyql_table_model(data) data_list = [] for i in data_li: new_dict = { "ratio": str(round(i["count_number"] / data_number,2) * 100) + "%" } new_dict.update(i) data_list.append(new_dict) 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_info_distinct_list(self, seach_word, page_param, 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: seach_word = f"%{seach_word}%" if where_base: where_base += " and" where_base += f" `name` like '{seach_word}' or english_name like '{seach_word}'" if where_base: where_base = "where" + where_base # 组装最终sql run_sql = sql_all % where_base+group_base try: count_number = len(self.execute(run_sql).fetchall()) except Exception: count_number = 0 page_param.totalRecords = count_number # 分页sql run_sql = Utils.sql_paging_assemble(run_sql, page_param) run_sql_data = self.execute(run_sql).fetchall() return run_sql_data # 药剂入库 def drugPutIn(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()): 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), is_empty=0, create_date=Utils.get_str_datetime(), create_user_id=entityUser.user_id, create_user_name=entityUser.real_name, ) # 创建事务 self.beginTrans() self.session.add(entityDrug) self.session.add(entityDrugRecord) boolean_ = self.commitTrans() if boolean_ is None: return True return boolean_ # 药剂领用 def drugUse(self, entityDrug=EntityMedicament(), entityClient=EntityClient(), entityUser=EntityUser()): #创建事务 self.beginTrans() self.session.merge(entityDrug) 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), create_date=Utils.get_str_datetime(), create_user_id=entityUser.user_id, create_user_name=entityUser.real_name, ) 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() 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.Return, 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) 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() # 获取领用和归还页面列表 def drug_use_return(self, status, page_param): sql_all = """ select * from rms_medicament %s """ sql_all = sql_all % (f"where status={status}", ) count_sql = f"SELECT count(*) FROM rms_medicament where status={status}" page_param.totalRecords = self.execute(count_sql).fetchone()[0] sql_all = Utils.sql_paging_assemble(sql_all, page_param) data_list = self.execute(sql_all).fetchall() count_sql = f"SELECT count(*) FROM rms_medicament where status={status}" page_param.totalRecords = self.execute(count_sql).fetchone()[0] return data_list # 获取库存信息总览 def get_stock_all_info(self, page_param, name=None): sql_all = """ select DISTINCT `name`, speci, cas_number,net_weight_unit, purity, client_id, sum(CASE WHEN `status`=1 THEN 1 ELSE 0 END) count_number, sum(CASE WHEN `status`=1 THEN remain ELSE 0 END) sum_remain FROM rms_medicament %s """ # 拼接查询条件及分组条件 filter_base = "" if name: filter_base = f"where `name` LIKE %'{name}'%" filter_base += " GROUP BY `name`, speci, purity" sql_all = sql_all % filter_base # 首次查询,判断长度,做分页使用 try: count_number = len(self.execute(sql_all).fetchall()) except Exception: count_number = 0 page_param.totalRecords = count_number # 组件分页参数,返回分页后数据 sql_all = Utils.sql_paging_assemble(sql_all, page_param) sql_data = self.execute(sql_all).fetchall() return sql_data #获取所有药剂列表 def getAllDrugList(self, search_word, page_param, customer_id=None, client_id=None): # (Name like :searchWord or BarCode like :searchWord or EnglishName like :searchWord) sql_all = """ select `name`,speci, manufacturer, distributor, net_weight_unit, remain, production_date, expiration_date, shelf_life, put_in_user_name, put_in_date, english_name, purity, is_supervise, by_user_name from rms_medicament %s """ # 动态添加查询条件 filter_base = "" if customer_id: filter_base = f"customer_id='{customer_id}'" if client_id: if filter_base: filter_base += " and " filter_base += f"client_id='{client_id}'" # 模糊搜索 if search_word: seach_w = f"%{search_word}%" if filter_base: filter_base += " and " filter_base += f" `name` like '{seach_w}' or english_name like '{seach_w}' or manufacturer like '{seach_w}'" if filter_base: filter_base = "where " + filter_base sql_all = sql_all % filter_base # 获取数量做分页 try: count_number= len(self.execute(sql_all).fetchall()) except Exception: count_number = 0 page_param.totalRecords = count_number # 进行分页sql拼接 sql_all = Utils.sql_paging_assemble(sql_all, page_param) return self.execute(sql_all).fetchall() # 入库、领用、归还记录 def drug_show_type_info(self, record_type, put_in_user_name, name, start_time, end_time, page_param): sql_all = """ SELECT b.`name`, b.english_name, b.bar_code, b.purity, b.cas_number, a.use_quantity, b.`status`, a.create_date, a.create_user_name, b.client_id FROM ( SELECT medicament_id, use_quantity, create_user_name, create_date FROM rms_medicament_record %s ) a LEFT JOIN ( SELECT medicament_id, `name`, english_name, bar_code, purity, cas_number, net_weight, remain, `status`, by_user_date, by_user_name, client_id FROM rms_medicament %s ) b on b.medicament_id = a.medicament_id """ filter_sql = f"WHERE record_type={record_type}" filter_sql_1 = '' if put_in_user_name: filter_sql += f" and create_user_name like {put_in_user_name}" if start_time and end_time: filter_sql += f"and create_date >= {start_time} and create_date <= {end_time}" if name: filter_sql_1 += f" where `name` like '{name}' or english_name like '{name}'" sql_all = sql_all % (filter_sql, filter_sql_1) finds = ["name", "english_name", "bar_code", "purity", "cas_number", "use_quantity", "status", "create_date", "create_user_name", "client_id"] sql_all += ' limit ' + str((page_param.curPage - 1) * page_param.pageRows) + ',' + str(page_param.pageRows) data_list = self.execute(sql_all).fetchall() count_sql = f"SELECT count(*) FROM rms_medicament_record WHERE record_type={record_type} " page_param.totalRecords = self.execute(count_sql).fetchone()[0] return Utils.mysqlfinds_list(data_list, finds) # #获取指定用户当前领用药剂 # def getUserUseDrugList(self, userId): # drugList = self.findList( # EntityMedicament.ByUserId == userId, EntityMedicament.Status == DrugStatus.Out).all() # return drugList 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) # if __name__ == '__main__': # 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)