Example #1
0
class ProjeRevizyon(FlaskView):
    """Proje revizyon view classı"""

    @staticmethod
    @login_required
    @auth.requires(
        And(Permission(*permission_dict["bap"]["proje"]["basvuru"]["proje_basvurusu_yapma"]),
            And(TamamlanmamisProjeBasvurusu(), ProjeYurutucusu())))
    @route('/revizyon/<int:proje_id>', methods=['GET'])
    def proje_revizyon_get(proje_id):
        """
        Proje yetkilisi tarafindan gerekli gorulup yurutucuden proje revizyonu yapmasi istenirse
        bu view methodu kullanilir.
        Projenin ilgili state durumunda olup olmadigi(P9 - Başvurunun onaylanması için yürütücü
        revizyonu bekleniyor (ilgili state id = 9))  kontrolu yapilir.
        :param proje_id: revizyon beklenen projenin id si
        :return:
        """
        user_id = current_user.id
        revizyon_proje = DB.session.query(Proje).filter(
            Proje.id == Proje.id,
            Proje.proje_basvuru_durumu == ProjeBasvuruDurumu.revizyon_bekleniyor).first()
        if not revizyon_proje:
            CustomErrorHandler.error_handler(
                hata="Revizyon istenmeyen bir proje revize edilmeye "
                     "calisildi".format(user_id, proje_id))
            return abort(404)

        proje_turu = get_proje_turu_with_related_field(revizyon_proje.proje_turu, False)
        proje_turu_dict = proje_turu_to_dict(proje_turu)
        yurutucu_calisan_id = None

        yurutucu_calisan = DB.session.query(ProjeCalisanlari).filter_by(
            proje_id=proje_id,
            personel_id=revizyon_proje.yurutucu).first()
        if yurutucu_calisan:
            yurutucu_calisan_id = yurutucu_calisan.id

        form_data = get_proje_data(proje_turu_dict, revizyon_proje)

        proje_formu = basvuru_formu_restriction(proje_turu_dict=proje_turu_dict, **form_data)
        return render_template(
            'arastirma_projesi_basvuru/arastirma_proje_basvurusu.html',
            yeni_basvuru_formu=proje_formu,
            proje_tur_dict=proje_turu.to_dict(),
            proje_id=proje_id,
            proje_hakem_onerileri=revizyon_proje.proje_hakem_onerileri,
            proje_calisanlari=[calisan for calisan in revizyon_proje.proje_calisanlari if
                               not (
                                           revizyon_proje.yurutucu and revizyon_proje.yurutucu == calisan.personel_id)],
            yurutucu_calisan_id=yurutucu_calisan_id,
            taslak_mi=False,
            revizyon_bekleniyor_mu=True,
            uyari_mesajlari=proje_turu_dict.get("genel_uyari_mesajlari", None)
        )
Example #2
0
    def _(user, topic=None):
        kwargs = {}

        if isinstance(topic, int):
            kwargs['topic_id'] = topic
        elif isinstance(topic, Topic):
            kwargs['topic'] = topic

        return Or(
            IsAtleastSuperModerator,
            And(IsModeratorInForum(), Has('deletetopic')),
            And(IsSameUser(), Has('deletetopic'),
                TopicNotLocked(**kwargs)))(user, request)
Example #3
0
def can_delete_topic(user, topic=None):
    kwargs = {}

    if isinstance(topic, int):
        kwargs["topic_id"] = topic
    elif isinstance(topic, Topic):
        kwargs["topic"] = topic

    return Permission(
        Or(
            IsAtleastSuperModerator,
            And(IsModeratorInForum(), Has("deletetopic")),
            And(IsSameUser(), Has("deletetopic"), TopicNotLocked(**kwargs)),
        ),
        identity=user,
    )
Example #4
0
    def _(user, topic_or_post=None):
        kwargs = {}

        if isinstance(topic_or_post, int):
            kwargs['topic_id'] = topic_or_post
        elif isinstance(topic_or_post, Topic):
            kwargs['topic'] = topic_or_post
        elif isinstance(topic_or_post, Post):
            kwargs['post'] = topic_or_post

        return Or(
            IsAtleastSuperModerator,
            And(IsModeratorInForum(), Has('editpost')),
            And(IsSameUser(topic_or_post), Has('editpost'),
                TopicNotLocked(**kwargs)),
        )(user, request)
def use_permission():
    with Permission(
            Or(
                HasLevel(AuthLevels.admin),
                HasLevel(AuthLevels.staff),
                And(HasLevel(AuthLevels.user), HasPermission("promote")),
            )):
        pass
    return "thumbs up"
Example #6
0
    def _(user, forum):
        kwargs = {}

        if isinstance(forum, int):
            kwargs['forum_id'] = forum
        elif isinstance(forum, Forum):
            kwargs['forum'] = forum

        return Or(IsAtleastSuperModerator, IsModeratorInForum(**kwargs),
                  And(Has('posttopic'), ForumNotLocked(**kwargs)))(user,
                                                                   request)
Example #7
0
    def _(user, topic=None):
        kwargs = {}

        if isinstance(topic, int):
            kwargs['topic_id'] = topic
        elif isinstance(topic, Topic):
            kwargs['topic'] = topic

        return Or(IsAtleastSuperModerator, IsModeratorInForum(),
                  And(Has('postreply'), TopicNotLocked(**kwargs)))(user,
                                                                   request)
Example #8
0
class ProjeKararlariView(FlaskView):
    """Proje kararları listeleme"""
    @staticmethod
    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_kararlari_goruntuleme"]),
            Or(ProjeYurutucusu(), Role('BAP Yetkilisi'), Role("BAP Admin"))))
    @route('<int:proje_id>/dashboard/karar',
           methods=["GET"],
           endpoint='proje_kararlari_listele')
    def proje_kararlari(proje_id):
        """Yönetim Kurulu Kararları Listesi Ekrani"""
        proje_yurutucusu_mu = ProjeYurutucusu().fulfill(user=current_user)

        proje = DB.session.query(Proje).options(
            joinedload(Proje.proje_yurutucu).load_only("id").joinedload(
                OgretimElemani.personel).load_only("id").joinedload(
                    Personel.person).load_only("ad", "soyad"),
            lazyload(Proje.proje_detayi),
            lazyload(Proje.kabul_edilen_proje_hakemleri),
            lazyload(Proje.proje_hakem_onerileri),
            lazyload(Proje.proje_destekleyen_kurulus),
            lazyload(Proje.proje_kalemleri),
        ).filter(
            Proje.id == proje_id,
            or_(
                Proje.proje_basvuru_durumu == ProjeBasvuruDurumu.tamamlandi,
                Proje.proje_basvuru_durumu ==
                ProjeBasvuruDurumu.revizyon_bekleniyor)).first()

        next_states_info = get_next_states_info(proje_id=proje_id)
        actions_info = get_actions_info(proje_id=proje_id)
        try:
            karar_listesi = DB.session.query(BapGundem).filter(
                BapGundem.proje_id == proje_id,
                BapGundem.karar_durum != KararDurumu.degerlendirilmedi)
        except SQLAlchemyError as exc:
            CustomErrorHandler.error_handler(
                hata="Proje kararları sorgusunda hata oluştu  "
                "Hata: {}, User id: {}, Proje id: {}".format(
                    exc, current_user.id, proje_id))

            return abort(500)

        return render_template("dashboard/proje_kararlari.html",
                               karar_listesi=karar_listesi,
                               proje_id=proje_id,
                               proje=proje,
                               next_states_info=next_states_info,
                               actions_info=actions_info,
                               proje_yurutucusu_mu=proje_yurutucusu_mu)
Example #9
0
def can_edit_post(user, topic_or_post=None):
    kwargs = {}

    if isinstance(topic_or_post, int):
        kwargs["topic_id"] = topic_or_post
    elif isinstance(topic_or_post, Topic):
        kwargs["topic"] = topic_or_post
    elif isinstance(topic_or_post, Post):
        kwargs["post"] = topic_or_post

    return Permission(
        Or(
            IsAtleastSuperModerator,
            And(IsModeratorInForum(), Has("editpost")),
            And(
                IsSameUser(topic_or_post),
                Has("editpost"),
                TopicNotLocked(**kwargs),
            ),
        ),
        identity=user,
    )
Example #10
0
def can_post_topic(user, forum):
    kwargs = {}

    if isinstance(forum, int):
        kwargs["forum_id"] = forum
    elif isinstance(forum, Forum):
        kwargs["forum"] = forum

    return Permission(
        Or(
            IsAtleastSuperModerator,
            IsModeratorInForum(**kwargs),
            And(Has("posttopic"), ForumNotLocked(**kwargs)),
        ),
        identity=user,
    )
Example #11
0
def can_post_reply(user, topic=None):
    kwargs = {}

    if isinstance(topic, int):
        kwargs["topic_id"] = topic
    elif isinstance(topic, Topic):
        kwargs["topic"] = topic

    return Permission(
        Or(
            IsAtleastSuperModerator,
            IsModeratorInForum(),
            And(Has("postreply"), TopicNotLocked(**kwargs)),
        ),
        identity=user,
    )
Example #12
0
def test_AndConditional_shortcircuit(always, never, member, request):
    cond = And(never, always)
    cond.fulfill(member, request)

    assert not always.called
def test_AndConditional_shortcircuit(always, never, member, request):
    cond = And(never, always)
    cond.fulfill(member, request)

    assert not always.called
Example #14
0
class CanAccessTopic(Requirement):
    def fulfill(self, user, request):
        topic_id = request.view_args['topic_id']
        group_ids = [g.id for g in user.groups]

        return Forum.query.join(Topic, Topic.forum_id == Forum.id).filter(
            Topic.id == topic_id,
            Forum.groups.any(Group.id.in_(group_ids))).count()


def IsAtleastModeratorInForum(forum_id=None, forum=None):
    return Or(IsAtleastSuperModerator,
              IsModeratorInForum(forum_id=forum_id, forum=forum))


IsMod = And(IsAuthed(), Has('mod'))
IsSuperMod = And(IsAuthed(), Has('super_mod'))
IsAdmin = And(IsAuthed(), Has('admin'))

IsAtleastModerator = Or(IsAdmin, IsSuperMod, IsMod)

IsAtleastSuperModerator = Or(IsAdmin, IsSuperMod)

CanBanUser = Or(IsAtleastSuperModerator, Has('mod_banuser'))

CanEditUser = Or(IsAtleastSuperModerator, Has('mod_edituser'))

CanEditPost = Or(IsAtleastSuperModerator,
                 And(IsModeratorInForum(), Has('editpost')),
                 And(IsSameUser(), Has('editpost'), TopicNotLocked()))
Example #15
0
class ProjeIslemGecmisiListesiView(FlaskView):
    """
        Proje islem gecmisini listeleyen view
    """
    @login_required
    @auth.requires(
        Or(
            And(
                Permission(*permission_dict["bap"]["proje"]["dashboard"]
                           ["islem_gecmisi_goruntuleme"]), ProjeYurutucusu()),
            RoleReq('BAP Yetkilisi'), RoleReq("BAP Admin")))
    @route('/<int:proje_id>/dashboard/islem-gecmisi',
           methods=['GET'],
           endpoint='proje_islem_gecmisi_listele')
    def islem_gecmisi(self, proje_id):
        """
        Projenin islem gecmisine ulasmak icin kullanilir
        :param proje_id: proje_id(int)
        :return: http response
        """
        proje_yurutucusu_mu = ProjeYurutucusu().fulfill(user=current_user)
        params = {"proje_id": proje_id}
        try:
            proje = DB.session.query(Proje).options(
                joinedload(Proje.proje_yurutucu).load_only("id").joinedload(
                    OgretimElemani.personel).load_only("id").joinedload(
                        Personel.person).load_only("ad", "soyad"),
                lazyload(Proje.proje_detayi),
                lazyload(Proje.kabul_edilen_proje_hakemleri),
                lazyload(Proje.proje_hakem_onerileri),
                lazyload(Proje.proje_destekleyen_kurulus),
                lazyload(Proje.proje_kalemleri),
            ).filter(
                Proje.id == proje_id,
                or_(
                    Proje.proje_basvuru_durumu ==
                    ProjeBasvuruDurumu.tamamlandi, Proje.proje_basvuru_durumu
                    == ProjeBasvuruDurumu.revizyon_bekleniyor)).first()

            next_states_info = get_next_states_info(proje_id=proje_id)
            actions_info = get_actions_info(proje_id=proje_id)

            islem_listesi = DB.session.query(AppStateTracker). \
                filter(AppStateTracker.params.contains(params),
                       or_(AppStateTracker.job_type == JobTypes.project_state_change,
                            AppStateTracker.job_type == JobTypes.project_action)). \
                       join(Person, Person.user_id == AppStateTracker.triggered_by). \
                       join(AppState, AppStateTracker.state_id == AppState.id). \
                       add_columns(
                           AppState.state_code,
                           Person.ad,
                           Person.soyad,
                       ).all()

        except Exception as exc:
            CustomErrorHandler.error_handler(
                hata="Proje işlem geçmişi görüntülenirken hata oluştu."
                "Hata: {}, Proje id: {}".format(proje_id, exc))
            return abort(500)

        return render_template("dashboard/proje_islem_gecmisi.html",
                               islem_listesi=islem_listesi,
                               proje_id=proje_id,
                               proje=proje,
                               next_states_info=next_states_info,
                               actions_info=actions_info,
                               proje_yurutucusu_mu=proje_yurutucusu_mu)
