Exemple #1
0
def cancel_all_prefs(trainess, cancelnote, site, ruser, d):
    trainess_course_records = TrainessCourseRecord.objects.filter(
        course__site=site, trainess=trainess)
    now = datetime.date.today()
    try:
        context = {
            "trainess": trainess,
            "site": site,
            "cancelnote": cancelnote
        }
        try:
            context['recipientlist'] = REPORT_RECIPIENT_LIST
            context['course_prefs'] = trainess_course_records
            approvedpref = TrainessCourseRecord.objects.filter(
                course__site=site,
                trainess=trainess,
                approved=True,
                consentemailsent=True)
            if site.application_end_date < now < site.event_start_date:
                if approvedpref:
                    context['recipientlist'].extend(
                        approvedpref[0].course.authorized_trainer.all(
                        ).values_list('user__username', flat=True))
            send_email_by_operation_name(context, "notice_for_canceled_prefs")
            context['recipientlist'] = [trainess.user.email]
            send_email_by_operation_name(context, "notice_for_canceled_prefs")
            trainess_course_records.delete()
        except Exception as e:
            log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno),
                      extra=d)
            log.error(e.message, extra=d)
            return 0
        if site.application_end_date < now:
            remaining_days = int((site.event_start_date - now).days)
            notestr = "Kursların başlamasına %d gun kala tüm başvurularını iptal etti." % remaining_days
            if approvedpref:
                # Kullanicinin tercihi kursa kaç gün kala kabul görmüş
                daysbetweenapproveandevent = int(
                    (site.event_start_date -
                     approvedpref[0].instapprovedate).days)
                notestr += "\nTercihi kursun başlamasına %d gün kala kabul edilmiş." % daysbetweenapproveandevent
        else:
            notestr = "Kullanici tercihlerini iptal etti"
        if cancelnote:
            notestr += "\nİptal Sebebi:%s" % cancelnote
        if notestr:
            note = TrainessNote(note=notestr,
                                note_from_profile=ruser.userprofile,
                                note_to_profile=trainess,
                                site=site,
                                note_date=now,
                                label="sistem")
            note.save()
        return 1
    except Exception as e:
        log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno),
                  extra=d)
        log.error(e.message, extra=d)
        return 2
Exemple #2
0
def applytrainerselections(postrequest, courses, data, d):
    note = ""
    now = timezone.now()
    if UserProfileOPS.is_authorized_inst(data["user"].userprofile):
        sendconsentemail = postrequest.get("send_consent_email", False)
        for course in courses:
            try:
                data["changedprefs"] = []
                data["course"] = course
                approvedr = postrequest.getlist('students' + str(course.pk))
                sendconsentmailprefs = postrequest.getlist('consentmail' + str(course.pk))
                for pref in data['dates']:
                    if data['dates'][pref].start_date <= now <= data['dates'][pref].end_date:
                        allprefs = TrainessCourseRecord.objects.filter(course=course.pk, preference_order=pref)
                        for p in allprefs:
                            if not p.consentemailsent:
                                if str(p.pk) not in approvedr and p.approved:
                                    p.approved = False
                                    p.trainess_approved = False
                                    data["changedprefs"].append(p)
                                elif str(p.pk) in approvedr and not p.approved:
                                    data['approvedpref'] = p
                                    trainess_approved_pref = is_trainess_approved_anothercourse(p.trainess, pref)
                                    if trainess_approved_pref:
                                        data['changedpref'] = trainess_approved_pref
                                        data["recipientlist"] = trainess_approved_pref.course.authorized_trainer.all() \
                                            .values_list('user__username', flat=True)
                                        send_email_by_operation_name(data, "inform_trainers_about_changes")
                                    p.approved = True
                                    p.instapprovedate = now
                                    course.trainess.add(p.trainess)
                                    course.save()
                                    if not REQUIRE_TRAINESS_APPROVE:
                                        p.trainess_approved = True
                                    data["changedprefs"].append(p)
                                if sendconsentemail == "on" and str(p.pk) in sendconsentmailprefs:
                                    if p.preference_order == 1 and p.approved:
                                        data['approvedpref'] = p
                                        data["recipientlist"] = [p.trainess.user.username]
                                        res = send_email_by_operation_name(data, "send_consent_email")
                                        if res == 1:
                                            p.consentemailsent = True
                                p.save()
                note = "Seçimleriniz başarılı bir şekilde kaydedildi."
                if data["changedprefs"]:
                    data["recipientlist"] = data['course'].authorized_trainer.all().values_list('user__username',
                                                                                                flat=True)
                    send_email_by_operation_name(data, "inform_about_changes")
            except Exception as e:
                note = "Beklenmedik bir hata oluştu!"
                log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), extra=d)
                log.error(e.message, extra=d)
    else:
        note = "Bu işlemi yapmaya yetkiniz yok!"
    return note
