You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
592 lines
29 KiB
592 lines
29 KiB
#!/usr/bin/env python
|
|
# encoding: utf-8
|
|
"""
|
|
@author: tx
|
|
@file: warning.py
|
|
@time: 2023/6/15 17:11
|
|
@desc: 报警
|
|
"""
|
|
from datetime import datetime, timedelta
|
|
import pytz
|
|
from fastapi import APIRouter, Depends, Request
|
|
from tortoise import Tortoise
|
|
from tortoise.functions import Count
|
|
from tortoise.queryset import Q
|
|
from tortoise.queryset import QuerySet
|
|
from pydantic import BaseModel
|
|
from conf import setting
|
|
from helper import login_required, respond_to
|
|
from helper.tool import parse_datetime
|
|
from helper.drug import drug_near_already_expired
|
|
from models import Log
|
|
from models.archive import Archive
|
|
from models.dictionary import Dictionary
|
|
from models.drug import Drug, DrugStateEnum
|
|
from models.drug_use_log import DrugUseLog, DrugUseStateEnum
|
|
from models.template import Template
|
|
from models.terminal import Terminal
|
|
from models.cabinet import Cabinet
|
|
|
|
# router = APIRouter(prefix='/warning', dependencies=[])
|
|
router = APIRouter(prefix='/warning', dependencies=[Depends(login_required)])
|
|
|
|
class SearchWord(BaseModel):
|
|
WarningType: str | None
|
|
archive_id: str | None
|
|
name: str | None
|
|
stime: str | None
|
|
etime: str | None
|
|
slack_day: int = 30
|
|
page_no: int = 1
|
|
page_size: int = 10
|
|
|
|
|
|
@router.get('/near_expired', summary="药剂临期")
|
|
async def index(request: Request,page_no: int = 1, page_size: int = 20):
|
|
"""
|
|
药剂临期信息
|
|
- 只查询在库与出库状态药剂
|
|
:param page_no:
|
|
:param page_size:
|
|
:return:
|
|
"""
|
|
archive_id = request.state.archive_id
|
|
count, drug_result = await get_near_expired(archive_id,page_no, page_size)
|
|
return respond_to(200, data=dict(count=count, data=drug_result))
|
|
|
|
|
|
@router.get('/already_expired', summary="药剂过期")
|
|
async def index(request: Request,page_no: int = 1, page_size: int = 10):
|
|
"""
|
|
药剂过期
|
|
- 只查询在库与出库状态药剂
|
|
:param page_no:
|
|
:param page_size:
|
|
:return:
|
|
"""
|
|
archive_id = request.state.archive_id
|
|
count,drug_result = await get_already_expired(archive_id,page_no, page_size)
|
|
return respond_to(200, data=dict(count=count, data=drug_result))
|
|
|
|
|
|
async def get_lack_stock(page_no: int = 1, page_size: int = 10, **kwargs):
|
|
"""
|
|
库存不足预警
|
|
预估采购量 = 预警数量 - 当前库存不足数量
|
|
:param page_no:
|
|
:param page_size:
|
|
:param kwargs:
|
|
:return:
|
|
"""
|
|
query = QuerySet(Dictionary).filter()
|
|
archive_id = kwargs.get("archive_id")
|
|
if archive_id:
|
|
query = query.filter(archive_id=archive_id)
|
|
dictionary_ids = await query.filter().all().values_list("id", flat=True)
|
|
drug_counts = await Drug.filter(~Q(state=DrugStateEnum.EMPTY),
|
|
dictionary_id__in=dictionary_ids
|
|
).prefetch_related('dictionary').annotate(count=Count('id')).group_by(
|
|
"dictionary_id").order_by("count").values("dictionary_id",
|
|
"count",
|
|
"template_id")
|
|
|
|
data = list()
|
|
for i in drug_counts:
|
|
template_obj = await Template.get(id=i.get("template_id"))
|
|
dictionary_obj = await Dictionary.get(id=i.get("dictionary_id"))
|
|
lack_stock_count = dictionary_obj.params.get("lack_stock_count") if dictionary_obj.params.get(
|
|
"lack_stock_count") else 10
|
|
if i.get("count") < lack_stock_count:
|
|
drug_info = await dictionary_obj.attribute_dictionary_info(template_obj)
|
|
|
|
data.append({
|
|
"drug_value": drug_info,
|
|
"drug_info": ",".join(list(map(lambda x:str(x), drug_info.values()))),
|
|
"count": i.get("count"),
|
|
"dictionary_id": i.get("dictionary_id")
|
|
})
|
|
|
|
count = len(data)
|
|
offset = (page_no - 1) * page_size
|
|
result = data[offset: offset + page_size]
|
|
return count, result
|
|
|
|
|
|
@router.get('/lack_stock', summary="试剂库存不足")
|
|
async def index(request: Request, page_no: int = 1, page_size: int = 10):
|
|
"""
|
|
试剂库存不足
|
|
:param page_no:
|
|
:param page_size:
|
|
:return:
|
|
"""
|
|
# 库存不足阈值 dictionary_obj.params.get("lack_stock_count")
|
|
archive_id = request.state.archive_id
|
|
count, result = await get_lack_stock(page_no, page_size, **{"archive_id": archive_id})
|
|
|
|
return respond_to(data=dict(count=count, data=result))
|
|
|
|
|
|
@router.get('/overdue_return', summary="逾期未归还")
|
|
async def index(request: Request, page_no: int = 1, page_size: int = 10):
|
|
"""
|
|
逾期未归还
|
|
使用期限在终端管理中配置,按照当日固定归还时间或每试剂使用时长
|
|
状态为出库状态药剂
|
|
最后领用时间与逾期时间比较,超过的为逾期未归还药剂
|
|
:param page_no:
|
|
:param page_size:
|
|
:return:
|
|
"""
|
|
# 逾期未归还需要根据大类来获取值
|
|
archive_id = request.state.archive_id
|
|
if archive_id:
|
|
archive_obj = await Archive.get(id=request.state.archive_id)
|
|
else:
|
|
cabinet_obj = await Cabinet.filter(terminal_id=setting.TERMINAL_ID).prefetch_related("archive").first()
|
|
archive_obj = cabinet_obj.archive
|
|
|
|
return_fixed_at = archive_obj.params.get("return_fixed_at") # 每日几点归还
|
|
receive_use_duration = archive_obj.params.get("receive_use_duration") # 领用几小时后归还
|
|
query = QuerySet(Drug).filter(state=DrugStateEnum.OUT)
|
|
if return_fixed_at:
|
|
today_begin_time = datetime.now().strftime("%Y-%m-%d 00:00:00")
|
|
today_end_time = datetime.now().strftime(f"%Y-%m-%d {return_fixed_at}")
|
|
now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
if now_time < today_end_time:
|
|
query = query.filter(Q(last_receive_at__lt=today_begin_time))
|
|
else:
|
|
query = query.filter()
|
|
elif receive_use_duration:
|
|
sub_time = datetime.now() - timedelta(hours=int(receive_use_duration))
|
|
query = query.filter(last_receive_at__lt=sub_time)
|
|
|
|
offset = (page_no - 1) * page_size
|
|
count = await query.count()
|
|
drug_objs = await query.limit(page_size).offset(offset)
|
|
|
|
result = list()
|
|
for drug_obj in drug_objs:
|
|
drug_info = await drug_obj.attribute_drug_info()
|
|
result.append({
|
|
"drug_info": ",".join(list(map(lambda x:str(x), drug_info.values()))),
|
|
"drug_value": drug_info,
|
|
"last_receive_at": parse_datetime(str(drug_obj.last_receive_at), "%Y-%m-%d %H:%M:%S"),
|
|
"user_name": await drug_obj.attribute_last_user()
|
|
})
|
|
return respond_to(200, data=dict(count=count, data=result))
|
|
|
|
|
|
@router.get('/return_weight', summary="归还未称重")
|
|
async def index(request: Request,page_no: int = 1, page_size: int = 10):
|
|
"""
|
|
归还未称重
|
|
:param page_no:
|
|
:param page_size:
|
|
:return:
|
|
"""
|
|
offset = (page_no - 1) * page_size
|
|
query = QuerySet(DrugUseLog).filter(state=DrugUseStateEnum.PUT, alarm_state=1)
|
|
archive_id = request.state.archive_id
|
|
if archive_id:
|
|
query = query.filter(drug__dictionary__archive_id=archive_id)
|
|
count = await query.count()
|
|
drug_use_log_objs = await query.prefetch_related("drug").limit(page_size).offset(offset).order_by("-created_at")
|
|
|
|
result = list()
|
|
for drug_use_log_obj in drug_use_log_objs:
|
|
# 领用人 领用时间
|
|
receive_drug_user_log_obj = await DrugUseLog.filter(drug_id=drug_use_log_obj.drug_id,
|
|
state=DrugUseStateEnum.TAKE,
|
|
created_at__lt=drug_use_log_obj.created_at
|
|
).order_by("-created_at").first()
|
|
|
|
drug_info = await drug_use_log_obj.drug.attribute_drug_info()
|
|
result.append({
|
|
"drug_id": drug_use_log_obj.drug_id,
|
|
"drug_use_log_id": drug_use_log_obj.id,
|
|
"drug_info": ",".join(list(map(lambda x:str(x), drug_info.values()))),
|
|
"drug_value": drug_info,
|
|
"return_user": drug_use_log_obj.users,
|
|
"return_created_at": parse_datetime(str(drug_use_log_obj.created_at), "%Y-%m-%d %H:%M:%S"),
|
|
"receive_user": receive_drug_user_log_obj.users,
|
|
"receive_created_at": parse_datetime(str(receive_drug_user_log_obj.created_at), "%Y-%m-%d %H:%M:%S"),
|
|
"drawer_id": drug_use_log_obj.drawer_id,
|
|
})
|
|
return respond_to(200, data=dict(count=count, data=result))
|
|
|
|
|
|
@router.get('/temperature_overrun', summary="温度超限")
|
|
async def temperature_overrun(page_no: int = 1, page_size: int = 10):
|
|
"""
|
|
温度超限
|
|
:param page_no:
|
|
:param page_size:
|
|
:return:
|
|
"""
|
|
count_query = """select count(*) num from (SELECT env.id, CONCAT('左温区:', env.left_temperature) as temperature , env.created_at, env.cabinet_id FROM environment_logs as env LEFT JOIN cabinets ON env.cabinet_id = cabinets.id WHERE (env.left_temperature >= JSON_EXTRACT(cabinets.params, '$.temperature[0]')+JSON_EXTRACT(cabinets.params, '$.temp_out') or env.left_temperature <= JSON_EXTRACT(cabinets.params, '$.temperature[0]')-JSON_EXTRACT(cabinets.params, '$.temp_out') ) UNION ALL SELECT env.id, CONCAT(IF(env.temperature_type = 1, '', '右温区:'), env.right_temperature) as temperature , env.created_at, env.cabinet_id FROM environment_logs as env LEFT JOIN cabinets ON env.cabinet_id = cabinets.id WHERE (env.right_temperature >= JSON_EXTRACT(cabinets.params, '$.temperature[1]')+JSON_EXTRACT(cabinets.params, '$.temp_out') or env.right_temperature <= JSON_EXTRACT(cabinets.params, '$.temperature[1]')-JSON_EXTRACT(cabinets.params, '$.temp_out') )) temp"""
|
|
query = """select id, temperature, created_at, cabinet_id from (SELECT env.id, CONCAT('左温区:', env.left_temperature) as temperature , env.created_at, env.cabinet_id FROM environment_logs as env LEFT JOIN cabinets ON env.cabinet_id = cabinets.id WHERE (env.left_temperature >= JSON_EXTRACT(cabinets.params, '$.temperature[0]')+JSON_EXTRACT(cabinets.params, '$.temp_out') or env.left_temperature <= JSON_EXTRACT(cabinets.params, '$.temperature[0]')-JSON_EXTRACT(cabinets.params, '$.temp_out') ) UNION ALL SELECT env.id, CONCAT(IF(env.temperature_type = 1, '', '右温区:'), env.right_temperature) as temperature , env.created_at, env.cabinet_id FROM environment_logs as env LEFT JOIN cabinets ON env.cabinet_id = cabinets.id WHERE (env.right_temperature >= JSON_EXTRACT(cabinets.params, '$.temperature[1]')+JSON_EXTRACT(cabinets.params, '$.temp_out') or env.right_temperature <= JSON_EXTRACT(cabinets.params, '$.temperature[1]')-JSON_EXTRACT(cabinets.params, '$.temp_out') )) temp ORDER BY created_at desc"""
|
|
offset = (page_no - 1) * page_size
|
|
page_method = f" limit {page_size} offset {offset}"
|
|
query = query + page_method
|
|
conn = Tortoise.get_connection(connection_name='default')
|
|
count_result = await conn.execute_query(count_query)
|
|
page_list = await conn.execute_query(query)
|
|
conn.close()
|
|
data = []
|
|
for item in page_list[1]:
|
|
cabinet_obj = await Cabinet.get(id=item.get("cabinet_id"))
|
|
item.setdefault("cabinet_name", cabinet_obj.label)
|
|
data.append(item)
|
|
return respond_to(200, data=dict(count=count_result[1][0].get("num"), data=data))
|
|
|
|
|
|
async def get_near_expired(archive_id:str = None, page_no: int = 1, page_size: int = 10,name:str='',stime:str='',etime:str=''):
|
|
query = QuerySet(Drug).filter()
|
|
if archive_id:
|
|
query = query.filter(dictionary__archive_id=archive_id)
|
|
if name:
|
|
query = query.filter(dictionary__k1__icontains=name)
|
|
drug_objs = await query.filter(state__in=[DrugStateEnum.IN, DrugStateEnum.OUT]).prefetch_related(
|
|
'dictionary', 'template').all()
|
|
result = await drug_near_already_expired(drug_objs, "near",stime,etime)
|
|
|
|
count = len(result)
|
|
offset = (page_no - 1) * page_size
|
|
drug_result = result[offset: offset + page_size]
|
|
return count, drug_result
|
|
|
|
|
|
async def get_last_stock(page_no: int = 1, page_size: int = 10, **kwargs):
|
|
query = QuerySet(Dictionary).filter()
|
|
archive_id = kwargs.get("archive_id")
|
|
if archive_id:
|
|
query = query.filter(archive_id=archive_id)
|
|
dictionary_ids = await query.filter().all().values_list("id", flat=True)
|
|
drug_counts = await Drug.filter(~Q(state=DrugStateEnum.EMPTY),
|
|
dictionary_id__in=dictionary_ids
|
|
).prefetch_related('dictionary').annotate(count=Count('id')).group_by(
|
|
"dictionary_id").order_by("count").values("dictionary_id",
|
|
"count",
|
|
"template_id")
|
|
|
|
data = list()
|
|
for i in drug_counts:
|
|
template_obj = await Template.get(id=i.get("template_id"))
|
|
dictionary_obj = await Dictionary.get(id=i.get("dictionary_id"))
|
|
lack_stock_count = dictionary_obj.params.get("lack_stock_count") if dictionary_obj.params.get(
|
|
"lack_stock_count") else 10
|
|
if i.get("count") < lack_stock_count:
|
|
drug_info = await dictionary_obj.attribute_dictionary_info(template_obj)
|
|
warning_date = datetime.now().date()
|
|
data.append({
|
|
"drug_info": ",".join(list(map(lambda x:str(x), drug_info.values()))),
|
|
"试剂名称":",".join(list(map(lambda x:str(x), drug_info.values()))),
|
|
"count": i.get("count"),
|
|
"types":"余量预警",
|
|
"warning_date":warning_date,
|
|
"dictionary_id": i.get("dictionary_id"),
|
|
"info":",".join(list(map(lambda x:str(x), drug_info.values())))+'库存不足'+str(i.get("count"))
|
|
})
|
|
|
|
count = len(data)
|
|
offset = (page_no - 1) * page_size
|
|
result = data[offset: offset + page_size]
|
|
return count, result
|
|
|
|
|
|
async def get_slack_drug(archive_id:str = None, page_no: int = 1, page_size: int = 10,name:str='',stime:str='',etime:str='',slack_day: int=30):
|
|
now_time = datetime.now(pytz.timezone('Asia/Shanghai'))
|
|
slack_date = now_time - timedelta(days=slack_day)
|
|
query = QuerySet(Drug).filter(state__in=[DrugStateEnum.IN])
|
|
if archive_id:
|
|
query = query.filter(dictionary__archive_id=archive_id)
|
|
if name:
|
|
query = query.filter(dictionary__k1__icontains=name)
|
|
drug_objs = await query.filter().all()
|
|
result=list()
|
|
for drug_obj in drug_objs:
|
|
now_slack_days = (now_time - drug_obj.last_receive_at).days if drug_obj.last_receive_at else (
|
|
now_time - drug_obj.storage_at).days#呆滞天数
|
|
if now_slack_days > slack_day:
|
|
warning_date =(now_time - timedelta(days=now_slack_days)).date()
|
|
last_use_at = drug_obj.last_return_at.strftime("%Y-%m-%d") if drug_obj.last_return_at else ''
|
|
attribute_drug = await drug_obj.attribute_drug_info()
|
|
data = {
|
|
"types":"呆滞预警",
|
|
"warning_date":warning_date,
|
|
"drug_id": drug_obj.id,
|
|
"rfid": drug_obj.rfid,
|
|
"hole": drug_obj.hole,
|
|
"cabinet_id": drug_obj.cabinet_id if drug_obj.cabinet_id else await drug_obj.attribute_cabinet_id(),
|
|
"drawer_id": drug_obj.drawer_id,
|
|
"board_id": drug_obj.board_id,
|
|
"position": drug_obj.position,
|
|
"expired_at": drug_obj.expired_at.strftime("%Y-%m-%d") if drug_obj.expired_at else '-',
|
|
"remain_gross_weight": await drug_obj.format_weight(),
|
|
"drug_info": attribute_drug,
|
|
"now_slack_days": now_slack_days, # 呆滞天数
|
|
"last_use_at": last_use_at, # 最后使用时间
|
|
"last_user": await drug_obj.attribute_last_user(), # 最后使用人
|
|
"info":drug_obj.position+drug_obj.fill_json_content.get('k1','')+'已放置'+str(now_slack_days)+'天未领用'
|
|
}
|
|
if stime:
|
|
if etime:
|
|
if etime >warning_date>stime:
|
|
result.append(data)
|
|
else:
|
|
if warning_date>stime:
|
|
result.append(data)
|
|
else:
|
|
if etime:
|
|
if etime >warning_date:
|
|
result.append(data)
|
|
else:
|
|
result.append(data)
|
|
count = len(result)
|
|
offset = (page_no - 1) * page_size
|
|
drug_result = result[offset: offset + page_size]
|
|
return count, drug_result
|
|
|
|
|
|
async def get_over_return(archive_id:str = None, page_no: int = 1, page_size: int = 10,name:str='',stime:str='',etime:str=''):
|
|
query = QuerySet(Drug).filter(state__in=[DrugStateEnum.OUT])
|
|
if archive_id:
|
|
query = query.filter(dictionary__archive_id=archive_id)
|
|
if name:
|
|
query = query.filter(dictionary__k1__icontains=name)
|
|
|
|
archive_obj = await Archive.get(id=archive_id)
|
|
return_fixed_at = archive_obj.params.get("return_fixed_at") # 每日几点归还
|
|
receive_use_duration = archive_obj.params.get("receive_use_duration") # 领用几小时后归还
|
|
|
|
if return_fixed_at:
|
|
today_begin_time = datetime.now().strftime("%Y-%m-%d 00:00:00")
|
|
today_end_time = datetime.now().strftime(f"%Y-%m-%d {return_fixed_at}")
|
|
now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
if now_time < today_end_time:
|
|
query = query.filter(Q(last_receive_at__lt=today_begin_time))
|
|
else:
|
|
query = query.filter()
|
|
elif receive_use_duration:
|
|
sub_time = datetime.now() - timedelta(hours=int(receive_use_duration))
|
|
query = query.filter(last_receive_at__lt=sub_time)
|
|
|
|
drug_objs = await query.filter().all()
|
|
result = list()
|
|
for drug_obj in drug_objs:
|
|
drug_info = await drug_obj.attribute_drug_info()
|
|
if return_fixed_at:
|
|
warning_date =today_end_time
|
|
else:
|
|
warning_date=drug_obj.last_receive_at + timedelta(hours=int(receive_use_duration))
|
|
data ={
|
|
"drug_info": ",".join(list(map(lambda x:str(x), drug_info.values()))),
|
|
"试剂名称":",".join(list(map(lambda x:str(x), drug_info.values()))),
|
|
"last_receive_at": parse_datetime(str(drug_obj.last_receive_at), "%Y-%m-%d %H:%M:%S"),
|
|
"user_name": await drug_obj.attribute_last_user(),
|
|
"warning_date":warning_date,
|
|
"types":"超期未归还预警",
|
|
"info":await drug_obj.attribute_last_user()+parse_datetime(str(drug_obj.last_receive_at), "%Y-%m-%d %H:%M:%S")+"领用"+",".join(list(map(lambda x:str(x), drug_info.values())))+'超期未归还'
|
|
}
|
|
if stime:
|
|
if etime:
|
|
if etime >warning_date.date()>stime:
|
|
result.append(data)
|
|
else:
|
|
if warning_date.date()>stime:
|
|
result.append(data)
|
|
else:
|
|
if etime:
|
|
if etime >warning_date.date():
|
|
result.append(data)
|
|
else:
|
|
result.append(data)
|
|
count = len(result)
|
|
offset = (page_no - 1) * page_size
|
|
drug_result = result[offset: offset + page_size]
|
|
return count, drug_result
|
|
|
|
|
|
async def get_filter_element(archive_id:str = None, page_no: int = 1, page_size: int = 10,name:str='',stime:str='',etime:str=''):
|
|
now_time = datetime.now(pytz.timezone('Asia/Shanghai')).date()
|
|
query = QuerySet(Cabinet).filter()
|
|
if archive_id:
|
|
query = query.filter(archive_id=archive_id)
|
|
if name:
|
|
query = query.filter(label__icontains=name)
|
|
cabinet_objs = await query.filter().all()
|
|
result = list()
|
|
for cabinet_obj in cabinet_objs:
|
|
filterExpire =cabinet_obj.params.get('filterExpire') if cabinet_obj.params else None
|
|
if filterExpire:
|
|
warning_date =datetime.strptime(filterExpire, '%Y-%m-%d').date()
|
|
if filterExpire and warning_date < now_time:
|
|
data={
|
|
"label":cabinet_obj.label,
|
|
"location":cabinet_obj.location,
|
|
"warning_date":filterExpire,
|
|
"types":"滤芯预警",
|
|
'info':cabinet_obj.label+'滤芯过期'
|
|
}
|
|
if stime:
|
|
if etime:
|
|
if etime >warning_date>stime:
|
|
result.append(data)
|
|
else:
|
|
if warning_date>stime:
|
|
result.append(data)
|
|
else:
|
|
if etime:
|
|
if etime >warning_date:
|
|
result.append(data)
|
|
else:
|
|
result.append(data)
|
|
|
|
count = len(result)
|
|
offset = (page_no - 1) * page_size
|
|
drug_result = result[offset: offset + page_size]
|
|
return count, drug_result
|
|
|
|
|
|
async def get_already_expired(archive_id:str = None, page_no: int = 1, page_size: int = 10,name:str='',stime:str='',etime:str=''):
|
|
query = QuerySet(Drug).filter()
|
|
if archive_id:
|
|
query = query.filter(dictionary__archive_id=archive_id)
|
|
if name:
|
|
query = query.filter(dictionary__k1__icontains=name)
|
|
drug_objs = await query.filter(state__in=[DrugStateEnum.IN, DrugStateEnum.OUT]).prefetch_related(
|
|
'dictionary', 'template').all()
|
|
result = await drug_near_already_expired(drug_objs, "already",stime,etime)
|
|
count = len(result)
|
|
offset = (page_no - 1) * page_size
|
|
drug_result = result[offset: offset + page_size]
|
|
return count,drug_result
|
|
|
|
|
|
async def get_illegal_takeout_log(archive_id:str = None, page_no: int = 1, page_size: int = 10,name:str='',stime:str='',etime:str=''):
|
|
query = Log.filter(kind="非法领用")
|
|
if stime:
|
|
# stime = datetime.strptime(stime, '%Y-%m-%d').date() 前面处理过了
|
|
query = query.filter(created_at__gte=stime)
|
|
if etime:
|
|
# etime = datetime.strptime(etime, '%Y-%m-%d').date()
|
|
query = query.filter(created_at__lte=etime)
|
|
count = await query.count()
|
|
offset = (page_no - 1) * page_size
|
|
illegal_takeout_logs = await query.order_by("-created_at").limit(page_size).offset(offset).all()
|
|
result = list()
|
|
for log in illegal_takeout_logs:
|
|
result.append({
|
|
"id": log.id,
|
|
"kind": log.kind,
|
|
"users": log.users,
|
|
"comment": log.comment,
|
|
"img_name": log.img_name,
|
|
"created_at": log.created_at.strftime("%Y-%m-%d %H:%M:%S"),
|
|
})
|
|
|
|
return count, result
|
|
|
|
|
|
async def get_over_temperature(archive_id:str = None, page_no: int = 1, page_size: int = 10,name:str='',stime:str='',etime:str=''):
|
|
Str ="where 1=1 "
|
|
if name:
|
|
Str +=" and label like '%{}%' ".format(name)
|
|
if stime:
|
|
Str +=" and created_at > '{}'".format(stime)
|
|
if stime:
|
|
Str +=" and created_at < '{}'".format(etime)
|
|
Str += " ORDER BY created_at desc"
|
|
count_query = """select count(*) num from (SELECT env.id, CONCAT('左温区:', env.left_temperature) as temperature , env.created_at, env.cabinet_id,cabinets.label FROM environment_logs as env LEFT JOIN cabinets ON env.cabinet_id = cabinets.id WHERE (env.left_temperature >= JSON_EXTRACT(cabinets.params, '$.temperature[0]')+JSON_EXTRACT(cabinets.params, '$.temp_out') or env.left_temperature <= JSON_EXTRACT(cabinets.params, '$.temperature[0]')-JSON_EXTRACT(cabinets.params, '$.temp_out') ) UNION ALL SELECT env.id, CONCAT(IF(env.temperature_type = 1, '', '右温区:'), env.right_temperature) as temperature , env.created_at, env.cabinet_id,cabinets.label FROM environment_logs as env LEFT JOIN cabinets ON env.cabinet_id = cabinets.id WHERE (env.right_temperature >= JSON_EXTRACT(cabinets.params, '$.temperature[1]')+JSON_EXTRACT(cabinets.params, '$.temp_out') or env.right_temperature <= JSON_EXTRACT(cabinets.params, '$.temperature[1]')-JSON_EXTRACT(cabinets.params, '$.temp_out') )) temp """ +Str
|
|
query = """select id, temperature, created_at, cabinet_id,temp_out,settemp from (SELECT env.id, CONCAT('左温区:', env.left_temperature) as temperature , env.created_at, env.cabinet_id,cabinets.label,JSON_EXTRACT(cabinets.params, '$.temp_out') as temp_out,JSON_EXTRACT(cabinets.params, '$.temperature[0]') as settemp FROM environment_logs as env LEFT JOIN cabinets ON env.cabinet_id = cabinets.id WHERE (env.left_temperature >= JSON_EXTRACT(cabinets.params, '$.temperature[0]')+JSON_EXTRACT(cabinets.params, '$.temp_out') or env.left_temperature <= JSON_EXTRACT(cabinets.params, '$.temperature[0]')-JSON_EXTRACT(cabinets.params, '$.temp_out') ) UNION ALL SELECT env.id, CONCAT(IF(env.temperature_type = 1, '', '右温区:'), env.right_temperature) as temperature , env.created_at, env.cabinet_id,cabinets.label,JSON_EXTRACT(cabinets.params, '$.temp_out') as temp_out,JSON_EXTRACT(cabinets.params, '$.temperature[1]') as settemp FROM environment_logs as env LEFT JOIN cabinets ON env.cabinet_id = cabinets.id WHERE (env.right_temperature >= JSON_EXTRACT(cabinets.params, '$.temperature[1]')+JSON_EXTRACT(cabinets.params, '$.temp_out') or env.right_temperature <= JSON_EXTRACT(cabinets.params, '$.temperature[1]')-JSON_EXTRACT(cabinets.params, '$.temp_out') )) temp """+Str
|
|
offset = (page_no - 1) * page_size
|
|
page_method = f" limit {page_size} offset {offset}"
|
|
query = query + page_method
|
|
conn = Tortoise.get_connection(connection_name='default')
|
|
count_result = await conn.execute_query(count_query)
|
|
page_list = await conn.execute_query(query)
|
|
conn.close()
|
|
data = []
|
|
for item in page_list[1]:
|
|
cabinet_obj = await Cabinet.get(id=item.get("cabinet_id"))
|
|
item.setdefault("cabinet_name", cabinet_obj.label)
|
|
item.setdefault("types", '温度预警')
|
|
item.setdefault("info", cabinet_obj.label+item.get("temperature")+'℃不在设置温度'+item.get("temp_out")+'℃范围之内')
|
|
data.append(item)
|
|
return count_result[1][0].get("num"),data
|
|
|
|
|
|
@router.post('/get_Warningdata', summary="预警")
|
|
async def get_Warningdata(request: Request, keyword:SearchWord):
|
|
"""
|
|
预警信息
|
|
:param request:
|
|
:param keyword:
|
|
:WarningType('1':'临期','2':'余量',3:'呆滞','4':'超期未归还','5':'滤芯保质期','6':'过期','7':'配存禁忌','8':'违规领用','9':'温湿度')
|
|
:return:
|
|
"""
|
|
page_no = keyword.page_no
|
|
page_size = keyword.page_size
|
|
name = keyword.name
|
|
stime = keyword.stime
|
|
etime = keyword.etime
|
|
slack_day = keyword.slack_day#呆滞时间默认30days
|
|
if stime:
|
|
stime =datetime.strptime(keyword.stime, '%Y-%m-%d').date()
|
|
if etime:
|
|
etime =datetime.strptime(keyword.etime, '%Y-%m-%d').date()
|
|
WarningType = keyword.WarningType
|
|
# archive_id = keyword.archive_id
|
|
archive_id = request.state.archive_id
|
|
if WarningType=='1':
|
|
count,drug_result = await get_near_expired(archive_id,page_no, page_size,name,stime,etime)
|
|
if WarningType=='2':
|
|
count, drug_result = await get_last_stock(page_no, page_size, **{"archive_id": archive_id})
|
|
if WarningType=='3':
|
|
count,drug_result = await get_slack_drug(archive_id,page_no, page_size,name,stime,etime,slack_day)
|
|
if WarningType=='4':
|
|
count,drug_result = await get_over_return(archive_id,page_no, page_size,name,stime,etime)
|
|
if WarningType=='5':
|
|
count,drug_result = await get_filter_element(archive_id,page_no, page_size,name,stime,etime)
|
|
if WarningType=='6':
|
|
count, drug_result = await get_already_expired(archive_id,page_no, page_size,name,stime,etime)
|
|
if WarningType=='7':
|
|
# count, drug_result = await get_illegal_takeout_log(archive_id,page_no, page_size,name,stime,etime)
|
|
count, drug_result = 0, []
|
|
if WarningType=='8':
|
|
count, drug_result = await get_illegal_takeout_log(archive_id,page_no, page_size,name,stime,etime)
|
|
if WarningType=='9':
|
|
count, drug_result = await get_over_temperature(archive_id,page_no, page_size,name,stime,etime)
|
|
return respond_to(200, data=dict(count=count, data=drug_result))
|
|
|
|
|
|
@router.get('/get_Warningnum', summary="预警数量")
|
|
async def get_Warningnum(request: Request,page_no: int = 1, page_size: int = 1):
|
|
"""
|
|
预警信息
|
|
:param request:
|
|
:return:
|
|
"""
|
|
archive_id = request.state.archive_id
|
|
near_expired_count,drug_result = await get_near_expired(archive_id,page_no, page_size)
|
|
last_stock_count, drug_result = await get_last_stock(page_no, page_size, **{"archive_id": archive_id})
|
|
slack_drug_count,drug_result = await get_slack_drug(archive_id,page_no, page_size)
|
|
over_return_count,drug_result = await get_over_return(archive_id,page_no, page_size)
|
|
filter_element_count,drug_result = await get_filter_element(archive_id,page_no, page_size)
|
|
already_expired_count, drug_result = await get_already_expired(archive_id,page_no, page_size)
|
|
# taboo_count, drug_result = await get_test(archive_id,page_no, page_size)
|
|
violation_count, drug_result = await get_illegal_takeout_log(archive_id,page_no, page_size)
|
|
over_temperature_count, drug_result = await get_over_temperature(archive_id,page_no, page_size)
|
|
data={
|
|
"near_expired_count":near_expired_count,
|
|
"last_stock_count":last_stock_count,
|
|
"slack_drug_count":slack_drug_count,
|
|
"over_return_count":over_return_count,
|
|
"filter_element_count":filter_element_count,
|
|
"already_expired_count":already_expired_count,
|
|
"taboo_count":0,
|
|
"violation_count":violation_count,
|
|
"over_temperature_count":over_temperature_count,
|
|
}
|
|
return respond_to(200, data=data) |