def post(self, request): # Check permission if not request.user.is_superuser: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) # Initialization form class CouponCodeListAPIPostForm(Form): code = CharField() discount = DecimalField(max_digits=2, decimal_places=2, validators=[ MinValueValidator(0.001), MaxValueValidator(0.999)]) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = CouponCodeListAPIPostForm(data) if form.is_valid(): # Update information cleaned_data = form.clean() exist_coupon_code = list( CouponCode.objects.filter(code=cleaned_data['code'])) if exist_coupon_code != []: return JsonResponse({ 'status': 409, 'message': 'CodeAlreadyExisted' }, status=409) coupon_code = CouponCode( code=cleaned_data['code'], discount=cleaned_data['discount']) try: with transaction.atomic(): coupon_code.save() log = Log(user=request.user, date=now( ), operation='Create a coupon code (id:' + str(coupon_code.id) + ')') log.save() except Exception as e: return JsonResponse({ 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success' }) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def delete(self, request, coupon_code_id): # Check permission if not request.user.is_superuser: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) try: coupon_code = CouponCode.objects.get(pk=coupon_code_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) try: with transaction.atomic(): log = Log(user=request.user, date=now(), operation='Delete a coupon code (id:' + str(coupon_code.id) + ' code:' + coupon_code.code + ')') log.save() coupon_code.delete() except Exception as e: return JsonResponse({ 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', })
def patch(self, request, bill_id): # Check permission if not request.user.is_superuser: return JsonResponse({ 'status': 403, 'message': 'Forbidden', }, status=403) # Initialization form class BillAPIPatchForm(Form): info = CharField(required=False) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = BillAPIPatchForm(data) if form.is_valid(): # Update information try: bill = Bill.objects.get( pk=bill_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) cleaned_data = form.clean() if 'info' in data: bill.info = cleaned_data['info'] try: with transaction.atomic(): log = Log(user=request.user, date=now( ), operation='Update info of the bill (id:' + str(bill.id) + ')') log.save() bill.save() except Exception as e: return JsonResponse({ 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', }) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def delete(self, request, user_id): # Check permission if not request.user.is_superuser: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) try: user = User.objects.get(pk=user_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) try: with transaction.atomic(): if user.picture is not None: user.picture.delete() log = Log(user=request.user, date=now(), operation='Delete a user ' + user.username + ' (id:' + str(user.id) + ')') log.save() user.delete() except Exception as e: return JsonResponse({ 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', })
def delete(self, request, course_id): try: course = Course.objects.get(pk=course_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) if not request.user.is_superuser and course.teacher != request.user: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) try: with transaction.atomic(): log = Log(user=request.user, date=now(), operation='Delete a course (course name:' + course.name + ' course id:' + str(course.id) + ')') log.save() if course.picture is not None: course.picture.delete() course.delete() except Exception as e: return JsonResponse({ 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', })
def put(self, request, user_id): # Check permission if not request.user.is_superuser and request.user.id != user_id: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) # Initialization form class UserAPIPutForm(Form): username = CharField() password = CharField(widget=PasswordInput) role = CharField() name = CharField() balance = DecimalField(max_digits=15, decimal_places=2) profile = CharField(required=False) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = UserAPIPutForm(data) if form.is_valid(): # Update information try: user = User.objects.get(pk=user_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) cleaned_data = form.clean() user_manager = UserManager() if cleaned_data['username'] != '' and user.username != cleaned_data[ 'username']: if not User.objects.filter( username=cleaned_data['username']).exists(): user.username == cleaned_data['username'] if cleaned_data['password'] != '': user.set_password(cleaned_data['password']) if cleaned_data['name'] != '': user.name = cleaned_data['name'] if request.user.is_superuser and ( cleaned_data['role'] == 'admin' or cleaned_data['role'] == 'teacher' or cleaned_data['role'] == 'student'): teacher_group = Group.objects.get(name='teacher') if cleaned_data['role'] == 'admin': user.is_superuser = True user.groups.add(teacher_group) else: user.is_superuser = False if cleaned_data['role'] == 'teacher': user.groups.add(teacher_group) else: user.groups.remove(teacher_group) if cleaned_data['profile'] != '': user.profile = cleaned_data['profile'] if request.user.id == user.id: try: with transaction.atomic(): user.save() log = Log(user=user, date=now(), operation='Update profile') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: try: with transaction.atomic(): user.save() log = Log( user=user, date=now(), operation='Update profile by an administrator (id:' + str(request.user.id) + ')') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) if request.user.is_superuser and cleaned_data[ 'balance'] is not None: balance_diff = cleaned_data['balance'] - user.balance try: with transaction.atomic(): bill = Bill( user=user, amount=balance_diff, date=now(), info='Adjust the balance by an administrator ' + request.user.username) user.balance = user.balance + balance_diff bill.save() user.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', }) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def patch(self, request, redemption_code_id): # Check permission if not request.user.is_superuser: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) # Initialization form class RedemptionCodeAPIPatchForm(Form): code = CharField(required=False) amount = DecimalField(max_digits=17, decimal_places=2, validators=[ MinValueValidator(0)], required=False) is_available = BooleanField(required=False) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = RedemptionCodeAPIPatchForm(data) if form.is_valid(): # Update information try: redemption_code = RedemptionCode.objects.get( pk=redemption_code_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) cleaned_data = form.clean() if 'code' in data and cleaned_data['code'] != '': redemption_code.code = cleaned_data['code'] if cleaned_data['amount'] is not None: redemption_code.amount = cleaned_data['amount'] if 'is_available' in data: redemption_code.is_available = cleaned_data['is_available'] try: with transaction.atomic(): redemption_code.save() log = Log(user=request.user, date=now( ), operation='Edit the redemption code (id:' + str(redemption_code.id) + ')') log.save() except Exception as e: return JsonResponse({ 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', }) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def post(self, request): # Check permission if not request.user.is_authenticated: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) # Initialization form class RedeemRedemptionCodeAPIPostForm(Form): username = CharField() code = CharField() try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = RedeemRedemptionCodeAPIPostForm(data) if form.is_valid(): # Update information cleaned_data = form.clean() try: cleaned_data['username'] = User.objects.get( username=cleaned_data['username']) except Exception as e: return JsonResponse({ 'status': 400, 'message': 'UserNotFound', }, status=400) try: redemption_code = RedemptionCode.objects.get( code=cleaned_data['code']) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) if redemption_code.is_available == False: return JsonResponse({ 'status': 403, 'message': 'AlreadyRedeemed', }, status=403) try: with transaction.atomic(): redemption_code.is_available = False cleaned_data['username'].balance = cleaned_data['username'].balance + \ redemption_code.amount bill = Bill(user=cleaned_data['username'], amount=redemption_code.amount, date=now( ), info='Redeem the redemption code ' + cleaned_data['code']) redemption_code.save() cleaned_data['username'].save() bill.save() log = Log(user=request.user, date=now(), operation='Redeem the redemption code ' + cleaned_data['code'] + ' for the user (username:'******'username'].username + ')') log.save() except Exception as e: return JsonResponse({ 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', }) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def post(self, request): # Initialization form class UserListAPIPostForm(Form): username = CharField() password = CharField(widget=PasswordInput) name = CharField() role = CharField(required=False) balance = DecimalField(max_digits=15, decimal_places=2, required=False) profile = CharField(required=False) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = UserListAPIPostForm(data) if form.is_valid(): # Update information cleaned_data = form.clean() if User.objects.filter(username=cleaned_data['username']).exists(): return JsonResponse( { 'status': 409, 'message': 'UserAlreadyExisted' }, status=409) user_manager = UserManager() user = user_manager.create_user(cleaned_data['username'], cleaned_data['password'], cleaned_data['name']) if request.user.is_superuser and ( cleaned_data['role'] == 'admin' or cleaned_data['role'] == 'teacher' or cleaned_data['role'] == 'student'): teacher_group = Group.objects.get(name='teacher') if cleaned_data['role'] == 'admin': user.is_superuser = True user.groups.add(teacher_group) else: user.is_superuser = False if cleaned_data['role'] == 'teacher': user.groups.add(teacher_group) else: user.groups.remove(teacher_group) if cleaned_data['profile'] != '': user.profile = cleaned_data['profile'] if request.user.is_authenticated: try: with transaction.atomic(): user.save() log = Log(user=user, date=now(), operation='Add by an administrator (id:' + str(request.user.id) + ')') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: try: with transaction.atomic(): user.save() log = Log(user=user, date=now(), operation='Sign up') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) if request.user.is_superuser and cleaned_data[ 'balance'] is not None: try: with transaction.atomic(): bill = Bill( user=user, amount=cleaned_data['balance'], date=now(), info='Adjust the balance by an administrator ' + request.user.username) user.balance = user.balance + cleaned_data['balance'] bill.save() user.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({'status': 200, 'message': 'Success'}) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def post(self, request): # Initialization form class UserLoginForm(Form): username = CharField() password = CharField(widget=PasswordInput) redirect_uri = CharField(required=False) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = UserLoginForm(data) if form.is_valid(): # Update information cleaned_data = form.clean() if 'redirect_uri' in data and cleaned_data[ 'redirect_uri'] != url_has_allowed_host_and_scheme( iri_to_uri(cleaned_data['redirect_uri']), settings.ALLOWED_HOSTS): cleaned_data['redirect_uri'] = iri_to_uri( cleaned_data['redirect_uri']) else: cleaned_data['redirect_uri'] = '/' user = authenticate(username=cleaned_data['username'], password=cleaned_data['password']) if user is not None: logout(request) login(request, user) request.session['is_teacher'] = request.user.groups.filter( name='teacher').exists() try: with transaction.atomic(): log = Log(user=request.user, date=now(), operation='Login') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', 'redirect_uri': cleaned_data['redirect_uri'], }) else: return JsonResponse({ 'status': 403, 'message': 'Login failed' }, status=403) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def delete(self, request, booking_id): if not request.user.is_authenticated: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) try: booking = Booking.objects.get(pk=booking_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) if booking.student == request.user: if booking.start_date > now(): try: with transaction.atomic(): log = Log(user=request.user, date=now(), operation='Cancel a booking (course:' + booking.course.name + ' booking id:' + str(booking.id) + ' student id:' + str(booking.student.id) + ')') log.save() course_instance = CourseInstance.objects.filter( course=booking.course, student=request.user) course_instance_target = course_instance[0] course_instance_target.quota = course_instance_target.quota + 1 booking.student = None course_instance_target.save() booking.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) elif booking.teacher == request.user or request.user.is_superuser: if booking.student is not None: if booking.start_date > now(): try: with transaction.atomic(): log = Log(user=request.user, date=now(), operation='Cancel a booking (course:' + booking.course.name + ' booking id:' + str(booking.id) + ' student id:' + str(booking.student.id) + ')') log.save() course_instance = CourseInstance.objects.filter( course=booking.course, student=booking.student) course_instance_target = course_instance[0] course_instance_target.quota = course_instance_target.quota + 1 booking.student = None course_instance_target.save() booking.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) try: with transaction.atomic(): log = Log(user=request.user, date=now(), operation='Delete a booking (course:' + booking.course.name + ' booking id:' + str(booking.id) + ')') log.save() booking.delete() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) return JsonResponse({ 'status': 200, 'message': 'Success', })
def post(self, request): # Check permission if not request.user.is_superuser: return JsonResponse({ 'status': 403, 'message': 'Forbidden', }, status=403) # Initialization form class BillListAPIPostForm(Form): username = CharField() amount = DecimalField(max_digits=17, decimal_places=2) info = CharField(required=False) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = BillListAPIPostForm(data) if form.is_valid(): # Update information cleaned_data = form.clean() try: cleaned_data['username'] = User.objects.get( username=cleaned_data['username']) except Exception as e: return JsonResponse({ 'status': 400, 'message': 'UserNotFound', }, status=400) try: with transaction.atomic(): bill = Bill(user=cleaned_data['username'], amount=cleaned_data['amount'], date=now( ), info=cleaned_data['info']) cleaned_data['username'].balance = cleaned_data['username'].balance + \ cleaned_data['amount'] bill.save() cleaned_data['username'].save() log = Log(user=request.user, date=now(), operation='Create a bill (id:' + str(bill.id) + ')') log.save() except Exception as e: return JsonResponse({ 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success' }) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def patch(self, request, booking_id): if not request.user.is_authenticated: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) class BookingAPIPatchForm(Form): start_date = DateTimeField(required=False) end_date = DateTimeField(required=False) student = CharField(required=False) info = CharField(required=False) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = BookingAPIPatchForm(data) if form.is_valid(): try: booking = Booking.objects.get(pk=booking_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) if booking.teacher == request.user or request.user.is_superuser: pass else: if CourseInstance.objects.filter(course=booking.course, student=request.user, quota__gt=0).exists(): pass else: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) cleaned_data = form.clean() if booking.teacher == request.user or request.user.is_superuser: if (cleaned_data['start_date'] is not None and booking.start_date != cleaned_data['start_date'] ) or (cleaned_data['end_date'] is not None and booking.end_date != cleaned_data['end_date']): if booking.student is not None and cleaned_data[ 'student'] is not None and cleaned_data[ 'student'] != '': return JsonResponse( { 'status': 400, 'message': 'StudentAlreadyBookedIt', }, status=400) else: if cleaned_data['start_date'] is None: cleaned_data['start_date'] = booking.start_date if cleaned_data['end_date'] is None: cleaned_data['end_date'] = booking.end_date if (cleaned_data['start_date'] > cleaned_data['end_date']) or ( cleaned_data['start_date'] < booking.course.start_date) or ( cleaned_data['end_date'] > booking.course.end_date): return JsonResponse( { 'status': 400, 'message': 'InvalidDate', }, status=400) crash_booking = Booking.objects.filter( Q(start_date__gt=cleaned_data['start_date'], start_date__lt=cleaned_data['end_date'], teacher=booking.teacher) | Q(end_date__gt=cleaned_data['start_date'], end_date__lt=cleaned_data['end_date'], teacher=booking.teacher)) if crash_booking: for each in crash_booking: if each != booking: return JsonResponse( { 'status': 400, 'message': 'TimeCrash', }, status=400) if cleaned_data['start_date'] is not None: booking.start_date = cleaned_data['start_date'] if cleaned_data['end_date'] is not None: booking.end_date = cleaned_data['end_date'] try: with transaction.atomic(): booking.save() log = Log(user=request.user, date=now(), operation= 'Update a booking\'s date (course:' + booking.course.name + ' booking id:' + str(booking.id) + ')') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) if cleaned_data['student'] is not None: if cleaned_data['student'] != '': if booking.student is None or cleaned_data[ 'student'] != booking.student.username: try: cleaned_data['student'] = User.objects.get( username=cleaned_data['student']) except Exception as e: return JsonResponse( { 'status': 400, 'message': 'StudentNotFound', }, status=400) course_instance = CourseInstance.objects.filter( course=booking.course, student=cleaned_data['student'], quota__gt=0) if not course_instance.exists(): return JsonResponse( { 'status': 400, 'message': 'InsufficientQuota', }, status=400) crash_booking = Booking.objects.filter( Q(start_date__gt=booking.start_date, start_date__lt=booking.end_date, student=request.user) | Q(end_date__gt=booking.start_date, end_date__lt=booking.end_date, student=request.user)) if crash_booking: for each in crash_booking: if each != booking: return JsonResponse( { 'status': 400, 'message': 'TimeCrash', }, status=400) if booking.start_date > now(): course_instance_target = course_instance[0] try: with transaction.atomic(): booking.student = cleaned_data[ 'student'] course_instance_target.quota = course_instance_target.quota - 1 log = Log( user=request.user, date=now(), operation= 'Update a booking\'s student (course:' + booking.course.name + ' booking id:' + str(booking.id) + ' student id:' + str(cleaned_data['student'].id) + ')') log.save() booking.save() course_instance_target.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: return JsonResponse( { 'status': 400, 'message': 'AlreadyGone', }, status=400) else: if booking.student is not None: if booking.start_date > now(): course_instance = CourseInstance.objects.filter( course=booking.course, student=booking.student) course_instance_target = course_instance[0] try: with transaction.atomic(): log = Log( user=request.user, date=now(), operation= 'Cancel a booking (course:' + booking.course.name + ' booking id:' + str(booking.id) + ' student id:' + str(booking.student.id) + ')') log.save() booking.student = None course_instance_target.quota = course_instance_target.quota + 1 booking.save() course_instance_target.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: return JsonResponse( { 'status': 400, 'message': 'AlreadyGone', }, status=400) if 'info' in data: try: with transaction.atomic(): booking.info = cleaned_data['info'] log = Log( user=request.user, date=now(), operation='Update a booking\'s info (course:' + booking.course.name + ' booking id:' + str(booking.id) + ')') log.save() booking.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: if cleaned_data[ 'student'] == request.user.username and booking.student is None: course_instance = CourseInstance.objects.filter( course=booking.course, student=request.user, quota__gt=0) if not course_instance.exists(): return JsonResponse( { 'status': 400, 'message': 'InsufficientQuota', }, status=400) crash_booking = Booking.objects.filter( Q(start_date__gt=booking.start_date, start_date__lt=booking.end_date, student=request.user) | Q(end_date__gt=booking.start_date, end_date__lt=booking.end_date, student=request.user)) if crash_booking: for each in crash_booking: if each != booking: return JsonResponse( { 'status': 400, 'message': 'TimeCrash', }, status=400) if booking.start_date > now(): course_instance_target = course_instance[0] try: with transaction.atomic(): booking.student = request.user course_instance_target.quota = course_instance_target.quota - 1 booking.save() course_instance_target.save() log = Log( user=request.user, date=now(), operation= 'Update a booking\'s student (course:' + booking.course.name + ' booking id:' + str(booking.id) + ' student id:' + str(request.user.id) + ')') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: return JsonResponse( { 'status': 400, 'message': 'AlreadyGone', }, status=400) elif booking.student == request.user and cleaned_data[ 'student'] is not None and cleaned_data[ 'student'] == '': if booking.start_date > now(): try: with transaction.atomic(): log = Log( user=request.user, date=now(), operation='Cancel a booking (course:' + booking.course.name + ' booking id:' + str(booking.id) + ' student id:' + str(booking.student.id) + ')') log.save() course_instance = CourseInstance.objects.filter( course=booking.course, student=request.user) course_instance_target = course_instance[0] course_instance_target.quota = course_instance_target.quota + 1 booking.student = None course_instance_target.save() booking.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: return JsonResponse( { 'status': 400, 'message': 'AlreadyGone', }, status=400) elif booking.student == request.user and ( cleaned_data['student'] is None or cleaned_data['student'] == request.user.username): pass else: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) return JsonResponse({ 'status': 200, 'message': 'Success', }) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def post(self, request): if not request.user.is_superuser and not request.user.groups.filter( name='teacher').exists(): return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) class BookingListAPIPostForm(Form): course = IntegerField() start_date = DateTimeField() end_date = DateTimeField() teacher = CharField(required=False) info = CharField(required=False) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = BookingListAPIPostForm(data) if form.is_valid(): cleaned_data = form.clean() try: cleaned_data['course'] = Course.objects.get( pk=cleaned_data['course']) except Exception as e: return JsonResponse( { 'status': 400, 'message': 'CourseNotFound', }, status=400) if request.user.is_superuser: if 'teacher' in data and cleaned_data[ 'teacher'] is not None and cleaned_data[ 'teacher'] != '': try: cleaned_data['teacher'] = User.objects.get( username=cleaned_data['teacher']) except Exception as e: return JsonResponse( { 'status': 400, 'message': 'TeacherNotFound', }, status=400) else: cleaned_data['teacher'] = cleaned_data['course'].teacher else: cleaned_data['teacher'] = request.user if cleaned_data[ 'course'].teacher != request.user and not request.user.is_superuser: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) if (cleaned_data['start_date'] > cleaned_data['end_date']) or ( cleaned_data['start_date'] < cleaned_data['course'].start_date ) or (cleaned_data['end_date'] > cleaned_data['course'].end_date): return JsonResponse({ 'status': 400, 'message': 'InvalidDate', }, status=400) crash_booking = Booking.objects.filter( Q(start_date__gt=cleaned_data['start_date'], start_date__lt=cleaned_data['end_date'], teacher=cleaned_data['teacher']) | Q(end_date__gt=cleaned_data['start_date'], end_date__lt=cleaned_data['end_date'], teacher=cleaned_data['teacher'])) if crash_booking: return JsonResponse({ 'status': 400, 'message': 'TimeCrash', }, status=400) booking = Booking(course=cleaned_data['course'], start_date=cleaned_data['start_date'], end_date=cleaned_data['end_date'], teacher=cleaned_data['teacher'], info=cleaned_data['info']) try: with transaction.atomic(): booking.save() log = Log(user=request.user, date=now(), operation='Create a booking for course ' + cleaned_data['course'].name + '(booking id:' + str(booking.id) + ')') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({'status': 200, 'message': 'Success'}) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def post(self, request): # Check permission if not request.user.is_superuser and not request.user.groups.filter( name='teacher').exists(): return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) # Initialization form class CourseListAPIPostForm(Form): name = CharField(max_length=200) info = CharField(required=False) start_date = DateTimeField() end_date = DateTimeField() teacher = CharField(required=False) price = DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0)]) quota = IntegerField(validators=[MinValueValidator(0)]) sold = IntegerField(validators=[MinValueValidator(0)], required=False) picture = FileField(required=False) form = CourseListAPIPostForm(request.POST, request.FILES) if form.is_valid(): # Update information cleaned_data = form.clean() if request.user.is_superuser and 'teacher' in request.POST: try: cleaned_data['teacher'] = User.objects.get( username=cleaned_data['teacher']) except Exception as e: return JsonResponse( { 'status': 400, 'message': 'TeacherNotFound', }, status=400) else: cleaned_data['teacher'] = request.user if cleaned_data['start_date'] > cleaned_data['end_date']: return JsonResponse({ 'status': 400, 'message': 'InvalidDate', }, status=400) if cleaned_data['sold'] is None: cleaned_data['sold'] = 0 course = Course(name=cleaned_data['name'], info=cleaned_data['info'], start_date=cleaned_data['start_date'], end_date=cleaned_data['end_date'], teacher=cleaned_data['teacher'], price=cleaned_data['price'], quota=cleaned_data['quota'], sold=cleaned_data['sold']) if cleaned_data['picture'] is not None: if cleaned_data['picture'].content_type[:5] != 'image': return JsonResponse( { 'status': 400, 'message': 'IllegalFileType' }, status=400) try: with transaction.atomic(): blob_storage = BlobStorage( data=cleaned_data['picture'].file.read(), content_type=cleaned_data['picture'].content_type) blob_storage.save() course.picture = blob_storage course.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) try: with transaction.atomic(): course.save() log = Log(user=request.user, date=now(), operation='Create a course ' + course.name + ' (id:' + str(course.id) + ')') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({'status': 200, 'message': 'Success'}) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def patch(self, request, course_instance_id): # Check permission if not request.user.is_superuser: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) # Initialization form class CourseInstanceAPIPatchForm(Form): quota = IntegerField(validators=[MinValueValidator(0)]) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = CourseInstanceAPIPatchForm(data) if form.is_valid(): # Update information try: course_instance = CourseInstance.objects.get( pk=course_instance_id) except Exception as e: return JsonResponse( { 'status': 404, 'message': 'Not Found', 'data': [], }, status=404) cleaned_data = form.clean() if cleaned_data['quota'] != '': course_instance.quota = cleaned_data['quota'] try: with transaction.atomic(): log = Log( user=request.user, date=now(), operation='Update quota for the course instance (id:' + str(course_instance.id) + ')') log.save() course_instance.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def post(self, request): # Check permission if not request.user.is_authenticated: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) # Initialization form class CourseInstanceListAPIPostForm(Form): course = IntegerField() coupon_code = CharField(required=False) try: data = json.loads(request.body) except: return JsonResponse({ 'status': 400, 'message': 'JSONDecodeError' }, status=400) form = CourseInstanceListAPIPostForm(data) if form.is_valid(): # Update information cleaned_data = form.clean() try: cleaned_data['course'] = Course.objects.get( pk=cleaned_data['course']) except Exception as e: return JsonResponse( { 'status': 400, 'message': 'CourseNotFound', }, status=400) if cleaned_data['coupon_code'] != '': try: coupon_code_discount = CouponCode.objects.get( code=cleaned_data['coupon_code']).discount except Exception as e: return JsonResponse( { 'status': 400, 'message': 'CouponCodeNotFound', }, status=400) else: coupon_code_discount = 0 need_to_pay = round( cleaned_data['course'].price * (1 - coupon_code_discount), 2) if request.user.balance < need_to_pay: return JsonResponse( { 'status': 403, 'message': 'InsufficientBalance', }, status=403) try: with transaction.atomic(): bill = Bill(user=request.user, amount=-need_to_pay, date=now(), info='Pay for the course ' + cleaned_data['course'].name) request.user.balance = request.user.balance - need_to_pay course_instance = CourseInstance( course=cleaned_data['course'], student=request.user, teacher=cleaned_data['course'].teacher, quota=cleaned_data['course'].quota) cleaned_data['course'].sold += 1 log = Log(user=request.user, date=now(), operation='Buy the course ' + cleaned_data['course'].name + ' (id:' + str(cleaned_data['course'].id) + ')') log.save() bill.save() request.user.save() course_instance.save() cleaned_data['course'].save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({'status': 200, 'message': 'Success'}) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def post(self, request, user_id): # Check permission if not request.user.is_superuser and request.user.id != user_id: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) # Initialization form class UserAPIPostForm(Form): username = CharField(required=False) old_password = CharField(widget=PasswordInput, required=False) password = CharField(widget=PasswordInput, required=False) name = CharField(required=False) role = CharField(required=False) balance = DecimalField(max_digits=15, decimal_places=2, required=False) profile = CharField(required=False) picture = FileField(required=False) form = UserAPIPostForm(request.POST, request.FILES) if form.is_valid(): # Update information try: user = User.objects.get(pk=user_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) cleaned_data = form.clean() user_manager = UserManager() if cleaned_data['username'] != '' and user.username != cleaned_data[ 'username']: if not User.objects.filter( username=cleaned_data['username']).exists(): user.username = cleaned_data['username'] if cleaned_data['password'] != '': if cleaned_data['old_password'] != '': if authenticate( username=user.username, password=cleaned_data['old_password']) is not None: user.set_password(cleaned_data['password']) else: return JsonResponse( { 'status': 403, 'message': 'OldPasswordIncorrect' }, status=403) elif request.user.is_superuser and user.id != request.user.id: user.set_password(cleaned_data['password']) else: return JsonResponse( { 'status': 403, 'message': 'NeedOldPassword' }, status=403) if cleaned_data['name'] != '': user.name = cleaned_data['name'] if request.user.is_superuser and ( cleaned_data['role'] == 'admin' or cleaned_data['role'] == 'teacher' or cleaned_data['role'] == 'student'): teacher_group = Group.objects.get(name='teacher') if cleaned_data['role'] == 'admin': user.is_superuser = True user.groups.add(teacher_group) else: user.is_superuser = False if cleaned_data['role'] == 'teacher': user.groups.add(teacher_group) else: user.groups.remove(teacher_group) if cleaned_data['profile'] != '': user.profile = cleaned_data['profile'] if cleaned_data['picture'] is not None: if cleaned_data['picture'].content_type[:5] != 'image': return JsonResponse( { 'status': 400, 'message': 'IllegalFileType' }, status=400) if user.picture is None: try: with transaction.atomic(): blob_storage = BlobStorage( data=cleaned_data['picture'].file.read(), content_type=cleaned_data['picture']. content_type) blob_storage.save() user.picture = blob_storage user.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: try: with transaction.atomic(): user.picture.data = data = cleaned_data[ 'picture'].file.read() user.picture.content_type = cleaned_data[ 'picture'].content_type user.picture.save() user.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) if request.user.id == user.id: try: with transaction.atomic(): user.save() log = Log(user=user, date=now(), operation='Update profile') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: try: with transaction.atomic(): user.save() log = Log( user=user, date=now(), operation='Update profile by an administrator (id:' + str(request.user.id) + ')') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) if request.user.is_superuser and cleaned_data[ 'balance'] is not None: balance_diff = cleaned_data['balance'] - user.balance try: with transaction.atomic(): bill = Bill( user=user, amount=balance_diff, date=now(), info='Adjust the balance by an administrator ' + request.user.username) user.balance = user.balance + balance_diff bill.save() user.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', }) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)
def post(self, request, course_id): # Initialization form class CourseAPIPostForm(Form): name = CharField(max_length=200) info = CharField(required=False) start_date = DateTimeField() end_date = DateTimeField() price = DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0)]) quota = IntegerField(validators=[MinValueValidator(0)]) sold = IntegerField(validators=[MinValueValidator(0)], required=False) picture = FileField(required=False) form = CourseAPIPostForm(request.POST, request.FILES) if form.is_valid(): # Update information try: course = Course.objects.get(pk=course_id) except Exception as e: return JsonResponse({ 'status': 404, 'message': 'Not Found', }, status=404) if not request.user.is_superuser and course.teacher != request.user: return JsonResponse({ 'status': 403, 'message': 'Forbidden' }, status=403) cleaned_data = form.clean() if cleaned_data['name'] != '': course.name = cleaned_data['name'] if cleaned_data['info'] != '': course.info = cleaned_data['info'] if cleaned_data['start_date'] != '': course.start_date = cleaned_data['start_date'] if cleaned_data['end_date'] != '': course.end_date = cleaned_data['end_date'] if cleaned_data['start_date'] > cleaned_data['end_date']: return JsonResponse({ 'status': 400, 'message': 'InvalidDate', }, status=400) if cleaned_data['price'] != '': course.price = cleaned_data['price'] if cleaned_data['quota'] != '': course.quota = cleaned_data['quota'] if cleaned_data['sold'] is not None: course.sold = cleaned_data['sold'] if cleaned_data['picture'] is not None: if cleaned_data['picture'].content_type[:5] != 'image': return JsonResponse( { 'status': 400, 'message': 'IllegalFileType' }, status=400) if course.picture is None: try: with transaction.atomic(): blob_storage = BlobStorage( data=cleaned_data['picture'].file.read(), content_type=cleaned_data['picture']. content_type) blob_storage.save() course.picture = blob_storage course.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) else: try: with transaction.atomic(): course.picture.data = cleaned_data[ 'picture'].file.read() course.picture.content_type = cleaned_data[ 'picture'].content_type course.picture.save() course.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) try: with transaction.atomic(): course.save() log = Log(user=request.user, date=now(), operation='Update infomation about the course ' + course.name + ' (id:' + str(course.id) + ')') log.save() except Exception as e: return JsonResponse( { 'status': 500, 'message': 'DatabaseError', }, status=500) return JsonResponse({ 'status': 200, 'message': 'Success', }) else: return JsonResponse({ 'status': 400, 'message': form.errors }, status=400)