Exemple #3
0
def send_confirm_link(instance, created, **kwargs):
    if not instance.is_staff:
        if created:
            instance.is_active = False
            user_verification, created = UserVerification.objects.get_or_create(user=instance)
            user_verification.activation_key = create_verification_link(instance)
            user_verification.save()
            context = {'user': instance, 'activation_key': user_verification.activation_key,
                       'site': Site.objects.get(is_active=True), 'recipientlist': [instance.username]}
            context['domain'] = context['site'].home_url.rstrip('/')
            send_email_by_operation_name(context, "send_activation_key")
def send_all_consent_email():
    from training.models import TrainessCourseRecord
    from abkayit.backend import send_email_by_operation_name
    from abkayit.models import Site
    active_site = Site.objects.get(is_active=True)
    data = {'site': active_site}
    trainessrecords = TrainessCourseRecord.objects.filter(course__site=active_site, approved=True, consentemailsent=False)
    for trainessrecord in trainessrecords:
        data["recipientlist"] = [trainessrecord.trainess.user.username]
        data["approvedpref"] = trainessrecord
        send_email_by_operation_name(data, "send_consent_email")
        trainessrecord.consentemailsent = True
        trainessrecord.save()
def send_all_consent_email():
    from training.models import TrainessCourseRecord
    from abkayit.backend import send_email_by_operation_name
    from abkayit.models import Site
    active_site = Site.objects.get(is_active=True)
    data = {'site': active_site}
    trainessrecords = TrainessCourseRecord.objects.filter(
        course__site=active_site, approved=True, consentemailsent=False)
    for trainessrecord in trainessrecords:
        data["recipientlist"] = [trainessrecord.trainess.user.username]
        data["approvedpref"] = trainessrecord
        send_email_by_operation_name(data, "send_consent_email")
        trainessrecord.consentemailsent = True
        trainessrecord.save()
Exemple #6
0
def send_confirm_link(instance, created, **kwargs):
    if not instance.is_staff:
        if created:
            instance.is_active = False
            user_verification, created = UserVerification.objects.get_or_create(user=instance)
            user_verification.activation_key = create_verification_link(instance)
            user_verification.save()
            context = {
                "user": instance,
                "activation_key": user_verification.activation_key,
                "site": Site.objects.get(is_active=True),
                "recipientlist": [instance.username],
            }
            context["domain"] = context["site"].home_url.rstrip("/")
            send_email_by_operation_name(context, "send_activation_key")
