safesite/safesite/tasks.py

416 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task
import json
import logging
import requests
from .models import User,Checkjob,Checktask,Trouble,Dickey,Partment,Dicclass,Train,Drill,TroubleAccess,Group,Yjyc,Yjsetup,Socertificate,Trainuser,Risk,Risktask,RiskActTask,Miss,Observe,RiskAct
import datetime
import calendar
import pandas as pd
from sklearn import linear_model
from django.db.models import Sum
from django.conf import settings
from .safespider import getTzzs
dirname = settings.BASE_DIR +'/safesite/'
def getcs(companyid):#获取公司相关参数设置
print(companyid)
return Yjsetup.objects.filter(usecomp__partid=companyid).values()[0]
def gettime(x=datetime.datetime.now()):
days_num = calendar.monthrange(x.year, x.month)[1]
first_day = datetime.date(x.year,x.month,1)
first_day_of_next_month = first_day + datetime.timedelta(days = days_num)
return first_day,first_day_of_next_month
@shared_task
def send_wechatmsgs(postdict,tolist):
with open(dirname + 'token.txt','r',encoding= 'utf-8') as f:
token=f.read()
try:
for i in tolist:
postdict['touser']=i
requests.post('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='+token,data=json.dumps(postdict))
except:
pass
@shared_task
def send_wechatmsg(postdict):
with open(dirname + 'token.txt','r',encoding= 'utf-8') as f:
token=f.read()
try:
v = requests.post('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='+token,data=json.dumps(postdict))
print(v.text())
except:
pass
@shared_task
def yjjs(companyid):
first_day,first_day_of_next_month = gettime()
#隐患算分
a = Trouble.objects.filter(fxsj__range=(first_day, first_day_of_next_month),usecomp__partid=companyid,deletemark=1)
#隐患按时上报率
if a.count()==0:
sbjs = 1
else:
sbjs = 0
#隐患整改率
if a.count() != 0:
zgjs = a.filter(yhzt__in=[4,5,6]).count()/a.count()
else:
zgjs = 4
if zgjs == 1:
zgjs = 0
elif zgjs>=0.8 and zgjs <1:
zgjs = 0.1
elif zgjs>=0.5 and zgjs<0.8:
zgjs = 0.3
elif zgjs>=0.3 and zgjs<0.5:
zgjs = 0.5
else:
zgjs = 1*4
cs = getcs(companyid)
yhsw = a.filter(yhpg__dickeyid=53).count() #死亡隐患数
yhzs = a.filter(yhpg__dickeyid=52).count()
yhqs = a.filter(yhpg__dickeyid=51).count()
yhqws = a.filter(yhpg__dickeyid=50).count()
yhwsh = a.filter(yhpg__dickeyid=49).count()
score = (((yhsw*1 + yhzs*0.6 + yhqs*0.3+ yhqws*0.2 + yhwsh*0.1)/cs['monthyhavg'] )* cs['yhpgqz']+ #隐患评估
(a.filter(yhdj__dickeyid=55).count()*0.3+a.filter(yhdj__dickeyid=56).count()*1)* cs['yhdjqz']+ #隐患等级
sbjs*cs['yhsblqz']+ #隐患上报率
zgjs*cs['yhzglqz']) #隐患整改率
#print(score)
year = first_day.year
month = first_day.month
obj,created = Yjyc.objects.get_or_create(usecomp__partid=companyid,year=year,month=month,defaults={'usecomp':Partment.objects.get(partid=companyid) ,'year':year,'month':month})
obj.troublevalue = score
obj.yjz = round(obj.troublevalue + obj.trainvalue + obj.drillvalue + obj.missvalue + obj.observevalue,2)
obj.save()
@shared_task
def yjjs_px(companyid):
first_day,first_day_of_next_month = gettime()
#培训算分
a = Train.objects.filter(starttime__range=(first_day, first_day_of_next_month),usecomp__partid=companyid,state=1,deletemark=1) #有效培训
#计算培训效果
participantnum = Trainuser.objects.filter(train__in=a).count()
knownum = a.aggregate(knownum = Sum('knownum'))['knownum']
if participantnum != 0:
x = knownum/participantnum
else:
x = 0
if x == 1:
pxxg = 1
elif 1>x>= 0.9:
pxxg = 0.8
elif 0.9>x>=0.6:
pxxg = 0.5
else:
pxxg = 0.1
#培训等级
cs = getcs(companyid)
score = ((a.filter(trainlevel__dicid=5).count()*0.5 + a.filter(trainlevel__dicid=6).count()*0.8 + a.filter(trainlevel__dicid=7).count()*0.5+ a.filter(trainlevel__dicid=42).count()*0.5)*cs['pxdjqz'] +
pxxg*cs['pxxgqz'] ) #培训效果
year = first_day.year
month = first_day.month
obj,created = Yjyc.objects.get_or_create(usecomp__partid=companyid,year=year,month=month,defaults={'usecomp':Partment.objects.get(partid=companyid) ,'year':year,'month':month})
obj.trainvalue = -score
obj.yjz = round(obj.troublevalue + obj.trainvalue + obj.drillvalue + obj.missvalue + obj.observevalue,2)
obj.save()
@shared_task
def yjjs_gc(companyid):
first_day,first_day_of_next_month = gettime()
#观察算分
a = Observe.objects.filter(looktime__range=(first_day, first_day_of_next_month),usecomp__partid=companyid,deletemark=1)
num = a.count()
if num>40:
score = (num-40)*0.04 + 40*0.4
else:
score = num*0.4
year = first_day.year
month = first_day.month
obj,created = Yjyc.objects.get_or_create(usecomp__partid=companyid,year=year,month=month,defaults={'usecomp':Partment.objects.get(partid=companyid) ,'year':year,'month':month})
obj.observevalue = -score
obj.yjz = round(obj.troublevalue + obj.trainvalue + obj.drillvalue + obj.missvalue + obj.observevalue,2)
obj.save()
@shared_task
def yjjs_ws(companyid):
#未遂算分
first_day,first_day_of_next_month = gettime()
a = Miss.objects.filter(misstime__range=(first_day, first_day_of_next_month),usecomp__partid=companyid,deletemark=1) #
score = (a.count())*0.6
year = first_day.year
month = first_day.month
obj,created = Yjyc.objects.get_or_create(usecomp__partid=companyid,year=year,month=month,defaults={'usecomp':Partment.objects.get(partid=companyid) ,'year':year,'month':month})
obj.missvalue = score
obj.yjz = round(obj.troublevalue + obj.trainvalue + obj.drillvalue + obj.missvalue + obj.observevalue,2)
obj.save()
@shared_task
def yjjs_yl(companyid):
first_day,first_day_of_next_month = gettime()
a = Drill.objects.filter(starttime__range=(first_day, first_day_of_next_month),usecomp__partid=companyid,state=1,deletemark=1) #有效演练
#计算演练效果
participantnum = Drill.objects.filter(drillid__in=a).count()
knownum = a.aggregate(knownum = Sum('knownum'))['knownum']
if participantnum != 0:
x = knownum/participantnum
else:
x = 0
if x == 1:
ylxg = 1
elif 1>x>= 0.9:
ylxg = 0.8
elif 0.9>x>=0.6:
ylxg = 0.5
else:
ylxg = 0.1
#演练等级
cs = getcs(companyid)
score = ((a.filter(drilllevel__dicid=20).count()*1 + a.filter(drilllevel__dicid=21).count()*0.5 + a.filter(drilllevel__dicid=22).count()*1 + a.filter(drilllevel__dicid=43).count()*0.5)*cs['yldjqz'] +
ylxg*cs['ylxgqz'] ) #演练效果
year = first_day.year
month = first_day.month
obj,created = Yjyc.objects.get_or_create(usecomp__partid=companyid,year=year,month=month,defaults={'usecomp':Partment.objects.get(partid=companyid) ,'year':year,'month':month})
obj.drillvalue = -score
obj.yjz = round(obj.troublevalue + obj.trainvalue + obj.drillvalue,2)
obj.save()
@shared_task
def ycjs():
#print('正在执行预测计算。。。')
companys = Partment.objects.filter(iscompany=1)
nowyear = datetime.datetime.now().year
nowmonth = datetime.datetime.now().month
objs = Yjyc.objects.exclude(yjz=0,year=nowyear,month=nowmonth)
for x in companys:
obj = objs.filter(usecomp=x).order_by('-yjycid')
objv = obj.values('yjycid','yjz')
#print(objv)
if len(obj)>1:
vl = list(objv)
for i in range(len(vl)):
vl[i]['num'] = i+1
if i == 0:
vl[i]['yjzs'] = vl[i]['yjz']
if i > 0 :
vl[i]['yjzs'] = vl[i-1]['yjzs'] + vl[i]['yjz']
df = pd.DataFrame(vl)
# 建立线性回归模型
regr = linear_model.LinearRegression()
# 拟合
regr.fit(df['num'].values.reshape(-1, 1), df['yjzs']) # 注意此处.reshape(-1, 1)因为X是一维的
# 得到直线的斜率、截距
a, b = regr.coef_, regr.intercept_
# 更新本月的预测值
# first_day,first_day_of_next_month = gettime()
# year = first_day_of_next_month.year
# month = first_day_of_next_month.month
objnew,created = Yjyc.objects.get_or_create(usecomp=x,year=nowyear,month=nowmonth,defaults={'usecomp':x,'year':nowyear,'month':nowmonth})
objnew.ycz = ("%.2f" % a)
objnew.b = ("%.2f" % b)
objnew.save()
#print('执行完毕!')
@shared_task
def risktask():
nowtime = datetime.datetime.now()
for i in Risk.objects.exclude(tasktype=0):
if i.tasktype == 1:
if i.tasktime:
if (nowtime - i.tasktime).seconds>=28800:
taskexpire = nowtime + datetime.timedelta(seconds=28800)
Risktask.objects.filter(risk=i).update(usable=0)
Risktask.objects.create(risk=i,group=i.group,taskexpire = taskexpire,taskadd=nowtime)
i.tasktime = nowtime
i.save()
elif i.tasktype == 2:
if i.tasktime:
if (nowtime - i.tasktime).days>=1:
taskexpire = nowtime + datetime.timedelta(days=1)
Risktask.objects.filter(risk=i).update(usable=0)
Risktask.objects.create(risk=i,group=i.group,taskexpire = taskexpire,taskadd=nowtime)
i.tasktime = nowtime
i.save()
elif i.tasktype == 3:
if i.tasktime:
if (nowtime - i.tasktime).days>=7:
taskexpire = nowtime + datetime.timedelta(days=7)
Risktask.objects.filter(risk=i).update(usable=0)
Risktask.objects.create(risk=i,group=i.group,taskexpire = taskexpire,taskadd=nowtime)
i.tasktime = nowtime
i.save()
# elif i.tasktype == 4:
# if i.tasktime:
# if (nowtime - i.tasktime).weeks>=4:
# taskexpire = i.tasktime + datetime.timedelta(weeks=4)
# Risktask.objects.filter(risk=i).update(usable=0)
# Risktask.objects.create(risk=i,group=i.group,taskexpire = taskexpire)
# i.tasktime = taskexpire
# i.save()
@shared_task
def riskacttask():
nowtime = datetime.datetime.now()
for i in RiskAct.objects.exclude(tasktype=0):
if i.tasktype == 1:
if i.tasktime:
if (nowtime - i.tasktime).seconds>=28800:
taskexpire = nowtime + datetime.timedelta(seconds=28800)
RiskActTask.objects.filter(riskact=i,istask=1).update(usable=0)
RiskActTask.objects.create(riskact=i,taskexpire = taskexpire,taskadd=nowtime,istask=1)
i.tasktime = nowtime
i.save()
elif i.tasktype == 2:
if i.tasktime:
if (nowtime - i.tasktime).days>=1:
taskexpire = nowtime + datetime.timedelta(days=1)
RiskActTask.objects.filter(riskact=i,istask=1).update(usable=0)
RiskActTask.objects.create(riskact=i,taskexpire = taskexpire,taskadd=nowtime,istask=1)
i.tasktime = nowtime
i.save()
elif i.tasktype == 3:
if i.tasktime:
if (nowtime - i.tasktime).days>=7:
taskexpire = nowtime + datetime.timedelta(days=7)
RiskActTask.objects.filter(riskact=i,istask=1).update(usable=0)
RiskActTask.objects.create(riskact=i,taskexpire = taskexpire,taskadd=nowtime,istask=1)
i.tasktime = nowtime
i.save()
@shared_task
def checktask():
nowtime = datetime.datetime.now()
for i in Checktask.objects.exclude(deletemark=0):
if i.tasktype==1:
if i.checktime:
if (nowtime - i.checktime).days>=1:
endtimes = nowtime + datetime.timedelta(days=1)
for j in i.checkname.all():
x=User.objects.get(userid=j.userid)
Checkjob.objects.filter(checktask=i,checkname=x).update(jobstate=2)
Checkjob.objects.create(checktask=i,checkname=x,starttime=nowtime,endtime = endtimes,usecomp=i.usecomp)
i.checktime = nowtime
i.save()
elif i.tasktype==2:
if i.checktime:
if (nowtime - i.checktime).days>=7:
endtimes = nowtime + datetime.timedelta(days=7)
for j in i.checkname.all():
x=User.objects.get(userid=j.userid)
Checkjob.objects.filter(checktask=i,checkname=x).update(jobstate=2)
Checkjob.objects.create(checktask=i,checkname=x,starttime=nowtime,endtime = endtimes,usecomp=i.usecomp)
i.checktime = nowtime
i.save()
elif i.tasktype==3:
if i.checktime:
if (nowtime - i.checktime).days>=30:
endtimes = nowtime + datetime.timedelta(days=30)
for j in i.checkname.all():
x=User.objects.get(userid=j.userid)
Checkjob.objects.filter(checktask=i,checkname=x).update(jobstate=2)
Checkjob.objects.create(checktask=i,checkname=x,starttime=nowtime,endtime = endtimes,usecomp=i.usecomp)
i.checktime = nowtime
i.save()
elif i.tasktype==4:
if i.checktime:
if (nowtime - i.checktime).days>=120:
endtimes = nowtime + datetime.timedelta(days=120)
for j in i.checkname.all():
x=User.objects.get(userid=j.userid)
Checkjob.objects.filter(checktask=i,checkname=x).update(jobstate=2)
Checkjob.objects.create(checktask=i,checkname=x,starttime=nowtime,endtime = endtimes,usecomp=i.usecomp)
i.checktime = nowtime
i.save()
elif i.tasktype==5:
if i.checktime:
if (nowtime - i.checktime).days>=182:
endtimes = nowtime + datetime.timedelta(days=182)
for j in i.checkname.all():
x=User.objects.get(userid=j.userid)
Checkjob.objects.filter(checktask=i,checkname=x).update(jobstate=2)
Checkjob.objects.create(checktask=i,checkname=x,starttime=nowtime,endtime = endtimes,usecomp=i.usecomp)
i.checktime = nowtime
i.save()
elif i.tasktype==6:
if i.checktime:
if (nowtime - i.checktime).days>=365:
endtimes = nowtime + datetime.timedelta(days=365)
for j in i.checkname.all():
x=User.objects.get(userid=j.userid)
Checkjob.objects.filter(checktask=i,checkname=x).update(jobstate=2)
Checkjob.objects.create(checktask=i,checkname=x,starttime=nowtime,endtime = endtimes,usecomp=i.usecomp)
i.checktime = nowtime
i.save()
def updateTzzs():
for x in Socertificate.objects.all():
data = getTzzs(x.cardnum,x.realname)
data1 = []
if data:
for i in data:
if i['操作项目'] not in data1:
updated_values={
'realname':i['姓名'],
'gender':i['性别'],
'zylb':i['作业类别'],
'czxm':i['操作项目'],
'fzjg':i['发证机关'],
'ccfzrq':i['初次发证日期'] if i['初次发证日期'] else None,
'yfsrq':i['应复审日期'] if i['应复审日期'] else None,
'yxqkssj':i['有效期开始时间'] if i['有效期开始时间'] else None,
'yxqjssj':i['有效期结束时间'] if i['有效期结束时间'] else None,
'sjfssj':i['实际复审时间'] if i['实际复审时间'] else None,
'url':i['url'],
}
try:
updated_values['zszt'] = guoqi(i['应复审日期'])
except:
pass
obj, created = Socertificate.objects.update_or_create(
cardnum=x.cardnum, czxm=i['操作项目'], defaults=updated_values)
data1.append(i['操作项目'])
else:
obj = Socertificate.objects.get(cardnum=x.cardnum, czxm=i['操作项目'])
if obj.yxqjssj.strftime('%Y-%m-%d')<i['有效期结束时间']:
obj.yfsrq = i['应复审日期'] if i['应复审日期'] else None
obj.yxqkssj = i['有效期结束时间'] if i['有效期结束时间'] else None
obj.yxqjssj = i['有效期结束时间'] if i['有效期结束时间'] else None
obj.sjfssj = i['实际复审时间'] if i['实际复审时间'] else None
try:
zsst = guoqi(i['应复审日期'])
obj.zszt = zsst
except:
pass
obj.save()
def guoqi(x):
now = datetime.datetime.now()
now1 = datetime.datetime.now() + datetime.timedelta(days=180)
if datetime.datetime.strptime(x,'%Y-%m-%d')>now1:
return 1
elif now1 > datetime.datetime.strptime(x,'%Y-%m-%d')>now:
return 2
else:
return 3
def updateAqzs():
pass