Example #16
0
class BasvuruPersonelView(FlaskView):
    """Basvuru Personel Kaydet View Class"""

    excluded_methods = ["ozgecmis_kaydet"]

    @staticmethod
    def ozgecmis_kaydet(ozgecmis_text, ozgecmis_file_id):
        """Proje calisanlarinin ozgecmislerini kaydeder. ozgecmis id doner"""
        calisan_ozgecmis = Ozgecmis(tecrube=ozgecmis_text,
                                    file_id=ozgecmis_file_id,
                                    user_id=current_user.id)
        DB.session.add(calisan_ozgecmis)
        DB.session.flush()
        return calisan_ozgecmis.id

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["basvuru"]
                       ["proje_basvurusu_yapma"]), ProjeYurutucusu(),
            TamamlanmamisProjeBasvurusu()))
    @route('/<int:proje_id>/arastirmaci-kaydet/', methods=['POST'])
    def arastirmaci_kaydet(self, proje_id):
        """
        Proje çalışanlarına araştırmacı kaydetmek için kullanılır
        """
        arastirmaci_data = request.get_json()
        personel_id = arastirmaci_data.get("personel_id")

        try:
            proje = DB.session.query(Proje).filter(Proje.id == proje_id).one()
            if proje.proje_yurutucu.personel.id == int(personel_id):
                return jsonify(
                    status="error",
                    error_message=_(
                        "Proje yürütücüsünü personel olarak ekleyemezsiniz")
                ), 400

            try:
                personel = DB.session.query(Personel).options(
                    load_only("id", "person_id"), lazyload(Personel.birimi),
                    lazyload(Personel.user),
                    joinedload(Personel.person).load_only(
                        "ad", "soyad")).filter_by(id=personel_id).one()
            except NoResultFound as exc:
                DB.session.rollback()
                CustomErrorHandler.error_handler(
                    hata=
                    "Var olmayan bir personel id si ile projeye arastirmaci eklenmeye calışıldı. "
                    "Hata: {}, Proje id: {}".format(exc, proje_id))
                return jsonify(status="error"), 400
            if personel_proje_calisani_mi(proje_id, personel_id):
                return jsonify(
                    status="error",
                    error_message=_(
                        "Eklemeye çalıştığınız personel zaten proje çalışanı.")
                ), 400
            arastirmaci_ozgecmis_id = self.ozgecmis_kaydet(
                ozgecmis_text=arastirmaci_data.pop("ozgecmis_text", None),
                ozgecmis_file_id=arastirmaci_data.pop("ozgecmis_file_id",
                                                      None))

            yeni_arastirmaci = ProjeCalisanlari(
                proje_id=proje_id,
                universite_disindan_mi=False,
                ozgecmis_id=arastirmaci_ozgecmis_id,
                **arastirmaci_data)
            personel_ad = personel.person.ad
            personel_soyad = personel.person.soyad
            DB.session.add(yeni_arastirmaci)
            DB.session.commit()
            signal_payload = {
                "message_type":
                USER_ACTIVITY_MESSAGES.get("bap").get(
                    "projeye_arastirmaci_eklendi").type_index,
                "nesne":
                'Proje Calisanlari',
                "nesne_id":
                yeni_arastirmaci.id,
                "etkilenen_nesne":
                "Personel",
                "etkilenen_nesne_id":
                personel.id,
                "ekstra_mesaj":
                "{} adlı kullanıcı, {} {} adlı personeli {} id'li projeye "
                "araştırmacı olarak ekledi.".format(current_user.username,
                                                    personel_ad,
                                                    personel_soyad, proje_id)
            }
            signal_sender(**signal_payload)
            return jsonify(status="success",
                           calisan={
                               "id": yeni_arastirmaci.id,
                               "ad": personel_ad,
                               "soyad": personel_soyad,
                               "gorevi": yeni_arastirmaci.projedeki_gorevi
                           })
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                hata="Proje idsi %s olan projeye arastirmaci atamaya"
                "çalışılırken bir sorun oluştu. Hata: %s" % (proje_id, exc))

        return jsonify(status="error"), 400

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["basvuru"]
                       ["proje_basvurusu_yapma"]), ProjeYurutucusu(),
            TamamlanmamisProjeBasvurusu()))
    @route('/<int:proje_id>/bursiyer-kaydet/', methods=['POST'])
    def bursiyer_kaydet(self, proje_id):
        """
        Proje çalışanlarına bursiyer kaydetmek için kullanılır
        """
        bursiyer_data = request.get_json()
        ogrenci_id = bursiyer_data.get("ogrenci_id")

        try:
            try:
                ogrenci = DB.session.query(Ogrenci).options(
                    load_only("id", "person_id"), lazyload(Ogrenci.user),
                    joinedload(Ogrenci.person).load_only(
                        "ad", "soyad")).filter_by(id=ogrenci_id).one()
            except NoResultFound as exc:
                CustomErrorHandler.error_handler(
                    hata=
                    "Var olmayan bir öğrenci id si ile projeye bursiyer eklenmeye calışıldı. "
                    "Hata: {}, Proje id: {}".format(proje_id, exc))

                return jsonify(status="error"), 400
            bursiyer_calisan = DB.session.query(ProjeCalisanlari.id).filter(
                ProjeCalisanlari.ogrenci_id == ogrenci_id,
                ProjeCalisanlari.proje_id == proje_id).scalar()
            if bursiyer_calisan:
                return jsonify(
                    status="error",
                    error_message=_(
                        "Eklemeye çalıştığınız öğrenci zaten proje çalışanı.")
                ), 400

            bursiyer_ozgecmis_id = self.ozgecmis_kaydet(
                ozgecmis_text=bursiyer_data.pop("ozgecmis_text", None),
                ozgecmis_file_id=bursiyer_data.pop("ozgecmis_file_id", None))

            yeni_bursiyer = ProjeCalisanlari(proje_id=proje_id,
                                             universite_disindan_mi=False,
                                             ozgecmis_id=bursiyer_ozgecmis_id,
                                             **bursiyer_data)
            ogrenci_ad = ogrenci.person.ad
            ogrenci_soyad = ogrenci.person.soyad
            DB.session.add(yeni_bursiyer)
            DB.session.commit()
            signal_payload = {
                "message_type":
                USER_ACTIVITY_MESSAGES.get("bap").get(
                    "projeye_bursiyer_eklendi").type_index,
                "nesne":
                'Proje Calisanlari',
                "nesne_id":
                yeni_bursiyer.id,
                "etkilenen_nesne":
                "Proje",
                "etkilenen_nesne_id":
                proje_id,
                "ekstra_mesaj":
                "{} adlı kullanıcı, {} {} adlı öğrenciyi bursiyer olarak "
                "ekledi.".format(current_user.username, ogrenci_ad,
                                 ogrenci_soyad)
            }
            signal_sender(**signal_payload)
            return jsonify(status="success",
                           calisan={
                               "id": yeni_bursiyer.id,
                               "ad": ogrenci_ad,
                               "soyad": ogrenci_soyad,
                               "gorevi": yeni_bursiyer.projedeki_gorevi
                           })
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                hata="Proje idsi %s olan projeye bursiyer atamaya"
                "çalışılırken bir sorun oluştu. Hata: %s" % (proje_id, exc))

        return jsonify(status="error"), 400

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["basvuru"]
                       ["proje_basvurusu_yapma"]), ProjeYurutucusu(),
            TamamlanmamisProjeBasvurusu()))
    @route('/<int:proje_id>/harici-arastirmaci-kaydet/', methods=['POST'])
    def harici_arastirmaci_kaydet(self, proje_id):
        """
        Proje çalışanlarına üniversite dışı araştırmacı kaydetmek için kullanılır.
        """
        harici_arastirmaci_data = request.get_json()
        adi = harici_arastirmaci_data.pop("ad")
        soyad = harici_arastirmaci_data.pop("soyad")
        email = harici_arastirmaci_data.pop("email")

        try:

            yeni_person = Person(ad=adi, soyad=soyad, birincil_eposta=email)
            DB.session.add(yeni_person)
            DB.session.flush()

            harici_arastirmaci_ozgecmis_id = self.ozgecmis_kaydet(
                ozgecmis_text=harici_arastirmaci_data.pop(
                    "ozgecmis_text", None),
                ozgecmis_file_id=harici_arastirmaci_data.pop(
                    "ozgecmis_file_id", None))

            yeni_harici_arastirmaci = ProjeCalisanlari(
                proje_id=proje_id,
                ozgecmis_id=harici_arastirmaci_ozgecmis_id,
                person_id=yeni_person.id,
                **harici_arastirmaci_data)
            DB.session.add(yeni_harici_arastirmaci)
            DB.session.commit()
            signal_payload = {
                "message_type":
                USER_ACTIVITY_MESSAGES.get("bap").get(
                    "projeye_harici_arastirmaci_eklendi").type_index,
                "nesne":
                'Proje Calisanlari',
                "nesne_id":
                yeni_harici_arastirmaci.id,
                "etkilenen_nesne":
                "Proje",
                "etkilenen_nesne_id":
                proje_id,
                "ekstra_mesaj":
                "{} adlı kullanıcı, {} {} adlı kisiyi üniversite dışı arastırmacı "
                "olarak kaydetti.".format(current_user.username, adi, soyad)
            }
            signal_sender(**signal_payload)
            return jsonify(status="success",
                           calisan={
                               "id": yeni_harici_arastirmaci.id,
                               "ad": adi,
                               "soyad": soyad,
                               "gorevi":
                               yeni_harici_arastirmaci.projedeki_gorevi
                           })
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                hata="Proje idsi %s olan projeye harici araştırmacı atamaya"
                "çalışılırken bir sorun oluştu. Hata: %s" % (proje_id, exc))

        return jsonify(status="error"), 400

    @staticmethod
    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["basvuru"]
                       ["proje_basvurusu_yapma"]), ProjeYurutucusu(),
            TamamlanmamisProjeBasvurusu()))
    @route('/<int:proje_id>/calisan-sil/<int:calisan_id>', methods=['DELETE'])
    def proje_calisani_sil(proje_id, calisan_id):
        """
        Daha önce projeye kaydedilmiş çalışanı siler.
        """
        try:
            try:
                silinecek_calisan = DB.session.query(
                    ProjeCalisanlari).filter_by(id=calisan_id,
                                                proje_id=proje_id).one()
            except NoResultFound as exc:
                DB.session.rollback()
                CustomErrorHandler.error_handler(
                    hata="Var olmayan bir id ile proje çalışanı silinmeye "
                    "çalışıldı. Proje id: {}, Hata: {}".format(proje_id, exc))
                return jsonify(status="error"), 400

            DB.session.delete(silinecek_calisan)
            if silinecek_calisan.person:
                DB.session.delete(silinecek_calisan.person)
            DB.session.commit()
            signal_payload = {
                "message_type":
                USER_ACTIVITY_MESSAGES.get("bap").get(
                    "proje_calisani_sil").type_index,
                "nesne":
                'Proje Calisanlari',
                "nesne_id":
                calisan_id,
                "etkilenen_nesne":
                "Proje",
                "etkilenen_nesne_id":
                proje_id,
                "ekstra_mesaj":
                "{} adlı kullanıcı, proje çalışanını projeden sildi.".format(
                    current_user.username)
            }
            signal_sender(**signal_payload)
            return jsonify(status="success")
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                hata=
                "Proje çalışanı silinmeye çalışırken hata ile karşılaşıldı. "
                "Proje id: {}, Calisan id: {}, Hata: {}".format(
                    proje_id, calisan_id, exc))
        return jsonify(status="error"), 400

    @staticmethod
    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["basvuru"]
                       ["proje_basvurusu_yapma"]), ProjeYurutucusu(),
            TamamlanmamisProjeBasvurusu()))
    @route('/<int:proje_id>/calisan/<int:calisan_id>', methods=['GET'])
    def get_proje_calisani(proje_id, calisan_id):
        """
        Var olan bir çalışanı almak için kullanılır.
        """
        try:
            try:
                calisan = DB.session.query(ProjeCalisanlari).options(
                    lazyload(ProjeCalisanlari.ogrenci),
                    lazyload(ProjeCalisanlari.personel),
                    joinedload(ProjeCalisanlari.person).load_only(
                        "ad", "soyad"),
                    joinedload(ProjeCalisanlari.fakulte).load_only("ad"),
                    joinedload(ProjeCalisanlari.bolum).load_only("ad"),
                    joinedload(ProjeCalisanlari.hitap_unvan).load_only(
                        "ad", "kod")).filter_by(id=calisan_id,
                                                proje_id=proje_id).one()
            except NoResultFound as exc:
                CustomErrorHandler.error_handler(
                    hata="Var olmayan bir id ile proje çalışanı alınmaya "
                    "çalışıldı. Proje id: {}, Hata: {}".format(proje_id, exc))
                return abort(404)
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                hata=
                "Proje çalışanı silinmeye çalışırken hata ile karşılaşıldı. "
                "Proje id: {}, Calisan id: {}, Hata: {}".format(
                    proje_id, calisan_id, exc))
            return abort(400)
        data = calisan.to_dict()
        data["projeye_katkisi"] = float(
            calisan.projeye_katkisi) if calisan.projeye_katkisi else float(0)

        data.update({
            "ozgecmis_text": calisan.ozgecmis.tecrube,
            "ozgecmis_file_id": calisan.ozgecmis.file_id
        })
        if calisan.person:
            hitap_unvan_ad = ""
            if calisan.hitap_unvan:
                hitap_unvan_ad = "{} {}".format(
                    calisan.hitap_unvan.kod,
                    calisan.hitap_unvan.ad if calisan.hitap_unvan else "")

            data.update({
                "hitap_unvan_ad":
                hitap_unvan_ad,
                "fakulte_ad":
                calisan.fakulte.ad if calisan.fakulte else "",
                "bolum_ad":
                calisan.bolum.ad if calisan.bolum else "",
                "ad":
                calisan.person.ad,
                "soyad":
                calisan.person.soyad,
            })
        return jsonify(status="success", calisan=data)

    @staticmethod
    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["basvuru"]
                       ["proje_basvurusu_yapma"]), ProjeYurutucusu(),
            TamamlanmamisProjeBasvurusu()))
    @route('/<int:proje_id>/calisan/<int:calisan_id>', methods=['POST'])
    def calisan_guncelle(proje_id, calisan_id):
        """
        Çalışan güncellemek için kullanılır.
        """
        calisan_data = request.get_json()
        try:
            try:
                calisan = DB.session.query(ProjeCalisanlari).filter_by(
                    id=calisan_id, proje_id=proje_id).one()
            except NoResultFound as exc:
                CustomErrorHandler.error_handler(
                    hata="Var olmayan bir id ile proje çalışanı alınmaya "
                    "çalışıldı. Proje id: {}, Hata: {}".format(proje_id, exc))
                return abort(404)
            if calisan.person_id:
                calisan.person.ad = calisan_data.get("ad")
                calisan.person.soyad = calisan_data.get("soyad")
            # todo: calisan guncellenirken ozgecmisinde bir degisklik var ise guncelle.
            calisan.ozgecmis.tecrube = calisan_data.pop("ozgecmis_text", None)
            calisan.ozgecmis.file_id = calisan_data.pop(
                "ozgecmis_file_id", None)
            calisan.update_obj_data(calisan_data)
            DB.session.commit()
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                hata=
                "Proje çalışanı silinmeye çalışırken hata ile karşılaşıldı. "
                "Proje id: {}, Calisan id: {}, Hata: {}".format(
                    proje_id, calisan_id, exc))
            return abort(400)
        data = {"id": calisan.id, "gorevi": calisan.projedeki_gorevi}
        if calisan.person_id:
            data.update({
                "ad": calisan.person.ad,
                "soyad": calisan.person.soyad
            })
        elif calisan.personel_id:
            data.update({
                "ad": calisan.personel.person.ad,
                "soyad": calisan.personel.person.soyad
            })
        else:
            data.update({
                "ad": calisan.ogrenci.person.ad,
                "soyad": calisan.ogrenci.person.soyad
            })
        signal_payload = {
            "message_type":
            USER_ACTIVITY_MESSAGES.get("bap").get(
                "proje_calisan_guncelle").type_index,
            "nesne":
            'Proje Calisanlari',
            "nesne_id":
            calisan_id,
            "etkilenen_nesne":
            "Proje",
            "etkilenen_nesne_id":
            proje_id,
            "ekstra_mesaj":
            "{} adlı kullanıcı, {} {} adlı proje çalışanının bilgilerini "
            "güncelledi.".format(current_user.username, data["ad"],
                                 data["soyad"])
        }
        signal_sender(**signal_payload)
        return jsonify(status="success", calisan=data)