Exemple #7
0
def password_reset_key(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    note = _("Please enter your registered email")
    if request.method == 'POST':
        email = request.POST['email']
        if email and email != "":
            try:
                user = User.objects.get(username=request.POST['email'])
                user_verification, created = UserVerification.objects.get_or_create(user=user)
                user_verification.password_reset_key = create_verification_link(user)
                user_verification.save()
                data['ruser'] = user
                data['activation_key'] = user_verification.password_reset_key
                domain = data['site'].home_url
                data['domain'] = domain.rstrip('/')
                data['recipientlist'] = [user.username]
                note = send_email_by_operation_name(data, "send_reset_password_key")
                if note:
                    note = "Parola sıfırlama e-postası adresinize gönderildi."
                else:
                    note = "E-posta gönderilemedi"
            except ObjectDoesNotExist:
                note = _("""There isn't any user record with this e-mail on the system""")
                log.error(note, extra=d)
            except Exception as e:
                note = _("""Password reset operation failed""")
                log.error(note, extra=d)
                log.error(e.message, extra=d)
        else:
            note = _("""Email field can not be empty""")
            log.error(note, extra=d)
    data['note'] = note
    return render_to_response("userprofile/change_password_key_request.html", data,
                              context_instance=RequestContext(request))
def send_to_not_approved_trainess_email(functionname):
    from training.models import TrainessCourseRecord
    from abkayit.backend import send_email_by_operation_name
    from abkayit.models import Site
    import logging
    log = logging.getLogger(__name__)
    active_site = Site.objects.get(is_active=True)
    data = {'site': active_site}
    trainessrecords = TrainessCourseRecord.objects.filter(
        course__site=active_site, approved=False, consentemailsent=False)
    for trainessrecord in trainessrecords:
        has_approved_pref = TrainessCourseRecord.objects.filter(
            trainess=trainessrecord.trainess,
            approved=True,
            course__site=active_site)
        if not has_approved_pref:
            data["recipientlist"] = [trainessrecord.trainess.user.username]
            data["approvedpref"] = trainessrecord
            if send_email_by_operation_name(data, functionname):
                log.info("%s kullanicisina %s"
                         " maili gonderildi" %
                         (trainessrecord.trainess.user.username, functionname),
                         extra={
                             'clientip': '',
                             'user': '******'
                         })
Exemple #9
0
def cancel_all_prefs(trainess, cancelnote, site, ruser, d):
    trainess_course_records = TrainessCourseRecord.objects.filter(course__site__is_active=True,
                                                                  trainess=trainess)
    now = datetime.date.today()
    try:
        context = {"trainess": trainess, "site": site, "cancelnote":cancelnote}
        try:
            context['recipientlist'] = REPORT_RECIPIENT_LIST
            context['course_prefs'] = trainess_course_records
            approvedpref = TrainessCourseRecord.objects.filter(course__site__is_active=True, trainess=trainess,
                                                            approved=True, consentemailsent=True)
            if site.application_end_date < now < site.event_start_date:
                if approvedpref:
                    context['recipientlist'].extend(approvedpref[0].course.authorized_trainer.all().values_list(
                        'user__username', flat=True))
            send_email_by_operation_name(context, "notice_for_canceled_prefs")
            context['recipientlist'] = [trainess.user.email]
            send_email_by_operation_name(context, "notice_for_canceled_prefs")
            trainess_course_records.delete()
        except Exception as e:
            log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), extra=d)
            log.error(e.message, extra=d)
            return 0
        if site.application_end_date < now:
            remaining_days = int((site.event_start_date - now).days)
            notestr = "Kursların başlamasına %d gun kala tüm başvurularını iptal etti." % remaining_days
            if approvedpref:
                # Kullanicinin tercihi kursa kaç gün kala kabul görmüş
                daysbetweenapproveandevent = int((site.event_start_date - approvedpref[0].instapprovedate).days)
                notestr += "\nTercihi kursun başlamasına %d gün kala kabul edilmiş." % daysbetweenapproveandevent
        else:
            notestr = "Kullanici tercihlerini iptal etti"
        if cancelnote:
            notestr += "\nİptal Sebebi:%s" % cancelnote
        if notestr:
            note = TrainessNote(note=notestr, note_from_profile=ruser.userprofile, note_to_profile=trainess,
                                site=site, note_date=now, label="sistem")
            note.save()
        return 1
    except Exception as e:
        log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), extra=d)
        log.error(e.message, extra=d)
        return 2
