예제 #1
0
class Takvim(Model):
    """
    olay, bir zaman araliginda gerceklesiyorsa(ayni gunun saat araliklari dahil),
                                                    baslangic ve bitis zamanlari ayri ayri verilir,
    olay, bir gun icinde ancak kesin zaman bagimsiz/belirsiz gerceklesiyorsa,
                                                    baslangic ve bitis zamanlari ayni verilir,
    olay, belirsiz bir baslangic yani son gun belirtilmisse, sadece bitis tarihi verilir,
    olay, belirsiz bir son yani baslama gun belirtilmisse, sadece baslangic tarihi verilir,
    """
    etkinlik = field.Integer(_(u"Etkinlik"), index=True, choices=AKADEMIK_TAKVIM_ETKINLIKLERI)
    baslangic = field.DateTime(_(u"Başlangıç"), index=True, format="%d.%m.%Y", required=False)
    bitis = field.DateTime(_(u"Bitiş"), index=True, format="%d.%m.%Y", required=False)
    akademik_takvim = AkademikTakvim(_(u"Akademik Takvim"))
    resmi_tatil = field.Boolean(_(u"Resmi Tatil"), index=True)

    def pre_save(self):
        if not self.baslangic and not self.bitis:
            raise Exception("Tarihlerden en az bir tanesi dolu olmalidir.")

    class Meta:
        app = 'Ogrenci'
        verbose_name = _(u"Takvim")
        verbose_name_plural = _(u"Takvimler")
        list_filters = ["etkinlik", "baslangic", "bitis", 'resmi_tatil']

    def __unicode__(self):
        return '%s %s %s' % (
            self.akademik_takvim.birim, self.akademik_takvim.ogretim_yili, self.etkinlik)
예제 #2
0
파일: bap.py 프로젝트: zetaops/ulakbus
class BAPSatinAlma(Model):
    class Meta:
        verbose_name = __(u"Bütçe Kalemi Satın Alma")
        verbose_name_plural = __(u"Bütçe Kalemi Satın Almaları")
        list_fields = ['ad', 'teklife_acilma_tarihi', 'teklife_kapanma_tarihi']

    ad = field.String(__(u"Satın Alma Duyuru Adı"))
    teklife_acilma_tarihi = field.DateTime(__(u"Teklife Açılma Tarihi"))
    teklife_kapanma_tarihi = field.DateTime(__(u"Teklife Kapanma Tarihi"))
    sonuclanma_tarihi = field.Date(__(u"Teklifin Sonuçlanma Tarihi"))
    onay_tarih_sayi = field.String(__(u"Onay Tarih/Sayı"))
    ekleyen = Personel()
    aciklama = field.Text(__(u"Açıklama"))
    teklif_durum = field.Integer(__(u"Teklif Durum"),
                                 choices='bap_satin_alma_durum')
    ilgili_proje = BAPProje()
    tek_firma = BAPFirma()
    tur = field.Integer(_(u"Satın Alma Türü"),
                        choices='bap_satin_alma_turleri')
    duyuruda = field.Boolean(_(u"Duyuru Durumu"), default=False)
    sorumlu = Role()
    duyuruda = field.Boolean(__(u"Duyurulma Durumu"), default=False)

    class ButceKalemleri(ListNode):
        butce = BAPButcePlani()

    def __unicode__(self):
        return "%s" % self.ad
