<commit_before># -*- coding: UTF-8 -*-
# Copyright 2016-2017 <NAME>
#
# License: BSD (see file COPYING for details)
"""
Database models for this plugin.

"""

from __future__ import unicode_literals
from __future__ import print_function
import six

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.db.models import Q
from django.db import models
from django.conf import settings

from lino.api import dd, rt
from lino.core.utils import lazy_format
from lino.modlib.users.mixins import UserAuthored, My
from lino.modlib.notify.choicelists import MailModes
from lino.mixins import Created, ObservedPeriod
from lino_xl.lib.cal.mixins import daterange_text
from .roles import VotesUser, VotesStaff
from .choicelists import VoteStates, VoteEvents  # , VoteViews
from .choicelists import Ratings


@dd.python_2_unicode_compatible
class Vote(UserAuthored, Created):
    """A **vote** is when a user has an opinion or interest about a given
    ticket (or any other votable).

    .. attribute:: votable

        The ticket (or other votable) being voted.

    .. attribute:: user

        The user who is voting.

    .. attribute:: state

        The state of this vote.  Pointer to :class:`VoteStates
        <lino_noi.lib.votes.choicelists.VoteStates>`.

    .. attribute:: priority

        My personal priority for this ticket.

    .. attribute:: rating

        How the ticket reporter rates my help on this ticket.

    .. attribute:: remark

        Why I am interested in this ticket.

    .. attribute:: nickname
    
        My nickname for this ticket. Optional. 

        If this is specified, then I get a quicklink to this ticket.

    """
    class Meta:
        app_label = 'votes'
        verbose_name = _("Vote")
        verbose_name_plural = _("Votes")
        abstract = dd.is_abstract_model(__name__, 'Vote')

    state = VoteStates.field(default=VoteStates.as_callable('watching'))
    votable = dd.ForeignKey(dd.plugins.votes.votable_model)
    priority = models.SmallIntegerField(_("Priority"), default=0)
    rating = Ratings.field(blank=True)
    # remark = dd.RichTextField(_("Remark"), blank=True)
    nickname = models.CharField(_("Nickname"), max_length=50, blank=True)
    mail_mode = MailModes.field(blank=True)

    quick_search_fields = "nickname votable__summary votable__description"
    workflow_state_field = 'state'
    
    def __str__(self):
        # return _("{0.user} {0.state} on {0.votable}").format(self)
        return _("{user}'s {vote} on {votable}").format(
            user=self.user, vote=self.state.vote_name,
            votable=self.votable)

    def disabled_fields(self, ar):
        df = super(Vote, self).disabled_fields(ar)
        me = ar.get_user()
        if not me.profile.has_required_roles([VotesStaff]):
            if me != self.votable.get_vote_rater():
                df.add('rating')
        return df

    @classmethod
    def get_parameter_fields(cls, **fields):
        fields.update(
            reporter=dd.ForeignKey(
                settings.SITE.user_model,
                verbose_name=_("Reporter"),
                blank=True, null=True,
                help_text=_(
                    "Only rows on votables reported by this user.")),
            # show_todo=dd.YesNo.field(_("To do"), blank=True),
            # vote_view=VoteViews.field(blank=True),
            state=VoteStates.field(
                blank=True, help_text=_("Only rows having this state.")),
            mail_mode=MailModes.field(
                blank=True, help_text=_("Only rows having this mail mode.")))
        model = dd.plugins.votes.votable_model
        fld = model._meta.get_field('state')
        hlp = lazy_format(
            _("Only rows whose {model} has this state."),
            model=model._meta.verbose_name)
        lbl = lazy_format(
            _("{model} state"), model=model._meta.verbose_name)
        fields.update(
            votable_state=fld.choicelist.field(
                lbl, blank=True, help_text=hlp))
        return super(Vote, cls).get_parameter_fields(**fields)

    @dd.displayfield(_("Description"))
    def votable_overview(self, ar):
        obj = self.votable
        if ar is None or obj is None:
            return ''
        return obj.get_overview(ar)


dd.update_field(Vote, 'user', verbose_name=_("Voter"))


class Votes(dd.Table):
    model = 'votes.Vote'
    # stay_in_grid = True
    required_roles = dd.required(VotesUser)

    parameters = ObservedPeriod(
        observed_event=VoteEvents.field(blank=True))

    params_layout = """
    user mail_mode state votable_state reporter 
    start_date end_date observed_event"""

    detail_layout = dd.FormLayout("""
    state mail_mode
    priority nickname
    rating 
    """, window_size=(40, 'auto'))
<commit_msg>test for empty Vote.votable field<commit_after># -*- coding: UTF-8 -*-
# Copyright 2016-2017 <NAME>
#
# License: BSD (see file COPYING for details)
"""
Database models for this plugin.

"""