Exemple #10
0
def active_resend(request):
    data = getsiteandmenus(request)
    note = _("Please activate your account.  If you want to re-send an activation email, please click following button")
    if request.POST:
        domain = data['site'].home_url
        data['domain'] = domain.rstrip('/')
        user_verification, created = UserVerification.objects.get_or_create(user=request.user)
        user_verification.activation_key = create_verification_link(request.user)
        user_verification.save()
        data['activation_key'] = user_verification.activation_key
        data['recipientlist'] = [request.user.username]
        note = send_email_by_operation_name(data, "send_activation_key")
    data['note'] = note
    return render_to_response("userprofile/activate_resend.html", data, context_instance=RequestContext(request))
Exemple #11
0
def active_resend(request):
    data = {
        "note":
        _("Please activate your account.  If you want to re-send an activation email, please click following button"
          )
    }
    if request.POST:
        domain = request.site.home_url
        data['domain'] = domain.rstrip('/')
        user_verification, created = UserVerification.objects.get_or_create(
            user=request.user)
        user_verification.activation_key = create_verification_link(
            request.user)
        user_verification.save()
        data['activation_key'] = user_verification.activation_key
        data['recipientlist'] = [request.user.username]
        data["note"] = send_email_by_operation_name(data,
                                                    "send_activation_key")
    return render(request, "userprofile/activate_resend.html", data)
def send_to_not_approved_trainess_email(functionname):
    from training.models import TrainessCourseRecord
    from abkayit.backend import send_email_by_operation_name
    from abkayit.models import Site
    import logging
    log = logging.getLogger(__name__)
    active_site = Site.objects.get(is_active=True)
    data = {'site': active_site}
    trainessrecords = TrainessCourseRecord.objects.filter(course__site=active_site, approved=False,
                                                          consentemailsent=False)
    for trainessrecord in trainessrecords:
        has_approved_pref = TrainessCourseRecord.objects.filter(trainess=trainessrecord.trainess, approved=True,
                                                                course__site=active_site)
        if not has_approved_pref:
            data["recipientlist"] = [trainessrecord.trainess.user.username]
            data["approvedpref"] = trainessrecord
            if send_email_by_operation_name(data, functionname):
                log.info(
                    "%s kullanicisina %s"
                    " maili gonderildi" % (trainessrecord.trainess.user.username, functionname),
                    extra={'clientip': '', 'user': '******'})
Exemple #13
0
def password_reset_key(request):
    data = {'note': _("Please enter your registered email")}
    if request.method == 'POST':
        email = request.POST['email']
        if email and email != "":
            try:
                user = User.objects.get(username=request.POST['email'])
                user_verification, created = UserVerification.objects.get_or_create(
                    user=user)
                user_verification.password_reset_key = create_verification_link(
                    user)
                user_verification.save()
                data['ruser'] = user
                data['activation_key'] = user_verification.password_reset_key
                domain = request.site.home_url
                data['domain'] = domain.rstrip('/')
                data['recipientlist'] = [user.username]
                data['note'] = send_email_by_operation_name(
                    data, "send_reset_password_key")
                if data['note']:
                    data[
                        'note'] = "Parola sıfırlama e-postası adresinize gönderildi."
                else:
                    data['note'] = "E-posta gönderilemedi"
            except ObjectDoesNotExist:
                data['note'] = _(
                    """There isn't any user record with this e-mail on the system"""
                )
                log.error(data['note'], extra=request.log_extra)
            except Exception as e:
                data['note'] = _("""Password reset operation failed""")
                log.error(data['note'], extra=request.log_extra)
                log.error(e.message, extra=request.log_extra)
        else:
            data['note'] = _("""Email field can not be empty""")
            log.error(data['note'], extra=request.log_extra)
    return render(request, "userprofile/change_password_key_request.html",
                  data)