예제 #3
0
class WFInstance(Model):
    """

    Running workflow instance

    """
    wf = BPMNWorkflow()
    task = Task()
    name = field.String(__(u"WF Name"))
    subject = field.String(__(u"Subject ID"))
    current_actor = RoleModel(__(u"Current Actor"))
    wf_object = field.String(__(u"Subject ID"))
    wf_object_type = field.String(__(u"Object type"),
                                  null=True,
                                  choices=get_model_choices)
    last_activation = field.DateTime(__(u"Last activation"))
    finished = field.Boolean(default=False)
    started = field.Boolean(default=False)
    in_external = field.Boolean(default=False)
    start_date = field.DateTime(__(u"Start time"))
    finish_date = field.DateTime(__(u"Finish time"))
    step = field.String(__(u"Last executed WF Step"))
    data = field.String(__(u"Task Data"))
    pool = field.String(__(u"Pool Data"))

    class Meta:
        verbose_name = "Workflow Instance"
        verbose_name_plural = "Workflows Instances"
        search_fields = ['name']
        list_fields = ['name', 'current_actor']

    def get_object(self):
        if self.wf_object_type:
            model = model_registry.get_model(self.wf_object_type)
            return model.objects.get(self.wf_object)
        else:
            return ''

    def actor(self):
        return self.current_actor.user.full_name if self.current_actor.exist else '-'

    actor.title = 'Current Actor'

    # class Pool(ListNode):
    #     order = field.Integer("Lane order")
    #     role = RoleModel()

    def pre_save(self):
        if not self.wf and self.name:
            self.wf = BPMNWorkflow.objects.get(name=self.name)

    def __unicode__(self):
        return '%s instance (%s)' % (self.wf.name, self.key)
예제 #4
0
파일: bap.py 프로젝트: zetaops/ulakbus
    class ProjeIslemGecmisi(ListNode):
        class Meta:
            verbose_name = __(u"İşlem Geçmişi")
            verbose_name_plural = __(u"İşlem Geçmişi")

        eylem = field.String(_(u"Eylem"))
        aciklama = field.String(_(u"Açıklama"))
        tarih = field.DateTime(_(u"Tarih"))
예제 #5
0
파일: uniqueness.py 프로젝트: zetaops/pyoko
class Uniques(Model):
    rel = UniqRelation(unique=True)
    other_rel = OtherUniqRelation()
    id = field.String()
    foo_id = field.String()
    name = field.String()
    username = field.String(unique=True)
    join_date = field.DateTime(unique=True, default='now')

    class Meta:
        unique_together = [('id', 'foo_id'), ('rel', 'other_rel')]
예제 #6
0
파일: bap.py 프로젝트: zetaops/ulakbus
class BAPTeklif(Model):
    class Meta:
        verbose_name = __(u"Firma Teklif")
        verbose_name_plural = __(u"Firma Teklifleri")

    firma = BAPFirma()
    satin_alma = BAPSatinAlma()
    durum = field.Integer(__(u"Durum"), choices='bap_teklif_durum')
    ilk_teklif_tarihi = field.DateTime(_(u"İlk Teklif Tarihi"))
    son_degisiklik_tarihi = field.DateTime(_(u"Son Değişiklik Tarihi"))
    sonuclanma_tarihi = field.Date(__(u"Firma Teklifinin Sonuçlanma Tarihi"))
    fiyat_islemesi = field.Boolean(__(u"Fiyat İşlemesi Yapıldı mı?"),
                                   default=False)

    class Belgeler(ListNode):
        belge = field.File(_(u"Firma Teklif Belgesi"),
                           random_name=False,
                           required=True)
        aciklama = field.String(__(u"Belge Açıklaması"), required=True)

    def __unicode__(self):
        return "%s-%s" % (self.firma.ad, self.satin_alma.ad)
예제 #7
0
class Template(Model):
    """Template Model.

    """

    template_type = field.Integer(choices=TEMPLATE_TYPES)
    template = field.File(random_name="Template")
    description = field.String("Description")
    preview = field.File(random_name="Preview")
    version = field.String("Version")
    modify_date = field.DateTime("ModifyDate", format='%d %b %Y %H:%M:%S')
    name = field.String("Name", unique=True)

    def post_save(self):
        """
        Get last_modified from S3 and update modify_date of this object.
        Returns:

        """
        s3_manager = S3FileManager()
        s3_time = s3_manager.get_last_modified_date(self.template)

        modify_date = self.change_date_format(s3_time)
        self.modify_date = modify_date

        self.save(internal=True)

    @staticmethod
    def change_date_format(s3_modify_date):
        """
        Change date time format for model.
        Args:
            s3_modify_date: <str>

        Returns: Formatted date time in str. <str>

        """
        s3_time = s3_modify_date.split(" ")[1:-1]
        cut_time = '{} {} {} {}'.format(s3_time[0], s3_time[1], s3_time[2],
                                        s3_time[3])
        return cut_time

    class Meta:
        app = 'Document'
        verbose_name = "Template"
        verbose_name_plural = "Templates"
        list_fields = ['description']
        search_fields = ['description']

    def __unicode__(self):
        return '%s' % self.description