from __future__ import unicode_literals
from __future__ import print_function
import six

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.db.models import Q
from django.db import models
from django.conf import settings

from lino.api import dd, rt
from lino.core.utils import lazy_format
from lino.modlib.users.mixins import UserAuthored, My
from lino.modlib.notify.choicelists import MailModes
from lino.mixins import Created, ObservedPeriod
from lino_xl.lib.cal.mixins import daterange_text
from .roles import VotesUser, VotesStaff
from .choicelists import VoteStates, VoteEvents  # , VoteViews
from .choicelists import Ratings


@dd.python_2_unicode_compatible
class Vote(UserAuthored, Created):
    """A **vote** is when a user has an opinion or interest about a given
    ticket (or any other votable).

    .. attribute:: votable

        The ticket (or other votable) being voted.

    .. attribute:: user

        The user who is voting.

    .. attribute:: state

        The state of this vote.  Pointer to :class:`VoteStates
        <lino_noi.lib.votes.choicelists.VoteStates>`.

    .. attribute:: priority

        My personal priority for this ticket.

    .. attribute:: rating

        How the ticket reporter rates my help on this ticket.

    .. attribute:: remark

        Why I am interested in this ticket.

    .. attribute:: nickname
    
        My nickname for this ticket. Optional. 

        If this is specified, then I get a quicklink to this ticket.

    """
    class Meta:
        app_label = 'votes'
        verbose_name = _("Vote")
        verbose_name_plural = _("Votes")
        abstract = dd.is_abstract_model(__name__, 'Vote')

    state = VoteStates.field(default=VoteStates.as_callable('watching'))
    votable = dd.ForeignKey(dd.plugins.votes.votable_model)
    priority = models.SmallIntegerField(_("Priority"), default=0)
    rating = Ratings.field(blank=True)
    # remark = dd.RichTextField(_("Remark"), blank=True)
    nickname = models.CharField(_("Nickname"), max_length=50, blank=True)
    mail_mode = MailModes.field(blank=True)

    quick_search_fields = "nickname votable__summary votable__description"
    workflow_state_field = 'state'
    
    def __str__(self):
        # return _("{0.user} {0.state} on {0.votable}").format(self)
        if self.votable_id:
            return _("{user}'s {vote} on {votable}").format(
                user=self.user, vote=self.state.vote_name,
                votable=self.votable)
                
        return _("{user}'s {vote} on {votable}").format(
            user=self.user, vote=self.state.vote_name,
            votable=None)

    def disabled_fields(self, ar):
        df = super(Vote, self).disabled_fields(ar)
        if self.votable_id:
            me = ar.get_user()
            if not me.profile.has_required_roles([VotesStaff]):
                if me != self.votable.get_vote_rater():
                    df.add('rating')
        return df

    @classmethod
    def get_parameter_fields(cls, **fields):
        fields.update(
            reporter=dd.ForeignKey(
                settings.SITE.user_model,
                verbose_name=_("Reporter"),
                blank=True, null=True,
                help_text=_(
                    "Only rows on votables reported by this user.")),
            # show_todo=dd.YesNo.field(_("To do"), blank=True),
            # vote_view=VoteViews.field(blank=True),
            state=VoteStates.field(
                blank=True, help_text=_("Only rows having this state.")),
            mail_mode=MailModes.field(
                blank=True, help_text=_("Only rows having this mail mode.")))
        model = dd.plugins.votes.votable_model
        fld = model._meta.get_field('state')
        hlp = lazy_format(
            _("Only rows whose {model} has this state."),
            model=model._meta.verbose_name)
        lbl = lazy_format(
            _("{model} state"), model=model._meta.verbose_name)
        fields.update(
            votable_state=fld.choicelist.field(
                lbl, blank=True, help_text=hlp))
        return super(Vote, cls).get_parameter_fields(**fields)

    @dd.displayfield(_("Description"))
    def votable_overview(self, ar):
        if ar is None or self.votable_id is None:
            return ''
        return self.votable.get_overview(ar)


dd.update_field(Vote, 'user', verbose_name=_("Voter"))


class Votes(dd.Table):
    model = 'votes.Vote'
    # stay_in_grid = True
    required_roles = dd.required(VotesUser)

    parameters = ObservedPeriod(
        observed_event=VoteEvents.field(blank=True))

    params_layout = """
    user mail_mode state votable_state reporter 
    start_date end_date observed_event"""

    detail_layout = dd.FormLayout("""
    state mail_mode
    priority nickname
    rating 
    """, window_size=(40, 'auto'))

{'fraction_non_alphanumeric': 0.10491902223116387, 'fraction_numerical': 0.00362136605975254, 'mean_word_length': 2.6945373467112597, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3489107', 'n_tokens_mistral': 3102, 'n_tokens_neox': 2966, 'n_words': 756}