Exemple #1
0
def submitandregister(request):
    d = {"clientip": request.META["REMOTE_ADDR"], "user": request.user}
    data = prepare_template_data(request)
    userops = UserProfileOPS()
    # TODO:site ve pages'e bi care bulmak lazim
    site = Site.objects.get(is_active=True)
    pages = Menu.objects.filter(site=site.pk).order_by("order")
    note = "Kurs onerisi olustur:"
    try:
        curuserprof = UserProfile.objects.get(user=request.user)
    except:
        log.info("%s kullanici profili bulunamadi" % (request.user), extra=d)
    curinstprofform = InstProfileForm(prefix="cur")
    forms = {}
    for x in xrange(4):
        forms[x] = [CreateInstForm(prefix=str(x) + "inst"), InstProfileForm(prefix=str(x) + "instprof")]
    form = CreateCourseForm()
    if "submit" in request.POST:
        allf = []
        forms = {}
        for x in xrange(4):
            if str(x) + "inst-email" in request.POST:
                forms[x] = [
                    CreateInstForm(request.POST, prefix=str(x) + "inst"),
                    InstProfileForm(request.POST, prefix=str(x) + "instprof"),
                ]
                allf.append(forms[x][0].is_valid())
                allf.append(forms[x][1].is_valid())
            else:
                pass
        curinstprofform = InstProfileForm(request.POST, prefix="cur")
        form = CreateCourseForm(request.POST)
        if all([curinstprofform.is_valid(), form.is_valid()]) and all(allf):
            curinst = curinstprofform.save(commit=False)
            curinst.user = request.user
            curinst.save()
            course = form.save(commit=False)
            if "fulltext" in request.FILES:
                course.fulltext = request.FILES["fulltext"]
            course.save()
            for key, f in forms.items():
                instx = f[0].save(commit=False)
                passwd = userops.generatenewpass(8)
                instx.set_password(passwd)
                instx.save()
                instxprof = f[1].save(commit=False)
                instxprof.user = instx
                instxprof.save()
                course.trainer.add(instxprof)
            course.trainer.add(curinst)
            course.save()
            note = "Egitim oneriniz basari ile alindi."
        else:
            note = "Olusturulamadi"
    return render_to_response(
        "training/submitandregister.html",
        {"site": site, "pages": pages, "note": note, "form": form, "curinstprofform": curinstprofform, "forms": forms},
        context_instance=RequestContext(request),
    )
Exemple #2
0
def submitandregister(request):
    """
    Bu view'ı kullanmıyoruz. Egitmen ve egitim başvurularını sistemden aldığımızda kullanılabilir.
    :param request:
    :return:
    """
    userops = UserProfileOPS()
    data = {'note': "Kurs onerisi olustur:"}
    curinstprofform = InstProfileForm(prefix="cur")
    forms = {}
    for x in xrange(4):
        forms[x] = [
            CreateInstForm(prefix=str(x) + "inst"),
            InstProfileForm(prefix=str(x) + "instprof")
        ]
    form = CreateCourseForm()
    if "submit" in request.POST:
        allf = []
        forms = {}
        for x in xrange(4):
            if str(x) + "inst-email" in request.POST:
                forms[x] = [
                    CreateInstForm(request.POST, prefix=str(x) + "inst"),
                    InstProfileForm(request.POST, prefix=str(x) + "instprof")
                ]
                allf.append(forms[x][0].is_valid())
                allf.append(forms[x][1].is_valid())
            else:
                pass
        curinstprofform = InstProfileForm(request.POST, prefix="cur")
        form = CreateCourseForm(request.POST)
        if all([curinstprofform.is_valid(), form.is_valid()]) and all(allf):
            curinst = curinstprofform.save(commit=False)
            curinst.user = request.user
            curinst.save()
            course = form.save(commit=False)
            if 'fulltext' in request.FILES:
                course.fulltext = request.FILES['fulltext']
            course.save()
            for key, f in forms.items():
                instx = f[0].save(commit=False)
                passwd = userops.generatenewpass(8)
                instx.set_password(passwd)
                instx.save()
                instxprof = f[1].save(commit=False)
                instxprof.user = instx
                instxprof.save()
                course.trainer.add(instxprof)
            course.trainer.add(curinst)
            course.save()
            data['note'] = "Egitim oneriniz basari ile alindi."
        else:
            data['note'] = "Olusturulamadi"
    data['note'] = note
    data['form'] = form
    data['curinstprofform'] = curinstprofform
    data['forms'] = forms
    return render(request, "training/submitandregister.html", data)
Exemple #3
0
def submitandregister(request):
    """
    Bu view'ı kullanmıyoruz. Egitmen ve egitim başvurularını sistemden aldığımızda kullanılabilir.
    :param request:
    :return:
    """
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    userops = UserProfileOPS()
    data = getsiteandmenus(request)
    note = "Kurs onerisi olustur:"
    curinstprofform = InstProfileForm(prefix="cur")
    forms = {}
    for x in xrange(4):
        forms[x] = [CreateInstForm(prefix=str(x) + "inst"), InstProfileForm(prefix=str(x) + "instprof")]
    form = CreateCourseForm()
    if "submit" in request.POST:
        allf = []
        forms = {}
        for x in xrange(4):
            if str(x) + "inst-email" in request.POST:
                forms[x] = [CreateInstForm(request.POST, prefix=str(x) + "inst"),
                            InstProfileForm(request.POST, prefix=str(x) + "instprof")]
                allf.append(forms[x][0].is_valid())
                allf.append(forms[x][1].is_valid())
            else:
                pass
        curinstprofform = InstProfileForm(request.POST, prefix="cur")
        form = CreateCourseForm(request.POST)
        if all([curinstprofform.is_valid(), form.is_valid()]) and all(allf):
            curinst = curinstprofform.save(commit=False)
            curinst.user = request.user
            curinst.save()
            course = form.save(commit=False)
            if 'fulltext' in request.FILES:
                course.fulltext = request.FILES['fulltext']
            course.save()
            for key, f in forms.items():
                instx = f[0].save(commit=False)
                passwd = userops.generatenewpass(8)
                instx.set_password(passwd)
                instx.save()
                instxprof = f[1].save(commit=False)
                instxprof.user = instx
                instxprof.save()
                course.trainer.add(instxprof)
            course.trainer.add(curinst)
            course.save()
            note = "Egitim oneriniz basari ile alindi."
        else:
            note = "Olusturulamadi"
    data['note'] = note
    data['form'] = form
    data['curinstprofform'] = curinstprofform
    data['forms'] = forms
    return render_to_response("training/submitandregister.html",
                              data,
                              context_instance=RequestContext(request))
	def createInst(self,postrequest,numofinst):
		insts=[]
		uprof=UserProfileOPS()
		for i in xrange(numofinst):
			n_str=str(i)+'-'
			upass=uprof.generatenewpass() # uretilen parola olusturulan kullaniciya gonderilecek.
			inst=User(first_name=postrequest[n_str+'first_name'],last_name=postrequest[n_str+'last_name'],
						email=postrequest[n_str+'email'],username=postrequest[n_str+'email'],password=upass)
			inst.save()
			instprof=UserProfile(job=postrequest[n_str+'job'],title=postrequest[n_str+'title'],
                        organization=postrequest[n_str+'organization'],is_instructor=True,
						user=inst)
			instprof.save()
			insts.append(instprof)
		return insts