예제 #8
0
class TaskInvitation(Model):
    """
    User facing part of task management system

    """
    instance = WFInstance()
    role = RoleModel()
    ownership = field.Integer(default=10, choices=OWNERSHIP_STATES)
    progress = field.Integer(default=10, choices=PROGRESS_STATES)
    wf_name = field.String(__(u"WF Name"))
    title = field.String(__(u"Task Name"))
    search_data = field.String(__(u"Combined full-text search data"))
    start_date = field.DateTime(__(u"Start time"))
    finish_date = field.DateTime(__(u"Finish time"))

    def get_object_name(self):
        return six.text_type(self.instance.get_object())

    def pre_save(self):
        self.title = self.title or self.instance.name

        self.search_data = '\n'.join([self.wf_name, self.title])

        self.progress = get_progress(
            start=self.start_date, finish=self.finish_date
        ) if self.start_date and self.finish_date else 30

    def __unicode__(self):
        return "%s invitation for %s" % (self.wf_name, self.role)

    def delete_other_invitations(self):
        """
        When one person use an invitation, we should delete other invitations
        """
        # TODO: Signal logged-in users to remove the task from their task list
        self.objects.filter(instance=self.instance).exclude(
            key=self.key).delete()
예제 #9
0
class HizmetKayitlari(Model):
    tckn = field.String(_(u"TC Kimlik No"), index=True)
    kayit_no = field.String(_(u"Kayıt No"), index=True)
    baslama_tarihi = field.Date(_(u"Başlama Tarihi"),
                                index=True,
                                format="%d.%m.%Y")
    bitis_tarihi = field.Date(_(u"Bitiş Tarihi"),
                              index=True,
                              format="%d.%m.%Y")
    gorev = field.String(_(u"Görev"), index=True)  # birim + kadro unvanı
    unvan_kod = field.Integer(_(u"Unvan Kod"), index=True)  # kadro unvan kodu
    yevmiye = field.String(_(u"Yevmiye"), index=True)
    ucret = field.String(_(u"Ücret"), index=True)
    hizmet_sinifi = field.Integer(
        _(u"Hizmet Sınıfı"), index=True,
        choices="hizmet_sinifi")  # atama modelinden gelecek
    kadro_derece = field.Integer(_(u"Kadro Derecesi"),
                                 index=True)  # personelden gelecek
    odeme_derece = field.Integer(_(u"Ödeme Derecesi"),
                                 index=True)  # personelden gelecek
    odeme_kademe = field.Integer(_(u"Ödeme Kademesi"),
                                 index=True)  # personelden gelecek (gorunen)
    odeme_ekgosterge = field.Integer(_(u"Ödeme Ek Göstergesi"),
                                     index=True)  # personelden gelecek
    kazanilmis_hak_ayligi_derece = field.Integer(
        _(u"Kazanılmış Hak Aylığı Derecesi"),
        index=True)  # personelden gelecek
    kazanilmis_hak_ayligi_kademe = field.Integer(
        _(u"Kazanılmış Hak Aylığı Kademesi"),
        index=True)  # personelden gelecek (gorunen)
    kazanilmis_hak_ayligi_ekgosterge = field.Integer(
        _(u"Kazanılmış Hak Aylığı Ek Göstergesi"),
        index=True)  # personelden gelecek
    emekli_derece = field.Integer(_(u"Emekli Derecesi"),
                                  index=True)  # personelden gelecek
    emekli_kademe = field.Integer(_(u"Emekli Kademe"),
                                  index=True)  # personelden gelecek (gorunen)
    emekli_ekgosterge = field.Integer(_(u"Emekli Ek Göstergesi"),
                                      index=True)  # personelden gelecek
    sebep_kod = HitapSebep(_(u"Hitap Sebep Kodu"))
    kurum_onay_tarihi = field.Date(_(u"Kurum Onay Tarihi"),
                                   index=True,
                                   format="%d.%m.%Y")
    sync = field.Integer(_(u"Senkronize"), index=True)
    personel = Personel()

    # hizmet cetveline birden c*k modelden veri girilmektedir. bu alanda, hizmet
    # cetveli kaydini olusturan diger modeldeki kaydin key i saklanir.
    model_key = field.String()

    # post save metodunda baslangic ya da bitis tarihinden set edilir.
    order_date = field.DateTime()

    class Meta:
        app = 'Personel'
        verbose_name = _(u"Kayıt")
        verbose_name_plural = _(u"Kayıtlar")
        list_fields = [
            'unvan_kod', 'gorev', 'yevmiye', 'ucret', 'hizmet_sinifi'
        ]
        search_fields = ['unvan_kod', 'gorev', 'yevmiye']
        hitap_service_prefix = "HitapHizmetCetveli"

    def post_save(self):
        """
        Hizmet cetvelindeki kayıtların başlama veya bitiş tarihleri
        geliyor. Her kaydın başlama ve bitiş tarihi beraber gelmiyor.
        Bu yüzden kayıtların sıralanabilmesi için order_date alanı
        eklendi. Bitiş tarihi başka bir kaydın başlangıç tarihi ise
        önce bitiş tarihi olan kayıt gürüntülenmelidir. Bu yüzden
        başlangıç tarihine +1 saat eklendi.
        """
        if self.baslama_tarihi != datetime.date(1900, 1, 1):
            self.order_date = datetime.datetime.combine(
                self.baslama_tarihi, datetime.time(1))
        else:
            self.order_date = self.bitis_tarihi
        self.save()

    def post_creation(self):
        if self.personel:
            self.tckn = self.personel.tckn
            self.gorev = "%s %s" % (self.personel.birim.name,
                                    self.personel.kadro.unvan)
            self.unvan_kod = self.personel.kadro.unvan
            self.hizmet_sinifi = self.personel.atama.hizmet_sinifi
            self.kadro_derece = self.personel.kadro_derece
            self.odeme_derece = self.personel.gorev_ayligi_derece
            self.odeme_kademe = self.personel.gorunen_gorev_ayligi_kademe
            self.odeme_ekgosterge = self.personel.gorev_ayligi_ekgosterge
            self.kazanilmis_hak_ayligi_derece = self.personel.kazanilmis_hak_derece
            self.kazanilmis_hak_ayligi_kademe = self.personel.gorunen_kazanilmis_hak_kademe
            self.kazanilmis_hak_ayligi_ekgosterge = self.personel.kazanilmis_hak_ekgosterge
            self.emekli_derece = self.personel.emekli_muktesebat_derece
            self.emekli_kademe = self.personel.gorunen_emekli_muktesebat_kademe
            self.emekli_ekgosterge = self.personel.emekli_muktesebat_ekgosterge
            self.save()

    def __unicode__(self):
        return '%s %s %s' % (self.unvan_kod, self.hizmet_sinifi, self.gorev)
