def attend(request): if request.method != 'POST' or _attended(request.user): return HttpResponse(status=204) attendance = Attendance(user=request.user) attendance.attendance = datetime.now() attendance.save() return HttpResponseRedirect('/')
def attendLesson(request): if request.method == 'POST': html = {} try: student = Student.objects.get(number=request.POST['number']) date = timezone.localtime(timezone.now()).date() today = Attendance(attendanceDate=date, student=student) # attend_list = student.attendance_set.all() isAttend = student.attendance_set.filter(attendanceDate=date, student=student) if not isAttend: today.save() student.attendance_set.add(today) html['is_valid'] = True html['scheduleTable'] = str(student.stname) + "(" + str( student.number) + ")" + " 의출석이 정상적으로 되었습니다." return JsonResponse(html) else: html['is_valid'] = False html['errorMsg'] = str(student.stname) + "(" + str( student.number) + ")" + " 이미 출석했습니다." return JsonResponse(html) except Exception as e: print("Error: " + str(e)) pythoncom.CoUninitialize() html['is_valid'] = False html['errorMsg'] = "Error: " + str(e) return JsonResponse(html)
def parse_text(wechat_context): message = wechat_context.get_message() if "2222" in message.content: d = {"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}} return wechat_context.response_text(wechat_context.create_qrcode(dict(d))) if u"考勤" in message.content: from attendance.models import Attendance, AttendanceParam import datetime now = datetime.datetime.now() a = Attendance(checking_date_sys=now, type="morning", remark_text="test") a.save() return wechat_context.response_text(Attendance.objects.all()) pass # if "QA" or "qa" in message.content: # articles = [] # q = message.content.replace('qa', '').replace('QA', '') # for item in QA.objects.filter(q__contains=q): # articles.append({ # 'title': item.q, # 'description': item.a, # }) # if len(articles) == 10: # break # if articles: # return wechat.response_news(articles) # else: # return parse_tuling_msg(wechat, tuling(message.source, q)) # else: return parse_tuling_msg(wechat_context, tuling(message.source, message.content))
def check_in_time(request): company_policy = Working_Days_Policy.objects.get( enterprise=request.user.company) current_employee = Employee.objects.get(user=request.user, emp_end_date__isnull=True) attendance_list = Attendance.objects.filter(employee=current_employee) current_date = datetime.now().date() current_time = datetime.now().time() opened_attendance = False for att in attendance_list: if att.check_out is None: opened_attendance = True if not opened_attendance: att_obj = Attendance( employee=current_employee, date=current_date, check_in=current_time, day_of_week=current_date.weekday(), created_by=request.user, ) att_obj.save() else: print("You still have attendance opened. Please check out first") messages.error( request, _("You still have attendance opened. Please check out first")) return redirect('attendance:user-list-attendance')
def parse_voice(wechat_context): message = wechat_context.get_message() if '考勤' in message.recognition: from attendance.models import Attendance, AttendanceParam import datetime now = datetime.datetime a = Attendance(checking_date_sys=now, type="morning", remark_text="test") a.save() pass else: response = parse_tuling_msg(wechat_context, tuling(message.source, message.recognition)) return response pass
def here(request, session_id, ninja_id): if request.method == "POST": ninja = get_object_or_404(Ninja, pk = ninja_id) print session_id session = get_object_or_404(DojoSession, pk = session_id) a = Attendance( ninja = ninja, session = session, added_by = request.user ) a.save() return redirect('attendance:signoff', dojo_session_id = session_id)
def post(self, request): try: data = json.loads(request.body) # employee_id = request.employee.id new_attendance = Attendance( employee=Employee.objects.get(id=data['employee']), label=AttendanceLabel.objects.get(id=data['label']), begin_at=data['start_time'], written_by=Employee.objects.get(id=employee_id), amended_by=Employee.objects.get(id=employee_id), content=data['content']).save() # new_attendance = Attendance( # employee = Employee.objects.get(id = data['employee']), # label = AttendanceLabel.objects.get(id = data['label']), # begin_at = data['begin_at'], # written_by = Employee.objects.get(id = employee_id), # amended_by = Employee.objects.get(id = employee_id), # content = data['content'] # ).save() return JsonResponse({"message": new_attendance}, status=200) except KeyError as e: return JsonResponse({'message': f'KEY_ERROR:{e}'}, status=400) except ValueError as e: return JsonResponse({"message": f"VALUE_ERROR:{e}"}, status=400)
def populate_attendance_table(date): atts = Attendance_Interface.objects.filter(date__date=date) if len(atts) == 0: print("Attendance Interface table doesn't have data for date selected") else: data = {} for att in atts: try: Employee.objects.get(user=request.user, emp_end_date__isnull=True) except Employee.DoesNotExist: continue # initialize the dictionary that hold attendance check in and check out data[att.user_id] = ({} if data.get(att.user_id, None) is None else data[att.user_id]) if att.punch == '0': data[att.user_id]['check_in'] = att.date.time() elif att.punch == '1': data[att.user_id]["check_out"] = att.date.time() for key, value in data.items(): emp = Employee.objects.get(emp_number=key, emp_end_date__isnull=True) try: attendance = Attendance.objects.filter(date=date).get( employee=emp) attendance.check_in = value.get("check_in", None) attendance.check_out = value.get("check_out", None) except Attendance.DoesNotExist: attendance = Attendance( employee=emp, date=date, check_in=value.get("check_in", None), check_out=value.get("check_out", None), ) attendance.save() # This part to get all employees who are absent this day att_employees = Attendance.objects.filter(date=date).values_list( "employee", flat=True) employees = Employee.objects.all().values_list("id", flat=True) for employee in employees: if employee not in att_employees: employee = Employee.objects.get(id=employee, emp_end_date__isnull=True) attendance = Attendance( employee=employee, date=date, ) attendance.save()
def post(self, request, *args, **kwargs): status = 200 day = request.POST['current_date'] month = request.POST['current_month'] year = request.POST['current_year'] students = ast.literal_eval(request.POST['students']) batch_details = ast.literal_eval(request.POST['batch']) batch = Batch.objects.get(id=batch_details['id']) user = request.user; date = dt.date(int(year), int(month), int(day)) try: attendance = Attendance.objects.get(batch=batch, date=date) except: attendance = Attendance() attendance.batch = batch attendance.date = date attendance.user = user attendance.topics_covered = batch_details['topics'] if batch_details['remarks']: attendance.remarks = batch_details['remarks'] attendance.save() for student_details in students: student = Student.objects.get(id=student_details['id']) if student.is_rolled == False: student_attendance, created = StudentAttendance.objects.get_or_create(student=student, attendance=attendance) if student_details['is_presented'] == 'true': student_attendance.status = "P" else: student_attendance.status = "A" student_attendance.save() res = { 'result': 'ok', } response = simplejson.dumps(res) return HttpResponse(response, status=status, mimetype='application/json')
def submit_page(employee_id): emp = Employee.query.all() #checking if the current day is saturday or not, strftime('%A') returns day in string format if dt.now().strftime('%A') != "Saturday" and dt.now().strftime( '%A') != "Sunday": for i in emp: #checking if curent date is in holidays table, adding leaves for all employess for current date if condition is satisfied if Work.query.filter_by(date=dt.now().date( ), employee_id=i.id).count() != 1 and Holidays.query.filter_by( date=dt.now().date()).count() != 1: data = Work(date=dt.now(), leaves=1, employee_id=i.id) db.session.add(data) db.session.commit() #checking if id is present in employee table if Employee.query.filter_by(id=employee_id).count() != 0: #determining if the reponse is for sign in or out x = Attendance.query.filter_by(employee_id=employee_id).count() if x % 2 == 0: inout = "in" else: inout = "out" #adding data to attendance table data = Attendance(employee_id=employee_id, in_out=inout, DT=dt.now()) db.session.add(data) db.session.commit() #extracting the last signin entry of current employee data1 = Attendance.query.filter_by(employee_id=employee_id, in_out="in")[-1] #converting the datetime format to string time forma hour1 = data1.DT.strftime("%H:%M:%S") hour11 = data1.DT.strftime("%I:%M:%S %p") #converting the datetime format to date format day = data.DT.date() if data.in_out == "in": return render_template("submit.html", text=gettext(sign_in) + " at " + ": " + hour11) elif data.in_out == "out": hour2 = data.DT.strftime("%H:%M:%S") hour22 = data.DT.strftime("%I:%M:%S %p") #time difference between sign in and out,converting the string time format to time format t1 = dt.strptime(hour2, "%H:%M:%S") - dt.strptime( hour1, "%H:%M:%S") #add data if row doesn't exist if Work.query.filter_by(date=day, employee_id=employee_id).count() == 0: db.session.add( Work(date=day, work_hours=t1, leaves=0, employee_id=employee_id)) db.session.commit() #replace data if row exist for work_hours value = None elif Work.query.filter_by(date=day, employee_id=employee_id, work_hours=None).count() == 1: dataa = Work.query.filter_by(date=day, employee_id=employee_id, work_hours=None).first() dataa.date = day dataa.work_hours = t1 dataa.leaves = 0 dataa.employee_id = employee_id db.session.commit() #update work_hours if row already exist elif Work.query.filter_by(date=day, employee_id=employee_id).count() == 1: data2 = Work.query.filter_by(date=day, employee_id=employee_id).first() if data2.work_hours != None: t2 = data2.work_hours.strftime("%H:%M:%S.%f") time_total = t1 + dt.strptime(t2, "%H:%M:%S.%f") data2.work_hours = time_total db.session.commit() else: pass else: pass return render_template("submit.html", text=gettext(sign_out) + " " + ": " + hour22) else: return render_template("submit.html", text=gettext(wrong_id))
def detect_faces(course_id, year, date, img_urls): group_id = str.lower(str(course_id)) + "_" + str(year) headers = { "Content-Type": 'application/json', "Ocp-Apim-Subscription-Key": MICROSOFT_KEY } url1 = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect" url2 = "https://westus.api.cognitive.microsoft.com/face/v1.0/identify" mappings = {} all_imgs = {} id_to_url = {} for img_url in img_urls: data1 = {"url": str(img_url)} resp1 = requests.post(url1, headers=headers, data=json.dumps(data1)) if resp1.status_code == 200: print "faces detected for " + img_url body = resp1.json() n = 0 while n < len(body): ids = [] imgs = copy.copy(body[n:n + 10]) for img in imgs: all_imgs[img['faceId']] = img['faceRectangle'] ids.append(img['faceId']) data2 = {"personGroupId": str(group_id), "faceIds": ids} resp2 = requests.post(url2, headers=headers, data=json.dumps(data2)) if resp2.status_code == 200: print "mappings obtained" a = resp2.json() print a for each in a: try: mappings[each['faceId']] = each['candidates'][0][ 'personId'] id_to_url[each['candidates'][0] ['personId']] = img_url except: pass else: print "mappings not obtained" print resp2.json() n = n + 10 else: print "faces not detected for " + img_url print resp1.json() people = mappings.values() people = list(set(people)) faces = mappings.keys() students = CourseGroup.objects.filter(person_group_id=group_id) instanceList = [] for each in students: person_id = each.person_id if person_id in people: img_url_store = id_to_url[person_id] for m in faces: if mappings[m] == person_id: rect = all_imgs[m] break instance = Attendance(courseID=course_id, date=date, studentID=each.student_id, present=True, year=year, url=img_url_store, top=rect['top'], left=rect['left'], width=rect['width'], height=rect['height']) instance.save() instanceList.append(instance) else: instance = Attendance(courseID=course_id, date=date, studentID=each.student_id, present=False, year=year) instance.save() instanceList.append(instance) return instanceList