Exemple #5
0
def getconsentmailfield(tcr, user):
    consentemailsentt = TrainessCourseRecord.objects.filter(
        trainess=tcr.trainess,
        course__site__is_active=True,
        consentemailsent=True).first()
    if tcr.consentemailsent:
        return "Gönderildi"
    elif consentemailsentt and consentemailsentt != tcr:
        return "%s. tercihi icin gonderildi" % str(
            consentemailsentt.preference_order)
    elif not tcr.consentemailsent and tcr.preference_order == 1 and UserProfileOPS.is_authorized_inst(
            user.userprofile, course=tcr.course):
        now = datetime.date(datetime.now())
        approvaldates = ApprovalDate.objects.filter(
            site=tcr.course.site).order_by("start_date")
        if approvaldates:
            if tcr.course.site.event_start_date > now and approvaldates[
                    0].start_date <= datetime.now(
                    ) <= approvaldates[0].end_date:
                dom = "<div>"
                dom += "<input type=\"checkbox\" name=\"consentmail%s\" value=\"%s\"/>" % (
                    tcr.course.pk, tcr.pk)
                dom += "</div>"
                return dom
        return "Gonderilmedi"
    else:
        return "Gönderilmedi"
Exemple #6
0
def control_panel(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    note = _("You can accept trainees")
    now = timezone.now()
    data["user"] = request.user
    try:
        if UserProfileOPS.is_instructor(request.user.userprofile):
            courses = Course.objects.filter(site=data['site'], approved=True, trainer__user=request.user)
            if courses:
                log.info("egitmenin " + str(len(courses)) + " tane kursu var", extra=d)
                data['now'] = now
                data['dates'] = get_approve_start_end_dates_for_inst(data['site'], d)
                data['trainess'] = {}
                if data['dates']:
                    for course in courses:
                        if now <= data['dates'].get(1).end_date:
                            data['trainess'][course] = get_trainess_by_course(course, d)
                        else:
                            note = _("Consent period is closed")
                            data['trainess'][course] = get_approved_trainess(course, d)
                if "send" in request.POST:
                    log.info("kursiyer onay islemi basladi", extra=d)
                    log.info(request.POST, extra=d)
                    note = applytrainerselections(request.POST, courses, data, d)
            data['note'] = note
            return render_to_response("training/controlpanel.html", data, context_instance=RequestContext(request))
        elif not request.user.is_staff:
            return redirect("applytocourse")
        return redirect("statistic")
    except UserProfile.DoesNotExist:
        return redirect("createprofile")
def isdategtnow_body(context, datedict, key, t, course, user):
    now = datetime.now()
    adate = datedict.get(key)
    if adate:
        if adate.end_date >= now >= adate.start_date and UserProfileOPS.is_authorized_inst(
                user.userprofile) and not t.consentemailsent:
            approvedprefs = TrainessCourseRecord.objects.filter(
                trainess=t.trainess,
                course__site=context['request'].site,
                approved=True)
            is_selectable = True
            priviliged_pref = None
            for approvedpref in approvedprefs:
                if t.preference_order > approvedpref.preference_order:
                    is_selectable = False
                    priviliged_pref = approvedpref
            if is_selectable:
                dom = "<div>"
                if t.approved:
                    dom += "<input type=\"checkbox\" checked name=\"students%s\" value=\"%s\"/>" % (
                        course.id, t.pk)
                else:
                    dom += "<input type=\"checkbox\" name=\"students%s\" value=\"%s\"/>" % (
                        course.id, t.pk)
                dom += "</div>"
                return dom
            else:
                return "%d. tercihi kabul edilmis." % priviliged_pref.preference_order
    if (t.trainess_approved and REQUIRE_TRAINESS_APPROVE) or (
            t.approved and not REQUIRE_TRAINESS_APPROVE):
        return "Evet"
    else:
        return "Hayir"
Exemple #8
0
 def clean(self):
     cleaned_data = super(StuProfileForm, self).clean()
     ruser = self.ruser
     if ruser:
         first_name = ruser.first_name.rstrip().lstrip()
         last_name = ruser.last_name.rstrip().lstrip()
         birthdate = cleaned_data.get('birthdate')
         byear = ""
         if birthdate:
             byear = birthdate.year
         if cleaned_data['tckimlikno'] and cleaned_data['ykimlikno']:
             raise forms.ValidationError(_("Please fill only one of them:tckimlikno,ykimlikno"))
         elif not cleaned_data['tckimlikno'] and cleaned_data['country'] == 'TR':
             raise forms.ValidationError(_("TC identity number can not be empty for Turkish citizens"))
         elif not cleaned_data.get('ykimlikno') and cleaned_data['country'] != 'TR':
             raise forms.ValidationError(_("Foreign identity number can not be empty for non Turkish citizens"))
         elif cleaned_data['tckimlikno'] and cleaned_data['country'] == 'TR':
             tcknosorgu = UserProfile.objects.filter(tckimlikno=cleaned_data['tckimlikno'])
             if tcknosorgu:
                 if tcknosorgu[0].user.username != ruser.username:
                     raise forms.ValidationError(_("Bu TC Kimlik numarasına sahip başka hesap var."))
             tckisvalid = UserProfileOPS.validateTCKimlikNo(cleaned_data['tckimlikno'].rstrip().lstrip(), first_name,
                                                            last_name, byear)
             if tckisvalid == -1:
                 raise forms.ValidationError(_("An error occured while verifing your TC identity number"))
             elif not tckisvalid:
                 raise forms.ValidationError(_(("Your identity information can not be verified, Please enter"
                                                "your TC identity number, your name, your last name (with Turkish"
                                                "characters if exist) and your birth date precisely")))
     else:
         raise forms.ValidationError(_("User not found"))
     return cleaned_data
Exemple #9
0
 def clean(self):
     cleaned_data = super(StuProfileForm, self).clean()
     ruser = self.ruser
     if ruser:
         first_name = ruser.first_name.rstrip().lstrip()
         last_name = ruser.last_name.rstrip().lstrip()
         byear = cleaned_data["birthdate"].year
         if cleaned_data["tckimlikno"] and cleaned_data["ykimlikno"]:
             raise forms.ValidationError(_("Please fill only one of them:tckimlikno,ykimlikno"))
         elif not cleaned_data["tckimlikno"] and cleaned_data["country"] == "TR":
             raise forms.ValidationError(_("TC identifier no can not be empty for Turkish citizens"))
         elif not cleaned_data["ykimlikno"] and cleaned_data["country"] != "TR":
             raise forms.ValidationError(_("Foreigner identifier no can not be blank for non Turkish citizens"))
         elif cleaned_data["tckimlikno"] and cleaned_data["country"] == "TR":
             tckisvalid = UserProfileOPS.validateTCKimlikNo(
                 cleaned_data["tckimlikno"].rstrip().lstrip(), first_name, last_name, byear
             )
             if tckisvalid == -1:
                 raise forms.ValidationError(_("Error occured during verify your TC identifier no"))
             elif not tckisvalid:
                 raise forms.ValidationError(
                     _(
                         "Your identification informations couldn't be verified, Please enter \
                                                  your TC identifier no, your name, your last name (with Turkish character) \
                                                  and your bird date completely"
                     )
                 )
     else:
         raise forms.ValidationError(_("User not found"))
     return cleaned_data
Exemple #10
0
def addtrainess(request):
    data = {}
    now = datetime.date(datetime.now())
    if UserProfileOPS.is_authorized_inst(
            request.user.userprofile) and request.site.event_start_date > now > request.site.application_end_date:
        data['form'] = AddTrainessForm(request=request)
        data['note'] = "Kursunuza eklemek istediğiniz katilimciyi seçin (E-posta adresine göre)"
        if "add" in request.POST:
            data['form'] = AddTrainessForm(request.POST, request=request)
            if data['form'].is_valid():
                tcourserecord = data['form'].save(commit=False)
                tcourserecord.preference_order = 1
                tcourserecord.trainess_approved = True
                tcourserecord.approved = True
                tcourserecord.save()
                notestr = "Bu kullanicinin %s kursu tercihi eğitmen tarafından eklendi." % tcourserecord.course.name
                tnote = TrainessNote(note=notestr, note_from_profile=request.user.userprofile,
                                     note_to_profile=tcourserecord.trainess,
                                     site=tcourserecord.course.site, note_date=timezone.now(), label="tercih")
                tnote.save()
                data['note'] = "Form kaydedildi. Eklediğiniz katılımcıları 1. tercih listesinde görüntüleyebilirsiniz."
                log.info("%s kullanicisi %s kullanicisini %s kursuna ekledi." % (
                    request.user.username, tcourserecord.trainess.user.username, tcourserecord.course.name),
                         extra=request.log_extra)
            else:
                data['note'] = "Form aşağıdaki sebeplerden dolayı kaydedilemedi."
        elif "cancel" in request.POST:
            return redirect("selectcoursefcp")
        return render(request, 'training/addtrainess.html', data)
    else:
        return redirect("selectcoursefcp")
def getoperationsmenu(uprofile):
    html = ""

    if UserProfileOPS.is_instructor(uprofile):
        html += """
        <li>
            <a href="/survey/answers/"><i class="fa fa-file-text-o fa-fw"></i> Anket Sonuçları</a>
        </li>
        <li>
        <a href="/egitim/selectcourse/"><i class="fa fa-book fa-fw"></i> Kurslarım </a>
        </li>
        <li>
            <a href="/egitim/katilimciekle"><i class="fa fa-book fa-fw"></i> Kursiyer Ekle</a>
        </li>
        """
    else:
        html += """
        <li>
            <a href="/egitim/applytocourse"><i class="fa fa-check-square-o fa-fw"></i> Kurs Başvurusu</a>
        </li>
        <li>
            <a href="/egitim/approve_course_preference"><i class="fa fa-thumbs-o-up fa-fw"></i> Başvuru Durum/Onayla</a>
        </li>
        """

    return html
Exemple #12
0
def select_course_for_control_panel(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    note = "İşlem Yapmak İstediğiniz Kursu Seçiniz"
    data["user"] = request.user
    try:
        if UserProfileOPS.is_instructor(request.user.userprofile):
            courses = Course.objects.filter(site=data['site'],
                                            approved=True,
                                            trainer__user=request.user)
            if courses:
                log.info("egitmenin " + str(len(courses)) + " tane kursu var",
                         extra=d)
                data['courses'] = courses
            else:
                note = "Bu etkinlikte kursunuz yok."
            data['note'] = note
            return render_to_response("training/courselistforinst.html",
                                      data,
                                      context_instance=RequestContext(request))
        elif not request.user.is_staff:
            return redirect("applytocourse")
        return redirect("statistic")
    except UserProfile.DoesNotExist:
        return redirect("createprofile")
Exemple #13
0
def addtrainess(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    now = datetime.date(datetime.now())
    if UserProfileOPS.is_authorized_inst(request.user.userprofile) and data['site'].event_start_date > now > data[
        'site'].application_end_date:
        data['form'] = AddTrainessForm(ruser=request.user)
        data['note'] = "Kursunuza eklemek istediğiniz katilimciyi seçin (E-posta adresine göre)"
        if "add" in request.POST:
            data['form'] = AddTrainessForm(request.POST, ruser=request.user)
            if data['form'].is_valid():
                tcourserecord = data['form'].save(commit=False)
                tcourserecord.preference_order = 1
                tcourserecord.trainess_approved = True
                tcourserecord.approved = True
                tcourserecord.save()
                notestr = "Bu kullanicinin %s kursu tercihi eğitmen tarafından eklendi." % tcourserecord.course.name
                note = TrainessNote(note=notestr, note_from_profile=request.user.userprofile,
                                    note_to_profile=tcourserecord.trainess,
                                    site=tcourserecord.course.site, note_date=timezone.now(), label="tercih")
                note.save()
                data['note'] = "Form kaydedildi. Eklediğiniz katılımcıları 1. tercih listesinde görüntüleyebilirsiniz."
                log.info("%s kullanicisi %s kullanicisini %s kursuna ekledi." % (
                    request.user.username, tcourserecord.trainess.user.username, tcourserecord.course.name), extra=d)
            else:
                data['note'] = "Form aşağıdaki sebeplerden dolayı kaydedilemedi."
        elif "cancel" in request.POST:
            return redirect("controlpanel")
        return render_to_response('training/addtrainess.html', data, context_instance=RequestContext(request))
    else:
        return redirect("controlpanel")
def isdategtnow_body(datedict, key, t, course, user):
    now = datetime.now()
    adate = datedict.get(key)
    if adate:
        if adate.end_date >= now >= adate.start_date and UserProfileOPS.is_authorized_inst(
                user.userprofile) and not t.consentemailsent:
            approvedprefs = TrainessCourseRecord.objects.filter(trainess=t.trainess, course__site__is_active=True, approved=True)
            is_selectable = True
            priviliged_pref = None
            for approvedpref in approvedprefs:
                if t.preference_order > approvedpref.preference_order:
                    is_selectable = False
                    priviliged_pref = approvedpref
            if is_selectable:
                dom = "<div>"
                if t.approved:
                    dom += "<input type=\"checkbox\" checked name=\"students%s\" value=\"%s\"/>" % (course.id, t.pk)
                else:
                    dom += "<input type=\"checkbox\" name=\"students%s\" value=\"%s\"/>" % (course.id, t.pk)
                dom += "</div>"
                return dom
            else:
                return "%d. tercihi kabul edilmis." % priviliged_pref.preference_order
    if (t.trainess_approved and REQUIRE_TRAINESS_APPROVE) or (t.approved and not REQUIRE_TRAINESS_APPROVE):
        return "Evet"
    else:
        return "Hayir"
Exemple #15
0
def showuserprofile(request, userid, courserecordid):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    if UserProfileOPS.is_instructor(request.user.userprofile) or request.user.is_staff:
        courserecord = None
        try:
            courserecord = TrainessCourseRecord.objects.get(pk=courserecordid,
                                                            trainess=UserProfile.objects.get(pk=userid))
            if not request.user.is_staff and request.user.userprofile not in courserecord.course.trainer.all() and \
                            request.user.userprofile not in courserecord.course.authorized_trainer.all():
                return redirect("controlpanel")
        except Exception as e:
            log.warning(e.message, extra=d)
            log.warning("Staff user show user profile", extra=d)
            if not request.user.is_staff:
                return redirect("controlpanel")
        user = UserProfile.objects.get(pk=userid)
        if user:
            data['note'] = "Detaylı kullanıcı bilgileri"
            data['tuser'] = user
            data['ruser'] = request.user
            if request.user.is_staff and "cancelall" in request.POST:
                cancelnote = request.POST.get('trainesscancelnotetext', '')
                res = cancel_all_prefs(user, cancelnote, data['site'], request.user, d)
                if res == 1:
                    data['note'] = "Kullanıcının Tüm Başvuruları Silindi"
                else:
                    data['note'] = "Kullanıcının Başvuruları silinirken hata oluştu"
            if courserecord:
                data['courseid'] = courserecord.course.pk
                if request.user.is_staff and courserecord.consentemailsent:
                    try:
                        data['forms'] = getparticipationforms(data['site'], courserecord)
                        if request.POST:
                            formsarevalid = []
                            frms = []
                            for f in data['forms']:
                                frm = ParticipationForm(request.POST,
                                                        prefix="participation" + str(
                                                            datetime.strptime(f.initial['day'], '%Y-%m-%d').day))
                                frm.courserecord = courserecord.pk
                                frm.day = f.initial['day']
                                formsarevalid.append(frm.is_valid())
                                frms.append(frm)
                            if all(formsarevalid):
                                for f in frms:
                                    f.save()
                                data['note'] = 'Seçimleriniz başarıyla kaydedildi.'
                                log.info("%s nolu kurs kaydinin yoklama kaydi girişi başarılı" % courserecord.pk, extra=d)
                            else:
                                data['note'] = 'Hata oluştu!'
                                log.info("%s nolu kurs kaydinin yoklama kaydi girişi hatalı" % courserecord.pk, extra=d)
                    except Exception as e:
                        log.error(e.message, extra=d)
        else:
            data['note'] = "Böyle Bir kullanıcı yoktur."
        return render_to_response("userprofile/showuserprofile.html", data, context_instance=RequestContext(request))
    return redirect("controlpanel")
def getconsentmailfield(tcr, user):
    if tcr.consentemailsent:
        return "Gönderildi"
    elif not tcr.consentemailsent and tcr.preference_order == 1 and UserProfileOPS.is_authorized_inst(user.userprofile):
        dom = "<div>"
        dom += "<input type=\"checkbox\" name=\"consentmail%s\" value=\"%s\"/>" % (tcr.course.pk, tcr.pk)
        dom += "</div>"
        return dom
    else:
        return "Gönderilmedi"
Exemple #17
0
def getconsentmailfield(tcr, user):
    if tcr.consentemailsent:
        return "Gönderildi"
    elif not tcr.consentemailsent and tcr.preference_order == 1 and UserProfileOPS.is_authorized_inst(user.userprofile):
        dom = "<div>"
        dom += "<input type=\"checkbox\" name=\"consentmail%s\" value=\"%s\"/>" % (tcr.course.pk, tcr.pk)
        dom += "</div>"
        return dom
    else:
        return "Gönderilmedi"
Exemple #18
0
def control_panel(request, courseid):
    data = {'note': _("You can accept trainees")}
    now = timezone.now()
    try:
        course = Course.objects.get(pk=courseid)
        data['now'] = now
        data['user'] = request.user
        data['dates'] = get_approve_start_end_dates_for_inst(
            request.site, request.log_extra)
        data['trainess'] = {}
        data['notesavedsuccessful'] = False
        if data['dates']:
            if now <= data['dates'].get(1).end_date:
                data['trainess'][course] = get_trainess_by_course(
                    course, request.log_extra)
            else:
                data['note'] = _("Consent period is closed")
                data['trainess'][course] = get_approved_trainess(
                    course, request.log_extra)
        if request.user.userprofile in course.authorized_trainer.all():
            log.info("Kullanıcı %s kursunda degisiklik yapiyor" % course.name,
                     extra=request.log_extra)
            if "send" in request.POST:
                log.info("kursiyer onay islemi basladi",
                         extra=request.log_extra)
                log.info(request.POST, extra=request.log_extra)
                data['note'] = applytrainerselections(request.POST, course,
                                                      data, request.site,
                                                      request.log_extra)
            return render(request, "training/controlpanel.html", data)
        elif request.user.userprofile in course.trainer.all():
            data['note'] = "Kursiyerler için not ekleyebilirsiniz."
            if "savescore" in request.POST:
                trainessnote = request.POST.get('trainessnotetext')
                trainessusername = request.POST.get('trainessnoteuser')
                user = User.objects.get(username=trainessusername)
                data['note'] = UserProfileOPS.savenote(request, user,
                                                       trainessnote)
                potentialinst = request.POST.get('potential-%s' % user.pk)
                uprobysite, created = UserProfileBySite.objects.get_or_create(
                    user=user, site=request.site)
                if potentialinst == 'on':
                    uprobysite.potentialinstructor = True
                else:
                    uprobysite.potentialinstructor = False
                uprobysite.save()
                data['savednoteuserid'] = user.userprofile.pk
                data['notesavedsuccessful'] = True
            return render(request, "training/controlpanelforunauthinst.html",
                          data)
        elif not request.user.is_staff:
            return redirect("applytocourse")
        return redirect("statistic")
    except UserProfile.DoesNotExist:
        return redirect("createprofile")
Exemple #19
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 #20
0
def getinstinfo(uprofile, site):
    html = ""
    if UserProfileOPS.is_instructor(uprofile):
        try:
            inst_info = InstructorInformation.objects.get(user=uprofile, site=site)
            html = "<td>%s</td><td>%s</td><td>%s</td><td>%s</td>" % (
                inst_info.transportation, inst_info.arrival_date, inst_info.departure_date,
                inst_info.additional_information)
        except Exception as e:
            return "<td></td><td></td><td></td><td></td>"
    return html
Exemple #21
0
 def createInst(self, postrequest, numofinst):
     insts = []
     uprof = UserProfileOPS()
     for i in xrange(numofinst):
         n_str = str(i) + '-'
         upass = uprof.generatenewpass(
         )  # uretilen parola olusturulan kullaniciya gonderilecek.
         inst = User(first_name=postrequest[n_str + 'first_name'],
                     last_name=postrequest[n_str + 'last_name'],
                     email=postrequest[n_str + 'email'],
                     username=postrequest[n_str + 'email'],
                     password=upass)
         inst.save()
         instprof = UserProfile(job=postrequest[n_str + 'job'],
                                title=postrequest[n_str + 'title'],
                                organization=postrequest[n_str +
                                                         'organization'],
                                is_instructor=True,
                                user=inst)
         instprof.save()
         insts.append(instprof)
     return insts
Exemple #22
0
def instructor_information_view(request):
    if not request.user.userprofile:
        log.error("Kullanıcı Profili Bulunamadı", extra=request.log_extra)
        return redirect("createprofile")
    data = {}
    if not UserProfileOPS.is_instructor(request.user.userprofile):
        data['note'] = _("You are not authorized to access here")
    else:
        data['note'] = _(
            "Please enter your transformation, arrival date, departure date information"
        )
        try:
            instructorinformation = InstructorInformation.objects.get(
                user=request.user.userprofile, site=request.site)
            form = InstructorInformationForm(instance=instructorinformation,
                                             site=request.site,
                                             request=request)

        except ObjectDoesNotExist as e:
            log.debug(
                "Egitmen bilgileri bulunamadi, yeni bilgiler olusturulmak icin form acilacak",
                extra=request.log_extra)
            log.error(e.message, extra=request.log_extra)
            form = InstructorInformationForm(site=request.site,
                                             request=request)
            instructorinformation = None

        if request.POST:
            if instructorinformation is not None:
                form = InstructorInformationForm(
                    request.POST,
                    instance=instructorinformation,
                    site=request.site,
                    request=request)
            else:
                form = InstructorInformationForm(request.POST,
                                                 site=request.site,
                                                 request=request)
            if form.is_valid():
                try:
                    instructor_info = form.save(commit=True)
                    data['note'] = _("Your information saved successfully")
                    log.info("%s egitmeni ek bilgilerini guncelledi" %
                             instructor_info.user.user.username,
                             extra=request.log_extra)
                except Exception as e:
                    data['note'] = _(
                        "An error occurred while saving your information")
                    log.error(e.message, extra=request.log_extra)
        data['form'] = form
    return render(request, "userprofile/instructor_information.html", data)
Exemple #23
0
def select_course_for_control_panel(request):
    data = {'note': "İşlem Yapmak İstediğiniz Kursu Seçiniz", 'user': request.user}
    try:
        if UserProfileOPS.is_instructor(request.user.userprofile):
            courses = Course.objects.filter(site=request.site, approved=True, trainer__user=request.user)
            if courses:
                log.info("egitmenin " + str(len(courses)) + " tane kursu var", extra=request.log_extra)
                data['courses'] = courses
            else:
                data['note'] = "Bu etkinlikte kursunuz yok."
            return render(request, "training/courselistforinst.html", data)
        elif not request.user.is_staff:
            return redirect("applytocourse")
        return redirect("statistic")
    except UserProfile.DoesNotExist:
        return redirect("createprofile")
Exemple #24
0
 def clean(self):
     cleaned_data = super(StuProfileForm, self).clean()
     ruser = self.ruser
     if ruser:
         first_name = ruser.first_name.rstrip().lstrip()
         last_name = ruser.last_name.rstrip().lstrip()
         birthdate = cleaned_data.get('birthdate')
         byear = ""
         if birthdate:
             byear = birthdate.year
         if cleaned_data['tckimlikno'] and cleaned_data['ykimlikno']:
             raise forms.ValidationError(
                 _("Please fill only one of them:tckimlikno,ykimlikno"))
         elif not cleaned_data['tckimlikno'] and cleaned_data[
                 'country'] == 'TR':
             raise forms.ValidationError(
                 _("TC identity number can not be empty for Turkish citizens"
                   ))
         elif not cleaned_data.get(
                 'ykimlikno') and cleaned_data['country'] != 'TR':
             raise forms.ValidationError(
                 _("Foreign identity number can not be empty for non Turkish citizens"
                   ))
         elif cleaned_data['tckimlikno'] and cleaned_data['country'] == 'TR':
             tcknosorgu = UserProfile.objects.filter(
                 tckimlikno=cleaned_data['tckimlikno'])
             if tcknosorgu:
                 if tcknosorgu[0].user.username != ruser.username:
                     raise forms.ValidationError(
                         _("Bu TC Kimlik numarasına sahip başka hesap var.")
                     )
             tckisvalid = UserProfileOPS.validateTCKimlikNo(
                 cleaned_data['tckimlikno'].rstrip().lstrip(), first_name,
                 last_name, byear)
             if tckisvalid == -1:
                 raise forms.ValidationError(
                     _("An error occured while verifing your TC identity number"
                       ))
             elif not tckisvalid:
                 raise forms.ValidationError(
                     _(("Your identity information can not be verified, Please enter"
                        "your TC identity number, your name, your last name (with Turkish"
                        "characters if exist) and your birth date precisely"
                        )))
     else:
         raise forms.ValidationError(_("User not found"))
     return cleaned_data
Exemple #25
0
def authorizedforelection(site, user):
    now = datetime.date(datetime.now())
    approvaldates = ApprovalDate.objects.filter(site__is_active=True).order_by("start_date")
    if approvaldates:
        if site.event_start_date > now and datetime.now() >= approvaldates[0].start_date and \
                UserProfileOPS.is_authorized_inst(user.userprofile):
            return """
            <div class="alert alert-danger">
                Uyarı: <p>* Onay tarihleri içerisinde kabul e-postaları onayladığınız 1. tercihi kursunuz olan katılımcılara gönderilir.</p>
                       <p>* Kabul e-postası gönderilen kullanıcıların onayını kaldıramazsınız!</p>
                       <p>* Onaylanan diğer (1. tercihi kursunuz olmayan) katılımcıların kabul e-postaları onay tarihi bitiminde gönderilir.</p>
                       <p>* El ile eklediğiniz katılımcıları 1. tercih listesinde görüntüleyebilirsiniz.</p>
            </div>
            <p><input type="checkbox" name="send_consent_email"/>  Kabul e-postaları gönderilsin</p>
            <button type="submit" class="btn btn-success pull-left" name="send">Gönder</button>
            """
    return ""
def authorizedforelection(site, user):
    now = datetime.date(datetime.now())
    approvaldates = ApprovalDate.objects.filter(site__is_active=True).order_by("start_date")
    if approvaldates:
        if site.event_start_date > now and datetime.now() >= approvaldates[0].start_date and \
                UserProfileOPS.is_authorized_inst(user.userprofile):
            return """
            <div class="alert alert-danger">
                Uyarı: <p>* Onay tarihleri içerisinde kabul e-postaları onayladığınız 1. tercihi kursunuz olan katılımcılara gönderilir.</p>
                       <p>* Kabul e-postası gönderilen kullanıcıların onayını kaldıramazsınız!</p>
                       <p>* Onaylanan diğer (1. tercihi kursunuz olmayan) katılımcıların kabul e-postaları onay tarihi bitiminde gönderilir.</p>
                       <p>* El ile eklediğiniz katılımcıları 1. tercih listesinde görüntüleyebilirsiniz.</p>
            </div>
            <p><input type="checkbox" name="send_consent_email"/>  Kabul e-postaları gönderilsin</p>
            <button type="submit" class="btn btn-success pull-left" name="send">Gönder</button>
            """
    return ""
def getconsentmailfield(tcr, user):
    consentemailsentt = TrainessCourseRecord.objects.filter(
        trainess=tcr.trainess,
        course__site__is_active=True,
        consentemailsent=True).first()
    if tcr.consentemailsent:
        return "Gönderildi"
    elif consentemailsentt and consentemailsentt != tcr:
        return "%s. tercihi icin gonderildi" % str(
            consentemailsentt.preference_order)
    elif not tcr.consentemailsent and tcr.preference_order == 1 and UserProfileOPS.is_authorized_inst(
            user.userprofile):
        dom = "<div>"
        dom += "<input type=\"checkbox\" name=\"consentmail%s\" value=\"%s\"/>" % (
            tcr.course.pk, tcr.pk)
        dom += "</div>"
        return dom
    else:
        return "Gönderilmedi"
def getoperationsmenu(uprofile):
    html = ""

    if UserProfileOPS.is_instructor(uprofile):
        html += """<li>
        <a href="/egitim/controlpanel"><i class="fa fa-book fa-fw"></i> Kursum</a>
        </li>
        <li>
            <a href="/egitim/katilimciekle"><i class="fa fa-book fa-fw"></i> Kursiyer Ekle</a>
        </li>"""
    else:
        html += """
        <li>
            <a href="/egitim/applytocourse"><i class="fa fa-check-square-o fa-fw"></i> Kurs Başvurusu</a>
        </li>
        <li>
            <a href="/egitim/approve_course_preference"><i class="fa fa-thumbs-o-up fa-fw"></i> Başvuru Durum/Onayla</a>
        </li>
        """

    return html
Exemple #29
0
def getoperationsmenu(uprofile):
    html = ""

    if UserProfileOPS.is_instructor(uprofile):
        html += """<li>
        <a href="/egitim/controlpanel"><i class="fa fa-book fa-fw"></i> Kursum</a>
        </li>
        <li>
            <a href="/egitim/katilimciekle"><i class="fa fa-book fa-fw"></i> Kursiyer Ekle</a>
        </li>"""
    else:
        html += """
        <li>
            <a href="/egitim/applytocourse"><i class="fa fa-check-square-o fa-fw"></i> Kurs Başvurusu</a>
        </li>
        <li>
            <a href="/egitim/approve_course_preference"><i class="fa fa-thumbs-o-up fa-fw"></i> Başvuru Durum/Onayla</a>
        </li>
        """

    return html
Exemple #30
0
def instructor_information(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    if not request.user.userprofile:
        log.error("Kullanıcı Profili Bulunamadı", extra=d)
        return redirect("createprofile")
    data = getsiteandmenus(request)
    if not UserProfileOPS.is_instructor(request.user.userprofile):
        note = _("You are not authorized to access here")
    else:
        note = _("Please enter your transformation, arrival date, departure date information")
        instructorinformation = None
        try:
            instructorinformation = InstructorInformation.objects.get(user=request.user.userprofile)
            form = InstructorInformationForm(instance=instructor_information)
        except Exception as e:
            log.debug("Egitmen bilgileri bulunamadi, yeni bilgiler olusturulmak icin form acilacak", extra=d)
            log.error(e.message, extra=d)
            form = InstructorInformationForm()
        if request.POST:
            if instructorinformation:
                form = InstructorInformationForm(request.POST, instance=instructorinformation)
            else:
                form = InstructorInformationForm(request.POST)
            if form.is_valid():
                try:
                    form.instance.user = request.user.userprofile
                    instructor_info = form.save(commit=True)
                    instructor_info.user = request.user.userprofile
                    instructor_info.save()
                    note = _("Your information saved successfully")
                except Exception as e:
                    note = _("An error occurred while saving your information")
                    log.error(e.message, extra=d)
        data['form'] = form
    data['note'] = note
    return render_to_response("userprofile/instructor_information.html", data, context_instance=RequestContext(request))
Exemple #31
0
 def clean(self):
     cleaned_data = super(StuProfileForm, self).clean()
     ruser = self.ruser
     if ruser:
         first_name = ruser.first_name.rstrip().lstrip()
         last_name = ruser.last_name.rstrip().lstrip()
         byear = cleaned_data['birthdate'].year
         if cleaned_data['tckimlikno'] and cleaned_data['ykimlikno']:
             raise forms.ValidationError(
                 _("Please fill only one of them:tckimlikno,ykimlikno"))
         elif not cleaned_data['tckimlikno'] and cleaned_data[
                 'country'] == 'TR':
             raise forms.ValidationError(
                 _("TC identifier no can not be empty for Turkish citizens")
             )
         elif not cleaned_data[
                 'ykimlikno'] and cleaned_data['country'] != 'TR':
             raise forms.ValidationError(
                 _("Foreigner identifier no can not be blank for non Turkish citizens"
                   ))
         elif cleaned_data['tckimlikno'] and cleaned_data['country'] == 'TR':
             tckisvalid = UserProfileOPS.validateTCKimlikNo(
                 cleaned_data['tckimlikno'].rstrip().lstrip(), first_name,
                 last_name, byear)
             if tckisvalid == -1:
                 raise forms.ValidationError(
                     _("Error occured during verify your TC identifier no"))
             elif not tckisvalid:
                 raise forms.ValidationError(
                     _("Your identification informations couldn't be verified, Please enter \
                                                  your TC identifier no, your name, your last name (with Turkish character) \
                                                  and your bird date completely"
                       ))
     else:
         raise forms.ValidationError(_("User not found"))
     return cleaned_data
Exemple #32
0
def instinfo(uprofile):
    html = ""
    if UserProfileOPS.is_instructor(uprofile):
        html += "<li><a href=\"/accounts/egitmen/bilgi\"><i class=\"fa fa-info-circle fa-fw\"></i> Egitmen Bilgileri </a></li>"

    return html
Exemple #33
0
def createprofile(request):
    data = {}
    log.info("create/update profile form", extra=request.log_extra)
    data['update_user_form'] = UpdateUserForm(instance=request.user)
    data['note'] = "Profilinizi güncelleyebilirsiniz."
    note, userprobysite, data['userproform'], data['userproformbysite'], data[
        'accomodations'], data['accomodation_records'] = getuserprofileforms(
            request.user, request.site, request.log_extra)
    data['sitewidequestions'] = TextBoxQuestions.objects.filter(
        site=request.site, active=True, is_sitewide=True)
    if 'register' in request.POST:
        data['update_user_form'] = UpdateUserForm(data=request.POST,
                                                  instance=request.user)
        try:
            data['userproform'] = StuProfileForm(
                request.POST,
                request.FILES,
                instance=request.user.userprofile,
                ruser=request.user)
        except UserProfile.DoesNotExist:
            data['userproform'] = StuProfileForm(request.POST,
                                                 request.FILES,
                                                 ruser=request.user)
        if userprobysite:
            data['userproformbysite'] = UserProfileBySiteForm(
                request.POST,
                request.FILES,
                instance=userprobysite,
                ruser=request.user,
                site=request.site)
        else:
            data['userproformbysite'] = UserProfileBySiteForm(
                request.POST,
                request.FILES,
                ruser=request.user,
                site=request.site)
        if data['update_user_form'].is_valid():
            data['update_user_form'].save()
            if data['userproform'].is_valid():
                log.info("formvalid", extra=request.log_extra)
                try:
                    data['userproform'].save()
                    if data['sitewidequestions']:
                        for question in data['sitewidequestions']:
                            # noinspection PyUnresolvedReferences
                            answer = request.POST.get("answer%s" % question.pk,
                                                      "")
                            if answer:
                                tca, created = TrainessClassicTestAnswers.objects.get_or_create(
                                    user=request.user.userprofile,
                                    question=question)
                                tca.answer = answer
                                tca.save()
                    if not UserProfileOPS.is_instructor(
                            request.user.userprofile
                    ) and ACCOMODATION_PREFERENCE_LIMIT:
                        prefs = UserAccomodationPref.objects.filter(
                            user=request.user.userprofile)
                        if prefs:
                            prefs.delete()
                        if 'tercih1' in request.POST.keys():
                            try:
                                uaccpref = UserAccomodationPref(
                                    user=request.user.userprofile,
                                    accomodation=Accommodation.objects.get(
                                        pk=request.POST.get('tercih1')),
                                    usertype="stu",
                                    preference_order=1)
                                uaccpref.save()
                                log.info(
                                    "Kullanıcı profilini ve konaklama tercihini güncelledi.",
                                    extra=request.log_extra)
                                if request.site.needs_document:
                                    if data['userproformbysite'].is_valid():
                                        data['userproformbysite'].save()
                                        if 'document' in request.FILES:
                                            log.info(
                                                "Kullanıcı evrakını güncelledi.",
                                                extra=request.log_extra)
                                    else:
                                        data[
                                            'note'] = "Profiliniz aşağıdaki sebeplerden dolayı kaydedilemedi"
                                        return render(
                                            request,
                                            "userprofile/user_profile.html",
                                            data)
                            except Exception as e:
                                log.error(e.message, extra=request.log_extra)
                                data['note'] = "Profiliniz kaydedildi ancak konaklama tercihleriniz kaydedilemedi." \
                                               " Sistem yöneticisi ile görüşün!"
                                return render(request,
                                              "userprofile/user_profile.html",
                                              data)
                    data['note'] = "Profiliniz başarılı bir şekilde kaydedildi. Kurs tercihleri adımından" \
                                   " devam edebilirsiniz"
                    return render(request, "userprofile/user_profile.html",
                                  data)
                except Exception as e:
                    log.error('Error on line {}'.format(
                        sys.exc_info()[-1].tb_lineno),
                              extra=request.log_extra)
                    log.error(e.message, extra=request.log_extra)
                    data[
                        'note'] = "Profiliniz kaydedilirken hata oluştu lütfen sayfayı yeniden yükleyip tekrar deneyin"
                    return render(request, "userprofile/user_profile.html",
                                  data)
        data['note'] = "Profiliniz aşağıdaki sebeplerden dolayı oluşturulamadı"
    elif 'cancel' in request.POST:
        return redirect("createprofile")
    return render(request, "userprofile/user_profile.html", data)
def inststatistic(uprofile):
    html = ""
    if UserProfileOPS.is_instructor(uprofile):
        html += "<li><a href='/egitim/istatistik/'><i class='fa fa-pie-chart fa-fw'></i> İstatistik </a></li>"
    return html
Exemple #35
0
def statistic(request):
    if request.user.is_staff or UserProfileOPS.is_instructor(request.user.userprofile):
        data = {}
        try:
            record_data = TrainessCourseRecord.objects.filter(course__site=request.site).values(
                    'course', 'preference_order').annotate(
                    Count('preference_order')).order_by(
                    'course', '-preference_order')
            statistic_by_course = {}
            for key, group in itertools.groupby(record_data, lambda item: item["course"]):
                course_object = Course.objects.get(pk=key, site=request.site)
                statistic_by_course[course_object] = {str(item['preference_order']): item['preference_order__count'] for
                                                      item in group}
                statistic_by_course[course_object]['total_apply'] = len(TrainessCourseRecord.objects.filter(
                        course=course_object))
                statistic_by_course[course_object]['total_apply_by_trainer'] = len(TrainessCourseRecord.objects.filter(
                        course=course_object, approved=True))
                statistic_by_course[course_object]['applicationbywomen'] = len(
                        TrainessCourseRecord.objects.filter(course=course_object, trainess__gender="K").order_by(
                                "trainess").values_list("trainess").distinct())
                statistic_by_course[course_object]['applicationbymen'] = len(
                        TrainessCourseRecord.objects.filter(course=course_object, trainess__gender="E").order_by(
                                "trainess").values_list("trainess").distinct())
            data['statistic_by_course'] = statistic_by_course

            data['statistic_by_gender_k'] = len(
                    TrainessCourseRecord.objects.filter(course__site=request.site, trainess__gender="K").order_by(
                            "trainess").values_list("trainess").distinct())
            data['statistic_by_gender_e'] = len(
                    TrainessCourseRecord.objects.filter(course__site=request.site, trainess__gender="E").order_by(
                            "trainess").values_list("trainess").distinct())
            data['statistic_by_gender_k_approved'] = len(
                    TrainessCourseRecord.objects.filter(course__site=request.site, trainess__gender="K",
                                                        approved=True).order_by("trainess").values_list(
                            "trainess").distinct())
            data['statistic_by_gender_e_approved'] = len(
                    TrainessCourseRecord.objects.filter(course__site=request.site, trainess__gender="E",
                                                        approved=True).order_by("trainess").values_list(
                            "trainess").distinct())
            data['statistic_by_university'] = TrainessCourseRecord.objects.filter(course__site=request.site).order_by(
                "-trainess__id__count").values("trainess__university").annotate(Count("trainess__university"),
                                                                                Count("trainess__id", distinct=True))

            data['statistic_by_university_for_approved'] = TrainessCourseRecord.objects.filter(
                course__site=request.site, approved=True).order_by("-trainess__id__count").values("trainess__university").annotate(
                Count("trainess__university"), Count("trainess__id", distinct=True))

            data['statistic_by_city'] = TrainessCourseRecord.objects.filter(course__site=request.site).order_by(
                "-trainess__id__count").values("trainess__city").annotate(Count("trainess__city"),
                                                                                Count("trainess__id", distinct=True))
            data['statistic_by_city_for_approved'] = TrainessCourseRecord.objects.filter(course__site=request.site, approved=True).order_by(
                "-trainess__id__count").values("trainess__city").annotate(Count("trainess__city"),
                                                                          Count("trainess__id", distinct=True))

            # kurs bazinda toplam teyitli olanlar
            total_profile = len(
                    TrainessCourseRecord.objects.filter(course__site=request.site).order_by("trainess").values(
                            "trainess").distinct())
            total_preference = len(TrainessCourseRecord.objects.filter(course__site=request.site))
            data['statistic_by_totalsize'] = {'Toplam Profil(Kişi)': total_profile, 'Toplam Tercih': total_preference}
        except Exception as e:
            log.error(e.message, extra=request.log_extra)
        return render(request, "training/statistic.html", data)
    else:
        return redirect("index")
Exemple #36
0
def showuserprofile(request, userid, courserecordid):
    data = {}
    if UserProfileOPS.is_instructor(
            request.user.userprofile) or request.user.is_staff:
        courserecord = None
        try:
            courserecord = TrainessCourseRecord.objects.get(
                pk=courserecordid, trainess=UserProfile.objects.get(pk=userid))
            if not UserProfileOPS.is_user_trainer_ofcourse_or_staff(
                    request.user, courserecord.course):
                return redirect("selectcoursefcp")
        except Exception as e:
            log.warning(e.message, extra=request.log_extra)
            if not request.user.is_staff:
                return redirect("selectcoursefcp")
            log.warning("Staff user show user profile",
                        extra=request.log_extra)
        user = UserProfile.objects.get(pk=userid)
        data['tuser'] = user
        data['ruser'] = request.user
        data['note'] = "Detaylı kullanıcı bilgileri"
        if user:
            userprofilebysite = None
            try:
                userprofilebysite = UserProfileBySite.objects.get(
                    user=user.user, site=request.site)
                data['userprofilebysiteform'] = UserProfileBySiteForStaffForm(
                    instance=userprofilebysite,
                    ruser=request.user,
                    site=request.site,
                    user=user.user)
            except UserProfileBySite.DoesNotExist as e:
                data['userprofilebysiteform'] = UserProfileBySiteForStaffForm(
                    ruser=request.user, site=request.site, user=user.user)
            if "savesitebasedprofile" in request.POST:
                if userprofilebysite:
                    data[
                        'userprofilebysiteform'] = UserProfileBySiteForStaffForm(
                            request.POST,
                            request.FILES,
                            instance=userprofilebysite,
                            ruser=request.user,
                            site=request.site,
                            user=user.user)
                else:
                    data[
                        'userprofilebysiteform'] = UserProfileBySiteForStaffForm(
                            request.POST,
                            request.FILES,
                            ruser=request.user,
                            site=request.site,
                            user=user.user)
                if data['userprofilebysiteform'].is_valid():
                    data['userprofilebysiteform'].save()
                    log.info(
                        "%s kullanıcısı için etkinlik bazlı profil kaydedildi",
                        extra=request.log_extra)
                    data['note'] = "Etkinlik bazlı profil kaydedildi."
                else:
                    data[
                        'note'] = "Kullanici bazlı profil formu doğrulanamadı."
            if request.user.is_staff and "cancelall" in request.POST:
                cancelnote = request.POST.get('trainesscancelnotetext', '')
                res = cancel_all_prefs(user, cancelnote, request.site,
                                       request.user, request.log_extra)
                if res == 1:
                    data['note'] = "Kullanıcının Tüm Başvuruları Silindi"
                else:
                    data[
                        'note'] = "Kullanıcının Başvuruları silinirken hata oluştu"
            if "savescore" in request.POST:
                '''
                    Kullanıcı için not girişi
                '''
                trainessnote = request.POST.get('trainessnotetext')
                data['note'] = UserProfileOPS.savenote(request, user.user,
                                                       trainessnote)
            if courserecord:
                '''
                    Kullanıcı profilindeki yoklamalar buradan alınıyor. (Görevli kullanıcı erişebilir)
                '''
                data['courseid'] = courserecord.course.pk
                if request.user.is_staff and courserecord.consentemailsent:
                    try:
                        data['forms'] = getparticipationforms(
                            request.site, courserecord)
                        if "save" in request.POST:
                            data['note'] = UserProfileOPS.saveparticipation(
                                request, courserecord)
                            data['forms'] = getparticipationforms(
                                request.site, courserecord)
                    except Exception as e:
                        log.error(e.message, extra=request.log_extra)
        else:
            data['note'] = "Böyle Bir kullanıcı yoktur."
        return render(request, "userprofile/showuserprofile.html", data)
    return redirect("controlpanel")
Exemple #37
0
def createprofile(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = getsiteandmenus(request)
    log.info("create profile form", extra=d)
    data['update_user_form'] = UpdateUserForm(instance=request.user)
    data['accomodations_preference_count'] = range(ACCOMODATION_PREFERENCE_LIMIT)
    data['form'] = None
    try:
        user_profile = request.user.userprofile
        note = _("You can update your profile below")
        data['form'] = StuProfileForm(instance=user_profile)
        if not UserProfileOPS.is_instructor(user_profile):
            log.debug("egitmen olmayan kullanici icin isleme devam ediliyor", extra=d)
            data['accomodations'] = Accommodation.objects.filter(
                usertype__in=['stu', 'hepsi'], gender__in=[user_profile.gender, 'H'], site=data['site']).order_by(
                'name')
            data['accomodation_records'] = UserAccomodationPref.objects.filter(user=user_profile).order_by(
                'preference_order')
    except:
        note = _("If you want to continue please complete your profile.")
        data['form'] = StuProfileForm()
        data['accomodations'] = Accommodation.objects.filter(usertype__in=['stu', 'hepsi'], gender__in=['K', 'E', 'H'],
                                                             site=data['site']).order_by('name')
    data['sitewidequestions'] = TextBoxQuestions.objects.filter(site=data["site"], active=True, is_sitewide=True)
    if 'register' in request.POST:
        data['update_user_form'] = UpdateUserForm(data=request.POST, instance=request.user)
        try:
            data['form'] = StuProfileForm(request.POST, request.FILES, instance=request.user.userprofile,
                                          ruser=request.user)
        except UserProfile.DoesNotExist:
            data['form'] = StuProfileForm(request.POST, request.FILES, ruser=request.user)

        if data['update_user_form'].is_valid():
            data['update_user_form'].save()
            if data['form'].is_valid():
                log.info("formvalid", extra=d)
                try:
                    profile = data['form'].save(commit=False)
                    profile.user = request.user
                    profile.profilephoto = data['form'].cleaned_data['profilephoto']
                    profile.save()
                    if data['sitewidequestions']:
                        for question in data['sitewidequestions']:
                            answer = request.POST.get("answer%s" % question.pk, "")
                            if answer:
                                tca, created = TrainessClassicTestAnswers.objects.get_or_create(
                                    user=request.user.userprofile, question=question)
                                tca.answer = answer
                                tca.save()
                    if not UserProfileOPS.is_instructor(request.user.userprofile) and ACCOMODATION_PREFERENCE_LIMIT:
                        prefs = UserAccomodationPref.objects.filter(user=request.user.userprofile)
                        if prefs:
                            prefs.delete()
                        for pref in range(0, len(data['accomodations'])):
                            if 'tercih' + str(pref + 1) in request.POST.keys():
                                try:
                                    uaccpref = UserAccomodationPref(user=profile,
                                                                    accomodation=Accommodation.objects.get(
                                                                        pk=request.POST['tercih' + str(pref + 1)]),
                                                                    usertype="stu", preference_order=pref + 1)
                                    uaccpref.save()
                                    note = "Profiliniz başarılı bir şekilde kaydedildi. Kurs tercihleri adımından" \
                                           " devam edebilirsiniz"
                                except Exception as e:
                                    log.error(e.message, extra=d)
                                    note = "Profiliniz kaydedildi ancak konaklama tercihleriniz kaydedilemedi." \
                                           " Sistem yöneticisi ile görüşün!"
                    else:
                        note = "Profiliniz başarılı bir şekilde kaydedildi. Kurs tercihleri adımından" \
                               " devam edebilirsiniz"
                except Exception as e:
                    log.error(e.message, extra=d)
                    note = "Profiliniz kaydedilirken hata oluştu lütfen sayfayı yeniden yükleyip tekrar deneyin"
            else:
                note = "Profiliniz aşağıdaki sebeplerden dolayı oluşturulamadı"
        else:
            note = "Profiliniz aşağıdaki sebeplerden dolayı oluşturulamadı"
    elif 'cancel' in request.POST:
        return redirect("createprofile")
    data['note'] = note
    return render_to_response("userprofile/user_profile.html", data, context_instance=RequestContext(request))
Exemple #38
0
def submitandregister(request):
    d = {'clientip': request.META['REMOTE_ADDR'], 'user': request.user}
    data = prepare_template_data(request)
    userops = UserProfileOPS()
    # TODO:site ve pages'e bi care bulmak lazim
    site = Site.objects.get(is_active=True)
    pages = Menu.objects.filter(site=site.pk).order_by('order')
    note = "Kurs onerisi olustur:"
    try:
        curuserprof = UserProfile.objects.get(user=request.user)
    except:
        log.info("%s kullanici profili bulunamadi" % (request.user), extra=d)
    curinstprofform = InstProfileForm(prefix="cur")
    forms = {}
    for x in xrange(4):
        forms[x] = [
            CreateInstForm(prefix=str(x) + "inst"),
            InstProfileForm(prefix=str(x) + "instprof")
        ]
    form = CreateCourseForm()
    if "submit" in request.POST:
        allf = []
        forms = {}
        for x in xrange(4):
            if str(x) + "inst-email" in request.POST:
                forms[x] = [
                    CreateInstForm(request.POST, prefix=str(x) + "inst"),
                    InstProfileForm(request.POST, prefix=str(x) + "instprof")
                ]
                allf.append(forms[x][0].is_valid())
                allf.append(forms[x][1].is_valid())
            else:
                pass
        curinstprofform = InstProfileForm(request.POST, prefix="cur")
        form = CreateCourseForm(request.POST)
        if all([curinstprofform.is_valid(), form.is_valid()]) and all(allf):
            curinst = curinstprofform.save(commit=False)
            curinst.user = request.user
            curinst.save()
            course = form.save(commit=False)
            if 'fulltext' in request.FILES:
                course.fulltext = request.FILES['fulltext']
            course.save()
            for key, f in forms.items():
                instx = f[0].save(commit=False)
                passwd = userops.generatenewpass(8)
                instx.set_password(passwd)
                instx.save()
                instxprof = f[1].save(commit=False)
                instxprof.user = instx
                instxprof.save()
                course.trainer.add(instxprof)
            course.trainer.add(curinst)
            course.save()
            note = "Egitim oneriniz basari ile alindi."
        else:
            note = "Olusturulamadi"
    return render_to_response("training/submitandregister.html", {
        'site': site,
        'pages': pages,
        'note': note,
        'form': form,
        'curinstprofform': curinstprofform,
        'forms': forms
    },
                              context_instance=RequestContext(request))
def instinfo(uprofile):
    html = ""
    if UserProfileOPS.is_instructor(uprofile):
        html += "<li><a href=\"/accounts/egitmen/bilgi\"><i class=\"fa-info-circle fa-fw\"></i> Egitmen Bilgileri </a></li>"

    return html
Exemple #40
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