Example #17
0
    def post(self, forum_id, slug=None):
        forum_instance, __ = Forum.get_forum(forum_id=forum_id,
                                             user=real(current_user))
        mod_forum_url = url_for('forum.manage_forum',
                                forum_id=forum_instance.id,
                                slug=forum_instance.slug)

        ids = request.form.getlist('rowid')
        tmp_topics = Topic.query.filter(Topic.id.in_(ids)).all()

        if not len(tmp_topics) > 0:
            flash(
                _('In order to perform this action you have to select at '
                  'least one topic.'), 'danger')
            return redirect(mod_forum_url)

        # locking/unlocking
        if 'lock' in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action='locked',
                                      reverse=False)

            flash(_('%(count)s topics locked.', count=changed), 'success')
            return redirect(mod_forum_url)

        elif 'unlock' in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action='locked',
                                      reverse=True)
            flash(_('%(count)s topics unlocked.', count=changed), 'success')
            return redirect(mod_forum_url)

        # highlighting/trivializing
        elif 'highlight' in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action='important',
                                      reverse=False)
            flash(_('%(count)s topics highlighted.', count=changed), 'success')
            return redirect(mod_forum_url)

        elif 'trivialize' in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action='important',
                                      reverse=True)
            flash(_('%(count)s topics trivialized.', count=changed), 'success')
            return redirect(mod_forum_url)

        # deleting
        elif 'delete' in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action='delete',
                                      reverse=False)
            flash(_('%(count)s topics deleted.', count=changed), 'success')
            return redirect(mod_forum_url)

        # moving
        elif 'move' in request.form:
            new_forum_id = request.form.get('forum')

            if not new_forum_id:
                flash(_('Please choose a new forum for the topics.'), 'info')
                return redirect(mod_forum_url)

            new_forum = Forum.query.filter_by(id=new_forum_id).first_or_404()
            # check the permission in the current forum and in the new forum

            if not Permission(
                    And(IsAtleastModeratorInForum(forum_id=new_forum_id),
                        IsAtleastModeratorInForum(forum=forum_instance))):
                flash(_('You do not have the permissions to move this topic.'),
                      'danger')
                return redirect(mod_forum_url)

            if new_forum.move_topics_to(tmp_topics):
                flash(_('Topics moved.'), 'success')
            else:
                flash(_('Failed to move topics.'), 'danger')

            return redirect(mod_forum_url)

        # hiding/unhiding
        elif "hide" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action="hide",
                                      reverse=False)
            flash(_("%(count)s topics hidden.", count=changed), "success")
            return redirect(mod_forum_url)

        elif "unhide" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action="unhide",
                                      reverse=False)
            flash(_("%(count)s topics unhidden.", count=changed), "success")
            return redirect(mod_forum_url)

        else:
            flash(_('Unknown action requested'), 'danger')
            return redirect(mod_forum_url)
Example #18
0
def test_AndConditional_fulfills(always, never, member, request):
    assert not And(always, never)(member, request)
    assert not And(never, always)(member, request)
Example #19
0
class ProjeSablonEkDosyaView(FlaskView):
    """
        Proje şablonlari ve ek dosyalari goruntulendigi view
    """
    @login_required
    @auth.requires(
        Or(
            And(
                Permission(*permission_dict["bap"]["proje"]["dashboard"]
                           ["proje_sablon_ek_dosya_goruntuleme"]),
                ProjeYurutucusu()), RoleReq('BAP Yetkilisi'),
            RoleReq("BAP Admin"), AtanmisHakem()))
    @route('/<int:proje_id>/sablon',
           methods=['GET'],
           endpoint='sablon_ekdosya_listele')
    def sablon_ekdosya_listele(self, proje_id):
        """
        Projenin şablon cikti ve ek dosyalarina ulasmak icin kullanilir
        """
        proje_yurutucusu_mu = ProjeYurutucusu().fulfill(user=current_user)
        atanmis_hakem = AtanmisHakem()
        proje = DB.session.query(Proje).options(
            joinedload(Proje.proje_proje_turu).load_only(
                "oneri_sablon_id", "hakem_degerlendirme_sablon_id",
                "hakem_ara_rapor_sablon_id", "ara_rapor_sablon_id",
                "sonuc_raporu_sablon_id", "sozlesme_sablon_id",
                "hakem_sonuc_rapor_sablon_id"),
            joinedload(Proje.proje_yurutucu).load_only("id").joinedload(
                OgretimElemani.personel).load_only("id").joinedload(
                    Personel.person).load_only("ad", "soyad"),
            joinedload(Proje.proje_belgeleri),
            lazyload(Proje.proje_detayi),
            lazyload(Proje.kabul_edilen_proje_hakemleri),
            lazyload(Proje.proje_hakem_onerileri),
            lazyload(Proje.proje_destekleyen_kurulus),
            lazyload(Proje.proje_kalemleri),
        ).filter(
            Proje.id == proje_id,
            or_(
                Proje.proje_basvuru_durumu == ProjeBasvuruDurumu.tamamlandi,
                Proje.proje_basvuru_durumu ==
                ProjeBasvuruDurumu.revizyon_bekleniyor)).first()

        next_states_info = get_next_states_info(proje_id=proje_id)
        actions_info = get_actions_info(proje_id=proje_id)

        proje_turu = DB.session.query(ProjeTuru).options(
            joinedload(ProjeTuru.cikti),
            joinedload(ProjeTuru.ek_dosyalar).joinedload(EkDosya.belge),
        ).filter_by(id=proje.proje_turu).one()
        ciktilar = []
        for cikti in proje_turu.cikti:
            ciktilar.append({
                "adi":
                cikti.adi,
                "yurutucu_gorebilir_mi":
                True if cikti.gorunurluk
                == GorunurlukSecenekleri.yurutucu_ve_yonetici else False,
                "sablon_id":
                cikti.sablon_id,
                "sablon_adi":
                cikti.sablon_belge.adi,
            })

        proje_ek_dosyalar = []
        proje_diger_dosyalar = []
        for ek_dosya in proje_turu.ek_dosyalar:
            for proje_belge in proje.proje_belgeleri:
                if proje_belge.proje_turu_ek_dosya_id == ek_dosya.id:
                    proje_ek_dosyalar.append({
                        # "proje_belge_id",
                        "proje_belge_file_id":
                        proje_belge.belge_id,
                        "proje_belge_aciklama":
                        proje_belge.aciklama,
                        "ornek_file_id":
                        ek_dosya.belge.file_id,
                        "ornek_file_ad":
                        ek_dosya.belge.adi,
                        "proje_icerik_dosyasi_mi":
                        ek_dosya.proje_icerik_dosyasi_mi,
                        "belgenin_ciktisi_alinacak_mi":
                        ek_dosya.belgenin_ciktisi_alinacak_mi,
                        "zorunlu_mu":
                        ek_dosya.zorunlu_mu
                    })
                    break
        for proje_belge in proje.proje_belgeleri:
            if proje_belge.proje_turu_ek_dosya_id is None:
                proje_diger_dosyalar.append({
                    "adi": proje_belge.baslik,
                    "aciklama": proje_belge.aciklama,
                    "file_id": proje_belge.belge_id
                })
                break

        # todo: gereklimi ? ustteki querye dahil edilip alinabilir
        proje_turu_sablonlari = DB.session.query(Sablon).filter(
            Sablon.id.in_([
                proje.proje_proje_turu.oneri_sablon_id,
                proje.proje_proje_turu.hakem_degerlendirme_sablon_id,
                proje.proje_proje_turu.hakem_ara_rapor_sablon_id,
                proje.proje_proje_turu.hakem_sonuc_rapor_sablon_id,
                proje.proje_proje_turu.ara_rapor_sablon_id,
                proje.proje_proje_turu.sonuc_raporu_sablon_id,
                proje.proje_proje_turu.sozlesme_sablon_id,
            ])).all()
        return render_template("dashboard/proje_sablon_ekdosyalar.html",
                               proje_id=proje_id,
                               proje=proje,
                               next_states_info=next_states_info,
                               actions_info=actions_info,
                               proje_yurutucusu_mu=proje_yurutucusu_mu,
                               ciktilar=ciktilar,
                               proje_ek_dosyalar=proje_ek_dosyalar,
                               proje_diger_dosyalar=proje_diger_dosyalar,
                               proje_turu_sablonlari=proje_turu_sablonlari,
                               proje_turu=proje_turu,
                               atanmis_hakem=atanmis_hakem)
