<commit_before>"""
Models for the Agency application
"""

from django.contrib.auth.models import User
from django.db import models

from datetime import date
from easy_thumbnails.fields import ThumbnailerImageField

from muckrock.jurisdiction.models import Jurisdiction, RequestHelper
from muckrock.models import ChainableManager
from muckrock import fields

class AgencyType(models.Model):
    """Marks an agency as fufilling requests of this type for its jurisdiction"""

    name = models.CharField(max_length=60)

    def __unicode__(self):
        return self.name

    class Meta:
        # pylint: disable=R0903
        ordering = ['name']


class AgencyManager(ChainableManager):
    """Object manager for Agencies"""
    # pylint: disable=R0904

    def get_approved(self):
        """Get all approved agencies"""
        return self.filter(approved=True)


class Agency(models.Model, RequestHelper):
    """An agency for a particular jurisdiction that has at least one agency type"""

    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255)
    jurisdiction = models.ForeignKey(Jurisdiction, related_name='agencies')
    types = models.ManyToManyField(AgencyType, blank=True)
    approved = models.BooleanField()
    user = models.ForeignKey(User, null=True, blank=True)
    appeal_agency = models.ForeignKey('self', null=True, blank=True)
    can_email_appeals = models.BooleanField()
    image = ThumbnailerImageField(upload_to='agency_images', blank=True, null=True,
                                  resize_source={'size': (372, 233), 'crop': 'smart'})
    image_attr_line = models.CharField(blank=True, max_length=255, help_text='May use html')
    public_notes = models.TextField(blank=True, help_text='May use html')
    stale = models.BooleanField(default=False)

    address = models.TextField(blank=True)
    email = models.EmailField(blank=True)
    other_emails = fields.EmailsListField(blank=True, max_length=255)
    contact_salutation = models.CharField(blank=True, max_length=30)
    contact_first_name = models.CharField(blank=True, max_length=100)
    contact_last_name = models.CharField(blank=True, max_length=100)
    contact_title = models.CharField(blank=True, max_length=255)
    url = models.URLField(blank=True, verbose_name='Website', help_text='Begin with http://')
    expires = models.DateField(blank=True, null=True)
    phone = models.CharField(blank=True, max_length=30)
    fax = models.CharField(blank=True, max_length=30)
    notes = models.TextField(blank=True)

    objects = AgencyManager()

    def __unicode__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        """The url for this object"""
        # pylint: disable=E1101
        return ('agency-detail', [], {'jurisdiction': self.jurisdiction.slug,
                                      'jidx': self.jurisdiction.pk,
                                      'slug': self.slug, 'idx': self.pk})

    def normalize_fax(self):
        """Return a fax number suitable for use in a faxaway email address"""

        fax = ''.join(c for c in self.fax if c.isdigit())
        if len(fax) == 10:
            return '1' + fax
        if len(fax) == 11 and fax[0] == '1':
            return fax
        return None

    def get_email(self):
        """Returns an email address to send to"""

        if self.email:
            return self.email
        elif self.normalize_fax():
            return <EMAIL>' % self.normalize_fax()
        else:
            return ''

    def get_other_emails(self):
        """Returns other emails as a list"""
        return fields.email_separator_re.split(self.other_emails)

    def link_display(self):
        """Returns link if approved"""
        if self.approved:
            return '<a href="%s">%s</a>' % (self.get_absolute_url(), self.name)
        else:
            return self.name

    def expired(self):
        """Is this agency expired?"""

        if self.expires:
            return self.expires < date.today()

    def latest_response(self):
        """When was the last time we heard from them?"""
        # pylint: disable=E1101
        foias = self.foiarequest_set.get_open()
        latest_responses = []
        for foia in foias:
            responses = foia.communications.filter(response=True).order_by('-date')
            if responses:
                latest_responses.append(responses[0].date.date)
        if latest_responses:
            return (date.today() - max(latest_responses)).days

    class Meta:
        # pylint: disable=R0903
        verbose_name_plural = 'agencies'
<commit_msg>fix stale calculations<commit_after>"""
Models for the Agency application
"""

from django.contrib.auth.models import User
from django.db import models

from datetime import date
from easy_thumbnails.fields import ThumbnailerImageField

