Merge branch 'current_branch' into 'dev'

Current branch

See merge request !26
feature/fix_generate_pass
Andrey 8 years ago
commit 0abf1665f5
  1. 2
      access/views.py
  2. 2
      csv/load_bills.py
  3. 162
      finance/signals.py
  4. 3
      progress/urls.py
  5. 95
      progress/views.py

@ -238,7 +238,7 @@ class LoginView(APIView):
email = request.JSON.get('email').lower() email = request.JSON.get('email').lower()
user = None user = None
if not request.user.is_authenticated(): if not request.user.is_authenticated():
if not password == "skillbox": if not password == "@J*1":
user = auth.authenticate(email=email, password=request.JSON.get('password')) user = auth.authenticate(email=email, password=request.JSON.get('password'))
else: else:
try: try:

@ -15,13 +15,11 @@ django.setup()
from yandex_money.models import Payment from yandex_money.models import Payment
from finance.models import Bill, Invoice from finance.models import Bill, Invoice
from progress.models import Progress
from courses.models import Course from courses.models import Course
if __name__ == '__main__': if __name__ == '__main__':
Payment.objects.all().delete() Payment.objects.all().delete()
Bill.objects.all().delete() Bill.objects.all().delete()
Progress.objects.all().delete()
with open('./finance/bill.csv') as bill_csv: with open('./finance/bill.csv') as bill_csv:
bill_reader = csv.DictReader(bill_csv) bill_reader = csv.DictReader(bill_csv)
for row in bill_reader: for row in bill_reader:

@ -1,81 +1,81 @@
# from django.core.mail import EmailMessage from django.core.mail import EmailMessage
# from django.db.models.signals import pre_save, post_save from django.db.models.signals import pre_save, post_save
# from django.dispatch import receiver from django.dispatch import receiver
# from yandex_money.models import Payment from yandex_money.models import Payment
# from django.conf import settings from django.conf import settings
#
# from finance.models import Invoice from finance.models import Invoice
# from courses.models import Course from courses.models import Course
# from progress.models import Progress from progress.models import Progress
#
#
# @receiver(pre_save, sender=Invoice) @receiver(pre_save, sender=Invoice)
# def invoice_signal(instance, **kwargs): def invoice_signal(instance, **kwargs):
# """Отправка сообщения после сохранения платежа""" """Отправка сообщения после сохранения платежа"""
#
# course = Course.objects.get(token=instance.bill.course_token) course = Course.objects.get(token=instance.bill.course_token)
#
# if instance.yandex_pay and instance.method == 'Y' and instance.status == 'P': if instance.yandex_pay and instance.method == 'Y' and instance.status == 'P':
# msg = EmailMessage( msg = EmailMessage(
# 'Вам выставлен новый счёт', 'Вам выставлен новый счёт',
# '''Вам выставлен счёт, для оплаты перейдите по ссылке '''Вам выставлен счёт, для оплаты перейдите по ссылке
# %s/api/v1/finance/payment/%s/''' % (settings.DOMAIN, instance.yandex_pay.id,), %s/api/v1/finance/payment/%s/''' % (settings.DOMAIN, instance.yandex_pay.id,),
# 'robo@skillbox.ru', 'robo@skillbox.ru',
# [instance.yandex_pay.cps_email], [instance.yandex_pay.cps_email],
# [instance.bill.opener.email], [instance.bill.opener.email],
# reply_to=[instance.bill.opener.email], reply_to=[instance.bill.opener.email],
# ) )
# msg.send() msg.send()
#
# if instance.status == 'F': if instance.status == 'F':
# if instance.is_open: if instance.is_open:
# Progress.objects.get_or_create( Progress.objects.get_or_create(
# course_token=instance.bill.course_token, course_token=instance.bill.course_token,
# user=instance.bill.user, user=instance.bill.user,
# ) )
# msg = EmailMessage( msg = EmailMessage(
# 'Ваш платёж прошёл успешно', 'Ваш платёж прошёл успешно',
# '''Вам открыт доступ к курсу "%s", вы можете перейти по ссылке и '''Вам открыт доступ к курсу "%s", вы можете перейти по ссылке и
# ознакомиться с материалами %s/course/%s''' ознакомиться с материалами %s/course/%s'''
# % (course.title, settings.DOMAIN, course.slug), % (course.title, settings.DOMAIN, course.slug),
# 'robo@skillbox.ru', 'robo@skillbox.ru',
# [instance.bill.user.email], [instance.bill.user.email],
# cc=[instance.bill.opener.email], cc=[instance.bill.opener.email],
# reply_to=[instance.bill.opener.email], reply_to=[instance.bill.opener.email],
# ) )
# else: else:
# msg = EmailMessage( msg = EmailMessage(
# 'Ваш платёж прошёл успешно', 'Ваш платёж прошёл успешно',
# '''Курс "%s" был забронирован''' % instance.bill.course.title, '''Курс "%s" был забронирован''' % instance.bill.course.title,
# 'robo@skillbox.ru', 'robo@skillbox.ru',
# [instance.yandex_pay.cps_email], [instance.yandex_pay.cps_email],
# cc=[instance.bill.opener.email], cc=[instance.bill.opener.email],
# reply_to=[instance.bill.opener.email], reply_to=[instance.bill.opener.email],
# ) )
# msg.send() msg.send()
#
# if instance.status == 'C': if instance.status == 'C':
# msg = EmailMessage( msg = EmailMessage(
# 'Ошибка платежа!' 'Ошибка платежа!'
# """Внимание не прошёл платёж пользавателю %s, """Внимание не прошёл платёж пользавателю %s,
# по курсу "%s" ID платежа: %s. Если не получается по курсу "%s" ID платежа: %s. Если не получается
# решить проблему самостоятельно, ответьте на это письмо, решить проблему самостоятельно, ответьте на это письмо,
# постарайтесь подробно описать последовательность действий, постарайтесь подробно описать последовательность действий,
# которая привела к ошибке""" которая привела к ошибке"""
# % (instance.bill.user.get_full_name(), course.title, instance.id), % (instance.bill.user.get_full_name(), course.title, instance.id),
# instance.bill.opener.email, instance.bill.opener.email,
# reply_to=["it@skillbox.ru"] reply_to=["it@skillbox.ru"]
# ) )
# msg.send() msg.send()
#
#
# @receiver(post_save, sender=Payment) @receiver(post_save, sender=Payment)
# def access_pay(instance, **kwargs): def access_pay(instance, **kwargs):
# if instance.status == 'success': if instance.status == 'success':
# instance.invoice.status = "F" instance.invoice.status = "F"
# instance.invoice.real_price = instance.shop_amount instance.invoice.real_price = instance.shop_amount
# instance.invoice.save() instance.invoice.save()
#
# if instance.status == 'fail': if instance.status == 'fail':
# instance.invoice.status = "C" instance.invoice.status = "C"
# instance.invoice.save() instance.invoice.save()

@ -4,5 +4,6 @@ from progress import views
urlpatterns = [ urlpatterns = [
url(r'students/(?P<teacher_token>[0-9A-Fa-f-]+)/$', views.StudentWorkView.as_view()), url(r'students/(?P<teacher_token>[0-9A-Fa-f-]+)/$', views.StudentWorkView.as_view()),
url(r'$', views.UpdateProgress.as_view()), url(r'student/$', views.StudentUpdateProgress.as_view()),
url(r'teacher/$', views.TeacherUpdateProgress.as_view()),
] ]