Example #20
0
class ProjeDegerlendirmeView(FlaskView):
    """ProjeDegerlendirmeleri View"""
    @staticmethod
    @login_required
    @auth.requires(
        Or(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_degerlendirme_goruntuleme"]),
            Role('BAP Yetkilisi'), Role("BAP Admin")))
    @route('<int:proje_id>/dashboard/degerlendirme',
           methods=["GET"],
           endpoint='degerlendirme_listele')
    def degerlendirme_listele(proje_id):
        """Proje degerlemdirmelerini goruntulemek icin kullanilir"""
        proje_yurutucusu_mu = ProjeYurutucusu()
        atanmis_hakem = AtanmisHakem()

        proje = DB.session.query(Proje).options(
            joinedload(Proje.proje_yurutucu).load_only("id").joinedload(
                OgretimElemani.personel).load_only("id").joinedload(
                    Personel.person).load_only("ad", "soyad"),
            lazyload(Proje.proje_detayi),
            lazyload(Proje.proje_hakem_onerileri),
            lazyload(Proje.proje_destekleyen_kurulus),
            lazyload(Proje.proje_kalemleri),
        ).filter(
            Proje.id == proje_id,
            or_(
                Proje.proje_basvuru_durumu == ProjeBasvuruDurumu.tamamlandi,
                Proje.proje_basvuru_durumu ==
                ProjeBasvuruDurumu.revizyon_bekleniyor)).first()

        next_states_info = get_next_states_info(proje_id=proje_id)
        actions_info = get_actions_info(proje_id=proje_id)

        proje_degerlendirmeleri = []
        """
        Proje degerlendirme teklifini kabul eden hakemlerin tamamlanan degerlendirmelerini 
        listeleyip proje_degerlendirme templatetine gonderir
        """
        for proje_hakemi in proje.kabul_edilen_proje_hakemleri:
            for proje_degerlendirme in proje_hakemi.tamamlanan_proje_degerlendirmeleri:
                hakem_ad_soyad = ""
                hakem = proje_hakemi.hakem
                if hakem.person_id:
                    hakem_ad_soyad = hakem.person.ad + hakem.person.soyad
                elif hakem.personel_id:
                    hakem_ad_soyad = hakem.personel.person.ad + hakem.personel.person.soyad
                proje_degerlendirmeleri.append({
                    "hakem_ad_soyad":
                    hakem_ad_soyad,
                    "degerlendirme_sonucu":
                    proje_degerlendirme.sonuc,
                    "degerlendirme_id":
                    proje_degerlendirme.id,
                    "degerlendirme_incelendi_mi":
                    proje_degerlendirme.degerlendirme_incelendi_mi,
                    "rapor_tipi":
                    proje_degerlendirme.rapor.rapor_tipi,
                    "degerlendirilen_rapor_file_id":
                    proje_degerlendirme.rapor.file_id
                })

        degerlendirme_guncelleme_formu = DegerlendirmeGuncelleForm()
        return render_template(
            'dashboard/proje_degerlendirmeleri.html',
            proje_degerlendirmeleri=proje_degerlendirmeleri,
            proje_id=proje_id,
            next_states_info=next_states_info,
            actions_info=actions_info,
            proje_yurutucusu_mu=proje_yurutucusu_mu,
            atanmis_hakem_mi=atanmis_hakem,
            degerlendirme_guncelleme_formu=degerlendirme_guncelleme_formu,
            proje=proje)

    # todo: işlevli mi ???
    @staticmethod
    @login_required
    # todo: proje yurutucusu olma durumu eklenmesi gerekiyormu.
    # todo: aynı kontrol buna benzer(proje kararlari, proje mesajlari vb)
    # todo: viewlarda yapilmalimi kontrol et
    @auth.requires(
        Or(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_degerlendirme_goruntuleme"]),
            Role('BAP Yetkilisi'), Role("BAP Admin")))
    @route('<int:proje_id>/dashboard/degerlendirme/<int:degerlendirme_id>',
           methods=["GET"],
           endpoint='degerlendirme_detay')
    def degerlendirme_detay(proje_id, degerlendirme_id):
        """Proje degerlendirme detayı goruntulemek icin kullanilir"""
        user_id = current_user.id
        try:
            # todo: degerlendirme tamamlandimi kontrol et
            # todo: degerlendirme ilgili projeye mi ait kontrol et
            proje_degerlendirme = DB.session.query(
                ProjeDegerlendirmeleri).join(
                    ProjeDegerlendirmeleri.degerlendirme_hakemi).filter(
                        ProjeDegerlendirmeleri.id == degerlendirme_id,
                        ProjeDegerlendirmeleri.degerlendirme_sonuclandi_mi ==
                        True, ProjeHakemleri.proje_id == proje_id).one()
        except NoResultFound as exc:
            CustomErrorHandler.error_handler(
                hata=
                "Var olmayan bir proje değerlendirmesine ulaşılmaya çalışıldı."
                "User id: {}, Hata: {}".format(user_id, exc))
            return abort(404)
        # todo: degerlendirme sablon uzerinden mi yapilacak var olan form ile mi devam edilecek ?
        degerlendirme_form = ProjeDegerlendirmeForm(
            **proje_degerlendirme.degerlendirme)
        return render_template('dashboard/proje_degerlendirme_detay.html',
                               degerlendirme_form=degerlendirme_form,
                               proje_id=proje_id)

    @staticmethod
    @login_required
    @auth.requires(
        Or(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_degerlendirme_goruntuleme"]),
            Role('BAP Yetkilisi'), Role("BAP Admin")))
    @route('hakem_rapor_gorusleri_oku/<int:degerlendirme_id>/',
           methods=["GET"],
           endpoint='hakem_rapor_gorusleri_oku')
    def hakem_rapor_gorusleri_oku(degerlendirme_id):
        try:
            proje_degerlendirme = DB.session.query(
                ProjeDegerlendirmeleri).filter(
                    ProjeDegerlendirmeleri.id == degerlendirme_id,
                    ProjeDegerlendirmeleri.degerlendirme_sonuclandi_mi ==
                    True).first()
            if not proje_degerlendirme:
                return jsonify(
                    status="error",
                    hata_mesaji="İlgili değerlendirme bulunamadı"), 400
            degerlendirme = {
                "rapor_turu":
                proje_degerlendirme.rapor.rapor_tipi.value,
                "degerlendirme_sonucu":
                proje_degerlendirme.sonuc.value,
                "gonderim_tarihi":
                proje_degerlendirme.degerlendirme_gonderim_tarihi.strftime(
                    "%d.%m.%Y"),
                "metin":
                proje_degerlendirme.degerlendirme,
            }
        except Exception as exc:
            return jsonify(status="error")

        return jsonify(status="success", degerlendirme=degerlendirme)

    @staticmethod
    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_degerlendirme_goruntuleme"]),
            Or(Role('BAP Yetkilisi'), Role("BAP Admin"))))
    @route('degerlendirme/<int:degerlendirme_id>/guncelle', methods=["POST"])
    def degerlendirme_guncelle(degerlendirme_id):
        """
        Yetkili tarafindan yapilir. Degerlendirme metninde hakemin ismi yazma durumunda silmek
        icin kullanilir.
        :param degerlendirme_id:
        :return:
        """
        proje_degerlendirme = DB.session.query(ProjeDegerlendirmeleri).filter(
            ProjeDegerlendirmeleri.id == degerlendirme_id,
            ProjeDegerlendirmeleri.degerlendirme_sonuclandi_mi ==
            True).first()
        if not proje_degerlendirme:
            return redirect(
                url_for("proje.degerlendirme_listele",
                        proje_id=proje_degerlendirme.rapor.proje_id))
        degerlendirme_guncelle_form = DegerlendirmeGuncelleForm(request.form)
        proje_degerlendirme.degerlendirme = degerlendirme_guncelle_form.degerlendirme_metni.data
        DB.session.commit()

        return redirect(
            url_for("proje.degerlendirme_listele",
                    proje_id=proje_degerlendirme.rapor.proje_id))
Example #21
0
class ProjeRaporView(FlaskView):
    """Proje ara ve sonuc raporlarini goruntuleme, filtreleme ve indirme viewi"""

    excluded_methods = [
        "qry",
        "proje_rapor_filtreleme_form",
    ]

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_raporlari_goruntuleme"]),
            Or(ProjeYurutucusu(), Role('BAP Yetkilisi'), Role("BAP Admin"),
               AtanmisHakem())))
    @route('<int:proje_id>/dashboard/rapor',
           methods=["GET"],
           endpoint='proje_rapor_index_get')
    def proje_rapor_get(self, proje_id):
        """Proje raporlarini goruntulemek icin kullanilir"""

        proje_yurutucusu_mu = ProjeYurutucusu().fulfill(user=current_user)
        atanmis_hakem = AtanmisHakem()
        proje = DB.session.query(Proje).options(
            joinedload(Proje.proje_proje_turu).load_only(
                "ara_rapor_sablon_id", "sonuc_raporu_sablon_id"),
            joinedload(Proje.proje_yurutucu).load_only("id").joinedload(
                OgretimElemani.personel).load_only("id").joinedload(
                    Personel.person).load_only("ad", "soyad"),
            joinedload(Proje.proje_raporlari),
            lazyload(Proje.proje_detayi),
            lazyload(Proje.kabul_edilen_proje_hakemleri),
            lazyload(Proje.proje_hakem_onerileri),
            lazyload(Proje.proje_destekleyen_kurulus),
            lazyload(Proje.proje_kalemleri),
        ).filter(
            Proje.id == proje_id,
            or_(
                Proje.proje_basvuru_durumu == ProjeBasvuruDurumu.tamamlandi,
                Proje.proje_basvuru_durumu ==
                ProjeBasvuruDurumu.revizyon_bekleniyor)).first()
        next_states_info = get_next_states_info(proje_id=proje_id)
        actions_info = get_actions_info(proje_id=proje_id)
        ara_rapor_degerlendirme_sablon_id = proje.proje_proje_turu.ara_rapor_sablon_id
        sonuc_raporu_degerlendirme_sablon_id = proje.proje_proje_turu.sonuc_raporu_sablon_id

        return render_template(
            'dashboard/proje_raporlari.html',
            ara_rapor_degerlendirme_sablon_id=ara_rapor_degerlendirme_sablon_id,
            sonuc_raporu_degerlendirme_sablon_id=
            sonuc_raporu_degerlendirme_sablon_id,
            proje_raporlari=proje.proje_raporlari,
            proje_id=proje_id,
            proje=proje,
            proje_yurutucusu_mu=proje_yurutucusu_mu,
            next_states_info=next_states_info,
            actions_info=actions_info,
            rapor_duzenle_formu=RaporForm(),
            atanmis_hakem=atanmis_hakem)

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_raporlari_goruntuleme"]),
            Or(ProjeYurutucusu(), Role('BAP Yetkilisi'), Role("BAP Admin"))))
    @route('<int:proje_id>/rapor/<int:rapor_id>/information', methods=["GET"])
    def get_rapor_information(self, proje_id, rapor_id):
        """Proje raporunun bilgilerini getirir"""
        rapor_bilgileri = DB.session.query(ProjeRapor).filter(
            ProjeRapor.id == rapor_id,
            ProjeRapor.proje_id == proje_id).scalar()
        if not rapor_bilgileri:
            return jsonify(status="error"), 404

        rapor_data = {
            "rapor_metni":
            rapor_bilgileri.rapor_icerigi,
            "tamamlandi_mi":
            True if rapor_bilgileri.durumu == ProjeRaporDurumu.tamamlandi else
            False,
            "file_id":
            rapor_bilgileri.file_id
        }
        return jsonify(status="success", rapor_data=rapor_data)

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_raporlari_duzenleme"]),
            Or(ProjeYurutucusu(), Role('BAP Yetkilisi'), Role("BAP Admin"))))
    @route("<int:proje_id>/rapor/<int:rapor_id>/",
           methods=["POST"],
           endpoint='proje_rapor_guncelle')
    def rapor_guncelle(self, proje_id, rapor_id):  # pylint: disable=R0201
        """
            Proje raporunu duzenlemek icin kullanilir
        """
        rapor_formu = RaporForm(request.form)

        proje_raporu = DB.session.query(ProjeRapor).filter(
            ProjeRapor.proje_id == proje_id, ProjeRapor.id == rapor_id).one()
        if proje_raporu.duzenlenebilir_mi:
            proje_raporu.rapor_icerigi = rapor_formu.rapor_metni.data
            proje_raporu.file_id = rapor_formu.rapor_dosya.data
            if rapor_formu.tamamlandi_mi.data:
                proje_raporu.duzenlenebilir_mi = False
                proje_raporu.durumu = ProjeRaporDurumu.tamamlandi
            signal_payload = {
                "message_type":
                USER_ACTIVITY_MESSAGES.get("bap").get(
                    "proje_raporu_guncellendi").type_index,
                "nesne":
                'Proje Rapor',
                "nesne_id":
                proje_raporu.id,
                "etkilenen_nesne":
                "Proje",
                "etkilenen_nesne_id":
                proje_id,
                "ekstra_mesaj":
                "{} adlı kullanıcı, {} id'li proje raporunu güncelledi.".
                format(current_user.username, proje_raporu.id)
            }
            signal_sender(**signal_payload)

            flash(_("Rapor başarıyla güncellendi."))
            DB.session.commit()
        else:
            flash(
                _("Rapor kaydedilemedi. Raporu güncelleyebilmeniz için düzenlenebilir olması gerekir"
                  ))

        return redirect(
            url_for('proje.proje_rapor_index_get', proje_id=proje_id))

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_raporlari_silme"]),
            Or(ProjeYurutucusu(), Role('BAP Yetkilisi'), Role("BAP Admin"))))
    @route("<int:proje_id>/rapor/<int:rapor_id>/sil",
           methods=["GET"],
           endpoint="proje_rapor_dosyasi_sil")
    def rapor_dosyasi_sil(self, proje_id, rapor_id):  # pylint: disable=R0201
        """
            Proje raporunu silmek icin kullanilir
        """
        rapor = DB.session.query(ProjeRapor).filter(
            ProjeRapor.proje_id == proje_id, ProjeRapor.id == rapor_id).one()

        rapor.file_id = None
        DB.session.commit()

        signal_payload = {
            "message_type":
            USER_ACTIVITY_MESSAGES.get("bap").get(
                "proje_rapor_dosyasi_sil").type_index,
            "nesne":
            'Proje Rapor',
            "nesne_id":
            rapor.id,
            "etkilenen_nesne":
            "Proje",
            "etkilenen_nesne_id":
            proje_id,
            "ekstra_mesaj":
            "{} adlı kullanıcı, {} id'li proje raporunun dosyasini kaldırdı.".
            format(current_user.username, rapor_id)
        }
        signal_sender(**signal_payload)
        flash(_("Rapor dosyası başarıyla kaldırıldı."))
        return redirect(
            url_for('proje.proje_rapor_index_get', proje_id=proje_id))

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_raporlari_duzenleme"]),
            Or(Role('BAP Yetkilisi'), Role("BAP Admin"))))
    @route("<int:proje_id>/rapor/<int:rapor_id>/duzenlenebilir_mi",
           methods=["GET"],
           endpoint="proje_rapor_duzenlenebilir_mi")
    def duzenlenebilir_mi(self, proje_id, rapor_id):  # pylint: disable=R0201
        """
            Proje raporunun duzenlenebilirligini degistirmek icin kullanilir
        """
        rapor = DB.session.query(ProjeRapor).filter(
            ProjeRapor.proje_id == proje_id, ProjeRapor.id == rapor_id).one()
        rapor.duzenlenebilir_mi = not rapor.duzenlenebilir_mi
        DB.session.commit()
        signal_payload = {
            "message_type":
            USER_ACTIVITY_MESSAGES.get("bap").get(
                "proje_raporu_duzenlenebilir").type_index,
            "nesne":
            'Proje Rapor',
            "nesne_id":
            rapor.id,
            "ekstra_mesaj":
            "{} adlı kullanıcı, {} id'li proje raporunu düzenlenebilir "
            "yaptı.".format(current_user.username, rapor.id)
        }
        signal_sender(**signal_payload)
        if rapor.duzenlenebilir_mi:
            flash(_("Seçtiğiniz rapor artık düzenlenebilir."))
        else:
            flash(_("Seçtiğiniz raporun düzenlenebilirliğini kaldırdınız."))
        return redirect(
            url_for('proje.proje_rapor_index_get', proje_id=proje_id))

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_raporlari_duzenleme"]),
            Or(ProjeYurutucusu(), Role('BAP Yetkilisi'), Role("BAP Admin"))))
    @route("<int:proje_id>/rapor-olustur/",
           methods=["POST"],
           endpoint='yeni_rapor_ekle')
    def yeni_rapor_ekle(self, proje_id):  # pylint: disable=R0201
        """
            Projeye yeni rapor eklemek icin kullanilir
        """
        ara_rapor_mu = request.args.get("ara_rapor_mu")
        rapor_form = RaporForm(request.form)

        # todo: monkey patch
        rapor_tipi = ProjeRaporTipi.ara_rapor if ara_rapor_mu == 'true' else ProjeRaporTipi.sonuc_raporu
        rapor_durumu = ProjeRaporDurumu.tamamlandi if rapor_form.tamamlandi_mi.data else ProjeRaporDurumu.tamamlanmadi
        duzenlenebilir_mi = False if rapor_durumu == ProjeRaporDurumu.tamamlandi else True

        yeni_rapor = ProjeRapor(rapor_tipi=rapor_tipi,
                                proje_id=proje_id,
                                file_id=rapor_form.rapor_dosya.data,
                                rapor_icerigi=rapor_form.rapor_metni.data,
                                durumu=rapor_durumu,
                                duzenlenebilir_mi=duzenlenebilir_mi)
        DB.session.add(yeni_rapor)
        DB.session.commit()
        signal_payload = {
            "message_type":
            USER_ACTIVITY_MESSAGES.get("bap").get(
                "proje_raporu_eklendi").type_index,
            "nesne":
            'Proje Rapor',
            "nesne_id":
            yeni_rapor.id,
            "etkilenen_nesne":
            "Proje",
            "etkilenen_nesne_id":
            proje_id,
            "ekstra_mesaj":
            "{} adlı kullanıcı, {} id'li proje raporu {} id'li projeye "
            "ekledi.".format(current_user.username, yeni_rapor.id, proje_id)
        }
        signal_sender(**signal_payload)

        flash(_("Rapor başarıyla projeye eklendi."))

        return redirect(
            url_for('proje.proje_rapor_index_get', proje_id=proje_id))

    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["dashboard"]
                       ["proje_raporlari_goruntuleme"]),
            Or(ProjeYurutucusu(), Role('BAP Yetkilisi'), Role("BAP Admin"),
               AtanmisHakem())))
    @route('<int:proje_id>/rapor/<int:rapor_id>', methods=["GET"])
    def get_single_proje_rapor(self, proje_id, rapor_id):
        """Projenin belirli bir raporunu almak icin kullanilir"""

        proje_rapor = DB.session.query(ProjeRapor).filter(
            ProjeRapor.proje_id == proje_id, ProjeRapor.id == rapor_id).one()

        return jsonify(status="success",
                       rapor={"rapor_metni": proje_rapor.rapor_icerigi})