Exemple #14
0
def applytrainerselections(postrequest, course, data, site, d):
    now = timezone.now()
    if UserProfileOPS.is_authorized_inst(data["user"].userprofile):
        sendconsentemail = postrequest.get("send_consent_email", False)
        try:
            data["changedprefs"] = []
            data["course"] = course
            approvedr = postrequest.getlist('students' + str(course.pk))
            sendconsentmailprefs = postrequest.getlist('consentmail' +
                                                       str(course.pk))
            for pref in data['dates']:
                if data['dates'][pref].start_date <= now <= data['dates'][
                        pref].end_date:
                    allprefs = TrainessCourseRecord.objects.filter(
                        course=course.pk, preference_order=pref)
                    for p in allprefs:
                        if not p.consentemailsent:
                            if str(p.pk) not in approvedr and p.approved:
                                p.approved = False
                                p.trainess_approved = False
                                data["changedprefs"].append(p)
                            elif str(p.pk) in approvedr and not p.approved:
                                data['approvedpref'] = p
                                trainess_approved_pref = is_trainess_approved_anothercourse(
                                    p.trainess, pref, site)
                                if trainess_approved_pref:
                                    data[
                                        'changedpref'] = trainess_approved_pref
                                    data["recipientlist"] = trainess_approved_pref.course.authorized_trainer.all() \
                                        .values_list('user__username', flat=True)
                                    send_email_by_operation_name(
                                        data, "inform_trainers_about_changes")
                                p.approved = True
                                p.instapprovedate = now
                                course.trainess.add(p.trainess)
                                course.save()
                                if not REQUIRE_TRAINESS_APPROVE:
                                    p.trainess_approved = True
                                data["changedprefs"].append(p)
                            if sendconsentemail == "on" and str(
                                    p.pk) in sendconsentmailprefs:
                                if p.preference_order == 1 and p.approved:
                                    data['approvedpref'] = p
                                    data["recipientlist"] = [
                                        p.trainess.user.username
                                    ]
                                    res = send_email_by_operation_name(
                                        data, "send_consent_email")
                                    if res == 1:
                                        p.consentemailsent = True
                            p.save()
            note = "Seçimleriniz başarılı bir şekilde kaydedildi."
            if data["changedprefs"]:
                data["recipientlist"] = data['course'].authorized_trainer.all(
                ).values_list('user__username', flat=True)
                send_email_by_operation_name(data, "inform_about_changes")
        except Exception as e:
            note = "Beklenmedik bir hata oluştu!"
            log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno),
                      extra=d)
            log.error(e.message, extra=d)
    else:
        note = "Bu işlemi yapmaya yetkiniz yok!"
    return note