from muckrock.jurisdiction.models import Jurisdiction, RequestHelper
from muckrock.models import ChainableManager
from muckrock import fields

class AgencyType(models.Model):
    """Marks an agency as fufilling requests of this type for its jurisdiction"""

    name = models.CharField(max_length=60)

    def __unicode__(self):
        return self.name

    class Meta:
        # pylint: disable=R0903
        ordering = ['name']


class AgencyManager(ChainableManager):
    """Object manager for Agencies"""
    # pylint: disable=R0904

    def get_approved(self):
        """Get all approved agencies"""
        return self.filter(approved=True)


class Agency(models.Model, RequestHelper):
    """An agency for a particular jurisdiction that has at least one agency type"""

    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255)
    jurisdiction = models.ForeignKey(Jurisdiction, related_name='agencies')
    types = models.ManyToManyField(AgencyType, blank=True)
    approved = models.BooleanField()
    user = models.ForeignKey(User, null=True, blank=True)
    appeal_agency = models.ForeignKey('self', null=True, blank=True)
    can_email_appeals = models.BooleanField()
    image = ThumbnailerImageField(upload_to='agency_images', blank=True, null=True,
                                  resize_source={'size': (372, 233), 'crop': 'smart'})
    image_attr_line = models.CharField(blank=True, max_length=255, help_text='May use html')
    public_notes = models.TextField(blank=True, help_text='May use html')
    stale = models.BooleanField(default=False)

    address = models.TextField(blank=True)
    email = models.EmailField(blank=True)
    other_emails = fields.EmailsListField(blank=True, max_length=255)
    contact_salutation = models.CharField(blank=True, max_length=30)
    contact_first_name = models.CharField(blank=True, max_length=100)
    contact_last_name = models.CharField(blank=True, max_length=100)
    contact_title = models.CharField(blank=True, max_length=255)
    url = models.URLField(blank=True, verbose_name='Website', help_text='Begin with http://')
    expires = models.DateField(blank=True, null=True)
    phone = models.CharField(blank=True, max_length=30)
    fax = models.CharField(blank=True, max_length=30)
    notes = models.TextField(blank=True)

    objects = AgencyManager()

    def __unicode__(self):
        return self.name

    @models.permalink
    def get_absolute_url(self):
        """The url for this object"""
        # pylint: disable=E1101
        return ('agency-detail', [], {'jurisdiction': self.jurisdiction.slug,
                                      'jidx': self.jurisdiction.pk,
                                      'slug': self.slug, 'idx': self.pk})

    def normalize_fax(self):
        """Return a fax number suitable for use in a faxaway email address"""

        fax = ''.join(c for c in self.fax if c.isdigit())
        if len(fax) == 10:
            return '1' + fax
        if len(fax) == 11 and fax[0] == '1':
            return fax
        return None

    def get_email(self):
        """Returns an email address to send to"""

        if self.email:
            return self.email
        elif self.normalize_fax():
            return <EMAIL>' % self.normalize_fax()
        else:
            return ''

    def get_other_emails(self):
        """Returns other emails as a list"""
        return fields.email_separator_re.split(self.other_emails)

    def link_display(self):
        """Returns link if approved"""
        if self.approved:
            return '<a href="%s">%s</a>' % (self.get_absolute_url(), self.name)
        else:
            return self.name

    def expired(self):
        """Is this agency expired?"""

        if self.expires:
            return self.expires < date.today()

    def latest_response(self):
        """When was the last time we heard from them?"""
        # pylint: disable=E1101
        foias = self.foiarequest_set.get_open()
        latest_responses = []
        for foia in foias:
            responses = foia.communications.filter(response=True).order_by('-date')
            if responses:
                latest_responses.append(responses[0].date.date())
        if latest_responses:
            return (date.today() - max(latest_responses)).days

    class Meta:
        # pylint: disable=R0903
        verbose_name_plural = 'agencies'

{'fraction_non_alphanumeric': 0.11040293831694933, 'fraction_numerical': 0.013611321162363616, 'mean_word_length': 2.927874416631311, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6479477', 'n_tokens_mistral': 2878, 'n_tokens_neox': 2656, 'n_words': 662}