예제 #10
0
class Task(Model):
    """

    Task definition for workflows

    """
    run = field.Boolean(__(u"Create tasks now!"), default=False)
    wf = BPMNWorkflow()
    name = field.String(__(u"Name of task"))
    abstract_role = AbstractRoleModel(__(u"Abstract Role"), null=True)
    role = RoleModel(null=True)
    unit = UnitModel(null=True)
    get_roles_from = field.String(__(u"Get roles from"),
                                  choices=ROLE_GETTER_CHOICES)
    role_query_code = field.String(__(u"Role query dict"), null=True)
    object_query_code = field.String(__(u"Object query dict"), null=True)
    object_key = field.String(__(u"Subject ID"), null=True)
    object_type = field.String(__(u"Object type"),
                               null=True,
                               choices=get_model_choices)
    start_date = field.DateTime(__(u"Start time"), format="%d.%m.%Y")
    finish_date = field.DateTime(__(u"Finish time"), format="%d.%m.%Y")
    repeat = field.Integer(__(u"Repeating period"),
                           default=0,
                           choices=JOB_REPEATING_PERIODS)
    notification_density = field.Integer(__(u"Notification density"),
                                         choices=JOB_NOTIFICATION_DENSITY)
    recursive_units = field.Boolean(__(u"Get roles from all sub-units"))

    class Meta:
        verbose_name = "Workflow Task"
        verbose_name_plural = "Workflows Tasks"
        search_fields = ['name']
        list_fields = [
            'name',
        ]

    def create_wf_instances(self, roles=None):
        """
        Creates wf instances.
        Args:
            roles (list): role list

        Returns:
            (list): wf instances
        """

        # if roles specified then create an instance for each role
        # else create only one instance

        if roles:
            wf_instances = [
                WFInstance(wf=self.wf,
                           current_actor=role,
                           task=self,
                           name=self.wf.name) for role in roles
            ]
        else:
            wf_instances = [
                WFInstance(wf=self.wf, task=self, name=self.wf.name)
            ]

        # if task type is not related with objects save instances immediately.
        if self.task_type in ["C", "D"]:
            return [wfi.save() for wfi in wf_instances]

        # if task type is related with its objects, save populate instances per object
        else:
            wf_obj_instances = []
            for wfi in wf_instances:
                role = wfi.current_actor if self.task_type == "A" else None
                keys = self.get_object_keys(role)
                wf_obj_instances.extend([
                    WFInstance(wf=self.wf,
                               current_actor=role,
                               task=self,
                               name=self.wf.name,
                               wf_object=key,
                               wf_object_type=self.object_type).save()
                    for key in keys
                ])

            return wf_obj_instances

    def create_task_invitation(self, instances, roles=None):
        for wfi in instances:
            current_roles = roles or [wfi.current_actor]
            for role in current_roles:
                inv = TaskInvitation(instance=wfi,
                                     role=role,
                                     wf_name=self.wf.name,
                                     progress=get_progress(
                                         start=self.start_date,
                                         finish=self.finish_date),
                                     start_date=self.start_date,
                                     finish_date=self.finish_date)
                inv.title = self.name
                inv.save()

    def create_tasks(self):
        """
        will create a WFInstance per object
        and per TaskInvitation for each role and WFInstance
        """
        roles = self.get_roles()

        if self.task_type in ["A", "D"]:
            instances = self.create_wf_instances(roles=roles)
            self.create_task_invitation(instances)

        elif self.task_type in ["C", "B"]:
            instances = self.create_wf_instances()
            self.create_task_invitation(instances, roles)

    def get_object_query_dict(self):
        """returns objects keys according to self.object_query_code
        which can be json encoded queryset filter dict or key=value set
         in the following format: ```"key=val, key2 = val2 , key3= value with spaces"```

        Returns:
             (dict): Queryset filtering dicqt
        """
        if isinstance(self.object_query_code, dict):
            # _DATE_ _DATETIME_
            return self.object_query_code
        else:
            # comma separated, key=value pairs. wrapping spaces will be ignored
            # eg: "key=val, key2 = val2 , key3= value with spaces"
            return dict(
                pair.split('=') for pair in self.object_query_code.split(','))

    def get_object_keys(self, wfi_role=None):
        """returns object keys according to task definition
        which can be explicitly selected one object (self.object_key) or
        result of a queryset filter.

        Returns:
            list of object keys
        """
        if self.object_key:
            return [self.object_key]
        if self.object_query_code:
            model = model_registry.get_model(self.object_type)
            return [
                m.key for m in self.get_model_objects(
                    model, wfi_role, **self.get_object_query_dict())
            ]

    @staticmethod
    def get_model_objects(model, wfi_role=None, **kwargs):
        """
        Fetches model objects by filtering with kwargs

        If wfi_role is specified, then we expect kwargs contains a
        filter value starting with role,

        e.g. {'user': '******'}

        We replace this `role` key with role instance parameter `wfi_role` and try to get
        object that filter value 'role.program.user' points by iterating `getattribute`. At
        the end filter argument becomes {'user': user}.

        Args:
            model (Model): Model class
            wfi_role (Role): role instance of wf instance
            **kwargs: filter arguments

        Returns:
            (list): list of model object instances
        """
        query_dict = {}
        for k, v in kwargs.items():
            if isinstance(v, list):
                query_dict[k] = [str(x) for x in v]
            else:
                parse = str(v).split('.')
                if parse[0] == 'role' and wfi_role:
                    query_dict[k] = wfi_role
                    for i in range(1, len(parse)):
                        query_dict[k] = query_dict[k].__getattribute__(
                            parse[i])
                else:
                    query_dict[k] = parse[0]

        return model.objects.all(**query_dict)

    def get_roles(self):
        """
        Returns:
            Role instances according to task definition.
        """
        if self.role.exist:
            # return explicitly selected role
            return [self.role]
        else:
            roles = []
            if self.role_query_code:
                #  use given "role_query_code"
                roles = RoleModel.objects.filter(**self.role_query_code)
            elif self.unit.exist:
                # get roles from selected unit or sub-units of it
                if self.recursive_units:
                    # this returns a list, we're converting it to a Role generator!
                    roles = (RoleModel.objects.get(k)
                             for k in UnitModel.get_role_keys(self.unit.key))
                else:
                    roles = RoleModel.objects.filter(unit=self.unit)
            elif self.get_roles_from:
                # get roles from selected predefined "get_roles_from" method
                return ROLE_GETTER_METHODS[self.get_roles_from](RoleModel)

        if self.abstract_role.exist and roles:
            # apply abstract_role filtering on roles we got
            if isinstance(roles, (list, types.GeneratorType)):
                roles = [
                    a for a in roles
                    if a.abstract_role.key == self.abstract_role.key
                ]
            else:
                roles = roles.filter(abstract_role=self.abstract_role)
        else:
            roles = RoleModel.objects.filter(abstract_role=self.abstract_role)

        return roles

    @property
    def task_type(self):
        """
        Returns:
            (string) a task type defined as below

        "Type A":
                Roles are gathered from intersection of `get_roles_from`, `abstract_role` and
                `unit` recursively.

                Objects are filtered by `object_type` and `object_query_code`. And relation between
                objects and roles specified in object_query_code by `role` key.

                    ```
                    unit="A faculty",
                    abstract_role="Lecturer",
                    object_type="Class"
                    object_query_code="lecturer_id='role.key'" # role means lecturer's current role.

                    ```

                "fields": ["unit", "abstract_role", "get_roles_from", "object_type",
                           "object_query_code", "recursive"]
        "Type B":
                Roles are gathered from intersection of `get_roles_from`, `abstract_role` and
                `unit` recursively.

                Objects are filtered by `object_type` and `object_query_code`.

                     ```
                     unit="A faculty",
                     abstract_role="Managers",
                     object_type="Class"
                     object_query_code="capacity>50"

                     ```
                "fields": ["unit", "abstract_role", "get_roles_from", "object_type",
                           "object_query_code", "recursive"]

        "Type C":
                Roles are gathered from `get_roles_from` or `abstract_role` or intersection of both.

                No objects are specified. This type of task is for wfs which are not dependent on
                any object or unit, etc. e.g, periodic system management wf.

                     ```
                     abstract_role="Managers",

                     ```
                "fields": ["abstract_role", "get_roles_from"]

        "Type D":
                Roles are gathered from intersection of `get_roles_from`, `abstract_role` and
                `unit` recursively.

                No objects are specified. This type of task is for wfs which are not dependent on
                any object, but unit. e.g, change timetable schedule, choose advisers
                for department.

                     ```
                     unit="A faculty"
                     abstract_role="Chief of Department",

                     ```
                "fields": ["unit", "abstract_role", "get_roles_from", "recursive"]
        """

        if self.object_type:
            return "A" if self.is_role_in_object_query_code() else "B"
        else:
            return "C" if not self.unit.exist else "D"

    def is_role_in_object_query_code(self):
        query_code = self.get_object_query_dict()
        for k, v in query_code.items():
            parse = str(v).split('.')
            if parse[0] == 'role':
                return True
        return False

    def post_save(self):
        """can be removed when a proper task manager admin interface implemented"""
        if self.run:
            self.run = False
            self.create_tasks()
            self.save()

    def __unicode__(self):
        return '%s' % self.name