Example #22
0
def test_AndConditional_defaults(always):
    Cond = And(always)

    assert (Cond.requirements, Cond.op, Cond.until, Cond.negated) == \
        ((always,), operator.and_, False, None)
Example #23
0
    def post(self, forum_id, slug=None):  # noqa: C901
        forum_instance, __ = Forum.get_forum(forum_id=forum_id,
                                             user=real(current_user))
        mod_forum_url = url_for("forum.manage_forum",
                                forum_id=forum_instance.id,
                                slug=forum_instance.slug)

        ids = request.form.getlist("rowid")
        tmp_topics = Topic.query.filter(Topic.id.in_(ids)).all()

        if not len(tmp_topics) > 0:
            flash(
                _("In order to perform this action you have to select at "
                  "least one topic."), "danger")
            return redirect(mod_forum_url)

        # locking/unlocking
        if "lock" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action="locked",
                                      reverse=False)

            flash(_("%(count)s topics locked.", count=changed), "success")
            return redirect(mod_forum_url)

        elif "unlock" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action="locked",
                                      reverse=True)
            flash(_("%(count)s topics unlocked.", count=changed), "success")
            return redirect(mod_forum_url)

        # highlighting/trivializing
        elif "highlight" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action="important",
                                      reverse=False)
            flash(_("%(count)s topics highlighted.", count=changed), "success")
            return redirect(mod_forum_url)

        elif "trivialize" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action="important",
                                      reverse=True)
            flash(_("%(count)s topics trivialized.", count=changed), "success")
            return redirect(mod_forum_url)

        # deleting
        elif "delete" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action="delete",
                                      reverse=False)
            flash(_("%(count)s topics deleted.", count=changed), "success")
            return redirect(mod_forum_url)

        # moving
        elif "move" in request.form:
            new_forum_id = request.form.get("forum")

            if not new_forum_id:
                flash(_("Please choose a new forum for the topics."), "info")
                return redirect(mod_forum_url)

            new_forum = Forum.query.filter_by(id=new_forum_id).first_or_404()
            # check the permission in the current forum and in the new forum

            if not Permission(
                    And(IsAtleastModeratorInForum(forum_id=new_forum_id),
                        IsAtleastModeratorInForum(forum=forum_instance))):
                flash(_("You do not have the permissions to move this topic."),
                      "danger")
                return redirect(mod_forum_url)

            if new_forum.move_topics_to(tmp_topics):
                flash(_("Topics moved."), "success")
            else:
                flash(_("Failed to move topics."), "danger")

            return redirect(mod_forum_url)

        # hiding/unhiding
        elif "hide" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action="hide",
                                      reverse=False)
            flash(_("%(count)s topics hidden.", count=changed), "success")
            return redirect(mod_forum_url)

        elif "unhide" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=real(current_user),
                                      action="unhide",
                                      reverse=False)
            flash(_("%(count)s topics unhidden.", count=changed), "success")
            return redirect(mod_forum_url)

        else:
            flash(_("Unknown action requested"), "danger")
            return redirect(mod_forum_url)
Example #24
0
class EskiProjeler(FlaskView):
    """
    Universitelerin eksi sistemlerinden kalma projelerle ilgili islemlerin yapildigi view
    """
    @staticmethod
    @login_required
    @auth.requires(And(
        Permission(*permission_dict["bap"]["proje"]["proje_arama"]
                   ["eski_projeleri_arama"]),
        Or(Role("BAP Admin"), Role("BAP Yetkilisi"))),
                   menu_registry={
                       "path": ".bap.proje.eski_projeler",
                       "title": _("Eski Projeler")
                   })
    @route('listele', methods=['GET'])
    def eski_projeler_listele():
        """Eski projelerin listelendigi view"""
        # todo: pagination ozelligi eklenmesi gerekiyor.
        return render_template("proje_arama/eski_projeler_listele.html")

    @staticmethod
    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["proje_arama"]
                       ["eski_projeleri_goruntuleme"]),
            Or(Role("BAP Admin"), Role("BAP Yetkilisi"))))
    @route('listele/data', methods=['POST'])
    def eski_projeler_datatable():
        """Eski projeleri Datatable'a gonderir"""
        eski_projeler = DB.session.query(EskiProje)

        dts = DataTableServer(columns={
            0: EskiProje.id,
            1: EskiProje.no,
            2: EskiProje.tipi,
            3: EskiProje.baslik,
            4: EskiProje.yurutucu_adi,
            5: EskiProje.fakulte_ismi,
            6: EskiProje.sure,
            7: EskiProje.butce,
            8: EskiProje.baslama_tarihi
        },
                              qry=eski_projeler)

        eski_projeler = dts.query(request)
        data = [[
            eski_proje.id, eski_proje.no, eski_proje.tipi, eski_proje.baslik,
            eski_proje.yurutucu_adi, eski_proje.fakulte_ismi,
            "{sure} {sure_birimi}".format(
                sure=eski_proje.sure,
                sure_birimi=eski_proje.sure_birimi.value),
            float(eski_proje.butce),
            eski_proje.baslama_tarihi.strftime("%d.%m.%Y")
        ] for eski_proje in eski_projeler.items]

        return jsonify({
            "data": data,
            "recordsFiltered": eski_projeler.total,
            "recordsTotal": eski_projeler.filtered_from
        })
Example #25
0
class ProjeHakemView(FlaskView):
    """Proje hakem önerilerinin ve proje hakemlerinin goruntulendigi view"""

    @login_required
    @auth.requires(
        And(Permission(
            *permission_dict["bap"]["proje"]["dashboard"]["proje_hakemleri_goruntuleme"]),
            Or(Role('BAP Yetkilisi'), Role("BAP Admin"))))
    @route('<int:proje_id>/dashboard/hakem', methods=["GET"], endpoint='proje_hakem_get')
    def proje_hakem_get(self, proje_id):
        """Proje raporlarini goruntulemek icin kullanilir"""

        proje = DB.session.query(Proje).options(
            joinedload(Proje.proje_yurutucu).load_only("id").joinedload(
                OgretimElemani.personel).load_only("id").joinedload(
                Personel.person).load_only("ad", "soyad"),
            lazyload(Proje.proje_detayi),
            lazyload(Proje.kabul_edilen_proje_hakemleri),
            lazyload(Proje.proje_destekleyen_kurulus),
            lazyload(Proje.proje_kalemleri),
        ).filter(Proje.id == proje_id, or_(Proje.proje_basvuru_durumu == ProjeBasvuruDurumu.tamamlandi,
                                           Proje.proje_basvuru_durumu == ProjeBasvuruDurumu.revizyon_bekleniyor)).first()

        next_states_info = get_next_states_info(proje_id=proje_id)
        actions_info = get_actions_info(proje_id=proje_id)
        proje_yurutucusu_mu = ProjeYurutucusu().fulfill(user=current_user)

        proje_hakem_onerileri = proje.proje_hakem_onerileri

        proje_hakemleri = DB.session.query(ProjeHakemleri).options(
            joinedload(ProjeHakemleri.hakem).joinedload("*")
        ).filter(ProjeHakemleri.proje_id == proje_id).all()

        hakem_ekle_form = HakemEkleForm()

        return render_template(
            'dashboard/proje_hakemleri.html',
            proje_id=proje_id,
            proje=proje,
            proje_yurutucusu_mu=proje_yurutucusu_mu,
            next_states_info=next_states_info,
            actions_info=actions_info,
            hakem_onerileri=proje_hakem_onerileri,
            proje_hakemleri=proje_hakemleri,
            hakem_ekle_form=hakem_ekle_form
        )

    @staticmethod
    @login_required
    @auth.requires(
        And(Permission(*permission_dict["bap"]["proje"]["dashboard"]["projeye_hakem_atama"]),
            Or(Role("BAP Yetkilisi"), Role("BAP Admin"))))
    @route('/<int:proje_id>/proje-hakemleri/<int:proje_hakem_id>', methods=['DELETE'])
    def proje_hakem_sil(proje_id, proje_hakem_id):
        """
        Seçilen hakemin projehakem davet durumunu cikarildi olarak degistirir.

        """
        try:

            proje_hakem = DB.session.query(ProjeHakemleri).filter(
                ProjeHakemleri.proje_id == proje_id,
                ProjeHakemleri.id == proje_hakem_id).one()
            proje_hakem.davet_durumu = ProjeHakemDavetDurumlari.cikarildi

            DB.session.commit()
            signal_payload = {
                "message_type": USER_ACTIVITY_MESSAGES.get("bap").get("hakem_atama_sil").type_index,
                "nesne": 'Proje Hakemleri',
                "nesne_id": proje_id,
                "ekstra_mesaj": "{} adlı kullanıcı, {} id'li hakemi proje hakemleri arasindan "
                                "cikardi.".format(current_user.username, proje_hakem_id)
            }
            signal_sender(**signal_payload)

            return jsonify(status="success")
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                                             hata="Proje idsi %s olan proje hakemleri arasından %s idli hakemi çıkarmaya "
                                                  "çalışılırken bir sorun oluştu. Hata: %s" % (
                                                      proje_id, proje_hakem_id, exc)
                                             )
        return jsonify(status="error"), 400

    @staticmethod
    @login_required
    @auth.requires(
        And(Permission(*permission_dict["bap"]["proje"]["dashboard"]["projeye_hakem_atama"]),
            Or(Role("BAP Yetkilisi"), Role("BAP Admin"))))
    @route('/<int:proje_id>/hakem/<int:hakem_id>/ekle', methods=['POST'])
    def proje_hakemi_ekle(proje_id, hakem_id):
        """
        Secilen hakemi proje hakemleri modeline kaydeder.
        Eger daha once kaydedilmemis bir hakem ise ProjeHakem model instance i olusturup kaydeder.
        Daha once projeye hakemlik teklifini reddeden bir hakeme teklif gonderilmis ise "davet_durumu"
        alani "gonderildi" yapilir.
        Eger daha önce projeye atanip proje hakemlerinden cikarilan bir hakemi eklemeye calisirsa
        var olan projehakem kaydini bulup "davet_durumu" alani "gonderildi" yapilir.


        """
        try:
            proje_hakem = DB.session.query(ProjeHakemleri).options(
                joinedload(ProjeHakemleri.hakem).joinedload(Hakem.person),
                joinedload(ProjeHakemleri.hakem).joinedload(Hakem.personel)
            ).filter(
                ProjeHakemleri.hakem_id == hakem_id,
                ProjeHakemleri.proje_id == proje_id).scalar()
            proje = DB.session.query(Proje.proje_no.label("proje_no")).filter(Proje.id == proje_id).first()
            if proje_hakem:
                if proje_hakem.davet_durumu == ProjeHakemDavetDurumlari.gonderildi:
                    # davet durumu gonderildi durumunda ise yani hakem daveti yanıtlamadıysa
                    # bu durum gecerlidir.
                    return jsonify(status="error",
                                   error_message=_("Bu hakeme zaten davet gönderildi")), 409
                elif proje_hakem.davet_durumu == ProjeHakemDavetDurumlari.kabul_edildi:
                    return jsonify(status="error",
                                   error_message=_("Bu kişi zaten proje hakemi")), 409

                else:
                    # daveti kabul etmeyen veya projeden cikarilan hakem durumlari icin gecerlidir
                    proje_hakem.davet_durumu = ProjeHakemDavetDurumlari.gonderildi
                # eger proje_hakem i var ise daha once bu hakeme teklif gonderilmis ve herhangi bir
                # "davet_durumu" stateinde olabilir.
                hakem_person_id = proje_hakem.hakem.personel.person_id if proje_hakem.hakem.personel else proje_hakem.hakem.person_id
            else:
                hakem = DB.session.query(Hakem).options(
                    joinedload(Hakem.person),
                    joinedload(Hakem.personel)
                ).filter(Hakem.id == hakem_id).first()
                # daha once bu hakem proje ile iliskilendirilmemis.
                yeni_hakem = ProjeHakemleri(proje_id=proje_id, hakem_id=hakem_id)
                DB.session.add(yeni_hakem)
                hakem_person_id = hakem.personel.person_id if hakem.personel else hakem.person_id

            payload = {
                "notification_receiver": hakem_person_id,
                "notification_title": "Proje Hakemlik Daveti",
                "notification_message": "{} numaralı projeye hakem olmanız için davet gönderildi.".format(
                    proje.proje_no),
                "proje_id": proje_id,
            }

            signal_sender(log=False, notification=True, **payload)

            DB.session.commit()
            signal_payload = {
                "message_type": USER_ACTIVITY_MESSAGES.get("bap").get("hakem_atama").type_index,
                "nesne": 'Proje Hakemleri',
                "nesne_id": proje_id,
                "ekstra_mesaj": "{} adlı kullanıcı, {} id'li hakeme hakemlik daveti gonderidi.".format(
                    current_user.username,
                    hakem_id
                )
            }
            signal_sender(**signal_payload)

            return jsonify(status="success")
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                                             hata="Proje idsi %s olan projeye hakem eklemeye çalışılırken bir sorun oluştu. Hata: %s"
                                                  % (proje_id, exc)
                                             )
        return jsonify(status="error", error_message=_(
            "Beklenmedik bir hata oluştur. Lütfen daha sonra tekrar deneyiniz")), 409