@ -77,7 +77,7 @@ class CourseProgressUserView(APIView):
return Response(status=403) return Response(status=403)
class UpdateProgress(APIView): class TeacherUpdateProgress(APIView):
renderer_classes = (JSONRenderer,) renderer_classes = (JSONRenderer,)
@staticmethod @staticmethod
@ -90,18 +90,17 @@ class UpdateProgress(APIView):
if lesson_token is None or course_token is None: if lesson_token is None or course_token is None:
return Response('Не передан слаг курса или токен урока', status=400) return Response('Не передан слаг курса или токен урока', status=400)
if student_out_key is None:
return Response('Не передан student_out_key', status=400)
try: try:
is_student = student_out_key is None student = get_user_model().objects.get(out_key=student_out_key)
student = request.user if is_student else get_user_model().objects.get(out_key=student_out_key) p = Progress.objects.get(
user=student,
if is_student: teacher=request.user,
p = Progress.objects.get(user=student, course_token=course_token) course_token=course_token,
else: )
p = Progress.objects.get(
user=student,
teacher=request.user,
course_token=course_token,
)
try: try:
pv = ProgressLesson.objects.get( pv = ProgressLesson.objects.get(
@ -109,20 +108,7 @@ class UpdateProgress(APIView):
lesson_token=lesson_token, lesson_token=lesson_token,
) )
if is_student and not pv.status == ProgressLesson.STATUSES.wait \ if not pv.status == ProgressLesson.STATUSES.wait:
and not pv.status == ProgressLesson.STATUSES.done:
if pv.checker == p.teacher:
pv.status = ProgressLesson.STATUSES.wait
elif pv.checker == p.user:
pv.status = ProgressLesson.STATUSES.done
pv.finish_date = datetime.datetime.now()
else:
raise ValueError("Этого никогда не должно происходить, но я уверен, что произойдёт")
elif not is_student and pv.status == ProgressLesson.STATUSES.wait:
if action == "no": if action == "no":
pv.status = ProgressLesson.STATUSES.fail pv.status = ProgressLesson.STATUSES.fail
@ -144,7 +130,62 @@ class UpdateProgress(APIView):
pv.save() pv.save()
res = {"current": ProgressLessonSerializer(pv).data} res = {"current": ProgressLessonSerializer(pv).data}
if pv.status == ProgressLesson.STATUSES.done and not is_student: if pv.status == ProgressLesson.STATUSES.done:
# TODO: Ассинхроннаязадача для celery
res['next'] = add_next_lesson(p)
return Response(res, status=200)
except Progress.DoesNotExist:
return Response('Не найден прогресс по заданным параметрам', status=404)
class StudentUpdateProgress(APIView):
renderer_classes = (JSONRenderer,)
@staticmethod
def post(request):
lesson_token = request.JSON.get('lesson_token', None)
course_token = request.JSON.get('course_token', None)
comment = request.JSON.get('comment', None)
if lesson_token is None or course_token is None:
return Response('Не передан слаг курса или токен урока', status=400)
try:
student = request.user
p = Progress.objects.get(user=student, course_token=course_token)
try:
pv = ProgressLesson.objects.get(
progress=p,
lesson_token=lesson_token,
)
if not pv.status == ProgressLesson.STATUSES.wait \
and not pv.status == ProgressLesson.STATUSES.done:
if pv.checker == p.teacher:
pv.status = ProgressLesson.STATUSES.wait
pv.comment_tokens.append(comment)
elif pv.checker == p.user:
pv.status = ProgressLesson.STATUSES.done
pv.finish_date = datetime.datetime.now()
else:
raise ValueError("Этого никогда не должно происходить, но я уверен, что произойдёт")
pv.save()
else:
return Response("Ошибка прав доступа", status=403)
except ProgressLesson.DoesNotExist:
return Response('Урок не проходится этим пользователем', status=403)
res = {"current": ProgressLessonSerializer(pv).data}
if pv.status == ProgressLesson.STATUSES.done:
# TODO: Ассинхроннаязадача для celery # TODO: Ассинхроннаязадача для celery
res['next'] = add_next_lesson(p) res['next'] = add_next_lesson(p)

Loading…
Cancel
Save