def analysis_data(request): if request.method == "GET": try: page = int(request.GET.get('page')) number = request.GET.get('num') dict_data = {} count = PartItemResult.objects.order_by("Id").count() if number == "All": data = PartItemResult.objects.order_by("Id").all().values() data = list(data) dict_data['data'] = data dict_data['page_count'] = count return restful.ok(data=dict_data) if number != "All": number = int(number) page_num = count // number # 总共多少页 if count % number > 0: page_num = page_num + 1 if page_num >= page: data = PartItemResult.objects.order_by( "Id").all().values()[(page - 1) * number:number * page] data = list(data) dict_data['data'] = data dict_data['page_count'] = page_num return restful.ok(data=dict_data) else: return restful.params_error( message="it had no other pages") except: return restful.params_error(message="data got fail")
def post(self,request): try: Employee_email = request.POST['Employee_email'] password = request.POST['u_password'] user = User.objects.get(Email=Employee_email) if (user.Password == password): if user.IsActivated == False: Update_User_IsActivated(Employee_email) request.session['user_Id'] = user.Id request.session.set_expiry(0) return restful.ok(message="login success") request.session['user_Id'] = user.Id request.session.set_expiry(0) return restful.ok(message="login success") return restful.params_error(message='password error') except: try: Employee_email = request.POST['Employee_email'] password = request.POST['u_password'] user = User.objects.get(EmployeeId=Employee_email) if (user.Password == password): if user.IsActivated == False: Update_User_IsActivated(Employee_email) request.session['user_Id'] = user.Id request.session.set_expiry(0) return restful.ok(message="login success") request.session['user_Id'] = user.Id request.session.set_expiry(0) return restful.ok(message="login success") return restful.params_error(message='password error') except: return restful.params_error(message="employee number error")
def modify_user(request): if request.method == "POST": id = int(request.POST['id']) username = request.POST['username'] department = request.POST['department'] role = request.POST['role'] session_id = request.session['user_Id'] user_obj = User.objects.get(Id=session_id) if user_obj.Role == "admin": try: user = User.objects.exclude(Id=id).get(Name=username) if user: return restful.params_error(message='user name had used') except: try: modify_department = Department.objects.get( Department=department) department_id = modify_department.Id User.objects.filter(Id=id).update( Name=username, Role=role, UpdatedTime=UpdatedTime, DepartmentId=department_id) return restful.ok(message="user modify success") except: User.objects.filter(Id=id).update(Name=username, Role=role, UpdatedTime=UpdatedTime) return restful.ok(message='User modify success') else: return restful.params_error(message="please connect admin")
def Model_add(request): if request.method == "POST": try: model = {} model['Name'] = request.POST.get("model_name", '') model['Code'] = request.POST.get("model_code", '') name_count = Project.objects.filter( Name=model['Name'], IsActivated=True).count() #激活的名字 code_count_2 = Project.objects.filter(Name=model['Name'], IsActivated=False).count() if model['Code'] == "": model.pop("Code") if name_count == 0 and code_count_2 == 0: #新机种的添加 Project.objects.create(**model) return restful.ok(message="Project name add success") if name_count == 0 and code_count_2 == 1: #删除的机种重新添加 Project.objects.filter(Name=model['Name']).update( Code=model['Code'], IsActivated=True, UpdatedTime=datetime.now()) return restful.ok(message="Project name add success") else: return restful.params_error("model name had exist") except Exception as e: return restful.params_error(repr(e))
def get(self, request): try: page = int(request.GET.get('page')) number = request.GET.get('num') dict_data = {} count = Department.objects.exclude(IsActivated='False').count() if number == "All": department_info = Department.objects.exclude( IsActivated='False') department_info = list(department_info.values()) dict_data['data'] = department_info dict_data['page_count'] = count return restful.ok(data=dict_data) if number != "All": number = int(number) page_num = count // number # 总共多少页 if count % number > 0: page_num = page_num + 1 if page_num >= page: department_info = Department.objects.exclude( IsActivated='False')[(page - 1) * number:number * page] department_info = list(department_info.values()) dict_data['data'] = department_info dict_data['page_count'] = page_num return restful.ok(data=dict_data) else: return restful.params_error( message="it had no other pages") except Exception as e: return restful.params_error(message=repr(e))
def get(self, request): try: page = int(request.GET.get('page')) number = request.GET.get('num') id = request.session['user_Id'] dict_data = {} count = BudgetCodeForm.objects.filter(PicId=id).count() # 总共多少条数据 if number == "All": budgetcode_info = BudgetCodeForm.objects.filter(PicId=id).order_by("-UpdatedTime","MergeId") \ .values("Id", "BillingType", "Department", "ApplyDate", "Pic", "ProductName", "Signer", "Status", "BudgetCode", "MergeId") budgetcode_info = list(budgetcode_info) dict_data['data'] = budgetcode_info dict_data['page_count'] = count return restful.ok(data=dict_data) if number != "All": number = int(number) page_num = count // number # 总共多少页 if count % number > 0: page_num = page_num + 1 if page_num >= page: budgetcode_info = BudgetCodeForm.objects.filter(PicId=id).order_by("-UpdatedTime","MergeId")\ .values("Id","BillingType","Department","ApplyDate","Pic","ProductName","Signer","Status","BudgetCode","MergeId")[(page-1)*number:number*page] budgetcode_info = list(budgetcode_info) dict_data['data'] = budgetcode_info dict_data['page_count'] = page_num return restful.ok(data=dict_data) else: return restful.params_error( message="it had no other pages", data={'count': count}) except Exception as e: return restful.params_error(message=repr(e))
def Subjects_add(request): if request.method == "POST": try: subjects = {} subjects['Type'] = request.POST.get("add_subject", '') subjects['Remark'] = request.POST.get("add_mark", '') subjects['Rule'] = request.POST.get("add_rule", '') subject_is = AccountTitle.objects.filter( Type=subjects['Type'], IsActivated=True).count() #激活的名字 subject_no = AccountTitle.objects.filter( Type=subjects['Type'], IsActivated=False).count() if subject_is == 0 and subject_no == 0: #新机种的添加 AccountTitle.objects.create(**subjects) return restful.ok(message="AccountTitle name add success") if subject_is == 0 and subject_no == 1: #删除的机种重新添加 AccountTitle.objects.filter(Type=subjects['Type']).update( Rule=subjects['Rule'], Remark=subjects['Rule'], IsActivated=True, UpdatedTime=datetime.now()) return restful.ok(message="AccountTitle name add success") else: return restful.params_error("AccountTitle Type had exist") except Exception as e: return restful.params_error(repr(e))
def del_user(request): if request.method == "POST": try: name = request.POST['name'] session_id = request.session['user_Id'] user_obj = User.objects.get(Id=session_id) if user_obj.Role == "admin" or user_obj.Role == "equipment_room": budget_code = BudgetCodeForm.objects.exclude( Status="Approve").filter(Pic=name) if len(budget_code) != 0: return restful.params_error( message="User had using can't delete") budget_code2 = BudgetCodeForm.objects.exclude( Status="Approve").filter(Signer=name) if len(budget_code2) != 0: return restful.params_error( message="User had using can't delete") else: user = User.objects.get(Name=name) user.IsActivated = False user.UpdatedTime = datetime.now() user.save() if user.Id == session_id: return restful.ok(message='delete success', data={'user': '******'}) else: return restful.ok(message='delete success', data={'user': '******'}) else: return restful.params_error(message="please connect admin") except Exception as e: return restful.params_error(message=repr(e))
def Location_list(request): if request.method == "GET": try: page = int(request.GET.get('page')) number = request.GET.get('num') dict_data = {} count = LocationLog.objects.exclude(IsActivated='False').count() if number == "All": data = list( LocationLog.objects.filter( IsActivated=True).order_by("-Id").values( "Id", "Location")) dict_data['data'] = data dict_data['page_count'] = count return restful.ok(data=dict_data) if number != "All": number = int(number) page_num = count // number # 总共多少页 if count % number > 0: page_num = page_num + 1 if page_num >= page: location_ob = LocationLog.objects.order_by("-Id").exclude( IsActivated='False')[(page - 1) * number:number * page] dict_data['data'] = list( location_ob.values("Id", "Location")) # dict_data['page_count'] = page_num dict_data['total_count'] = count dict_data['page_current'] = page dict_data['page_count'] = page_num return restful.ok(data=dict_data) else: return restful.params_error( message="it had no other pages") except Exception as e: return restful.params_error(repr(e))
def post(self, request): maintain_count = request.POST['maintain_count'] maintain_date = request.POST['maintain_date'] maintain_receiver = request.POST.getlist('maintain_receiver[]') maintain_receiver = list(maintain_receiver) try: parameter_count = Configuration.objects.filter(Type="mt_count") parameter_date = Configuration.objects.filter(Type="mt_date") mail_receiver_count = ",".join(maintain_receiver) if parameter_count and parameter_date: Configuration.objects.filter(Type="mt_count").update( Max=maintain_count, Min=0, Reminders=mail_receiver_count) Configuration.objects.filter(Type="mt_date").update( Max=maintain_date, Min=0, Reminders=mail_receiver_count) return restful.ok(message="setup parameter success") else: Configuration.objects.create(Type="mt_count", Max=maintain_count, Min=0, Reminders=mail_receiver_count) Configuration.objects.create(Type="mt_date", Max=maintain_date, Min=0, Reminders=mail_receiver_count) return restful.ok(message="setup parameter create success") except: return restful.params_error(message="setup information error")
def post(self, request): customer = request.POST['customer_val'] updatedtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S') try: customer_ob = Customer.objects.get(Customer=customer) if customer_ob.Id and customer_ob.IsActivated == False: customer_ob.IsActivated = True customer_ob.save() return restful.ok(message="Customer add success") else: return restful.params_error(message="Customer had exist") except: Customer.objects.create(Customer=customer, UpdatedTime=updatedtime) return restful.ok(message='Customer add success')
def post(self, request): department = request.POST['department'] updatedtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S') try: part = Department.objects.get(Department=department) if part.Id and part.IsActivated == False: part.IsActivated = True part.save() return restful.ok(message="Department create success") else: return restful.params_error(message="Department had Exist") except: Department.objects.create(Department=department, UpdatedTime=updatedtime) return restful.ok(message='Department create success')
def Budget_check_principal(request): if request.method == "POST": principal = request.POST['principal'] try: user_c = User.objects.get(Name=principal) if user_c: return restful.ok() except: try: user_num = User.objects.get(EmployeeId=principal) if user_num: return restful.ok() except: return restful.params_error( message='the PIC user not exist need admin check')
def modify_PartCode(request): try: if request.method == "POST": id = request.POST['id'] modify_requirement = request.POST['modify_requirement'] check_data = list(ModelStage.objects.filter(Id=id).values("BrushNumber","RequireQuantity")) if int(modify_requirement) > check_data[0]["BrushNumber"]: ModelStage.objects.filter(Id=id).update(RequireQuantity=modify_requirement,Status="Open") return restful.ok(message="modify requirement success") if int(modify_requirement) < check_data[0]["BrushNumber"]: return restful.params_error(message="need first to release this model") if int(modify_requirement) == check_data[0]["BrushNumber"]: return restful.ok(message="no need to modify") except Exception as e: return restful.params_error(message=e)
def monitor_equipment_change(request): if request.method == "GET": try: end_time = datetime.now() # 这里默认是查询前几周的数据 start_time = date(2017, 1, 1) # 这里默认是查询前几周的数据 # delta = timedelta(days=21) # start_time = end_time-delta # 页面html显示需要的数据+分页效果 page = int(request.GET.get('page')) number = request.GET.get('num') dict_data = {} count = PartItem.objects.order_by("Id").filter( TrnDate__range=(start_time, end_time), UseStatus='normal').count() # 页面显示需要的数据 if number == "All": data = PartItem.objects.order_by("Id").filter( TrnDate__range=(start_time, end_time), UseStatus='normal') limit_value = Configuration.objects.filter( Type="NG_range").values("Max", "Min", "Id") limit_value = list(limit_value) data = list(data.values()) dict_data['data'] = data dict_data['limit_value'] = limit_value dict_data['page_count'] = count return restful.ok(data=dict_data) if number != "All": number = int(number) page_num = count // number # 总共多少页 if count % number > 0: page_num = page_num + 1 if page_num >= page: data = PartItem.objects.order_by("Id").filter( TrnDate__range=(start_time, end_time), UseStatus='normal')[(page - 1) * number:number * page] limit_value = Configuration.objects.filter( Type="NG_range").values("Max", "Min", "Id") limit_value = list(limit_value) data = list(data.values()) dict_data['data'] = data dict_data['limit_value'] = limit_value dict_data['page_count'] = page_num return restful.ok(data=dict_data) else: return restful.params_error( message='it had no others page') except Exception as e: return restful.params_error(message=repr(e))
def analysis_query_tab_info(request): if request.method == "POST": try: startTime = request.POST['begin'] endTime = request.POST['end'] stage = request.POST['stage'] fixture = request.POST['fixture'] usn = request.POST['usn'] result = request.POST['result'] sql = 'SELECT * FROM "PartItemResult" where 1=1 ' if stage != "": sql = sql + 'AND "Stage"= \'' + stage + '\'' if fixture != "": sql = sql + 'AND "FixtureId"=\'' + fixture + '\'' if usn != "": sql = sql + 'AND "USN"=\'' + usn + '\'' if result != "": sql = sql + 'AND "USN"=\'' + result + '\'' if startTime != "": sql = sql + 'AND "TrnDate" >=\'' + startTime + '\'' if endTime != "": sql = sql + 'AND "TrnDate" <=\'' + endTime + '\'' cur = connection.cursor() cur.execute(sql) data = cur.fetchall() return restful.ok(data=data) except: return restful.params_error(message="query data is null")
def get(self, request): #这里是获取近一周的数据,但是由于数据没有更新,所以捞取全部当前300天的数据,后面进行修改天数 end_time = datetime.now() delta = timedelta(days=300) start_time = end_time - delta dict_data = {} data = PartItem.objects.order_by("Id").filter( TrnDate__range=(start_time, end_time)) data = list(data.values()) # start_time = str(datetime.now()).split(' ')[0] # start_time = datetime.strptime(start_time, "%Y-%m-%d") # #计算保养次数和保养日期达不达标 # for i in range(0,len(data)): # if data[i]['NextCheckDate'] == None and data[i]['NextCheckCount'] ==0: # data[i]['NextCheckDate'] = data[i]['CreatedTime'].split(' ')[0] # data[i]['stand_date'] = 0 # data[i]['stand_count'] = 0 # else: # time_u = datetime.strptime(str(data[i]['NextCheckDate']).split(' ')[0], "%Y-%m-%d") # days = time_u - start_time # data[i]['stand_date'] = days.days # data[i]['stand_count'] = data[i]['NextCheckCount'] - data[i]['UsedTimes'] dict_data['data'] = data try: return restful.ok(data=dict_data) except Exception as e: return restful.params_error(message=repr(e))
def webapp_login(request): try: if request.method == "POST": try: data = json.loads(request.body) input_user_id = data.get('user_id', '') input_password = data.get('u_password', '') except: return restful.params_error(message='data error', data='error') if input_user_id != "": user = User.objects.get(EmployeeId=input_user_id) user_password = user.Password if (user_password == input_password): return restful.ok(message='login success', data="ok") else: return restful.params_error(message='password error', data='error') else: return restful.params_error(message='account error', data='error') else: return restful.params_error(message='method error', data='error') except Exception as e: return restful.params_error(message="网络错误", data='error')
def check_NGRate(): NG_monitor_type = "NG_range" parmeter_stands = Configuration.objects.get(Type=NG_monitor_type) # limit_value = [parmeter_stands.Min, parmeter_stands.Max] parmeter_stands_min = str(parmeter_stands.Min) parmeter_stands_receiver = str(parmeter_stands.Reminders) sql_remenber = 'select "SN" from "PartItem" where "NGRate" >= \'' + parmeter_stands_min + '\'' cur = connection.cursor() cur.execute(sql_remenber) data = cur.fetchall() data = str(data) if len(data) > 0: email_1 = [] receiver_list = parmeter_stands_receiver.split(',') for i in range(len(receiver_list)): email_1.append(receiver_list[i] + '@wistron.com') subject = "NG reported rate of abnormal equipment" content = """ <pre> Dear All, The follow equipment NG rate have reached or exceed the standard. Please click the link below to see the detail information: <a href="http://10.41.95.106:90/index">index AEMSLite</a> -------------------------------------------------------------------------------------------- THIS EMAIL WAS SENT BY AEMS Lite SERVER AUTOMATICALLY. PLEASE DON'T DIRECTLY REPLY!!! </pre> """ mail.sendmail(email_1, content, subject) else: return restful.ok(message="partName is normal")
def Delete_alterParCode(request): if request.method == "POST": try: model_id = request.POST['model_id'] original_parcode = request.POST['original_parcode'] del_ParCode = request.POST['del_ParCode'] #这里需要去检查是否有绑定,如果有绑定的话,就需要去解绑 check_SN = list(SerialNumberInfo.objects.filter(PartCode=del_ParCode).values("BoxIdBindingId")) if len(check_SN) !=0: boxname = list(Box.objects.filter(Id=check_SN[0]["BoxIdBindingId"]).values())[0]["BoxId"] return restful.params_error(message=boxname+" this "+del_ParCode+" need to release") # 检查是否有该料号 if len(original_parcode) !=0: pc = original_parcode.split(",") if del_ParCode not in pc: return restful.params_error(original_parcode+" have no this "+del_ParCode) else: str = "" for i in pc: if i==del_ParCode or i=='': pc.remove(i) for j in pc: str += j+',' ModelStage.objects.filter(Id=model_id).update(AlternativePartCode=str) return restful.ok(message=del_ParCode+' delete success') else: return restful.params_error(message=original_parcode+" have no this "+del_ParCode) except Exception as e: return restful.params_error(message=e)
def analysis_setup_value(request): if request.method == "POST": try: form_data = request.POST.get('data') form_data = eval(form_data) dict_analysis = {} for i, j in form_data.items(): dict_analysis[i.split('[')[0][8] + i.split('[')[1].split(']')[0]] = int(j) dict_an = {} distinct_li = [] for i in dict_analysis.keys(): distinct_li.append(i[1:]) distinct_li = list(set(distinct_li)) for k in distinct_li: val = [] for i, j in dict_analysis.items(): if i[1:] == k: val.append(j) val.sort() dict_an[k] = val for key, v in dict_an.items(): try: analysis_obj = Configuration.objects.get(Id=eval(key)) analysis_obj.Min = v[0] analysis_obj.Max = v[1] analysis_obj.save() except: Configuration.objects.create(Type="at_count", Min=v[0], Max=v[1]) return restful.ok(data=form_data, message="setup success") #("/index/") except: return restful.params_error(data=request.POST.get('data'))
def get(self, request): try: start = datetime.now() # delta = timedelta(days=20) # end = start - delta #数据选择区间 start_select = (list( PartItemResult.objects.order_by("-TrnDate").filter( TrnDate__lte=start).values("TrnDate")))[0]['TrnDate'] delta_select = timedelta(days=7) end_select = start_select - delta_select time_select_sql = ' to_char("TrnDate",\'yyyy-MM-dd\') >= \'' + end_select.strftime( "%Y-%m-%d" ) + '\' and to_char("TrnDate",\'yyyy-MM-dd\') <= \'' + start_select.strftime( "%Y-%m-%d") + '\'' visua_data = {} #柱状图需要的数据 li = [] sql1 = 'SELECT "ErrorCode", COUNT("SN") FROM "PartItemResult" where ' + time_select_sql + ' AND "Result"= \'FAIL\' GROUP BY "ErrorCode" ORDER BY -COUNT(*)' cur = connection.cursor() cur.execute(sql1) visua_data['errorcode'] = cur.fetchall() sql2 = 'SELECT "PartName", COUNT("SN") FROM "PartItemResult" where' + time_select_sql + ' GROUP BY "PartName" ORDER BY -COUNT("SN")' cur = connection.cursor() cur.execute(sql2) visua_data['Partname'] = cur.fetchall() range_area = Configuration.objects.filter( Type="at_count").order_by("Min") #查用户设定的次数 if len(range_area) != 0: range_sql = 'SELECT COUNT("SN") FROM "PartItemResult" where ' + time_select_sql + ' AND "Result"= \'FAIL\'' for i in range(len(range_area)): range_data = range_sql + ' AND "UsedTimes">=\'' + str( int(range_area[i].Min )) + '\' AND "UsedTimes"<=\'' + str( int(range_area[i].Max)) + '\'' cur = connection.cursor() cur.execute(range_data) rank = cur.fetchall() new = [ str(int(range_area[i].Min)) + '~' + str(int(range_area[i].Max)), rank[0][0] ] li.append(new) visua_data['user'] = li else: sql3 = 'SELECT COUNT("SN") FROM "PartItemResult" where ' + time_select_sql + ' AND "Result"= \'FAIL\' and "UsedTimes">0' cur = connection.cursor() cur.execute(sql3) rankelse = cur.fetchall() visua_data['user'] = ['0~0', rankelse[0][0]] sql4 = 'SELECT COUNT("SN"),"PartName" FROM (select distinct "SN","PartName","Result" from "PartItemResult" WHERE ' + time_select_sql + ') as foo where "Result"= \'FAIL\' GROUP BY "PartName" ORDER BY -COUNT("SN")' cur = connection.cursor() cur.execute(sql4) visua_data['filterSN'] = cur.fetchall() visua_data['select_start'] = start_select visua_data['select_end'] = end_select return restful.ok(data=visua_data) except Exception as e: return restful.params_error(repr(e))
def FeeDel_limit(request): if request.method == "POST": try: id = request.POST.get("del_id", '') FeeLimit.objects.filter(Id=id).update(Isactivated=False) return restful.ok(message='delete success') except Exception as e: return restful.params_error(repr(e))
def analysis_setup_data(request): if request.method == "GET": try: limit_data = Configuration.objects.filter(Type="at_count").order_by("Id").values("Id","Min","Max") limit_data = list(limit_data) return restful.ok(data=limit_data) except: return restful.params_error(message="data error")
def analysis_data(request): if request.method == "GET": #数据显示部分的data try: data = PartItemResult.objects.order_by().all().values() data =list(data) return restful.ok(data=data) except: return restful.params_error(message="data got fail")
def analysis_delete_data(request): if request.method == "POST": try: range_id = request.POST['div_id'] range_id = range_id.split('_')[0] Configuration.objects.filter(Id=int(range_id)).delete() return restful.ok(message="") except: return restful.params_error(message='data error')
def Subjects_delete(request): if request.method == "POST": try: type = request.POST.get("subjects_type", '') AccountTitle.objects.filter(Type=type).update( IsActivated=False, UpdatedTime=datetime.now()) return restful.ok(message="AccountTitle delete success") except Exception as e: return restful.params_error(repr(e))
def budget_code_detail(request): if request.method == "POST": detail_id = request.POST['detail_id'] detail_merged_id = request.POST['detail_merged_id'] detail_merged_id = str(detail_merged_id) try: try: detail_data = BudgetCodeForm.objects.filter( MergeId=detail_merged_id).values() detail_data = list(detail_data) return restful.ok(data=detail_data) except: detail_data = BudgetCodeForm.objects.filter( Id=detail_id).values() detail_data = list(detail_data) return restful.ok(data=detail_data) except: return restful.params_error(message='data fail ')
def Rate_info(request): if request.method == "GET": try: dict_data = {} dict_data['data'] = list( ExchangeRate.objects.filter(IsActivated=True).values()) return restful.ok(data=dict_data) except Exception as e: return restful.params_error(repr(e))
def Rate_delete(request): if request.method == "POST": try: Id = request.POST.get("del_id", '') ExchangeRate.objects.filter(Id=Id).update( IsActivated=False, UpdatedTime=datetime.now()) return restful.ok(message="ExchangeRate delete success") except Exception as e: return restful.params_error(repr(e))