Example #26
0
class HakemOneriView(FlaskView):
    """Hakem Oneri View Class"""

    @staticmethod
    @login_required
    @auth.requires(
        And(Permission(*permission_dict["bap"]["proje"]["hakem"]["projeye_hakem_onerme"]),
            ProjeYurutucusu(), TamamlanmamisProjeBasvurusu()))
    @route('/<int:proje_id>/hakem-oner/', methods=['POST'])
    def hakem_oner(proje_id):
        """
        Ad, Soyad ve email ile önerilen kişileri HakemOneri modeline kaydeder.

        Projenin belirli bir hakem limiti vardır.Bunlar kontrol edilip kaydedilir.
        Limite ulaşılmış ise hata dönülür
        Returns:

        """
        adi = request.get_json().get('ad')
        soyad = request.get_json().get('soyad')
        email = request.get_json().get('email')
        ogretim_elemani_id = request.get_json().get("ogretim_elemani_id")
        try:
            try:
                proje = DB.session.query(Proje).filter_by(id=proje_id).one()
                proje_turu = DB.session.query(ProjeTuru).filter_by(id=proje.proje_turu).one()
            except NoResultFound as exc:
                CustomErrorHandler.error_handler(
                    hata="Var Olmayan bir proje_turu_id veya proje_id ile hakem onerisi eklenmeye "
                    "çalışıldı. Hata: {}".format(exc))
                return abort(400)
            if not proje_turu.hakem_onerilsin_mi:
                # todo: bu projeye hakem onerilemez hatası dön
                pass
            if ogretim_elemani_id:
                try:
                    onerilen_hakemlerde_var_mi = DB.session.query(HakemOneri).filter_by(
                        proje_id=proje_id, ogretim_elemani_id=ogretim_elemani_id).first()
                    if onerilen_hakemlerde_var_mi:
                        return abort(400)
                    ogretim_elemani = DB.session.query(OgretimElemani).filter_by(
                        id=ogretim_elemani_id).one()
                    hakem_onerisi = HakemOneri(proje_id=proje_id,
                                               ogretim_elemani_id=ogretim_elemani_id)
                    DB.session.add(hakem_onerisi)
                    DB.session.commit()
                    signal_payload = {
                        "message_type": USER_ACTIVITY_MESSAGES.get("bap").get(
                            "oe_hakem_onerildi").type_index,
                        "nesne": 'Hakem Oneri',
                        "nesne_id": ogretim_elemani_id,
                        "etkilenen_nesne": "Proje",
                        "etkilenen_nesne_id": proje_id,
                        "ekstra_mesaj": "{} adlı kullanıcı, {} {} öğretim elemanını hakem olarak "
                                        "önerdi.".format(current_user.username, adi, soyad)
                    }
                    signal_sender(**signal_payload)
                    person = ogretim_elemani.person
                    return jsonify(status="success",
                                   hakemOneriData={
                                       "id": hakem_onerisi.id,
                                       "ad": person.ad,
                                       "soyad": person.soyad,
                                       "email": person.birincil_eposta or person.ikincil_eposta})
                except NoResultFound as exc:
                    DB.session.rollback()
                    CustomErrorHandler.error_handler(
                                                     hata="Var Olmayan bir ogretim_elemani_id ile hakem onerisi eklenmeye "
                                                          "çalışıldı. Hata: {}".format(exc)
                                                     )
                    return jsonify(status="error"), 400
            else:
                hakem_onerisi = HakemOneri(proje_id=proje_id,
                                           ad=adi,
                                           soyad=soyad,
                                           email=email)
                DB.session.add(hakem_onerisi)
                DB.session.commit()
                signal_payload = {
                    "message_type": USER_ACTIVITY_MESSAGES.get("bap").get(
                        "kisi_hakem_onerildi").type_index,
                    "nesne": 'Hakem Oneri',
                    "nesne_id": ogretim_elemani_id,
                    "etkilenen_nesne": "Proje",
                    "etkilenen_nesne_id": proje_id,
                    "ekstra_mesaj": "{} adlı kullanıcı, {} {} kişiyi hakem olarak önerdi.".format(
                        current_user.username,
                        adi, soyad)
                }
                signal_sender(**signal_payload)
                return jsonify(status="success", hakemOneriData={"id": hakem_onerisi.id,
                                                                 "ad": adi,
                                                                 "soyad": soyad,
                                                                 "email": email})
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                                             hata="Proje idsi %s olan projeye hakem önerisi eklemeye"
                                                  "çalışılırken bir sorun oluştu. Hata: %s" % (
                                                      proje_id, exc)
                                             )
        return jsonify(status="error"), 400

    @staticmethod
    @login_required
    @auth.requires(
        And(Permission(*permission_dict["bap"]["proje"]["hakem"]["projeye_hakem_onerme"]),
            ProjeYurutucusu(), TamamlanmamisProjeBasvurusu()))
    @route('/<int:proje_id>/hakem-oneri-sil/<int:oneri_id>', methods=['DELETE'])
    def hakem_oneri_sil(proje_id, oneri_id):
        """
        Daha önce proje için önerilip kaydedilmiş hakem önerisini siler
        """
        try:
            silinecek_oneri = DB.session.query(HakemOneri).filter_by(
                id=oneri_id, proje_id=proje_id).first()
            DB.session.delete(silinecek_oneri)
            DB.session.commit()
            signal_payload = {
                "message_type": USER_ACTIVITY_MESSAGES.get("bap").get(
                    "hakem_onerisi_kaldirildi").type_index,
                "nesne": 'Hakem Oneri',
                "nesne_id": oneri_id,
                "etkilenen_nesne": "Proje",
                "etkilenen_nesne_id": proje_id,
                "ekstra_mesaj": "{} adlı kullanıcı, {} {} kişiyi hakem önerilerinden "
                                "kaldırdı.".format(current_user.username,
                                                   silinecek_oneri.ad, silinecek_oneri.soyad)
            }
            signal_sender(**signal_payload)
            return jsonify(status="success")
        except SQLAlchemyError as exc:
            DB.session.rollback()
            CustomErrorHandler.error_handler(
                                             hata="Proje idsi %s olan projeye hakem önerisi silinmeye"
                                                  "çalışılırken bir sorun oluştu. Hata: %s" % (
                                                      proje_id, exc)
                                             )
        return jsonify(status="error"), 400
Example #27
0
def manage_forum(forum_id, slug=None):
    page = request.args.get('page', 1, type=int)

    forum_instance, forumsread = Forum.get_forum(forum_id=forum_id,
                                                 user=current_user)

    # remove the current forum from the select field (move).
    available_forums = Forum.query.order_by(Forum.position).all()
    available_forums.remove(forum_instance)

    if not Permission(IsAtleastModeratorInForum(forum=forum_instance)):
        flash(_("You do not have the permissions to moderate this forum."),
              "danger")
        return redirect(forum_instance.url)

    if forum_instance.external:
        return redirect(forum_instance.external)

    topics = Forum.get_topics(forum_id=forum_instance.id,
                              user=current_user,
                              page=page,
                              per_page=flaskbb_config["TOPICS_PER_PAGE"])

    mod_forum_url = url_for("forum.manage_forum",
                            forum_id=forum_instance.id,
                            slug=forum_instance.slug)

    # the code is kind of the same here but it somehow still looks cleaner than
    # doin some magic
    if request.method == "POST":
        ids = request.form.getlist("rowid")
        tmp_topics = Topic.query.filter(Topic.id.in_(ids)).all()

        if not len(tmp_topics) > 0:
            flash(
                _("In order to perform this action you have to select at "
                  "least one topic."), "danger")
            return redirect(mod_forum_url)

        # locking/unlocking
        if "lock" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=current_user,
                                      action="locked",
                                      reverse=False)

            flash(_("%(count)s topics locked.", count=changed), "success")
            return redirect(mod_forum_url)

        elif "unlock" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=current_user,
                                      action="locked",
                                      reverse=True)
            flash(_("%(count)s topics unlocked.", count=changed), "success")
            return redirect(mod_forum_url)

        # highlighting/trivializing
        elif "highlight" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=current_user,
                                      action="important",
                                      reverse=False)
            flash(_("%(count)s topics highlighted.", count=changed), "success")
            return redirect(mod_forum_url)

        elif "trivialize" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=current_user,
                                      action="important",
                                      reverse=True)
            flash(_("%(count)s topics trivialized.", count=changed), "success")
            return redirect(mod_forum_url)

        # deleting
        elif "delete" in request.form:
            changed = do_topic_action(topics=tmp_topics,
                                      user=current_user,
                                      action="delete",
                                      reverse=False)
            flash(_("%(count)s topics deleted.", count=changed), "success")
            return redirect(mod_forum_url)

        # moving
        elif "move" in request.form:
            new_forum_id = request.form.get("forum")

            if not new_forum_id:
                flash(_("Please choose a new forum for the topics."), "info")
                return redirect(mod_forum_url)

            new_forum = Forum.query.filter_by(id=new_forum_id).first_or_404()
            # check the permission in the current forum and in the new forum

            if not Permission(
                    And(IsAtleastModeratorInForum(forum_id=new_forum_id),
                        IsAtleastModeratorInForum(forum=forum_instance))):
                flash(_("You do not have the permissions to move this topic."),
                      "danger")
                return redirect(mod_forum_url)

            new_forum.move_topics_to(tmp_topics)
            return redirect(mod_forum_url)

    return render_template(
        "forum/edit_forum.html",
        forum=forum_instance,
        topics=topics,
        available_forums=available_forums,
        forumsread=forumsread,
    )
Example #28
0
        if not current_forum:
            raise FlaskPetError("Could not load forum data")

        forum_groups = {g.id for g in current_forum.groups}
        user_groups = {g.id for g in user.groups}
        return bool(forum_groups & user_groups)


def IsAtleastModeratorInForum(forum_id=None, forum=None):
    return Or(
        IsAtleastSuperModerator,
        IsModeratorInForum(forum_id=forum_id, forum=forum),
    )


IsMod = And(IsAuthed(), Has("mod"))
IsSuperMod = And(IsAuthed(), Has("super_mod"))
IsAdmin = And(IsAuthed(), Has("admin"))

IsAtleastModerator = Or(IsAdmin, IsSuperMod, IsMod)

IsAtleastSuperModerator = Or(IsAdmin, IsSuperMod)

CanBanUser = Or(IsAtleastSuperModerator, Has("mod_banuser"))

CanEditUser = Or(IsAtleastSuperModerator, Has("mod_edituser"))

