def post(self, request, id): try: employee = Employee.objects.get(user=request.user) lessonOwned = LessonOwned.objects.get(lesson__id=id, owner=employee) if not lessonOwned.isComplete: isComplete = False for i in lessonOwned.stepOwned.all(): if not i.isComplete: isComplete = False break else: isComplete = True lessonOwned.isComplete = isComplete lessonOwned.save() return Response({ "status": status.HTTP_200_OK, "message": "success", "data": { "id": lessonOwned.lesson.id, "is_complete": lessonOwned.isComplete } }) except FieldError as e: return FieldErrorHandler(e) except Exception as e: return ExceptionHandler(e)
def get(self, request): try: return Response({ "status" : status.HTTP_200_OK, "message" : "success", "data" : TrainingListToJSON(request) }, status=status.HTTP_200_OK) ''' data : [ { date : , training :[ { "id" :, "name" : , "img" : , " " } ] , }, { date : , training :[] } ] ''' except Exception as e: return ExceptionHandler(e)
def get(self, request, id): try: employee = Employee.objects.get(user=request.user) lessonOwned = LessonOwned.objects.filter(lesson__id=id, owner=employee) if not lessonOwned: raise PermissionDenied("user do not have this lesson") else: lessonOwned = LessonOwned.objects.filter(lesson__id=id, owner=employee)[0] dataResponse = [] for i in lessonOwned.stepOwned.all(): data = { "id": i.step.id, "title": i.step.title, "type": i.step.type, "is_complete": i.isComplete, } dataResponse.append(data) return Response({ "status": status.HTTP_200_OK, "message": "success", "data": { "steps": dataResponse } }) except PermissionDenied as e: return PermissionDeniedHandler(e) except Exception as e: return ExceptionHandler(e)
def get(self, request, id): try: article = Article.objects.filter(id=id) if id == "": raise FieldError("id input not valid") if not article: raise EmptyResultSet("no result for article id = " + str(id)) else: article = Article.objects.get(id=id) return Response( { "status": status.HTTP_200_OK, "message": "success", "data": { "id": article.id, "title": article.title, "content": article.content } }, status=status.HTTP_200_OK) except FieldError as e: return FieldErrorHandler(e) except EmptyResultSet as e: return EmptyResultSetHandler(e) except Exception as e: return ExceptionHandler(e)
def get(self, request, id): try: forum = Forum.objects.filter(id=id) if not id: raise FieldError("id input not valid") if not forum: raise EmptyResultSet("no result for forum id = " + str(id)) else: forum = Forum.objects.get(id=id) answer = [] for i in forum.answer.all(): isUpvote = False if Employee.objects.get(user=request.user) in i.upvote.all(): isUpvote = True data = { "id": i.id, "username": i.owner.user.username, "answer": i.answer, "upvote": i.upvote.count(), "is_upvote": isUpvote, "created_at": i.createdAt } answer.append(data) isUpvote = False if Employee.objects.get(user=request.user) in forum.upvote.all(): isUpvote = True return Response({ "status": status.HTTP_200_OK, "message": "success", "data": { "id": forum.id, "username": forum.owner.user.username, "title": forum.title, "question": forum.question, "upvote": forum.upvote.count(), "answer": answer, "is_upvote": isUpvote, "created_at": forum.createdAt } }) except FieldError as e: return FieldErrorHandler(e) except EmptyResultSet as e: return EmptyResultSetHandler(e) except Exception as e: return ExceptionHandler(e)
def post(self, request, id): try: forum = Forum.objects.get(id=id) if not id: raise FieldError("id input not valid") if forum == []: raise EmptyResultSet("no result for forum id = ", id) if request.data['is_increase'] == "": raise FieldError("answer is not valid") employee = Employee.objects.get(user=request.user) if request.data['is_increase'] == "true": if employee in forum.upvote.all(): raise Exception("Already upvote") else: forum.upvote.add(employee) else: forum.upvote.remove(employee) isUpvote = False if Employee.objects.get(user=request.user) in forum.upvote.all(): isUpvote = True return Response({ "status": status.HTTP_200_OK, "message": "success", "data": { "id": forum.id, "username": forum.owner.user.username, "title": forum.title, "question": forum.question, "upvote": forum.upvote.count(), "is_upvote": isUpvote, "created_at": forum.createdAt } }) except FieldError as e: return FieldErrorHandler(e) except EmptyResultSet as e: return EmptyResultSetHandler(e) except Exception as e: return ExceptionHandler(e)
def get(self, request, id): try: dataRes = {} allQuiz = [] owner = Employee.objects.get(user=request.user) for i in QuizSectionOwned.objects.get(quizSection_id=id, owner=owner).quizOwned.all(): data = { "id": i.quiz.id, "question": i.quiz.question, "choice_1": { "id": i.quiz.choice1.id, "choice": i.quiz.choice1.choice, "is_right": i.quiz.choice1.isRight }, "choice_2": { "id": i.quiz.choice2.id, "choice": i.quiz.choice2.choice, "is_right": i.quiz.choice2.isRight }, "choice_3": { "id": i.quiz.choice3.id, "choice": i.quiz.choice3.choice, "is_right": i.quiz.choice3.isRight }, "choice_4": { "id": i.quiz.choice4.id, "choice": i.quiz.choice4.choice, "is_right": i.quiz.choice4.isRight }, "point": i.quiz.point } allQuiz.append(data) dataRes["quiz_section"] = allQuiz dataRes["attempt"] = QuizSectionOwned.objects.get( quizSection_id=id, owner=owner).attempt return Response({ "status": status.HTTP_200_OK, "message": "success", "data": dataRes }) except Exception as e: return ExceptionHandler(e)
def get(self, request): try : employee = Employee.objects.get(user=request.user) if employee.status == 0 : raise PermissionDenied("user is not admin") dateInput = datetime.now().strftime("%Y-%m-%d") date = datetime.strptime(dateInput, "%Y-%m-%d").date() dataresp = [] schedule = Schedule.objects.filter(startTime__date=date) for i in schedule: data = { "id": i.id, "name": i.training.name, "img": i.training.img.url, "method": i.method, "start_time": i.startTime, "end_time": i.endTime, } if i.method == 0: data["linkUrl"] = i.linkUrl elif i.method == 1: data['location'] = i.location dataresp.append(data) return Response({ "status" : 200, "message" : "success", "data" : { "user_total" : Employee.objects.all().count(), "course_total" : Course.objects.all().count(), "training_total" : Training.objects.all().count(), "training_today" : dataresp, } }) except PermissionDenied as e: return PermissionDeniedHandler(e) except Exception as e : return ExceptionHandler(e)
def post(self, request, id): try: forum = Forum.objects.get(id=id) if not id: raise FieldError("id input not valid") if forum == []: raise EmptyResultSet("no result for forum id = ", id) if request.data['answer'] == "": raise FieldError("answer is not valid") owner = Employee.objects.get(user=request.user) answer = Answer.objects.create(answer=request.data['answer'], owner=owner) forum.answer.add(answer) isUpvote = False if Employee.objects.get(user=request.user) in answer.upvote.all(): isUpvote = True return Response({ "status": status.HTTP_201_CREATED, "message": "objects created", "data": { "id": answer.id, "username": answer.owner.user.username, "upvote": answer.upvote.count(), "is_upvote": isUpvote, "created_at": answer.createdAt } }) except FieldError as e: return FieldErrorHandler(e) except EmptyResultSet as e: return EmptyResultSetHandler(e) except Exception as e: return ExceptionHandler(e)
def get(self, request, id): try: employee = Employee.objects.get(user=request.user) stepOwned = StepOwned.objects.get(step__id=id, owner=employee) data = { "id": stepOwned.step.id, "title": stepOwned.step.title, "type": stepOwned.step.type, "content_text": stepOwned.step.contentText, "content_video": stepOwned.step.contentVideo, "transcript": stepOwned.step.transcript, "is_complete": stepOwned.isComplete, "time_consume": stepOwned.timeConsume if stepOwned.timeConsume else '00:00:00', "next_id": stepOwned.step.nextID.id if stepOwned.step.nextID else -1, "prev_id": stepOwned.step.prevID.id if stepOwned.step.prevID else -1, } return Response({ "status": status.HTTP_200_OK, "message": "success", "data": data }) except Exception as e: return ExceptionHandler(e)
def post(self, request, id): try: timestamp = request.data['timestamp'] if not timestamp: raise FieldError("timestamp is not valid") employee = Employee.objects.get(user=request.user) step = Step.objects.get(id=id) stepOwned = StepOwned.objects.get(step__id=id, owner=employee) if not stepOwned.isComplete: stepOwned.isComplete = True if datetime.strptime( timestamp, '%H:%M:%S').time() >= stepOwned.step.timeMinimum else False stepOwned.timeConsume = timestamp stepOwned.save() if stepOwned.isComplete: lessonOwned = LessonOwned.objects.filter( stepOwned=stepOwned)[0] sectionOwned = SectionOwned.objects.filter( lessonOwned=lessonOwned)[0] courseOwned = CourseOwned.objects.filter( sectionOwned=sectionOwned)[0] courseOwned.lastLesson = lessonOwned.lesson courseOwned.lastStep = stepOwned.step courseOwned.lastQuiz = None courseOwned.totalComplete += 1 courseOwned.save() isLessonComplete = False for i in lessonOwned.stepOwned.all(): if i.isComplete: isLessonComplete = True else: isLessonComplete = False break lessonOwned.isComplete = isLessonComplete lessonOwned.save() isSectionComplete = False for i in sectionOwned.lessonOwned.all(): if i.isComplete: isSectionComplete = True else: isSectionComplete = False break for i in sectionOwned.quizSectionOwned.all(): if i.isComplete: isSectionComplete = True else: isSectionComplete = False break sectionOwned.isComplete = isSectionComplete sectionOwned.save() if courseOwned.totalComplete / courseOwned.course.totalStepAndQuiz == 1.0: employee.pewiraMilesBalance += courseOwned.course.reward BalanceHistory.objects.create( owner=employee, description="Hadiah kursus " + courseOwned.course.name, balance=courseOwned.course.reward, type="Kursus") Notification.objects.create( owner=employee, notif= "Kamu mendapatkan hadiah karena menyelesaikan kursus" + courseOwned.course.name, category="Kursus") return Response({ "status": status.HTTP_200_OK, "message": "success", "data": { "id": stepOwned.step.id, "time_consume": stepOwned.timeConsume, "is_complete": stepOwned.isComplete } }) except FieldError as e: return FieldErrorHandler(e) except Exception as e: return ExceptionHandler(e)
def post(self, request): try: with transaction.atomic(): employee = Employee.objects.get(user=request.user) if employee.status == 0: raise PermissionDenied("user is not admin") trainingInput = request.data["training"] name = trainingInput['name'] topic = trainingInput["topic"] img = trainingInput["img"] organizer = trainingInput["organizer"] about = trainingInput["about"] topicObject = Topic.objects.filter(topic=topic) if len(topicObject) == 0 : newTopic = Topic.objects.create(topic=topic) topicObject = Topic.objects.filter(topic=topic) else : topicObject = Topic.objects.filter(topic=topic) training = Training.objects.create(name=name, organizer=organizer, img=img, about=about) for i in topicObject : training.topic.add(i) startTime = datetime.strptime(trainingInput["schedule"]["start_time"], '%Y-%m-%d %H:%M:%S') endTime = datetime.strptime(trainingInput["schedule"]["end_time"], '%Y-%m-%d %H:%M:%S') method = trainingInput["method"] schedule = None if method == 0 : linkUrl = trainingInput["link_url"] schedule = Schedule.objects.create(title=name, startTime=startTime, endTime=endTime, training=training, method=method, linkUrl=linkUrl ) else : location = trainingInput["location"] schedule = Schedule.objects.create(title=name, startTime=startTime, endTime=endTime, training=training, method=method, location=location ) for i in trainingInput["participant"] : owner = Employee.objects.get(user__username=i['username']) trainingOwned = TrainingOwned.objects.create(owner=owner, training=training) notif = Notification.objects.create(owner=owner, notif="Kamu telah terdaftar pada pelatihan " + trainingOwned.training.name, category="Pelatihan") return Response({ "status" : 201, "message" : "success", }, status=status.HTTP_201_CREATED) except PermissionDenied as e : return PermissionDeniedHandler(e) except Exception as e : return ExceptionHandler(e)
def get(self, request): try: search = request.GET.get("search") article = ArticleSection.objects.all() if not search: category = request.GET.get("category") if not category: raise FieldError("category or search input not valid") categoryObject = Topic.objects.get(topic=category) if not categoryObject: raise EmptyResultSet article = ArticleSection.objects.filter(topic=categoryObject) articleSection = [] for i in article: article = [] for j in i.section.all(): article.append({ "id": j.id, "title": j.title, "content": j.content }) articleSection.append({ "id": i.id, "title": i.title, "article": article }) return Response( { "status": status.HTTP_200_OK, "message": "success", "data": { 'section': articleSection, 'count': len(articleSection), } }, status=status.HTTP_200_OK) else: article = Article.objects.filter(title__icontains=search) articles = [] for i in article: articles.append({ 'id': i.id, 'title': i.title, 'content': i.content }) return Response( { "status": status.HTTP_200_OK, "message": "success", "data": { "articles": articles, 'count': len(article) } }, status=status.HTTP_200_OK) except FieldError as e: return FieldErrorHandler(e) except EmptyResultSet as e: return EmptyResultSetHandler(e) except Exception as e: return ExceptionHandler(e)
def TrainingListToJSON(request) : try: if not request.GET.get("date"): owner = Employee.objects.get(user=request.user) idTrainingOwned = [i.training.id for i in TrainingOwned.objects.filter(owner=owner)] schedule = Schedule.objects.filter(training__in=idTrainingOwned).order_by("startTime") dicts = {} for i in schedule: if i.startTime.date() in dicts: data = { "id": i.id, "name": i.training.name, "img": i.training.img.url, "start_time": i.startTime, "end_time": i.endTime } if i.method == 0: data["linkUrl"] = i.linkUrl elif i.method == 1: data['location'] = i.location dicts[i.startTime.date()].append(data) else: lst = [] data = { "id": i.id, "name": i.training.name, "img": i.training.img.url, "start_time": i.startTime, "end_time": i.endTime } if i.method == 0: data["linkUrl"] = i.linkUrl elif i.method == 1: data['location'] = i.location lst.append(data) dicts[i.startTime.date()] = lst dataresp = [] for x, y in dicts.items(): dataresp.append( { "date": x, "training": y } ) else: dataresp = [] owner = Employee.objects.get(user=request.user) idTrainingOwned = [i.training.id for i in TrainingOwned.objects.filter(owner=owner)] dateInput = request.GET.get("date") date = datetime.strptime(dateInput, "%Y-%m-%d").date() schedule = Schedule.objects.filter(training__in=idTrainingOwned, startTime__date=date) for i in schedule: data = { "id": i.id, "name": i.training.name, "img": i.training.img.url, "method": i.method, "start_time": i.startTime, "end_time": i.endTime, } if i.method == 0: data["linkUrl"] = i.linkUrl elif i.method == 1: data['location'] = i.location dataresp.append(data) return dataresp except Exception as e: return ExceptionHandler(e)
def post(self, request): try: if request.data['title'] == "": raise FieldError("title is not valid") if request.data['question'] == "": raise FieldError("question is not valid") if request.data['topic'] == "": raise FieldError("topic is not valid") owner = Employee.objects.get(user=request.user) forum = Forum.objects.create(title=request.data['title'], question=request.data['question'], owner=owner) for i in request.data['topic']: topic = Topic.objects.filter(topic=i) if topic.count() == 0: topic = Topic.objects.create(topic=i) else: topic = topic[0] forum.topic.add(topic) answer = [] for i in forum.answer.all(): isUpvote = False if Employee.objects.get(user=request.user) in i.upvote.all(): isUpvote = True data = { "id": i.id, "username": i.owner.user.username, "answer": i.answer, "upvote": i.upvote.count(), "is_upvote": isUpvote } answer.append(data) isUpvote = False if Employee.objects.get(user=request.user) in forum.upvote.all(): isUpvote = True return Response({ "status": status.HTTP_201_CREATED, "message": "object created", "data": { "id": forum.id, "username": forum.owner.user.username, "title": forum.title, "question": forum.question, "upvote": forum.upvote.count(), "answer": answer, "is_upvote": isUpvote, "created_at": forum.createdAt } }) except FieldError as e: return FieldErrorHandler(e) except EmptyResultSet as e: return EmptyResultSetHandler(e) except Exception as e: return ExceptionHandler(e)
def get(self,request): employee = Employee.objects.get(user=request.user) try: if employee.status == 0 : raise PermissionDenied("user is not admin") allCourse = "" category = request.GET.get("category") search = request.GET.get("search") if category or search : topicID=[] searchQuery = "" if search : topicID = [i.id for i in Topic.objects.filter(topic__icontains=search)] searchQuery = search categoryObject = Topic.objects.filter(topic=category) if len(categoryObject) != 0 : categoryObject = categoryObject[0] allCourse = Course.objects.filter(Q(topic=categoryObject) | Q(topic__in=topicID) | Q(name__icontains=searchQuery)).distinct() else : allCourse = Course.objects.filter( Q(topic__in=topicID) | Q(name__icontains=searchQuery)).distinct() else : allCourse = Course.objects.all() dataResp = [] for i in allCourse : data = { "id" : i.id, "name" : i.name, "price" : i.price, "input_date" : i.dateAdded, "user" : CourseOwned.objects.filter(course=i).count() } if category: data["category"] = [category] else: data["category"] = [j.topic for j in i.topic.all()] dataResp.append(data) return Response({ "status" : 200, "message" : "success", "data" : { "course" : dataResp, "count" : len(dataResp) } }) except PermissionDenied as e: return PermissionDeniedHandler(e) except Exception as e: return ExceptionHandler(e)
def post(self, request, id): try: ''' answer : [ { id : question : answer : { id : answer : } }, { id : question : answer : { id : answer : } }, ] ''' employee = Employee.objects.get(user=request.user) totalPoint = 0 quizSection = QuizSection.objects.get(id=id) quizSectionOwned = QuizSectionOwned.objects.get(owner=employee, quizSection_id=id) if quizSectionOwned.attempt < 3: allPoint = 0 for i in request.data["answer"]: quizOwned = QuizOwned.objects.get(owner=employee, quiz_id=i["id"]) answer = Choice.objects.get(id=i["answer"]["id"]) quizOwned.isRight = answer.isRight quizOwned.save() if quizOwned.isRight: totalPoint += quizOwned.quiz.point allPoint += quizOwned.quiz.point quizSectionOwned.quizResult = (totalPoint / allPoint) * 100 quizSectionOwned.attempt += 1 quizSectionOwned.save() if quizSectionOwned.quizResult >= quizSection.minimumQuizScore and not quizSectionOwned.isComplete: quizSectionOwned.isPassedQuiz = True quizSectionOwned.isComplete = True quizSectionOwned.save() sectionOwned = SectionOwned.objects.filter( quizSectionOwned=quizSectionOwned)[0] courseOwned = CourseOwned.objects.filter( sectionOwned=sectionOwned)[0] courseOwned.lastLesson = None courseOwned.lastStep = None courseOwned.lastQuiz = quizSection courseOwned.totalComplete += 1 courseOwned.save() if courseOwned.totalComplete / courseOwned.course.totalStepAndQuiz == 1.0: employee.pewiraMilesBalance += courseOwned.course.reward employee.save() BalanceHistory.objects.create( owner=employee, description="Hadiah kursus " + courseOwned.course.name, balance=courseOwned.course.reward, type="Kursus") Notification.objects.create( owner=employee, notif= "Kamu mendapatkan hadiah karena menyelesaikan kursus" + courseOwned.course.name, category="Kursus") else: raise PermissionDenied("maximum attempt") return Response( { "status": status.HTTP_200_OK, "message": "success", "data": { "id": quizSection.id, "is_complete": quizSectionOwned.isComplete, "quiz_result": quizSectionOwned.quizResult, "is_passed": quizSectionOwned.isPassedQuiz, "attempt": quizSectionOwned.attempt } }, status=status.HTTP_200_OK) except PermissionDenied as e: return PermissionDeniedHandler(e) except AttributeError as e: return FieldErrorHandler(e) except Exception as e: return ExceptionHandler(e)
def get(self, request): try: category = request.GET.get("category") sortInput = request.GET.get("sort") search = request.GET.get("search") forum = Forum.objects.all() # Validate search if not search: # Validate category and sort if not category: raise FieldError("category or search input not valid") if not sortInput: raise FieldError("sort or search input not valid") # Get topic object based on category categoryObject = Topic.objects.get(topic=category) if not categoryObject: raise EmptyResultSet # Get forum based on category and sort input if sortInput == "date": forum = Forum.objects.filter( topic__in=[categoryObject.id]).order_by("-createdAt") elif sortInput == "vote": forum = Forum.objects.filter( topic__in=[categoryObject.id]).annotate( num_vote=Count('upvote')).order_by('-num_vote') elif sortInput == "answer": forum = Forum.objects.filter( topic__in=[categoryObject.id]).annotate( num_answer=Count('answer')).order_by('-num_answer') else: raise FieldError("sort input not valid") else: # if sort exist forum = Forum.objects.filter(title__icontains=search) # Create list of forum forumList = [] for i in forum: # Check is upvote isUpvote = False if Employee.objects.get(user=request.user) in i.upvote.all(): isUpvote = True # Append forumList.append({ "id": i.id, "username": i.owner.user.username, "title": i.title, "question": i.question, "upvote": i.upvote.count(), "total_answer": i.answer.count(), "created_at": i.createdAt, "is_upvote": isUpvote }) # Response resp = { "status": status.HTTP_200_OK, "message": "success", "data": { "forum": forumList, "count": forum.count() } } return Response(resp, status=status.HTTP_200_OK) except FieldError as e: return FieldErrorHandler(e) except EmptyResultSet as e: return EmptyResultSetHandler(e) except Exception as e: return ExceptionHandler(e)