Exemple #15
0
def save_course_prefferences(userprofile,
                             course_prefs,
                             site,
                             d,
                             answersforcourse=None):
    res = {'status': '-1', 'message': 'error'}
    if len(course_prefs) <= PREFERENCE_LIMIT:
        context = {}
        oldprefs = TrainessCourseRecord.objects.filter(course__site=site,
                                                       trainess=userprofile)

        context['oldprefs'] = {}
        is_changed = False
        if oldprefs:
            for oldpref in oldprefs:
                context['oldprefs'][oldpref.preference_order] = {
                    'course_id': oldpref.course.pk,
                    'course_no': oldpref.course.no,
                    'course_name': oldpref.course.name
                }
            oldprefs.delete()
        else:
            is_changed = True
        try:
            course_records = []
            for i in range(1, len(course_prefs) + 1):
                if context['oldprefs']:
                    if len(context['oldprefs']) != len(
                            course_prefs) or context['oldprefs'][i].get(
                                'course_id') != int(course_prefs[str(i)]):
                        is_changed = True
                course = Course.objects.get(id=int(course_prefs[str(i)]))
                course_record = TrainessCourseRecord(
                    trainess=userprofile,
                    course=course,
                    preference_order=i,
                )
                course_record.save()
                course_records.append(course_record)
                if answersforcourse:
                    answers = answersforcourse.get(course_prefs[str(i)])
                    if answers:
                        tta = TrainessTestAnswers(tcourserecord=course_record)
                        tta.save()
                        tta.answer.add(*answers)
                        tta.save()
            res['status'] = 0
            res['message'] = "Tercihleriniz başarılı bir şekilde güncellendi"
            context['user'] = userprofile.user
            context['course_prefs'] = course_records
            domain = site.home_url
            context['domain'] = domain.rstrip('/')
            try:
                if is_changed:
                    if SEND_REPORT:
                        context['recipientlist'] = REPORT_RECIPIENT_LIST
                        send_email_by_operation_name(
                            context, "notice_for_pref_changes")
                    context['recipientlist'] = [userprofile.user.username]
                    send_email_by_operation_name(context, "preference_saved")
            except Exception as e:
                log.error('Error on line {}'.format(
                    sys.exc_info()[-1].tb_lineno),
                          extra=d)
                log.error(e.message, extra=d)
                log.error("rapor e-postası gönderilemedi", extra=d)
        except Exception as e:
            log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno),
                      extra=d)
            log.error(e.message, extra=d)
            res['message'] = "Tercihleriniz kaydedilirken hata oluştu"
    else:
        res['message'] = "En fazla " + PREFERENCE_LIMIT + " tane tercih hakkına sahipsiniz"
    return res
Exemple #16
0
def save_course_prefferences(userprofile, course_prefs, site, d, answersforcourse=None):
    res = {'status': '-1', 'message': 'error'}
    if len(course_prefs) <= PREFERENCE_LIMIT:
        context = {}
        oldprefs = TrainessCourseRecord.objects.filter(course__site__is_active=True, trainess=userprofile)

        context['oldprefs'] = {}
        is_changed = False
        if oldprefs:
            for oldpref in oldprefs:
                context['oldprefs'][oldpref.preference_order] = {
                    'course_id': oldpref.course.pk,
                    'course_no': oldpref.course.no,
                    'course_name': oldpref.course.name}
            oldprefs.delete()
        else:
            is_changed = True
        try:
            course_records = []
            for i in range(1, len(course_prefs) + 1):
                if context['oldprefs']:
                    if len(context['oldprefs']) != len(course_prefs) or context['oldprefs'][i].get('course_id') != int(
                            course_prefs[str(i)]):
                        is_changed = True
                course = Course.objects.get(id=int(course_prefs[str(i)]))
                course_record = TrainessCourseRecord(trainess=userprofile,
                                                     course=course,
                                                     preference_order=i,
                                                     )
                course_record.save()
                course_records.append(course_record)
                if answersforcourse:
                    answers = answersforcourse.get(course_prefs[str(i)])
                    if answers:
                        tta = TrainessTestAnswers(tcourserecord=course_record)
                        tta.save()
                        tta.answer.add(*answers)
                        tta.save()
            res['status'] = 0
            res['message'] = "Tercihleriniz başarılı bir şekilde güncellendi"
            context['user'] = userprofile.user
            context['course_prefs'] = course_records
            context['site'] = site
            domain = site.home_url
            context['domain'] = domain.rstrip('/')
            try:
                if is_changed:
                    if SEND_REPORT:
                        context['recipientlist'] = REPORT_RECIPIENT_LIST
                        send_email_by_operation_name(context, "notice_for_pref_changes")
                    context['recipientlist'] = [userprofile.user.username]
                    send_email_by_operation_name(context, "preference_saved")
            except Exception as e:
                log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), extra=d)
                log.error(e.message, extra=d)
                log.error("rapor e-postası gönderilemedi", extra=d)
        except Exception as e:
            log.error('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), extra=d)
            log.error(e.message, extra=d)
            res['message'] = "Tercihleriniz kaydedilirken hata oluştu"
    else:
        res['message'] = "En fazla " + PREFERENCE_LIMIT + " tane tercih hakkına sahipsiniz"
    return res