CanEditPost = Or(
    IsAtleastSuperModerator,
    And(IsModeratorInForum(), Has("editpost")),
    And(CanAccessForum(), IsSameUser(), Has("editpost"), TopicNotLocked()),
Example #29
0
class ProjeMesajView(FlaskView):
    """Proje mesajlari"""
    @staticmethod
    @login_required
    @auth.requires(
        Or(
            And(
                Permission(*permission_dict["bap"]["proje"]
                           ["dashboard"]["proje_mesajlari_goruntuleme"]),
                ProjeYurutucusu()), Role("BAP Yetkilisi"), Role("BAP Admin")))
    @route('<int:proje_id>/dashboard/mesaj',
           methods=["GET"],
           endpoint='proje_mesajlari')
    def proje_mesajlari(proje_id):
        """Proje mesajlarini gosterir"""
        proje_yurutucusu_mu = ProjeYurutucusu().fulfill(user=current_user)
        proje = DB.session.query(Proje).options(
            joinedload(Proje.proje_yurutucu).load_only("id").joinedload(
                OgretimElemani.personel).load_only("id").joinedload(
                    Personel.person).load_only("ad", "soyad"),
            lazyload(Proje.proje_detayi),
            lazyload(Proje.kabul_edilen_proje_hakemleri),
            lazyload(Proje.proje_hakem_onerileri),
            lazyload(Proje.proje_destekleyen_kurulus),
            lazyload(Proje.proje_kalemleri),
        ).filter(
            Proje.id == proje_id,
            or_(
                Proje.proje_basvuru_durumu == ProjeBasvuruDurumu.tamamlandi,
                Proje.proje_basvuru_durumu ==
                ProjeBasvuruDurumu.revizyon_bekleniyor)).first()

        next_states_info = get_next_states_info(proje_id=proje_id)
        actions_info = get_actions_info(proje_id=proje_id)

        proje_mesajlari = DB.session.query(Mesaj).join(
            ProjeMesaj, ProjeMesaj.mesaj_id == Mesaj.id).filter(
                ProjeMesaj.proje_id == proje_id).all()

        return render_template('dashboard/proje_mesajlari.html',
                               proje_id=proje_id,
                               next_states_info=next_states_info,
                               proje_mesajlari=proje_mesajlari,
                               proje_yurutucusu_mu=proje_yurutucusu_mu,
                               actions_info=actions_info,
                               proje=proje)

    @staticmethod
    @login_required
    @auth.requires(
        Or(
            And(
                Permission(*permission_dict["bap"]["proje"]
                           ["dashboard"]["proje_mesajlari_goruntuleme"]),
                ProjeYurutucusu()), Role("BAP Yetkilisi"), Role("BAP Admin")))
    @route('<int:proje_id>/dashboard/mesaj/<int:mesaj_id>',
           methods=["GET"],
           endpoint='proje_mesaj_detay')
    def proje_mesaj_detay(proje_id, mesaj_id):
        """ Gelen kutusuna dusen mesajlarin, icerigini, kimden geldigini vs. gosterir."""
        mesaj = DB.session.query(Mesaj).filter_by(id=mesaj_id).options(
            joinedload(Mesaj.gonderen_kisi).load_only(
                'ad', 'soyad', 'birincil_eposta')).one()
        if not mesaj.okundu:
            mesaj.okundu = True
            mesaj.okunma_zamani = datetime.now()
            okunma_tarihi = datetime.now().strftime('%d-%m-%Y')
            okunma_ip_adresi = request.remote_addr
            mesaj.okunma_ip_adresi = request.remote_addr
            DB.session.commit()
        else:
            okunma_tarihi = mesaj.okunma_zamani.strftime('%d-%m-%Y')
            okunma_ip_adresi = mesaj.okunma_ip_adresi

        signal_payload = {
            "message_type":
            USER_ACTIVITY_MESSAGES.get("common").get(
                "mesaj_okundu").type_index,
            "nesne":
            'Mesaj',
            "nesne_id":
            mesaj_id,
            "ekstra_mesaj":
            "{} adlı kullanıcı {} id'li mesajı okudu.".format(
                current_user.username, mesaj_id)
        }
        signal_sender(**signal_payload)
        mesaj_detay = {
            'gonderim_tarihi':
            mesaj.gonderim_zamani.strftime('%d-%m-%Y'),
            'okunma_tarihi':
            okunma_tarihi,
            'okunma_ip_adresi':
            okunma_ip_adresi,
            'gonderen_kisi_ad_soyad':
            mesaj.gonderen_kisi.ad + " " + mesaj.gonderen_kisi.soyad,
            'gonderen_kisi_birincil_eposta':
            mesaj.gonderen_kisi.birincil_eposta,
            'baslik':
            mesaj.baslik,
            'metin':
            mesaj.metin,
            'mesaj_ek':
            render_template_string("""
                       <ul class="attached-document clearfix">
                            {% for ek in mesaj_ek %}
                                {% if ek.belge_r.content %}
                                    <li>
                                        <div class="document-name">
                                         <form method="post">
                                                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
                                            <button class="btn btn-link" id="ek_{{ ek.belge }}" name="ek_{{ ek.belge }}"
                                                            value="{{ ek.belge }}" style="white-space: normal;"
                                                            formaction="{{ url_for('mesaj.mesaj_ek', 
                                                                                    mesaj_id=mesaj_id, 
                                                                                    belge_id= ek.belge ) }}">
                                               {{ ek.belge_r.content.file.filename }}
                                                    </button>
                                               </form>
                                        </div>
                                    </li>
                                {% endif %}
                            {% endfor %}
                        </ul>""",
                                   mesaj_ek=mesaj.mesajek,
                                   mesaj_id=mesaj_id)
        }

        return jsonify(status="success",
                       mesaj=mesaj_detay,
                       mesaj_id=int(mesaj_id))
Example #30
0
class ProjeBasvuruView(FlaskView):
    """Proje başvurusu view classı"""

    excluded_methods = [
        "basvuru_formu_restriction", "proje_diger_dosya_kaydet",
        "proje_ek_dosyalar_kaydet", "yurutucu_kaydet", "butce_kaydet"
    ]

    @staticmethod
    @login_required
    @auth.requires(Permission(
        *permission_dict["bap"]["proje"]["basvuru"]["proje_basvurusu_yapma"]),
                   menu_registry={
                       "path": ".bap.yeni_basvuru",
                       "title": _("Proje Başvuru"),
                       "order": 0
                   })
    @route('/yeni-basvuru', methods=['GET'])
    def basvuru_icin_proje_turu_sec():
        """Proje başvurusu yapabilmek için başvuracağımız proje türünü seçmek için kullanırız"""
        proje_turleri = DB.session.query(ProjeTuru).filter_by(
            basvuru_aktif_mi=True,
            guncel_mi=True).order_by(desc(ProjeTuru.updated_at)).all()
        return render_template(
            'arastirma_projesi_basvuru/proje_basvuru_sec.html',
            proje_turleri=proje_turleri)

    @staticmethod
    @login_required
    @auth.requires(
        Permission(*permission_dict["bap"]["proje"]["basvuru"]
                   ["proje_basvurusu_yapma"]))
    @route('/yeni-basvuru/tur/<int:tur_id>',
           methods=['GET'],
           endpoint='proje_yeni_basvuru')
    def yeni_basvuru(tur_id):
        """Yeni proje başvurusu formları"""
        user_id = current_user.id
        try:
            p_tur = DB.session.query(ProjeTuru).filter_by(
                id=tur_id, basvuru_aktif_mi=True, guncel_mi=True).one()
        except NoResultFound as exc:
            CustomErrorHandler.error_handler(
                hata="Güncel olmayan veya var olmayan bir proje türü ile proje "
                "basvurusu yapılmaya çalışıldı. Hata: {}, User id: {}, "
                "Proje turu id: {}".format(exc, user_id, tur_id))
            return abort(404)

        proje_tur_dict = proje_turu_to_dict(p_tur)

        # basvuruyu yapan ogretim elamanininin id sini getirir
        ogretim_elemani = DB.session.query(
            OgretimElemani.id.label("ogretim_elemani_id")).join(
                Personel, OgretimElemani.personel_id == Personel.id).join(
                    Person, Personel.person_id == Person.id).filter(
                        Person.user_id == current_user.id).one()
        yurutucu_id = ogretim_elemani.ogretim_elemani_id

        yeni_basvuru_formu = basvuru_formu_restriction(proje_tur_dict)
        yeni_basvuru_formu.proje_personeli.yurutucu.yurutucu_id.data = yurutucu_id

        yeni_proje = Proje(proje_turu=p_tur.id,
                           proje_turu_numarasi=p_tur.tur_kodu,
                           yurutucu=yurutucu_id,
                           user_id=user_id)
        DB.session.add(yeni_proje)
        DB.session.flush()
        proje_no = "{}{}".format(date.today().year, yeni_proje.id)
        yeni_proje.proje_no = proje_no
        # proje_basvuru_durumu=ProjeBasvuruDurumu.taslak
        DB.session.commit()
        signal_payload = {
            "message_type":
            USER_ACTIVITY_MESSAGES.get("bap").get(
                "proje_basvuru_basla").type_index,
            "nesne":
            'Proje',
            "nesne_id":
            yeni_proje.id,
            "ekstra_mesaj":
            "{} adlı kullanıcı, {} kategorisine proje başvuru islemine "
            "basladi.".format(current_user.username, p_tur.kategori)
        }
        signal_sender(**signal_payload)
        # yeni_basvuru_formu.proje_id.data = yeni_proje.id

        return render_template(
            'arastirma_projesi_basvuru/arastirma_proje_basvurusu.html',
            yeni_basvuru_formu=yeni_basvuru_formu,
            proje_tur_dict=proje_tur_dict,
            proje_id=yeni_proje.id,
            revizyon_bekleniyor_mu=False,
            uyari_mesajlari=proje_tur_dict.get("genel_uyari_mesajlari", None))

    @staticmethod
    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["basvuru"]
                       ["proje_basvurusu_yapma"]), ProjeYurutucusu(),
            TamamlanmamisProjeBasvurusu()))
    @route('/proje/<int:proje_id>/kaydet',
           methods=['POST'],
           endpoint='yeni_proje_kaydet')
    def proje_kaydet(proje_id):
        """
        Proje başvurusunun taslak olarak kaydedilmedi kaydedilen taslağın güncellenmesi ve
        başvurunun tamamlanıp sonuçlandırılması işini yapar
        """
        taslak_mi = request.args.get("taslak_mi", False)
        user_id = current_user.id
        form_data = request.form

        proje_turu_id = form_data.get("proje_turu")
        try:
            proje_turu = get_proje_turu_with_related_field(proje_turu_id)
        except NoResultFound as exc:
            CustomErrorHandler.error_handler(
                hata="Güncel olmayan veya var olmayan bir proje türü id si ile "
                "başvuru yapılmaya çalışıldı. Hata: {}, User id: {}, "
                "Proje Turu id: {}".format(exc, user_id, proje_turu_id))
            return abort(404)

        proje_tur_dict = proje_turu_to_dict(proje_turu)

        proje_formu = basvuru_formu_restriction(initial_form_data=form_data,
                                                proje_turu_dict=proje_tur_dict)
        proje = DB.session.query(Proje).filter_by(id=proje_id).one()
        revizyon_bekleniyor_mu = True if proje.proje_basvuru_durumu == ProjeBasvuruDurumu.revizyon_bekleniyor else False

        if not taslak_mi and not proje_formu.validate():
            hata_listesi = set()

            form_errors_dict_to_set(proje_formu.errors, hata_listesi)
            proje_formu.proje_personeli.yurutucu.yurutucu_id.data = proje.yurutucu
            return render_template(
                'arastirma_projesi_basvuru/arastirma_proje_basvurusu.html',
                yeni_basvuru_formu=proje_formu,
                proje_tur_dict=proje_turu.to_dict(),
                proje_id=proje_id,
                proje_hakem_onerileri=proje.proje_hakem_onerileri,
                proje_calisanlari=[
                    calisan for calisan in proje.proje_calisanlari
                    if not (proje.yurutucu
                            and proje.yurutucu == calisan.personel_id)
                ],
                taslak_mi=taslak_mi,
                revizyon_bekleniyor_mu=revizyon_bekleniyor_mu,
                hata_mesajlari=hata_listesi)
        try:
            form_genel = proje_formu.genel_bilgiler
            proje.update_obj_data(form_genel.genel_bilgiler.data)
            proje.update_obj_data(form_genel.fakulte.data)
            proje.update_obj_data(form_genel.ozet_bilgiler.data)
            proje.onaylayan_yetkili_id = form_genel.onaylayan_yetkili.onaylayan_yetkili_id.data
            proje.onay_tarihi = form_genel.onaylayan_yetkili.onay_tarihi.data

            toplam_katki = Decimal(0)

            # yürütücü kaydeder
            # yurutucu calisan olarak kaydedilmis ise gerekli veriyi getirir
            yurutucu_calisan = DB.session.query(ProjeCalisanlari).filter_by(
                proje_id=proje_id,
                personel_id=proje.proje_yurutucu.personel_id).first()
            if not yurutucu_calisan:
                yurutucu_kaydet(proje_id, proje_tur_dict,
                                proje_formu.proje_personeli.yurutucu,
                                proje.yurutucu, taslak_mi)
            else:
                yurutucu = DB.session.query(ProjeCalisanlari).filter_by(
                    proje_id=proje_id,
                    personel_id=proje.proje_yurutucu.personel_id).first()
                yurutucu.update_obj_data(
                    proje_formu.proje_personeli.yurutucu.data)

            # destekleyen kuruluş kaydeder
            if proje.proje_destekleyen_kurulus:

                proje.proje_destekleyen_kurulus.update_obj_data(
                    form_genel.destekleyen_kurulus.data)
            else:
                proje_destekleyen_kurulus = ProjeDestekleyenKurulus(
                    proje_id=proje.id, **form_genel.destekleyen_kurulus.data)
                DB.session.add(proje_destekleyen_kurulus)

            # proje formu diger alanlarını kaydeder
            if proje_formu.diger:
                # proje basvurusu için ek dosyalari kaydeder
                proje_ek_dosyalar_kaydet(user_id, proje_id,
                                         proje_formu.diger.ek_dosyalar,
                                         proje.proje_belgeleri, taslak_mi)

                # proje basvurusu için diğer dosyaları kaydeder
                var_olan_dosyalar = []
                if proje_formu.diger.proje_diger:
                    var_olan_dosyalar = proje_diger_dosya_kaydet(
                        user_id, proje_id, proje_formu.diger.proje_diger,
                        proje.proje_belgeleri)

                for dosya in proje.proje_belgeleri:
                    if dosya.id not in var_olan_dosyalar and not dosya.proje_turu_ek_dosya_id:
                        DB.session.delete(dosya)
            # proje basvurusu butce alanlarini kaydeder
            for proje_kalemi in proje.proje_kalemleri:
                DB.session.delete(proje_kalemi)
            DB.session.flush()
            onerilen_proje_butcesi, butce_hatalari = butce_kaydet(
                proje_id, proje_formu.butce.data)
            proje.teklif_edilen_butce = onerilen_proje_butcesi

            # proje başvurusu tamamlanmaya çalışılıyorsa gerekli kontroller yapılır
            if not taslak_mi:
                # proje turunden gelen proje sure alt ve ust limitleri
                sure_alt_limiti = proje_tur_dict.get("sure_alt_limiti")
                sure_ust_limiti = proje_tur_dict.get("sure_ust_limiti")
                sure_birimi = proje_tur_dict.get("sure_birimi")

                # karsilastirma yapabilmek icin teklif edilen, sure alt limitini ve sure ust
                # limitini gun cinsine ceviriyoruz
                min_sure = month_year_to_day(sure_alt_limiti, sure_birimi)
                max_sure = month_year_to_day(sure_ust_limiti, sure_birimi)
                teklif_edilen_proje_suresi = month_year_to_day(
                    proje_formu.genel_bilgiler.genel_bilgiler.proje_suresi.
                    data, proje_formu.genel_bilgiler.genel_bilgiler.
                    proje_suresi_birimi.data)

                if teklif_edilen_proje_suresi < min_sure or teklif_edilen_proje_suresi > max_sure:
                    flash(
                        _("Proje süreniz {} ile {} {} arasında olabilir".
                          format(sure_alt_limiti, sure_ust_limiti,
                                 sure_birimi)), "error")

                if proje.teklif_edilen_butce:
                    if proje_turu.butce.butce_alt_limiti > proje.teklif_edilen_butce:
                        flash(
                            _("Proje bütçeniz en az {} TL olabilir".format(
                                proje_turu.butce.butce_alt_limiti)), "error")
                    elif proje_turu.butce.butce_ust_limiti < proje.teklif_edilen_butce:
                        flash(
                            _("Proje bütçeniz en fazla {} TL olabilir".format(
                                proje_turu.butce.butce_ust_limiti)), "error")

                for calisan in proje.proje_calisanlari:
                    toplam_katki += Decimal(
                        calisan.projeye_katkisi
                    ) if calisan.projeye_katkisi else Decimal(0)
                    if proje_tur_dict.get("ozgecmis_yuklenmesi_zorunlu_mu"):
                        if calisan.ozgecmis.file_id is None and not calisan.ozgecmis.tecrube:
                            flash(
                                _("Proje personeli İçin Özgeçmiş Yüklemeniz Zorunludur"
                                  ), "error")
                            break
                    zorunlu_banka_bilgileri = proje_tur_dict.get(
                        "banka_bilgilerini_girmek_zorunlu_mu")
                    if zorunlu_banka_bilgileri and not calisan.banka_bilgisi:
                        flash(
                            _("Proje personeli İçin Banka Bilgileri Girilmesi Zorunludur"
                              ), "error")
                        break

                if proje_tur_dict.get("hakem_onerilsin_mi", None):
                    basvuru_hakem_oneri_sayisi = proje_tur_dict.get(
                        "basvuru_hakem_oneri_sayisi", 0)
                    if len(proje.proje_hakem_onerileri
                           ) < basvuru_hakem_oneri_sayisi:
                        flash(
                            _("Projenizin değerlendirmeye alınabilmesi için en az {} adet hakem "
                              "önerisinde bulunmanız gerekmektedir"
                              ".").format(basvuru_hakem_oneri_sayisi), "error")

                if toplam_katki > 100:
                    flash(
                        _("Personellerin toplam katkı değerleri en fazla 100 olabilir."
                          ), "error")
                form_personel = proje_turu.personel_ayarlari
                # projede bulunan personel sayisindan yurutucuyu cikarinca
                # projeye eklenen personel sayisi bulunur
                calisan_sayisi = len(proje.proje_calisanlari) - 1
                if form_personel.yardimci_arastirmaci_secenekleri == \
                        YardimciArastirmaciSecenekleri.sinirli:
                    if form_personel.yardimci_arastirmaci_alt_limiti > calisan_sayisi:
                        flash(
                            _("{} personel eklediniz. En az {} personel eklemelisiniz."
                              ).format(
                                  calisan_sayisi, form_personel.
                                  yardimci_arastirmaci_alt_limiti), "error")
                    elif form_personel.yardimci_arastirmaci_ust_limiti < calisan_sayisi:
                        flash(
                            _("{} personel eklediniz. En fazla {} personel ekleyebilirsiniz."
                              ).format(
                                  calisan_sayisi, form_personel.
                                  yardimci_arastirmaci_ust_limiti), "error")
                for butce_hata in butce_hatalari:
                    flash(butce_hata, "error")

                if get_flashed_messages(category_filter=["error"]):
                    DB.session.rollback()
                    proje_formu.proje_personeli.yurutucu.yurutucu_id.data = proje.yurutucu
                    return render_template(
                        'arastirma_projesi_basvuru/arastirma_proje_basvurusu.html',
                        yeni_basvuru_formu=proje_formu,
                        proje_tur_dict=proje_tur_dict,
                        proje_id=proje_id,
                        proje_hakem_onerileri=proje.proje_hakem_onerileri,
                        proje_calisanlari=[
                            calisan for calisan in proje.proje_calisanlari
                            if not (proje.yurutucu
                                    and proje.yurutucu == calisan.personel_id)
                        ],
                        taslak_mi=taslak_mi,
                        revizyon_bekleniyor_mu=revizyon_bekleniyor_mu,
                        hata_mesajlari=get_flashed_messages(
                            category_filter=["error"]))

            if taslak_mi:
                proje.proje_basvuru_durumu = ProjeBasvuruDurumu.taslak
                signal_payload = {
                    "message_type":
                    USER_ACTIVITY_MESSAGES.get("bap").get(
                        "proje_basvuru_guncelle").type_index,
                    "nesne":
                    'Proje',
                    "nesne_id":
                    proje_id,
                    "ekstra_mesaj":
                    "{} adlı kullanıcı, proje başvurusunu güncelledi.".format(
                        current_user.username)
                }
                signal_sender(**signal_payload)
                return redirect(
                    url_for('proje.proje_yeni_basvuru_taslak_with_id',
                            proje_id=proje.id))

            # todo: revizyon tamamlaninca admine mesaj !!!
            proje.proje_basvuru_durumu = ProjeBasvuruDurumu.tamamlandi

            if not revizyon_bekleniyor_mu:
                proje.gelir_kasasi_id = proje_tur_dict.get(
                    "gelir_kasasi_id", None)
                proje.teklif_edilen_baslama_tarihi = date.today()
                ProjeStateDispacther.project_init(
                    params={"proje_id": proje_id},
                    triggered_by=current_user.id,
                    proje_id=proje_id)
                signal_payload = {
                    "message_type":
                    USER_ACTIVITY_MESSAGES.get("bap").get(
                        "proje_basvuru_tamamla").type_index,
                    "nesne":
                    'Proje',
                    "nesne_id":
                    proje_id,
                    "ekstra_mesaj":
                    "{} adlı kullanıcı, proje başvurusunu tamamladi.".format(
                        current_user.username)
                }

                signal_sender(**signal_payload)
            else:
                revizyon_signal_payload = {
                    "message_type":
                    USER_ACTIVITY_MESSAGES.get("bap").get(
                        "proje_basvuru_tamamla").type_index,
                    "nesne":
                    'Proje',
                    "nesne_id":
                    proje_id,
                    "ekstra_mesaj":
                    "{} adlı kullanıcı, projesinin revizyonunu tamamladi.".
                    format(current_user.username)
                }

                signal_sender(**revizyon_signal_payload)

                for bap_admin in bap_yetkili_and_admin_ids():
                    payload = {
                        "message_type":
                        USER_ACTIVITY_MESSAGES.get("bap").get(
                            "proje_islem").type_index,
                        "ekstra_mesaj":
                        "{} id li projenin revizyon işlemi tamamlandı".format(
                            proje.id),
                        "notification_receiver":
                        bap_admin.person_id,
                        "notification_title":
                        _("Proje revize edildi"),
                        "notification_message":
                        "{} numaralı projenin revizyon işlemi proje yürütücüsü"
                        " tarafından tamamlandı.".format(proje.proje_no),
                        "proje_id":
                        proje.id
                    }

                    signal_sender(log=False, notification=True, **payload)

            DB.session.commit()
            return redirect(url_for('proje.proje_dashboard',
                                    proje_id=proje.id))
        except IntegrityError as exc:
            CustomErrorHandler.error_handler(
                hata="Bir hata meydana geldi. Hata: {}".format(exc))
            DB.session.rollback()
            proje_formu.proje_personeli.yurutucu.yurutucu_id.data = proje.yurutucu
            return render_template(
                'arastirma_projesi_basvuru/arastirma_proje_basvurusu.html',
                yeni_basvuru_formu=proje_formu,
                proje_tur_dict=proje_turu.to_dict(),
                proje_id=proje_id,
                proje_hakem_onerileri=proje.proje_hakem_onerileri,
                proje_calisanlari=[
                    calisan for calisan in proje.proje_calisanlari
                    if not (proje.yurutucu
                            and proje.yurutucu == calisan.personel_id)
                ],
                revizyon_bekleniyor_mu=revizyon_bekleniyor_mu,
                taslak_mi=taslak_mi)

    @staticmethod
    @login_required
    @auth.requires(
        And(
            Permission(*permission_dict["bap"]["proje"]["basvuru"]
                       ["proje_basvurusu_yapma"]),
            And(TamamlanmamisProjeBasvurusu(), ProjeYurutucusu())))
    @route('/yeni-basvuru/taslak/<int:proje_id>',
           methods=['GET'],
           endpoint='proje_yeni_basvuru_taslak_with_id')
    # pylint: disable=too-many-locals
    def get_proje_taslak_with_id(proje_id):
        """Id'si verilen kaydedilmiş taslak projeyi getirir"""
        user_id = current_user.id
        try:
            proje = DB.session.query(Proje).filter_by(
                id=proje_id,
                proje_basvuru_durumu=ProjeBasvuruDurumu.taslak).one()

        except NoResultFound as exc:
            CustomErrorHandler.error_handler(
                hata=
                "Basvuru durumu taslak olmayan veya var olmayan bir proje ile "
                "proje basvurusu taslağına ulaşılmaya calışıldı. Hata: {}, "
                "User id: {}, Proje id: {}".format(exc, user_id, proje_id))
            return abort(404)
        proje_turu = get_proje_turu_with_related_field(proje.proje_turu)
        if not proje_turu:
            #  todo: current app logger customerror handlera cevrilecek
            CustomErrorHandler.error_handler(
                hata=
                "Güncel olmayan bir proje türünün kayıtlı taslagına ulaşılmaya"
                " çalışıldı. User id: {}, Proje id: {}".format(
                    user_id, proje_id))
            flash(
                "Taslak kaydı yaptığınız projenin başvuru koşulları BAP birimi tarafından "
                "güncellenmiştir. Lütfen güncel proje türü üzerinden tekrar başvurunuzu "
                "gerçekleştiriniz.")
            return redirect(
                url_for("proje.ProjeBasvuruView:basvuru_icin_proje_turu_sec"))
        proje_turu_dict = proje_turu_to_dict(proje_turu)
        yurutucu_calisan_id = None

        yurutucu_calisan = DB.session.query(ProjeCalisanlari).filter_by(
            proje_id=proje_id, personel_id=proje.yurutucu).first()
        if yurutucu_calisan:
            yurutucu_calisan_id = yurutucu_calisan.id

        form_data = get_proje_data(proje_turu_dict, proje)

        proje_formu = basvuru_formu_restriction(
            proje_turu_dict=proje_turu_dict, **form_data)
        return render_template(
            'arastirma_projesi_basvuru/arastirma_proje_basvurusu.html',
            yeni_basvuru_formu=proje_formu,
            proje_tur_dict=proje_turu.to_dict(),
            proje_id=proje_id,
            proje_hakem_onerileri=proje.proje_hakem_onerileri,
            proje_calisanlari=[
                calisan for calisan in proje.proje_calisanlari if not (
                    proje.yurutucu and proje.yurutucu == calisan.personel_id)
            ],
            yurutucu_calisan_id=yurutucu_calisan_id,
            taslak_mi=True,
            revizyon_bekleniyor_mu=False,
            uyari_mesajlari=proje_turu_dict.get("genel_uyari_mesajlari", None))