예제 #11
0
파일: auth.py 프로젝트: tahademir95/ulakbus
class PermissionsRestrictions(Model):
    """PermissionsRestrictions yetki sınırlandırması ile ilgili kuralların
    saklandığı data modelidir.

    Başlangıç ve bitiş tarihleri kuralın geçerli olduğu zaman aralığını
    belirler.

    `allow_or_ban` ise kuralın yetkileri genişleteceğini mi yoksa
    sınırlandıracağını mı belirler.

    IPList kuralın geçerli olacağı IP adreslerini belirtir.

    Permissions kuralın hangi yetkilere uygulanacağını belirtir.

    Roles ve AbstractRoles ise kuralın kimi etkileyeceğini belirtir.

    """
    allow_or_ban = field.Boolean(_(u"Yasakla / İzin Ver"), default=False)
    time_start = field.DateTime(_(u"Başlangıç"), index=True)
    time_end = field.DateTime(_(u"Bitiş"), index=True)
    role_code = field.String("Role")
    permission_code = field.String()
    abstract_role_code = field.String("Abstract Role")
    ip_address = field.String("IP")

    class Meta:
        app = 'Sistem'
        verbose_name = _(u"Sınırlandırılmış Yetki")
        verbose_name_plural = _(u"Sınırlandırılmış Yetkiler")
        unique_together = [
            ('role_code', 'permission_code'),
            ('abstract_role_code', 'permission_code'),
        ]

    def __unicode__(self):
        return "%s - %s" % (self.time_start, self.time_end)

    def pre_save(self):
        if not self.permission_code:
            raise IntegrityError("Izin belirtilmelidir!")

        if self.role_code and self.abstract_role_code:
            raise IntegrityError(
                "Rol veya Rol Gruplarindan (Role / Abstract Role)sadece biri seçili olmalıdır.")

    @classmethod
    def get_active_restrictions_by_filter(cls, **kw):
        """
        Gets query filter args from **kw and add time_end__lt=datetime.now()

        Args:
            **kw: keyword arguments

        Returns:
            tuple: allowed and banned permissions

        """
        allow, ban = [], []

        for rule in cls.objects.filter(time_end__lt=datetime.now(), **kw):
            perm = rule.permission_code
            allow.append(perm) if rule.allow_or_ban else ban.append(perm)

        return allow, ban

    @classmethod
    def get_restrictions_by_role(cls, role):
        """
        Args:
            role (Role, Abstract Role): role or abtract role instance

        Returns:
            tuple: allowed and banned permissions

        """
        if isinstance(role, AbstractRole):
            return cls.get_active_restrictions_by_filter(abstract_role_code=role.key)
        else:
            return cls.get_active_restrictions_by_filter(role_code=role.key)

    @classmethod
    def clean_up_expired_rules(cls):
        """
        cleans expired rules
        """
        cls.objects.filter(time_end__lt=datetime.now()).delete()